public ReprocessSession CollectReprocessSession(Character character, Container container, IEnumerable <long> targetEids) { var ec = ErrorCodes.NoError; var materialMultiplier = GetMaterialMultiplier(character); #if (DEBUG) Logger.Info("material multiplier for reprocess: " + materialMultiplier); #endif var reprocessSession = _reprocessSessionFactory(); foreach (var targetEid in targetEids) { var targetItem = container.GetItem(targetEid, true); if (targetItem == null) { continue; } if ((ec = ProductionHelper.CheckReprocessCondition(targetItem, character)) != ErrorCodes.NoError) { continue; } reprocessSession.AddMember(targetItem, materialMultiplier, character); } if (targetEids.Count() == 1) { ec.ThrowIfNotEqual(ErrorCodes.NoError, ec); } return(reprocessSession); }
protected void Page_Load(object sender, EventArgs e) { work_id = Convert.ToInt32(Request["work_id"]); if (!Page.IsPostBack) { Session["anti_refresh"] = "1"; string Sql = "select * from Tb_Working where work_id=@work_id"; helper.Params.Add("@work_id", work_id); DataTable dt = helper.ExecDataTable(Sql); if (dt.Rows.Count > 0) { factory_manager.Text = dt.Rows[0]["factory_manager"].ToString(); our_manager.Text = dt.Rows[0]["our_manager"].ToString(); start_date.Text = Convert.ToDateTime(dt.Rows[0]["start_date"]).ToShortDateString(); end_date.Text = Convert.ToDateTime(dt.Rows[0]["end_date"]).ToShortDateString(); work_remark.Text = dt.Rows[0]["work_remark"].ToString(); int_factory_id = Convert.ToInt32(dt.Rows[0]["factory_id"]); int_from_warehouse_id = Convert.ToInt32(dt.Rows[0]["warehouse_id"]); } StorageHelper.BindWarehouseList(from_warehouse_id, int_from_warehouse_id, my_warehouse_id.ToString(), ""); ProductionHelper.BindFactoryList(factory_id, int_factory_id); bindTemplatePro(); } }
protected void Page_Load(object sender, EventArgs e) { work_id = Convert.ToInt32(Request["work_id"]); //wm_id = helper.ExecScalar("select wm_id from Tb_Working_main where "); if (!Page.IsPostBack) { string Sql = "select * from Tb_Working where work_id=@work_id"; helper.Params.Add("@work_id", work_id); dt = helper.ExecDataTable(Sql); if (dt.Rows.Count > 0) { factory_manager.Text = dt.Rows[0]["factory_manager"].ToString(); our_manager.Text = dt.Rows[0]["our_manager"].ToString(); start_date.Text = Convert.ToDateTime(dt.Rows[0]["start_date"]).ToShortDateString(); end_date.Text = Convert.ToDateTime(dt.Rows[0]["end_date"]).ToShortDateString(); work_remark.Text = dt.Rows[0]["work_remark"].ToString(); int_factory_id = Convert.ToInt32(dt.Rows[0]["factory_id"]); int_from_warehouse_id = Convert.ToInt32(dt.Rows[0]["warehouse_id"]); work_status_old.Value = Convert.ToString(dt.Rows[0]["work_status"]); bind_status_list(Convert.ToInt32(dt.Rows[0]["work_status"])); } else { Response.Write("数据传递有误"); Response.End(); } ProductionHelper.BindFactoryList(factory_id, int_factory_id); StorageHelper.BindWarehouseList(from_warehouse_id, int_from_warehouse_id, my_warehouse_id.ToString(), ""); bindTemplatePro(); Session["anti_in_refresh"] = "1"; } }
public void HandleRequest(IRequest request) { var character = request.Session.Character; var offsetInDays = request.Data.GetOrDefault <int>(k.offset); var forCorporation = request.Data.GetOrDefault <int>(k.corporation) == 1; PrivateCorporation corporation = null; if (forCorporation) { corporation = character.GetPrivateCorporationOrThrow(); corporation.GetMemberRole(character).IsAnyRole(CorporationRole.CEO, CorporationRole.DeputyCEO, CorporationRole.Accountant, CorporationRole.ProductionManager).ThrowIfFalse(ErrorCodes.InsufficientPrivileges); } var dictionary = new Dictionary <string, object> { { k.history, ProductionHelper.ProductionLogList(character, offsetInDays, corporation) }, { k.corporation, forCorporation } }; Message.Builder.FromRequest(request) .WithData(dictionary) .WrapToResult() .Send(); }
public IDictionary <string, object> CalibrateLine(Character character, long calibrationEid, Container container) { var lineCount = ProductionLine.CountLinesForCharacter(character, Eid); var maxSlots = RealMaxSlotsPerCharacter(character); lineCount.ThrowIfGreaterOrEqual(maxSlots, ErrorCodes.MaximumAmountOfProducionsReached); var calibrationItem = (CalibrationProgram)container.GetItemOrThrow(calibrationEid); calibrationItem.Quantity.ThrowIfNotEqual(1, ErrorCodes.ServerError); var targetDefinition = calibrationItem.TargetDefinition; targetDefinition.ThrowIfEqual(0, ErrorCodes.CPRGNotProducible); var targetDefault = EntityDefault.Get(targetDefinition); calibrationItem.HasComponents.ThrowIfFalse(ErrorCodes.CPRGNotProducible); //no mission stuff here if (calibrationItem.IsMissionRelated || targetDefault.CategoryFlags.IsCategory(CategoryFlags.cf_random_items)) { if (this.GetDockingBase().IsOnGammaZone()) { throw new PerpetuumException(ErrorCodes.MissionItemCantBeProducedOnGamma); } } ProductionLine.CreateCalibratedLine(character, Eid, calibrationItem); //remove from container container.RemoveItemOrThrow(calibrationItem); //parent the cprg to the facility this.GetStorage().AddChild(calibrationItem); calibrationItem.Save(); container.Save(); ProductionHelper.ProductionLogInsert(character, targetDefinition, 1, ProductionInProgressType.inserCT, 0, 0, false); var informDict = container.ToDictionary(); var linesList = GetLinesList(character); var facilityInfo = GetFacilityInfo(character); var replyDict = new Dictionary <string, object> { { k.lines, linesList }, { k.lineCount, linesList.Count }, { k.sourceContainer, informDict }, { k.facility, facilityInfo } }; return(replyDict); }
protected void Page_Load(object sender, EventArgs e) { SiteHelper.CheckLogin(); if (!Page.IsPostBack) { string where = "1=1"; BindMemberList(SiteHelper.getPage()); ProductionHelper.BindFactoryList(factory_id, 0); } }
/// <summary> /// 初始化[注意初始化顺序] /// </summary> public static void Initialize() { InitBasicConfig(); InitSqlDependency(); InitContainer(); if (ProductionHelper.IsProductionEnvironment()) { InitWechatParas(); InitBaiduParas(); } SystemConfigObject.Notify((int)SystemStatus.Start); }
public ProductionInProgress StartPrototype(Character character, ProductionDescription productionDescription, Container container, bool useCorporationWallet, out bool hasBonus) { var foundComponents = productionDescription.SearchForAvailableComponents(container).ToList(); var materialMultiplier = CalculateMaterialMultiplier(character, productionDescription.definition, out hasBonus); var itemsNeeded = productionDescription.ProcessComponentRequirement(ProductionInProgressType.prototype, foundComponents, 1, materialMultiplier); //put them to storage long[] reservedEids; ProductionHelper.ReserveComponents_noSQL(itemsNeeded, StorageEid, container, out reservedEids).ThrowIfError(); var prototypeTimeSeconds = CalculatePrototypeTimeSeconds(character, productionDescription.definition); prototypeTimeSeconds = GetShortenedProductionTime(prototypeTimeSeconds); var productionInProgress = ProductionInProgressFactory(); productionInProgress.amountOfCycles = 1; productionInProgress.baseEID = Parent; productionInProgress.character = character; productionInProgress.facilityEID = Eid; productionInProgress.finishTime = DateTime.Now.AddSeconds(prototypeTimeSeconds); productionInProgress.pricePerSecond = GetPricePerSecond(); productionInProgress.ReservedEids = reservedEids; productionInProgress.resultDefinition = productionDescription.GetPrototypeDefinition(); productionInProgress.startTime = DateTime.Now; productionInProgress.totalProductionTimeSeconds = prototypeTimeSeconds; productionInProgress.type = ProductionInProgressType.prototype; productionInProgress.useCorporationWallet = useCorporationWallet; if (!productionInProgress.TryWithdrawCredit()) { if (useCorporationWallet) { throw new PerpetuumException(ErrorCodes.CorporationNotEnoughMoney); } throw new PerpetuumException(ErrorCodes.CharacterNotEnoughMoney); } return(productionInProgress); }
public void HandleRequest(IRequest request) { using (var scope = Db.CreateTransaction()) { var lineId = request.Data.GetOrDefault <int>(k.ID); var character = request.Session.Character; var facilityEid = request.Data.GetOrDefault <long>(k.facility); _productionManager.PrepareProductionForPublicContainer(facilityEid, character, out Mill mill, out PublicContainer publicContainer); var productionLine = ProductionLine.LoadByIdAndCharacterAndFacility(character, lineId, facilityEid); productionLine.IsActive().ThrowIfTrue(ErrorCodes.ProductionIsRunningOnThisLine); var calibrationProgram = productionLine.ExtractCalibrationProgram(mill); //add to public container publicContainer.AddItem(calibrationProgram, character.Eid, false); //save container publicContainer.Save(); //delete line ProductionLine.DeleteById(productionLine.Id); ProductionHelper.ProductionLogInsert(character, productionLine.TargetDefinition, 1, ProductionInProgressType.removeCT, 0, 0, false); var linesList = mill.GetLinesList(character); var containerList = publicContainer.ToDictionary(); var result = new Dictionary <string, object> { { k.lineCount, linesList.Count }, { k.lines, linesList }, { k.container, containerList } }; Message.Builder.FromRequest(request).WithData(result).Send(); scope.Complete(); } }
protected void Page_Load(object sender, EventArgs e) { id = Convert.ToInt32(Request["id"]); if (!Page.IsPostBack) { Session["anti_refresh"] = "1"; string Sql = "select * from Tb_template where tpl_id=@id"; helper.Params.Add("@id", id); DataTable dt = helper.ExecDataTable(Sql); if (dt.Rows.Count > 0) { pro_name.Text = dt.Rows[0]["pro_name"].ToString(); pro_code.Text = dt.Rows[0]["pro_code"].ToString(); do_cost.Text = dt.Rows[0]["do_cost"].ToString(); other_cost.Text = dt.Rows[0]["other_cost"].ToString(); remark.Text = dt.Rows[0]["remark"].ToString(); int_factory_id = Convert.ToInt32(dt.Rows[0]["factory_id"]); } ProductionHelper.BindFactoryList(factory_id, 0); bindTemplatePro(id); } }
protected void Button1_Click(object sender, EventArgs e) { if (Session["anti_refresh"] != "1") { // JSHelper.WriteScript("alert('请勿重复提交');history.back();"); // Response.End(); } Session["anti_refresh"] = "0"; helper.Params.Clear(); helper.Params.Add("factory_manager", Request["factory_manager"]); helper.Params.Add("our_manager", Request["our_manager"]); helper.Params.Add("factory_id", Request["factory_id"]); helper.Params.Add("warehouse_id", Request["from_warehouse_id"]); helper.Params.Add("start_date", Request["start_date"]); helper.Params.Add("end_date", Request["end_date"]); helper.Params.Add("work_remark", work_remark.Text); if (work_id == 0) { string ProductionSn = ProductionHelper.genProductionSn(); helper.Params.Add("work_sn", ProductionSn); helper.Params.Add("operator_id", HttpContext.Current.Session["ManageUserId"].ToString()); helper.Insert("Tb_Working"); work_id = Convert.ToInt32(helper.ExecScalar("select top 1 work_id from Tb_Working order by work_id desc")); helper.Params.Clear(); helper.Execute("update Tb_Working_material set work_id=" + work_id + " where wm_id in (select wm_id from Tb_Working_main where work_id=0 and operator_id=" + HttpContext.Current.Session["ManageUserId"].ToString() + ")"); helper.Execute("update Tb_Working_main set work_id=" + work_id + " where work_id=0 and operator_id=" + HttpContext.Current.Session["ManageUserId"].ToString()); helper.Execute(" update a set a.do_cost=b.do_cost,a.other_cost=b.other_cost,a.pro_code_new=b.pro_code from dbo.Tb_Working_main a,Tb_template b where a.work_id=" + work_id + " and a.tpl_id=b.tpl_id"); } else { helper.Params.Add("work_id", work_id); helper.Update("Tb_Working", "work_id"); } JSHelper.WriteScript("alert('编辑成功');location.href='ProductionList.Aspx';"); Response.End(); }
private void Calculate(object arg) { var materials = new List <RawMaterial> { InputA, InputB }; if (InputC != null) { materials.Add(InputC); } TargetProduct.OutputBatchSize = ProductionHelper.GetOutputBatchSize(ProductionLevel); TargetProduct.ExportCost = ProductionHelper.GetExportCost(ProductionLevel, AverageTax); foreach (var material in materials) { material.ImportCost = ProductionHelper.GetImportCost(material.InputLevel, AverageTax); material.InputBatchSize = ProductionHelper.GetInputBatchSize(material.InputLevel); } var result = ProductionHelper.Calculate(TargetProduct, materials, BatchSize); InputQuantity = result.InputQuantity; OutputQuantity = result.OutputQuantity; SaleCost = result.SaleCost; Expenses = result.Expenses; PurchaseCost = result.PurchaseCost; ProfitMargin = result.ProfitMargin; RaisePropertyChanged("InputQuantity"); RaisePropertyChanged("OutputQuantity"); RaisePropertyChanged("SaleCost"); RaisePropertyChanged("PurchaseCost"); RaisePropertyChanged("Expenses"); RaisePropertyChanged("ProfitMargin"); RaisePropertyChanged("RequiresThirdInput"); }
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 object PutProduction([FromBody] IEnumerable <ProductionDetail> details) { if (details == null || !details.Any()) { return(Result.GenError <Result>(Error.ParamError)); } if (details.Any(x => x.Id == 0)) { return(Result.GenError <Result>(Error.ProductionNotExist)); } if (details.Any(x => x.Name.IsNullOrEmpty())) { var ids = details.Select(x => x.Id); var cnt = ProductionHelper.Instance.GetCountByIds(ids); if (cnt != details.Count()) { return(Result.GenError <Result>(Error.ProductionNotExist)); } var markedDateTime = DateTime.Now; foreach (var detail in details) { detail.MarkedDateTime = markedDateTime; } ProductionHelper.Enable(details); } else { if (details.GroupBy(x => x.Name).Any(y => y.Count() > 1)) { return(Result.GenError <Result>(Error.ProductionDuplicate)); } if (details.Any(x => x.StepIds.Count != x.Rates.Count || x.StepIds.Count != x.Costs.Count)) { return(Result.GenError <Result>(Error.ProductionCapacityListError)); } var ids = details.Select(x => x.Id); var data = ProductionHelper.Instance.GetByIds <Production>(ids); if (data.Count() != details.Count()) { return(Result.GenError <Result>(Error.ProductionNotExist)); } var wId = details.FirstOrDefault()?.WorkshopId ?? 0; var userId = Request.GetIdentityInformation(); var markedDateTime = DateTime.Now; foreach (var detail in details) { detail.CreateUserId = userId; detail.MarkedDateTime = markedDateTime; detail.Remark = detail.Remark ?? ""; detail.FlowList = detail.Args?.Select(x => x.FlowId).Distinct().Join() ?? ""; foreach (var arg in detail.Args) { arg.WorkshopId = wId; arg.CreateUserId = userId; arg.MarkedDateTime = markedDateTime; arg.ProductionId = detail.Id; arg.Para = arg.Para ?? ""; arg.Other = arg.Other ?? ""; } } var newDetails = details.Where(x => ClassExtension.HaveChange(x, data.First(y => y.Id == x.Id))); if (newDetails.Any()) { var tIds = newDetails.Select(x => x.TypeId).Distinct(); var flowTypes = FlowTypeHelper.Instance.GetByIds <FlowType>(tIds).ToDictionary(x => x.Id); if (tIds.Count() != flowTypes.Count) { return(Result.GenError <Result>(Error.FlowTypeNotExist)); } var cIds = newDetails.Select(x => x.CapacityId).Distinct(); var cnt = CapacityHelper.Instance.GetCountByIds(cIds); if (cIds.Count() != cnt) { return(Result.GenError <Result>(Error.CapacityNotExist)); } var aTypeFlows = FlowCodeHelper.GetDetails(wId, null, tIds); var flowIds = newDetails.SelectMany(x => x.FlowIds).Distinct(); if (flowIds.Any(x => aTypeFlows.All(y => y.Id != x))) { return(Result.GenError <Result>(Error.FlowCodeNotExist)); } var typeFlows = aTypeFlows.Where(x => flowIds.Contains(x.Id)); var flowCodes = typeFlows.ToDictionary(x => x.Id); if (flowIds.Count() != flowCodes.Count) { return(Result.GenError <Result>(Error.FlowCodeNotExist)); } if (newDetails.Count(detail => { var fIds = detail.Args.Select(arg => arg.FlowId).Distinct(); return(fIds.Any(fId => { var mFcDic = detail.Args.Where(x => x.FlowId == fId).GroupBy(x => x.StepId).ToDictionary(y => y.Key, y => y.Count()); var fcDic = flowCodes[fId].StepIds.GroupBy(y => y).ToDictionary(y => y.Key, y => y.Count()); return detail.Args.Count(x => x.FlowId == fId) != flowCodes[fId].StepIds.Count || mFcDic.Any(x => x.Value != fcDic[x.Key]); })); }) > 0) { return(Result.GenError <Result>(Error.ProductionFlowCodeStepCountError)); } var sames = newDetails.Select(x => x.Name); if (ProductionHelper.GetHaveSame(wId, sames, ids)) { return(Result.GenError <Result>(Error.ProductionIsExist)); } var stepIds = newDetails.SelectMany(x => x.StepIds).Distinct(); if (stepIds.Any()) { var steps = FlowStepHelper.Instance.GetByIds <FlowStep>(stepIds).ToDictionary(x => x.Id); var formatIds = steps.Values.Select(x => x.FormatId).Distinct(); if (formatIds.Any()) { var formats = ArgsFormatHelper.Instance.GetByIds <ArgsFormat>(formatIds).ToDictionary(x => x.Id); if (newDetails.Any(x => x.Args.Any(arg => { if (steps.ContainsKey(arg.StepId) && steps[arg.StepId].FormatId != 0 && formats.ContainsKey(steps[arg.StepId].FormatId)) { var format = formats[steps[arg.StepId].FormatId]; return(ArgsFormatHelper.CheckPara(format, arg.Para)); } return(false); }))) { return(Result.GenError <Result>(Error.ProductionFlowCodeStepFormatError)); } } } ProductionHelper.Instance.Update(newDetails); } var args = ProductionArgHelper.GetMenus(ids, null); var argTmps = details.SelectMany(x => x.Args); var add = new List <ProductionArg>(); var up = new List <ProductionArg>(); var del = new List <int>(); add.AddRange(argTmps.Where(x => x.Id == 0)); up.AddRange(argTmps.Where(x => x.Id != 0).Where(x => argTmps.Any(y => ClassExtension.HaveChange(y, x)))); del.AddRange(args.Where(x => !argTmps.Any(y => y.Id == x.Id)).Select(x => x.Id)); if (add.Any()) { ProductionArgHelper.Instance.Add(add); } if (up.Any()) { ProductionArgHelper.Instance.Update <ProductionArg>(up); } if (del.Any()) { ProductionArgHelper.Instance.Delete(del); } } return(Result.GenError <Result>(Error.Success)); }
public ProductionInProgress LineStart(Character character, ProductionLine productionLine, Container sourceContainer, int cycles, bool useCorporationWallet, out bool hasBonus) { var cprg = productionLine.GetOrCreateCalibrationProgram(this); var components = cprg.Components; //search for components var foundComponents = ProductionHelper.SearchForAvailableComponents(sourceContainer, components).ToList(); var materialMultiplier = CalculateFinalMaterialMultiplier(character, productionLine.GetMaterialPoints(), productionLine.TargetDefinition, out hasBonus); if (cprg.IsMissionRelated) { //clamp the material multiplier at 1.0 //so it can ask less that in the mission but never more var preMatMult = materialMultiplier; materialMultiplier = materialMultiplier.Clamp(); Logger.Info("pre material multiplier:" + preMatMult + " -> " + materialMultiplier); } //match components var itemsNeeded = ProductionHelper.ProcessComponentRequirement(ProductionInProgressType.massProduction, foundComponents, cycles, materialMultiplier, components); //put them to storage long[] reservedEids; ProductionHelper.ReserveComponents_noSQL(itemsNeeded, StorageEid, sourceContainer, out reservedEids).ThrowIfError(); //calculate time var productionTimeSeconds = cycles * CalculateFinalProductionTimeSeconds(character, cprg.TargetDefinition, productionLine.GetTimePoints()); productionTimeSeconds = GetShortenedProductionTime(productionTimeSeconds); if (cprg.IsMissionRelated) { productionTimeSeconds = 10; } var newProduction = ProductionInProgressFactory(); newProduction.startTime = DateTime.Now; newProduction.finishTime = DateTime.Now.AddSeconds(productionTimeSeconds); newProduction.type = ProductionInProgressType.massProduction; newProduction.character = character; newProduction.facilityEID = Eid; newProduction.resultDefinition = productionLine.TargetDefinition; newProduction.totalProductionTimeSeconds = productionTimeSeconds; newProduction.baseEID = Parent; newProduction.pricePerSecond = cprg.IsMissionRelated ? 0.0 : GetPricePerSecond(productionLine.TargetDefinition); newProduction.ReservedEids = reservedEids; newProduction.amountOfCycles = cycles; newProduction.useCorporationWallet = useCorporationWallet; if (!newProduction.TryWithdrawCredit()) { //not enough money return(null); } //save to sql newProduction.InsertProductionInProgess(); //set running production id to line ProductionLine.SetRunningProductionId(productionLine.Id, newProduction.ID).ThrowIfError(); productionLine.DecreaseRounds(); sourceContainer.Save(); Transaction.Current.OnCommited(() => { //add to ram ProductionProcessor.AddToRunningProductions(newProduction); }); //send info to client newProduction.SendProductionEventToCorporationMembersOnCommitted(Commands.ProductionRemoteStart); return(newProduction); }
private void Analyze(IProgress <AnalysisResult> progress) { int index = 0; var itemTasks = new List <Task>(); foreach (var item in AnalysisItems) { itemTasks.Add(Task.Factory.StartNew(() => { using (MarketDataHelper helper = new MarketDataHelper(MarketDataHelper.QuickLook)) { MarketDataRequest request = new MarketDataRequest { TypeId = item.Product.ItemId.ToString(), SystemId = MarketDataHelper.Jita, Duration = MarketDataHelper.Freshness }; var productData = helper.GetData(request); MarketDataResponse.ResequenceOrders(productData); var order = productData.HighestBuyOrder; item.Product.Price = order != null ? order.Price : 0.0; item.Product.ExportCost = ProductionHelper.GetExportCost(ProductionLevel); item.Product.OutputBatchSize = ProductionHelper.GetOutputBatchSize(ProductionLevel); item.Product.Data = productData; foreach (var input in item.Materials) { request = new MarketDataRequest { TypeId = input.ItemId.ToString(), Duration = MarketDataHelper.Freshness, SystemId = MarketDataHelper.Jita }; var materialData = helper.GetData(request); MarketDataResponse.ResequenceOrders(materialData); order = materialData.LowestSellOrder(null); input.Price = order != null ? order.Price : 0.0; input.ImportCost = ProductionHelper.GetImportCost(input.InputLevel); input.InputBatchSize = ProductionHelper.GetInputBatchSize(input.InputLevel); input.Data = materialData; } var productionResult = ProductionHelper.Calculate(item.Product, item.Materials); item.ProductionCost = productionResult.PurchaseCost; item.SaleValue = productionResult.SaleCost; item.ProfitMargin = productionResult.ProfitMargin; item.UpdateProperties(); var currentProgress = ((double)++index / AnalysisItems.Count) * 100; progress.Report(new AnalysisResult { ProgressIndex = (int)currentProgress, Item = item }); Task.Delay(2000).Wait(); } }, TaskCreationOptions.AttachedToParent)); } Task.Factory.ContinueWhenAll(itemTasks.ToArray(), groupedTasks => { }); }
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); }