Ejemplo n.º 1
0
        public DataResult GetCurrentWarning([FromQuery] int wId, int sId, WarningType type, WarningDataType dataType)
        {
            wId = wId == 0 ? 1 : wId;
            var result = new DataResult();

            if (HWarningHelper.CurrentData != null && HWarningHelper.CurrentData.Any())
            {
                var r = sId == 0 ? HWarningHelper.CurrentData.Where(x => x.Key.Item3 == dataType && x.Key.Item4 == type).Select(y => y.Value)
                    : HWarningHelper.CurrentData.Where(x => x.Key.Item3 == dataType && x.Key.Item4 == type).Where(y => y.Value.SetId == sId).Select(z => z.Value);
                if (r.Any())
                {
                    var sets       = WarningSetHelper.GetMenus(wId, r.Select(x => x.SetId));
                    var devices    = DeviceHelper.GetMenus(wId, r.Select(x => x.DeviceId));
                    var categories = DeviceCategoryHelper.GetMenus(wId, r.Select(x => x.CategoryId));
                    //var classes = ServerConfig.ApiDb.Query<DeviceClass>("SELECT `Id`, `Class` FROM `device_class` WHERE `MarkedDelete` = 0 AND Id IN @Id;", new
                    //{
                    //    Id = data.Select(x => x.ClassId)
                    //});
                    foreach (var current in r.OrderBy(x => x.ItemId).ThenBy(x => x.DeviceId))
                    {
                        var d = ClassExtension.ParentCopyToChild <WarningCurrent, WarningCurrentDetail>(current);
                        d.SetName = sets.FirstOrDefault(x => x.Id == d.SetId)?.Name ?? "";
                        d.Code    = devices.FirstOrDefault(x => x.Id == d.DeviceId)?.Code ?? "";
                        //d.Class = classes.FirstOrDefault(x => x.Id == d.ClassId)?.Class ?? "";
                        d.CategoryName = categories.FirstOrDefault(x => x.Id == d.CategoryId)?.Name ?? "";
                        result.datas.Add(d);
                    }
                }
            }
            return(result);
        }
Ejemplo n.º 2
0
        public object GetSet([FromQuery] bool init = false, int wId = 1, int qId = 0, int page = 0)
        {
            var workshop = WorkshopHelper.Instance.Get <Workshop>(wId);

            if (init)
            {
                var data = MonitoringKanBanSetHelper.GetDetail(wId).ToList();
                data.Insert(0, new MonitoringKanBanSet
                {
                    Id     = 0,
                    Name   = "所有设备",
                    Type   = KanBanEnum.设备详情看板,
                    Order  = -1,
                    IsShow = true
                });
                var item = MonitoringKanBanSetHelper.Instance.Configs.ToDictionary(c => (int)c.Key, c =>
                {
                    foreach (var v in c.Value)
                    {
                        v.FieldList = v.FieldList.Select((x, i) => MonitoringKanBanSetHelper.ConvertFieldConfig(x, i, v.Display != KanBanItemDisplayEnum.Chart)).ToList();
                    }
                    return(c.Value);
                });
                foreach (var d in data)
                {
                    if (d.Type != KanBanEnum.生产相关看板)
                    {
                        continue;
                    }

                    var t = new List <KanBanItemSet>();
                    foreach (var list in d.ItemList)
                    {
                        var configs = MonitoringKanBanSetHelper.Instance.Configs[d.Type];
                        var config  = configs.FirstOrDefault(x => x.Item == list.Item);
                        if (config == null)
                        {
                            continue;
                        }
                        if ((list.FieldList == null || !list.FieldList.Any()) && MonitoringKanBanSetHelper.Instance.Configs.ContainsKey(d.Type))
                        {
                            list.FieldList = (config.FieldList.Select((x, i) => MonitoringKanBanSetHelper.ConvertFieldSet(x, i, config.Display != KanBanItemDisplayEnum.Chart)).ToList());
                        }
                        else if (list.FieldList.Count != config.FieldList.Count && config.FieldList.Any(x => list.FieldList.All(y => y.Field != x.Field)))
                        {
                            var fieldList = new List <KanBanTableFieldSet>();
                            for (var i = 0; i < config.FieldList.Count; i++)
                            {
                                var order  = i + 1;
                                var field  = config.FieldList[i];
                                var sField = list.FieldList.FirstOrDefault(x => x.Field == field.Field);
                                if (sField != null)
                                {
                                    //sField.Order = order;
                                    fieldList.Add(sField);
                                }
                                else
                                {
                                    fieldList.Add(MonitoringKanBanSetHelper.ConvertFieldSet(field, order,
                                                                                            config.Display != KanBanItemDisplayEnum.Chart));
                                }
                            }
                            list.FieldList = fieldList;
                        }
                        t.Add(list);
                    }

                    d.Items = t.ToJSON();
                }

                return(new
                {
                    errno = 0,
                    errmsg = "成功",
                    menu = EnumHelper.EnumToList <KanBanEnum>().Select(x => new { Id = x.EnumValue, Type = x.EnumName }),
                    item,
                    shift = EnumHelper.EnumToList <KanBanShiftsEnum>(true).Select(x => new { Id = x.EnumValue, Type = x.EnumName }),
                    //data
                    data = data.Select(x =>
                    {
                        var t = ClassExtension.CopyTo <MonitoringKanBanSet, MonitoringKanBanSetWeb>(x);
                        t.DeviceIdList = x.DeviceIdList;
                        t.VariableList = x.VariableList;
                        t.ItemList = x.ItemList.Select(y =>
                        {
                            var ty = ClassExtension.CopyTo <KanBanItemSet, KanBanItemSetWeb>(y);
                            ty.FieldList = y.FieldList;
                            ty.ConfigList = y.ConfigList;
                            return ty;
                        }).ToList();
                        return t;
                    })
                });
            }

            var set = qId != 0 ? MonitoringKanBanSetHelper.Instance.Get <MonitoringKanBanSet>(qId) : new MonitoringKanBanSet
            {
                Type = KanBanEnum.设备详情看板
            };

            if (set != null)
            {
                MonitoringKanBan kanBan;
                var key = new Tuple <int, int>(set.Id, set.WorkshopId);
                switch (set.Type)
                {
                case KanBanEnum.设备详情看板:
                    kanBan = HKanBanHelper.MonitoringKanBanDic.ContainsKey(key)
                            ? HKanBanHelper.MonitoringKanBanDic[key]
                            : new MonitoringKanBan();
                    return(new
                    {
                        errno = 0,
                        errmsg = "成功",
                        type = set.Type,
                        time = kanBan?.Time ?? DateTime.Now,
                        data = kanBan
                    });

                case KanBanEnum.设备状态看板:
                    #region 设备状态看板
                {
                    var ret = new MonitoringKanBan();
                    page = page < 0 ? 0 : page;
                    var idList = set.DeviceIdList;
                    var deviceLibraryDetails = ServerConfig.ApiDb.Query <DeviceDetail>(
                        "SELECT a.*, b.ModelName, b.CategoryId, b.CategoryName, c.FirmwareName, d.ApplicationName, e.HardwareName, f.SiteName, f.Region, " +
                        "g.ScriptName, IFNULL(h.`Name`, '')  AdministratorName, i.`Class`, j.FlowCardId, j.FlowCard, j.LastFlowCardId, j.LastFlowCard, j.StartTime FROM device_library a " +
                        $"JOIN device_model_all b ON a.ModelId = b.Id " +
                        "JOIN firmware c ON a.FirmwareId = c.Id " +
                        "JOIN application d ON a.ApplicationId = d.Id " +
                        "JOIN hardware e ON a.HardwareId = e.Id " +
                        "JOIN site f ON a.SiteId = f.Id " +
                        "JOIN script_version g ON a.ScriptId = g.Id " +
                        "LEFT JOIN (SELECT * FROM(SELECT * FROM maintainer ORDER BY MarkedDelete)a GROUP BY a.Account) h ON a.Administrator = h.Account " +
                        "JOIN device_class i ON a.ClassId = i.Id " +
                        "JOIN `npc_proxy_link` j ON a.Id = j.DeviceId " +
                        $"WHERE a.`MarkedDelete` = 0" +
                        $"{(idList.Any() ? " AND a.Id IN @idList" : "")}" +
                        $" ORDER BY a.Id;", new { idList }).ToDictionary(x => x.Id);

                    var faultDevices = ServerConfig.ApiDb.Query <dynamic>(
                        $"SELECT * FROM (SELECT a.* FROM `fault_device_repair` a " +
                        $"JOIN `device` b ON a.DeviceId = b.Id " +
                        $"WHERE a.`State` != @state" +
                        $"{(idList.Any() ? " AND a.DeviceId IN @idList" : "")}" +
                        $" AND a.MarkedDelete = 0 ORDER BY a.DeviceId, a.State DESC ) a GROUP BY DeviceCode;",
                        new { state = RepairStateEnum.Complete, idList });
                    foreach (var faultDevice in faultDevices)
                    {
                        var device = deviceLibraryDetails.Values.FirstOrDefault(x => x.Id == faultDevice.DeviceId);
                        if (device != null)
                        {
                            device.RepairState = faultDevice.State;
                        }
                    }

                    var url = ServerConfig.GateUrl + UrlMappings.Urls[UrlMappings.deviceListGate];
                    //向GateProxyLink请求数据
                    var resp = !idList.Any() ? HttpServer.Get(url) :
                               HttpServer.Get(url, new Dictionary <string, string>
                        {
                            { "ids", idList.Join() }
                        });
                    DeviceResult dataResult = null;
                    if (resp != "fail")
                    {
                        try
                        {
                            dataResult = JsonConvert.DeserializeObject <DeviceResult>(resp);
                            if (dataResult.errno == Error.Success)
                            {
                                foreach (var deviceInfo in dataResult.datas)
                                {
                                    var deviceId = deviceInfo.DeviceId;
                                    if (deviceLibraryDetails.ContainsKey(deviceId))
                                    {
                                        deviceLibraryDetails[deviceId].State       = deviceInfo.State;
                                        deviceLibraryDetails[deviceId].DeviceState = deviceInfo.DeviceState;
                                        if (deviceLibraryDetails[deviceId].DeviceState == DeviceState.Waiting &&
                                            deviceLibraryDetails[deviceId].StartTime != default(DateTime) &&
                                            deviceLibraryDetails[deviceId].TotalTime <= HKanBanHelper.IdleSecond)
                                        {
                                            deviceLibraryDetails[deviceId].DeviceState = DeviceState.Readying;
                                        }
                                    }
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Log.Error($"{UrlMappings.Urls[UrlMappings.deviceListGate]},信息:{e}");
                        }
                    }

                    //var data = deviceLibraryDetails.Values.All(x => int.TryParse(x.Code, out _))
                    //    ? deviceLibraryDetails.Values.OrderByDescending(x => x.DeviceState).ThenByDescending(x => x.DeviceStateStr).ThenBy(x => int.Parse(x.Code))
                    //    : deviceLibraryDetails.Values.OrderByDescending(x => x.DeviceState).ThenByDescending(x => x.DeviceStateStr).ThenBy(x => x.Code);

                    var allDevices = deviceLibraryDetails.Values.OrderBy(x => int.TryParse(x.Code, out var a) ? a : 9999999).ThenBy(x => x.Code).ToList();

                    var sum   = allDevices.Count;
                    var gz    = allDevices.Count(x => x.RepairState != -1);
                    var other = allDevices.Where(x => x.RepairState == -1);
                    var zc    = other.Count(x => x.DeviceState == DeviceState.Processing)
                                + other.Count(x => x.DeviceState == DeviceState.Restart)
                                + other.Count(x => x.DeviceState == DeviceState.UpgradeFirmware)
                                + other.Count(x => x.DeviceState == DeviceState.UpgradeScript)
                                + other.Count(x => x.DeviceState == DeviceState.Readying)
                                + other.Count(x => x.DeviceState == DeviceState.Waiting);
                    var jg  = other.Count(x => x.DeviceState == DeviceState.Processing);
                    var zb  = other.Count(x => x.DeviceState == DeviceState.Readying);
                    var xz  = other.Count(x => x.DeviceState == DeviceState.Waiting);
                    var wlj = sum - zc;
                    var tp  = (int)Math.Ceiling((decimal)sum / (set.Length <= 0 ? 30 : set.Length));
                    if (page >= tp)
                    {
                        page = 0;
                    }
                    var devices              = allDevices.Skip(set.Length * page).Take(set.Length);
                    var scriptIds            = devices.Select(y => y.ScriptId);
                    var dataNameDictionaries = scriptIds.Any() ? DataNameDictionaryHelper.GetDataNameDictionaryDetails(scriptIds) : new List <DataNameDictionaryDetail>();
                    ret.Id = qId;

                    foreach (var device in devices)
                    {
                        var t  = ClassExtension.ParentCopyToChild <DeviceDetail, MonitoringSetData>(device);
                        var vs = set.VariableList.OrderBy(x => x.Order);

                        DeviceData deviceData = null;
                        if (dataResult != null &&
                            dataResult.datas.Any(d => d.Id == device.Id) &&
                            dataResult.datas.First(d => d.Id == device.Id).DeviceData != null)
                        {
                            deviceData = dataResult.datas.First(d => d.Id == device.Id).DeviceData;
                        }

                        //if (device.RepairState != -1 && device.State != SocketState.Connected)
                        //{
                        //    deviceLibraryDetails[deviceId].in
                        //}
                        //else
                        //{
                        //    FlowCard fc = null;
                        //    if (int.TryParse(device.FlowCard, out var id))
                        //    {
                        //        fc = flowCards.FirstOrDefault(x => x.Id == id);
                        //    }
                        //    deviceLibraryDetails[deviceId].FlowCard = fc?.Card ?? "";
                        //}

                        foreach (var x in vs)
                        {
                            var dn = dataNameDictionaries.FirstOrDefault(d =>
                                                                         d.VariableTypeId == x.VariableTypeId && d.PointerAddress == x.PointerAddress);

                            ////设备状态
                            //var stateDId = 1;
                            ////总加工次数
                            //var processCountDId = 63;
                            ////总加工时间
                            //var processTimeDId = 64;
                            ////当前加工流程卡号
                            //var currentFlowCardDId = 6;
                            ////累积运行总时间
                            //var runTimeDId = 5;

                            if (dn == null)
                            {
                                continue;
                            }

                            var r = new MonitoringSetSingleDataDetail
                            {
                                Order     = x.Order,
                                SubOrder  = x.SubOrder,
                                Delimiter = x.Delimiter,
                                Sid       = x.ScriptId,
                                Type      = x.VariableTypeId,
                                Add       = x.PointerAddress,
                                VName     = x.VariableName.IsNullOrEmpty() ? dn.VariableName ?? "" : x.VariableName,
                            };

                            if (dn.VariableTypeId == 1 && dn.VariableNameId == AnalysisHelper.stateDId)
                            {
                                r.V = device.DeviceStateStr;
                            }
                            else if (deviceData != null)
                            {
                                List <int> bl = null;
                                switch (x.VariableTypeId)
                                {
                                case 1: bl = deviceData.vals; break;

                                case 2: bl = deviceData.ins; break;

                                case 3: bl = deviceData.outs; break;

                                default: break;
                                }

                                if (bl != null)
                                {
                                    if (bl.Count > x.PointerAddress - 1)
                                    {
                                        var chu = Math.Pow(10, dn.Precision);
                                        var v   = (decimal)(bl.ElementAt(x.PointerAddress - 1) / chu);
                                        if (dn.VariableTypeId == 1 && (dn.VariableNameId == AnalysisHelper.flowCardDId || dn.VariableNameId == AnalysisHelper.nextFlowCardDId))
                                        {
                                            //var flowCard = FlowCardHelper.Instance.Get<FlowCard>((int)v);
                                            //r.V = flowCard?.Card ?? "";
                                            r.V = device.LastFlowCard;
                                        }
                                        else if (dn.VariableTypeId == 1 && dn.VariableNameId == AnalysisHelper.currentProductDId)
                                        {
                                            //var production = ProductionHelper.Instance.Get<Production>((int)v);
                                            //r.V = production?.ProductionName ?? "";

                                            var production = ProductionHelper.GetProduction(device.LastFlowCardId);
                                            r.V = production?.Name ?? "";
                                        }
                                        else
                                        {
                                            r.V = v.ToString();
                                        }
                                    }
                                }
                            }
                            t.Data.Add(r);
                        }
                        ret.MSetData.Add(t);
                    }
                    var monitoringProcesses = new List <MonitoringProcess>();
                    //monitoringProcesses.AddRange(AnalysisHelper.GetMonitoringProcesses(idList));
                    //if (!monitoringProcesses.Any())
                    //{
                    //    monitoringProcesses.AddRange(ServerConfig.ApiDb.Query<MonitoringProcess>(
                    //        "SELECT b.*, c.CategoryId, c.CategoryName, a.`Code`, a.`ScriptId` FROM `device` a " +
                    //        "JOIN `npc_proxy_link` b ON a.Id = b.DeviceId " +
                    //        "JOIN (SELECT a.*, b.CategoryName FROM `device_model` a " +
                    //        "JOIN `device_category` b ON a.CategoryId = b.Id) c ON a.ModelId = c.Id WHERE a.Id in @idList AND a.MarkedDelete = 0;", new { idList }));
                    //}
                    monitoringProcesses.AddRange(AnalysisHelper.GetMonitoringProcesses(wId, idList));
                    if (!monitoringProcesses.Any())
                    {
                        monitoringProcesses.AddRange(ServerConfig.ApiDb.Query <MonitoringProcess>(
                                                         "SELECT b.*, c.CategoryId, c.CategoryName, a.`Code`, a.`ScriptId` FROM `device` a " +
                                                         "JOIN `npc_proxy_link` b ON a.Id = b.DeviceId " +
                                                         "JOIN device_model_all c ON a.ModelId = c.Id WHERE a.Id in @idList AND a.MarkedDelete = 0;"));
                    }
                    var timeRate    = new List <decimal>();
                    var processTime = monitoringProcesses.Sum(x => x.ProcessTime);
                    var runTime     = monitoringProcesses.Sum(x => x.RunTime);
                    var rate        = runTime > 0 ? (processTime * 100m / (runTime)).ToRound() : 0;
                    timeRate.Add(rate);
                    timeRate.AddRange(workshop.StatisticTimeList.Select((_, i) =>
                        {
                            var p = monitoringProcesses.Where(x => x.ExtraData.Parts.Count > i).Sum(y => y.ExtraData.Parts.FirstOrDefault(x => x.Shift == i)?.ProcessTime ?? 0);
                            var r = monitoringProcesses.Where(x => x.ExtraData.Parts.Count > i).Sum(y => y.ExtraData.Parts.FirstOrDefault(x => x.Shift == i)?.RunTime ?? 0);
                            return(r > 0 ? (p * 100m / (r)).ToRound() : 0);
                        }));

                    //var now = DateTime.Now;
                    //var currentWorkTime = DateTimeExtend.GetDayWorkTimeRanges(workshop.Shifts, workshop.StatisticTimeList, now);
                    //var workTime = DateTimeExtend.GetDayWorkDay(workshop.ShiftTimeList, now);
                    //var reports = FlowCardReportGetHelper.GetReport(wId, workTime.Item1, workTime.Item2, 18).ToList();
                    var qualifiedRate = new List <decimal>();
                    //var qualified = reports.Sum(x => x.HeGe);
                    //var total = reports.Sum(x => x.Total);
                    var qualified = monitoringProcesses.Sum(y => y.DayQualified);
                    var total     = monitoringProcesses.Sum(x => x.DayTotal);
                    rate = total > 0 ? (qualified * 100m / (total)).ToRound() : 0;
                    qualifiedRate.Add(rate);
                    qualifiedRate.AddRange(workshop.StatisticTimeList.Select((range, i) =>
                        {
                            //var p = reports.Where(x => x.Time.InSameRange(range)).Sum(y => y.HeGe);
                            //var r = reports.Where(x => x.Time.InSameRange(range)).Sum(y => y.Total);
                            var p = monitoringProcesses.Where(x => x.ExtraData.Parts.Count > i).Sum(y => y.ExtraData.Parts.FirstOrDefault(x => x.Shift == i)?.DayQualified ?? 0);
                            var r = monitoringProcesses.Where(x => x.ExtraData.Parts.Count > i).Sum(y => y.ExtraData.Parts.FirstOrDefault(x => x.Shift == i)?.DayTotal ?? 0);
                            return(r > 0 ? (p * 100m / (r)).ToRound() : 0);
                        }));

                    return(new
                        {
                            errno = 0,
                            errmsg = "成功",
                            type = set.Type,
                            time = DateTime.Now,
                            jg,
                            zc,
                            zb,
                            xz,
                            gz,
                            wlj,
                            sum,
                            timeRate,
                            qualifiedRate,
                            row = set.Row,
                            col = set.Col,
                            cCol = set.ContentCol,
                            cName = set.ColNameList,
                            len = set.Length,
                            cp = page,
                            tp,
                            data = ret.MSetData
                        });
                }

                    #endregion
                case KanBanEnum.生产相关看板:
                    #region 生产相关看板
                    kanBan = HKanBanHelper.MonitoringKanBanDic.ContainsKey(key)
                            ? HKanBanHelper.MonitoringKanBanDic[key]
                            : new MonitoringKanBan();
                    return(new
                    {
                        errno = 0,
                        errmsg = "成功",
                        type = set.Type,
                        time = kanBan?.Time ?? DateTime.Now,
                        items = set.ItemList.Select(y =>
                        {
                            var ty = ClassExtension.CopyTo <KanBanItemSet, KanBanItemSetWeb>(y);
                            ty.FieldList = y.FieldList;
                            return ty;
                        }).ToList(),
                        colSet = set.ColSet,
                        data = kanBan?.ItemData ?? new Dictionary <string, List <dynamic> >()
                    });

                    #endregion
                }
            }

            return(new
            {
                errno = 0,
                type = 0,
                errmsg = "成功",
                time = DateTime.Now,
            });
        }
        public DataResult PutMaterialLog([FromBody] IEnumerable <MaterialLog> materialLogs)
        {
            return(Result.GenError <DataResult>(Error.Fail));

            if (materialLogs == null || !materialLogs.Any())
            {
                return(Result.GenError <DataResult>(Error.MaterialLogNotExist));
            }

            if (materialLogs.Any(x => x.Number < 0))
            {
                return(Result.GenError <DataResult>(Error.NumberCannotBeNegative));
            }
            if (materialLogs.GroupBy(x => x.Type).Count() > 1)
            {
                return(Result.GenError <DataResult>(Error.MaterialLogTypeDifferent));
            }

            var logIds  = materialLogs.Where(x => x.Number == 0).Select(y => y.Id);
            var billIds = materialLogs.Select(x => x.BillId);
            var timeLog = ServerConfig.ApiDb.Query <MaterialLog>("SELECT * FROM (SELECT * FROM `material_log` " +
                                                                 $"WHERE BillId IN @billIds{(logIds.Any() ? " AND Id NOT IN @logIds" : "")} AND Number > 0 Order By Time DESC) a GROUP BY Type;",
                                                                 new { billIds, logIds });
            var oldLogs =
                ServerConfig.ApiDb.Query <MaterialLog>("SELECT * FROM `material_log` WHERE Id IN @id;",
                                                       new { id = materialLogs.Select(x => x.Id) });

            if (oldLogs.Count() != materialLogs.Count())
            {
                return(Result.GenError <DataResult>(Error.MaterialLogNotExist));
            }

            var result         = new DataResult();
            var markedDateTime = DateTime.Now;
            var newLogs        = new List <MaterialLog>();
            var newLogChanges  = new List <MaterialLogChange>();
            var materials      = billIds.ToDictionary(x => x, x =>
            {
                var change = new MaterialChange
                {
                    BillId = x,
                    Number = 0
                };
                // 1 入库; 2 出库;3 冲正;
                var inLog = timeLog.FirstOrDefault(y => y.BillId == x && y.Type == MaterialOp.入库);
                if (inLog != null)
                {
                    change.InTime = inLog.Time;
                }

                var outLog = timeLog.FirstOrDefault(y => y.BillId == x && y.Type == MaterialOp.出库);
                if (outLog != null)
                {
                    change.OutTime = outLog.Time;
                }

                return(change);
            });

            foreach (var billId in billIds)
            {
                var minId    = materialLogs.Where(x => x.BillId == billId).Min().Id;
                var billLogs = ServerConfig.ApiDb.Query <MaterialLog>("SELECT * FROM `material_log` WHERE Id >= @Id AND BillId = @BillId Order By Time;", new { Id = minId, BillId = billId });
                foreach (var billLog in billLogs)
                {
                    var changeBillLog = ClassExtension.ParentCopyToChild <MaterialLog, MaterialLogChange>(billLog);
                    if (!materials.ContainsKey(billId))
                    {
                        continue;
                    }
                    var material = materials[billId];
                    if (!material.Init)
                    {
                        material.Init   = true;
                        material.Number = billLog.OldNumber;
                    }
                    var update = materialLogs.FirstOrDefault(x => x.Id == billLog.Id);
                    if (update == null)
                    {
                        billLog.OldNumber = material.Number;
                    }
                    var num = update?.Number ?? billLog.Number;
                    // 1 入库; 2 出库;3 冲正;
                    switch (billLog.Type)
                    {
                    case MaterialOp.入库:
                        billLog.Number    = num;
                        billLog.OldNumber = material.Number;
                        material.Number  += num;
                        break;

                    case MaterialOp.出库:
                        billLog.Number = num;
                        if (billLog.Number > material.Number)
                        {
                            result.datas.Add(billLog.Name);
                            result.errno = Error.MaterialLogConsumeLaterError;
                            return(result);
                        }
                        billLog.OldNumber = material.Number;
                        material.Number  -= num;
                        break;

                    case MaterialOp.冲正:
                        billLog.Number    = num;
                        billLog.OldNumber = material.Number;
                        material.Number   = num;
                        break;
                    }
                    changeBillLog.ChangeNumber    = billLog.Number;
                    changeBillLog.ChangeOldNumber = billLog.OldNumber;
                    newLogs.Add(billLog);
                    newLogChanges.Add(changeBillLog);
                }
            }

            if (newLogChanges.All(x => x.ChangeNumber == x.Number))
            {
                return(Result.GenError <DataResult>(Error.Success));
            }
            var planLogs = newLogChanges.Where(x => x.PlanId != 0 && x.ChangeNumber != x.Number);

            if (planLogs.Any())
            {
                var existProductionPlanBills = ServerConfig.ApiDb.Query <ProductPlanBill>(
                    "SELECT * FROM `production_plan_bill` WHERE MarkedDelete = 0 AND PlanId IN @PlanId AND BillId IN @BillId;",
                    new
                {
                    PlanId = planLogs.Select(x => x.PlanId),
                    BillId = planLogs.Select(x => x.BillId),
                });
                foreach (var billLog in newLogChanges.OrderByDescending(x => x.Id))
                {
                    if (billLog.PlanId != 0)
                    {
                        var planBill = existProductionPlanBills.FirstOrDefault(x =>
                                                                               x.PlanId == billLog.PlanId && x.BillId == billLog.BillId);
                        if (planBill != null)
                        {
                            // 1 退回; 2 领用;
                            switch (billLog.Type)
                            {
                            case MaterialOp.入库:
                                planBill.ActualConsumption += billLog.Number;
                                break;

                            case MaterialOp.出库:
                                planBill.ActualConsumption -= billLog.Number;
                                break;

                            case MaterialOp.冲正:
                                break;
                            }
                        }
                    }
                }

                //var productionPlanBills = new List<ProductionPlanBill>();
                foreach (var billLog in newLogChanges)
                {
                    if (billLog.PlanId != 0)
                    {
                        var planBill = existProductionPlanBills.FirstOrDefault(x =>
                                                                               x.PlanId == billLog.PlanId && x.BillId == billLog.BillId);
                        if (planBill != null)
                        {
                            // 1 退回; 2 领用;
                            switch (billLog.Type)
                            {
                            case MaterialOp.入库:
                                if (planBill.ActualConsumption < billLog.ChangeNumber)
                                {
                                    result.datas.Add(billLog.Name);
                                    result.errno = Error.ProductionPlanBillActualConsumeLess;
                                    return(result);
                                }
                                planBill.ActualConsumption -= billLog.ChangeNumber;
                                break;

                            case MaterialOp.出库:
                                planBill.ActualConsumption += billLog.ChangeNumber;
                                break;

                            case MaterialOp.冲正:
                                break;
                            }
                        }
                    }
                }

                ServerConfig.ApiDb.Execute(
                    "UPDATE `production_plan_bill` SET `ActualConsumption` = @ActualConsumption WHERE `Id` = @Id;",
                    existProductionPlanBills);
            }

            var purchases = newLogChanges.Where(x => x.ItemId != 0);

            if (purchases.Any())
            {
                //var erpIds = purchases.Select(x => int.TryParse(x.Purpose.Replace("Erp采购-", ""), out var erpId) ? erpId : 0).Where(y => y != 0);
                //var pBillIds = purchases.Select(x => x.BillId);
                var purchaseItemIds = purchases.Select(x => x.ItemId).Where(x => x != 0);
                var purchaseItems   = ServerConfig.ApiDb.Query <MaterialPurchaseItem>(
                    "SELECT a.*, b.ErpId FROM `material_purchase_item` a " +
                    "JOIN `material_purchase` b ON a.PurchaseId = b.Id " +
                    "WHERE a.Id IN @purchaseItemIds AND a.MarkedDelete = 0 AND b.MarkedDelete = 0;", new
                {
                    purchaseItemIds
                });

                foreach (var purchase in purchases)
                {
                    var pItem = purchaseItems.FirstOrDefault(x => x.Id == purchase.ItemId);
                    //if (purchase.ChangeNumber < purchase.Number)
                    if (pItem != null)
                    {
                        pItem.Stock += purchase.ChangeNumber - purchase.Number;
                    }
                }

                ServerConfig.ApiDb.Execute("UPDATE `material_purchase_item` SET `Stock` = @Stock WHERE `Id` = @Id;",
                                           purchaseItems);
            }
            if (newLogs.Any())
            {
                ServerConfig.ApiDb.Execute(
                    "UPDATE `material_log` SET `Number` = @Number, `OldNumber` = @OldNumber WHERE `Id` = @Id;",
                    newLogs);

                ServerConfig.ApiDb.Execute(
                    "UPDATE `material_management` SET " +
                    "`InTime` = IF(ISNULL(`InTime`) OR `InTime` != @InTime, @InTime, `InTime`), " +
                    "`OutTime` = IF(ISNULL(`OutTime`) OR `OutTime` != @OutTime, @OutTime, `OutTime`), " +
                    "`Number` = @Number WHERE `BillId` = @BillId;",
                    materials.Values.Where(x => x.Init));

                ServerConfig.ApiDb.Execute(
                    "INSERT INTO `material_log_change` (`NewTime`, `Id`, `Time`, `BillId`, `Code`, `NameId`, `Name`, `SpecificationId`, `Specification`, `Type`, `Mode`, `Purpose`, `PlanId`, `Plan`, `Number`, `OldNumber`, `RelatedPerson`, `Manager`, `ChangeNumber`, `ChangeOldNumber`) " +
                    "VALUES ( @NewTime, @Id, @Time, @BillId, @Code, @NameId, @Name, @SpecificationId, @Specification, @Type, @Mode, @Purpose, @PlanId, @Plan, @Number, @OldNumber, @RelatedPerson, @Manager, @ChangeNumber, @ChangeOldNumber);",
                    newLogChanges.OrderBy(x => x.BillId).ThenBy(y => y.Time).Select(z =>
                {
                    z.NewTime = markedDateTime;
                    return(z);
                }));

                //TimerHelper.DayBalance(newLogs.GroupBy(x => x.Time).Where(y => !y.Key.InSameDay(markedDateTime)).Select(z => z.Key));
                //TimerHelper.DayBalance(newLogs);
            }


            return(Result.GenError <DataResult>(Error.Success));
        }
Ejemplo n.º 4
0
        public object PostSmartSchedulePreview([FromBody] SmartTaskOrderArrangeParam arrange)
        {
            var taskOrders = arrange.Previews;
            var wId        = arrange.WorkshopId;

            if (taskOrders == null)
            {
                return(Result.GenError <Result>(Error.ParamError));
            }
            var taskIds = taskOrders.GroupBy(x => x.Id).Select(y => y.Key);

            if (taskIds.Count() != taskOrders.Count())
            {
                return(Result.GenError <Result>(Error.SmartTaskOrderDuplicate));
            }
            var result   = new DataResult();
            var allTasks = new List <SmartTaskOrderPreview>();

            if (taskOrders.Any())
            {
                var tOrders = SmartTaskOrderHelper.Instance.GetByIds <SmartTaskOrderPreview>(taskIds);
                if (taskIds.Count() != tOrders.Count())
                {
                    result.errno = Error.SmartTaskOrderNotExist;
                    result.datas.AddRange(taskOrders.Where(x => tOrders.All(y => y.Id != x.Id)).Select(x => x.TaskOrder.IsNullOrEmpty() ? x.Id.ToString() : x.TaskOrder));
                    return(result);
                }

                //var arranged = tOrders.Where(x => x.Arranged);
                //if (arranged.Any())
                //{
                //    result.errno = Error.SmartTaskOrderArranged;
                //    result.datas.AddRange(arranged.Select(x => x.TaskOrder));
                //    return result;
                //}

                foreach (var task in tOrders)
                {
                    var t = taskOrders.FirstOrDefault(x => x.Id == task.Id);
                    if (t == null)
                    {
                        result.errno = Error.SmartTaskOrderNotExist;
                        result.datas.Add(task.TaskOrder);
                    }
                    else
                    {
                        //页面选择顺序
                        task.Order     = !t.Arranged && t.Order == 0 ? int.MaxValue : t.Order;
                        task.StartTime = t.StartTime;
                        task.EndTime   = t.EndTime;
                        task.Needs     = t.Needs;
                    }
                }
                allTasks.AddRange(tOrders);
            }
            if (result.errno != Error.Success)
            {
                return(result);
            }
            var otherTasks = SmartTaskOrderHelper.GetArrangedButNotDoneSmartTaskOrders(wId);

            if (otherTasks.Any())
            {
                taskIds = otherTasks.Select(x => x.Id);
                var taskNeeds = SmartTaskOrderNeedHelper.GetSmartTaskOrderNeedsByTaskOrderIds(wId, taskIds);
                foreach (var otherTask in otherTasks)
                {
                    var aTask = allTasks.FirstOrDefault(x => x.Id == otherTask.Id);
                    var needs = taskNeeds.Where(need => need.TaskOrderId == otherTask.Id);
                    if (aTask != null)
                    {
                        aTask.Arranged = true;
                        if (!aTask.Needs.Any())
                        {
                            aTask.Needs.AddRange(needs);
                        }
                        else
                        {
                            aTask.Needs = aTask.Needs.Select(x =>
                            {
                                var need = needs.FirstOrDefault(y => y.TaskOrderId == x.TaskOrderId && y.PId == x.PId);
                                if (need != null)
                                {
                                    x.DoneTarget = need.DoneTarget;
                                    x.HavePut    = need.HavePut;
                                }
                                return(x);
                            }).ToList();
                        }
                    }
                    else
                    {
                        var t = ClassExtension.ParentCopyToChild <SmartTaskOrder, SmartTaskOrderPreview>(otherTask);
                        t.Arranged = true;
                        t.Needs.AddRange(needs);
                        allTasks.Add(t);
                    }
                }
            }

            if (result.errno != Error.Success)
            {
                return(result);
            }
            var productIds = allTasks.GroupBy(x => x.ProductId).Select(y => y.Key);

            if (!productIds.Any())
            {
                return(Result.GenError <Result>(Error.SmartProductNotExist));
            }

            var products = SmartProductHelper.Instance.GetByIds <SmartProduct>(productIds);

            if (products.Count() != productIds.Count())
            {
                return(Result.GenError <Result>(Error.SmartProductNotExist));
            }

            var productCapacities = SmartProductCapacityHelper.GetSmartProductCapacities(productIds);

            if (!productCapacities.Any())
            {
                return(Result.GenError <Result>(Error.SmartProductCapacityNotExist));
            }

            var capacityIds = products.GroupBy(x => x.CapacityId).Select(y => y.Key);

            if (!capacityIds.Any())
            {
                return(Result.GenError <Result>(Error.SmartCapacityNotExist));
            }
            var capacityLists = SmartCapacityListHelper.GetSmartCapacityListsWithOrder(capacityIds);

            foreach (var productId in productIds)
            {
                var tasks       = allTasks.Where(x => x.ProductId == productId);
                var product     = products.FirstOrDefault(x => x.Id == productId);
                var pCapacities = productCapacities.Where(x => x.ProductId == productId);
                var cLists      = capacityLists.Where(x => x.CapacityId == product.CapacityId);
                if (cLists.Count() != pCapacities.Count())
                {
                    result.errno = Error.SmartProductCapacityNotExist;
                    result.datas.AddRange(tasks.Select(x => x.TaskOrder));
                }
            }

            if (result.errno != Error.Success)
            {
                return(result);
            }

            var data = allTasks.ToDictionary(x => x.Id, x =>
            {
                var t     = ClassExtension.ParentCopyToChild <SmartTaskOrder, SmartTaskOrderPreview>(x);
                t.Product = products.FirstOrDefault(y => y.Id == x.ProductId)?.Product ?? "";
                return(t);
            });

            foreach (var task in allTasks)
            {
                var productId   = task.ProductId;
                var product     = products.FirstOrDefault(x => x.Id == productId);
                var pCapacities = productCapacities.Where(x => x.ProductId == productId);
                var cLists      = capacityLists.Where(x => x.CapacityId == product.CapacityId);
                var target      = task.Target;
                foreach (var list in cLists.Reverse())
                {
                    var need       = task.Needs.FirstOrDefault(x => x.Order == list.Order && x.ProcessId == list.ProcessId);
                    var stock      = need?.Stock ?? 0;
                    var doneTarget = need?.DoneTarget ?? 0;
                    var havePut    = need?.HavePut ?? 0;

                    if (target < stock)
                    {
                        stock  = target;
                        target = 0;
                    }
                    else
                    {
                        target -= stock;
                    }

                    var pCapacity = pCapacities.FirstOrDefault(x => x.ProcessId == list.ProcessId);
                    var rate      = 0m;
                    var y         = pCapacity;
                    if (y.DeviceList.Any())
                    {
                        rate = y.DeviceList.First().Rate;
                    }
                    else if (y.OperatorList.Any())
                    {
                        rate = y.OperatorList.First().Rate;
                    }

                    var put = rate != 0 ? (int)Math.Ceiling((target) * 100 / rate) : 0;
                    data[task.Id].Needs.Insert(0, new SmartTaskOrderNeedDetail
                    {
                        TaskOrderId = task.Id,
                        ProductId   = productId,
                        ProcessId   = list.ProcessId,
                        PId         = list.PId,
                        Target      = target,
                        DoneTarget  = doneTarget,
                        Stock       = stock,
                        Rate        = rate,
                        Put         = put,
                        HavePut     = havePut,
                        Process     = list.Process,
                        Order       = list.Order
                    });
                    target = put;
                }
            }
            var r = new SmartTaskOrderNeedWithOrderResult();

            r.datas.AddRange(data.Values.OrderBy(x => x.Arranged).ThenBy(x => x.ModifyId));
            var orders = data.Values.SelectMany(x => x.Needs).GroupBy(y => new { y.PId, y.Order, y.Process }).Select(z => new SmartTaskOrderNeedWithOrder
            {
                Id      = z.Key.PId,
                Process = z.Key.Process,
                Order   = z.Key.Order
            });

            r.Orders.AddRange(orders.OrderBy(z => z.Order));
            return(r);
        }
Ejemplo n.º 5
0
        public object GetProduction([FromQuery] int qId, int wId, bool menu, bool step)
        {
            if (step && qId != 0)
            {
                var data    = ProductionHelper.GetDetail(wId, qId);
                var flowIds = data.SelectMany(x => x.FlowIds);
                if (flowIds.Any())
                {
                    var flows = FlowCodeHelper.Instance.GetByIds <FlowCode>(flowIds).ToDictionary(x => x.Id);
                    foreach (var d in data)
                    {
                        d.Flows = d.FlowIds.Where(flowId => flows.ContainsKey(flowId)).Select(flowId => flows[flowId].Code).Join();
                    }
                }
                var pIds = data.Select(x => x.Id);
                if (pIds.Any())
                {
                    var args    = ProductionArgHelper.GetDetails(pIds, null);
                    var stepIds = data.SelectMany(x => x.Args.Select(y => y.StepId));
                    var steps   = stepIds.Any() ? FlowStepHelper.Instance.GetByIds <FlowStep>(stepIds).ToDictionary(x => x.Id) : new Dictionary <int, FlowStep>();
                    foreach (var d in data)
                    {
                        d.Args.AddRange(args.Where(x => x.ProductionId == d.Id).Select(x =>
                        {
                            var y      = ClassExtension.ParentCopyToChild <ProductionArg, ProductionArgFormat>(x);
                            y.FormatId = steps.ContainsKey(x.StepId) ? steps[x.StepId].FormatId : 0;
                            return(y);
                        }));
                    }
                }
                return(new
                {
                    errno = 0,
                    errmsg = "成功",
                    datas = data
                });
            }
            var result = new DataResult();

            if (menu)
            {
                result.datas.AddRange(ProductionHelper.GetMenu(wId, qId));
            }
            else
            {
                var data    = ProductionHelper.GetDetail(wId, qId);
                var flowIds = data.SelectMany(x => x.FlowIds);
                if (flowIds.Any())
                {
                    var flows = FlowCodeHelper.Instance.GetByIds <FlowCode>(flowIds).ToDictionary(x => x.Id);
                    foreach (var d in data)
                    {
                        d.Flows = d.FlowIds.Where(flowId => flows.ContainsKey(flowId)).Select(flowId => flows[flowId].Code).Join();
                    }
                }
                result.datas.AddRange(data);
            }
            if (qId != 0 && !result.datas.Any())
            {
                result.errno = Error.ProductionNotExist;
                return(result);
            }
            return(result);
        }