using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using System.Threading.Tasks; using Volo.Abp.Application.Dtos; using Volo.Abp.Domain.Repositories; using Business.Models; using Microsoft.AspNetCore.Authorization; using Business.Permissions; using XCZ; using Business.ResourceExamineManagement.Dto; using Bussiness.Model.MES.IC; using AutoMapper.Internal.Mappers; using Bussiness.Model.Tech; using Bussiness.Model.Production; using Business.Core.MongoDBHelper; using Business.Core.Utilities; using Hangfire.Storage.Monitoring; using Business.BookManagement.Dto; using Volo.Abp.ObjectMapping; using Volo.Abp.Application.Services; using ZstdSharp.Unsafe; using System.Transactions; using NUglify.JavaScript.Syntax; using System.Linq.Expressions; using XCZ.Extensions; using System.ComponentModel; using System.Reflection.Emit; using NUglify.Helpers; using Microsoft.AspNetCore.SignalR.Protocol; using System.ComponentModel.Design; using Volo.Abp.Validation.StringValues; using System.Runtime.CompilerServices; using MongoDB.Driver; using Volo.Abp.Validation.Localization; using Hangfire.Annotations; using System.Globalization; using MongoDB.Driver.Linq; using Bussiness.Model.SRM; using System.ComponentModel.DataAnnotations; namespace Business.ResourceExamineManagement { /// /// 资源检查 /// //[Authorize(BusinessPermissions.ResourceExamine.Default)] public class ResourceExamineAppService : ApplicationService, IResourceExamineAppService { #region 服务 /// /// 工艺路径 /// private readonly IMongoDB _mes_technique; private IRepository _mysql_mes_technique; /// /// 工序 /// private readonly IMongoDB _mes_process; /// /// 工艺关联工序 /// private readonly IMongoDB _mes_tech_process; /// /// 工作日历 /// private readonly IMongoDB _mes_work_calendar; /// /// 工作日历明细 /// private readonly IMongoDB _mes_work_calendar_list; /// /// 工艺工序关联工位 /// private readonly IMongoDB _mes_tech_proc_workshop; /// /// 排程占用记录 /// private readonly IMongoDB _mes_schedule_occupy; /// /// 物料占用记录 /// private readonly IMongoDB _ic_item_stockoccupy; /// /// 物料详情 /// private readonly IMongoDB _ic_item; private IRepository _mysql_ic_item; /// /// 物料BOM /// private readonly IMongoDB _ic_bom; private IRepository _mysql_ic_bom; /// /// 物料BOM明细 /// private readonly IMongoDB _ic_bom_child; private IRepository _mysql_ic_bom_child; /// /// 物料库存表 /// private readonly IMongoDB _ic_item_stock; private IRepository _mysql_ic_item_stock; /// /// 物料工厂明细表 /// private readonly IMongoDB _ic_factory_details; private IRepository _mysql_ic_factory_details; /// /// 采购申请单 /// private readonly IMongoDB _srm_pr_main; private IRepository _mysql_srm_pr_main; /// /// 委外工单 /// private readonly IMongoDB _mes_oorder; private IRepository _mysql_mes_oorder; /// /// 物料质检表 /// private readonly IMongoDB _ic_check; /// /// 替代群组 /// private readonly IMongoDB _ic_substitute; /// /// 替代群组 /// private readonly IMongoDB _ic_substitute_all; /// /// 替代群组 /// private readonly IMongoDB _ic_substitute_all_dtl; /// /// 生产工单主表 /// private readonly IMongoDB _mes_morder; /// /// 生产工单子表 /// private readonly IMongoDB _mes_moentry; /// /// 在制工单占用记录表 /// private readonly IMongoDB _mes_mooccupy; /// /// 销售工单 /// private readonly IRepository _mysql_crm_seorder; /// /// 销售工单 /// private readonly IRepository _mysql_crm_seorderentry; #endregion /// /// 构造函数 /// /// /// public ResourceExamineAppService( IMongoDB mes_technique, IMongoDB mes_process, IMongoDB mes_tech_process, IMongoDB mes_tech_proc_workshop, IMongoDB ic_item, IMongoDB ic_bom, IMongoDB ic_bom_child, IMongoDB ic_item_stock, IMongoDB ic_check, IMongoDB ic_factory_details, IMongoDB mes_oorder, IMongoDB srm_pr_main, //IMongoDB ic_substitute, //IMongoDB ic_substitute_all, //IMongoDB ic_substitute_all_dtl, IMongoDB mes_morder, IMongoDB mes_moentry, IMongoDB mes_mooccupy, IMongoDB ic_item_stockoccupy, IRepository mysql_ic_item, IRepository mysql_ic_bom, IRepository mysql_ic_bom_child, IRepository mysql_mes_technique, IRepository mysql_crm_seorder, IRepository mysql_crm_seorderentry, IRepository mysql_ic_item_stock, IRepository mysql_ic_factory_details, IRepository mysql_mes_oorder, IRepository mysql_srm_pr_main ) { _mes_technique = mes_technique; _mes_process = mes_process; _mes_tech_process = mes_tech_process; _mes_tech_proc_workshop = mes_tech_proc_workshop; _ic_item = ic_item; _ic_bom = ic_bom; _ic_bom_child = ic_bom_child; _ic_item_stock = ic_item_stock; _ic_check = ic_check; _ic_factory_details= ic_factory_details; _mes_oorder= mes_oorder; _srm_pr_main= srm_pr_main; //_ic_substitute = ic_substitute; //_ic_substitute_all = ic_substitute_all; //_ic_substitute_all_dtl = ic_substitute_all_dtl; _mes_morder = mes_morder; _mes_moentry = mes_moentry; _mes_mooccupy = mes_mooccupy; _ic_item_stockoccupy = ic_item_stockoccupy; _mysql_ic_item = mysql_ic_item; _mysql_ic_bom = mysql_ic_bom; _mysql_ic_bom_child = mysql_ic_bom_child; _mysql_crm_seorder = mysql_crm_seorder; _mysql_crm_seorderentry = mysql_crm_seorderentry; _mysql_mes_technique = mysql_mes_technique; _mysql_ic_item_stock = mysql_ic_item_stock; _mysql_ic_factory_details= mysql_ic_factory_details; _mysql_mes_oorder= mysql_mes_oorder; _mysql_srm_pr_main= mysql_srm_pr_main; } /// /// mongoDB示例方法,后期删除 /// /// public async Task test() { ////多条插入 //List infos = new List(); //mes_technique info; //for (int i = 0; i < 3; i++) //{ // info = new mes_technique(); // info.GenerateNewId(); // info.tech_name = "多条" + i; // info.level = i; // infos.Add(info); //} //await _mes_technique.InsertMany(infos); //var info2 = _mes_technique.GetAll().Result; //var a = new PschedDto(); //a.count = info2.Count; ////获取数据 //var info1 = await _mes_technique.GetOneByID((long)1732029975067480064); ////更新数据 //info1.tech_name = "更新***"; //var rlt = await _mes_technique.UpdateOne(info1, info1.Id); ////根据条件查询数据 //Expression> filter = x => x.Id == (long)1732376973889097728 && x.tech_name == "多条0"; //var info3 = await _mes_technique.GetManyByCondition(filter); ////删除数据 ////根据id删除数据 ////await _ic_item_stock.DeleteByIds(136123); ////根据id删除表数据 //List aa = new List(); //aa.Add(136131); //aa.Add(136132); //aa.Add(136133); //FilterDefinition filter = Builders.Filter.In(s => s.icitem_id, aa); //await _ic_item_stock.Delete(filter); //根据条件删除数据 //await _ic_item_stock.Delete(p=>p.icitem_name == "test"); //await _ic_item_stock.DeleteByIds(aa); //await _ic_item_stock.DeleteAll(); } /// /// 资源检查 /// /// /// /// public async Task ReceiveResult(SeorderentryDto input) { //数据库快照-同步mysql库数据到mongoDB中 //await SyncData(input.factoryId); //生成当前计算bangid //SnowFlake snow = new SnowFlake(); //long bangid = snow.NextId(); //产能检查 //await ProductiveExamine(1733221167209762816, 100); await GenerateMorder(14); return null; throw new NotImplementedException(); } /// /// 数据库快照 /// /// public async Task SyncData(long factoryId) { //同步物料库存数据 var icitemStokc = _mysql_ic_item_stock.GetListAsync(p => p.factory_id == factoryId).Result; if (icitemStokc.Count > 0) { await _ic_item_stock.InsertMany(icitemStokc); } } /// /// 产能计算 /// /// 工艺路径主键 /// 需要生产产品件数 /// 生产时长 public async Task ProductiveExamine(long tech_id, int packages) { if (packages <= 0) { throw new NotImplementedException("产能计算参数有误!"); } #region 1、数据准备 //1.1、获取工艺路径数据 mes_technique tech = await _mes_technique.GetOneByID(tech_id); //1.2、获取工艺路径关联工序数据 List tech_Processes = await _mes_tech_process.GetManyByCondition(x => x.tech_id == tech_id); //1.3、获取当前工艺路径下的工序数据 FilterDefinition filter = Builders.Filter.In(s => s.Id, tech_Processes.Select(m => m.proc_id).ToList()); List process = await _mes_process.GetManyByIds(filter); //1.3、获取工艺工序关联工位信息 FilterDefinition filter1 = Builders.Filter.In(s => s.tech_proc_id, tech_Processes.Select(m => m.Id).ToList()); List tech_Proc_Workshops = await _mes_tech_proc_workshop.GetManyByIds(filter1); #endregion #region 计算产能,得到耗时 decimal sumTimes = 0.00m;//总耗时(分钟) //工序需要等待时间记录 List starts = new List(); //1、获取工艺路径下的第一层级工序 List fistChilds = tech_Processes.Where(p => p.parentprocid == tech_id).OrderBy(m => m.Id).ToList(); if (fistChilds.Count == 0) { throw new NotImplementedException("当前工艺路径没有配置工序,请调整!"); } decimal curTakeTime = 0.00m;//当前工序耗时(分钟) //添加第一个工序需要等待时间记录 StartTimeDto dto; foreach (var chd in fistChilds) { dto = new StartTimeDto(); if (chd.nextprocid == null)//最后一个工序 { //计算最后一个工序耗时 curTakeTime = CalcTakeTime(chd, packages); } else { curTakeTime = CalcTakeTime(chd, chd.lq.Value); } sumTimes += curTakeTime; //添加耗时记录 dto.tech_id = tech_id; dto.proc_id = chd.proc_id; dto.nextproc_id = chd.nextprocid; dto.wait_time = curTakeTime; starts.Add(dto); } #endregion return sumTimes; } /// /// 计算当前工序前置准备时间 /// /// /// LeadQuantity to Start Next /// private decimal CalcTakeTime(mes_tech_process proc, decimal quantity) { decimal takeTime = 0.00m;//当前工序前置准备时间(分钟) if (proc.wctype == 1)//人工型:数量/uph(一小时生产数量)*60(小时转换为分钟)/wsinuse(工位数) { takeTime = quantity / proc.uph.Value * 60 / proc.wsinuse.Value; return takeTime; } else if (proc.wctype == 2)//流水线型:数量*ct(生产一件所需时间) { takeTime = quantity * proc.ct.Value; return takeTime; } else if (proc.wctype == 3)//设备型:向上取整(数量/一次可加工数量)*ct(老化一次所需时间) { takeTime = Math.Ceiling(quantity / proc.upe.Value) * proc.ct.Value; return takeTime; } return takeTime; } /// /// 生成工单 /// /// Bom编码 /// 需要数量 /// 交付日期 /// 销售订单子表ID /// public async Task GenerateMorder(long seorderentry_id) { //1.库存、在制工单检查完成后 当前BOM需要自制时 产生工单。 //2.每一个销售订单行对应一个工单。 //查询销售订单子表数据 var seorderentry = _mysql_crm_seorderentry.GetListAsync(x => x.Id == seorderentry_id).Result.FirstOrDefault(); //获取销售订单信息 var seorder = await _mysql_crm_seorder.FindAsync(x => x.Id == seorderentry.seorder_id); //物料BOM var ic_bom = _ic_bom.GetManyByCondition(x => x.bom_number == seorderentry.bom_number && x.tenant_id == seorderentry.tenant_id).Result.FirstOrDefault(); mes_morder mes_Morder = new mes_morder(); mes_Morder.GenerateNewId(); mes_Morder.morder_type = "销售工单"; //mes_Morder.morder_icitem_type mes_Morder.work_order_type = "常规工单"; mes_Morder.morder_state = "初始"; mes_Morder.morder_no = string.Format("VMO{0}", DateTime.Now.ToString("yyyyMMddhhmmss"));//测试编码 mes_Morder.fms_number = seorderentry.fms_number; mes_Morder.bom_number = seorderentry.bom_number; mes_Morder.fmodel = seorderentry.specification; //最早的开工时间3天后、 最晚时间为订单承诺时间-采购提前期-质检提前期-入库提前期-发料提前期 =最晚开工时间 最早或最晚为系统建议开工日期 //根绝系统配置参数 取最早或者最晚开始日期 var StartDate = DateTime.Now.Date.AddDays(3); mes_Morder.moentry_sys_stime = StartDate; var ProductiveDate = ProductiveExamine(ic_bom.tech_id, (int)(seorderentry.qty.Value)); //系统建议完工日期为 开工日期+产能检查时间=完工日期 var Day = ProductiveDate.Result / (60 * 10); //返回的分钟除以十个小时得出工作天数; mes_Morder.moentry_sys_etime = StartDate.AddDays((double)Day); mes_Morder.morder_need_time = ProductiveDate.Result; mes_Morder.moentry_startup_status = 0; mes_Morder.tenant_id = seorderentry.tenant_id; mes_Morder.product_code = seorderentry.item_number; mes_Morder.product_name = seorderentry.item_name; mes_Morder.project_name = seorder.project_name; mes_Morder.planner_num = seorderentry.planner_no; mes_Morder.planner_name = seorderentry.planner_name; mes_Morder.morder_date = DateTime.Now.Date; //TODO:目前没有取值位置 mes_Morder.moentry_prd = null; mes_Morder.moentry_prdname = null; mes_Morder.moentry_wrkc = null; mes_Morder.moentry_wrkcname = null; mes_Morder.picking_qty = 0; //TODO:可删除主表字段 mes_Morder.unit = seorderentry.unit; mes_Morder.morder_production_number = seorderentry.qty; mes_Morder.need_number = seorderentry.qty; mes_Morder.remaining_number = 0; //生成工单子表数据 mes_moentry mes_Moentry = new mes_moentry(); mes_Moentry.GenerateNewId(); mes_Moentry.moentry_moid = mes_Morder.Id; mes_Moentry.moentry_mono = mes_Morder.morder_no; mes_Moentry.soentry_id = seorderentry.Id; mes_Moentry.fbill_no = seorderentry.bill_no; mes_Moentry.fentry_id = seorderentry.entry_seq.Value; mes_Moentry.unit = seorderentry.unit; mes_Moentry.morder_production_number = seorderentry.qty; mes_Moentry.need_number = seorderentry.qty; mes_Moentry.remaining_number = 0; using (TransactionScope scope = new TransactionScope()) { await _mes_morder.InsertOne(mes_Morder); await _mes_moentry.InsertOne(mes_Moentry); scope.Complete(); } } /// /// 将decimal转换成日期格式 /// /// yyyyMMddHHmmss /// yyyy-MM-dd HH:mm:ss public static string TransDecimalToDateTime(string date) { DateTimeFormatInfo dtfi = new CultureInfo("zh-CN", false).DateTimeFormat; DateTime dateTime = DateTime.Now; DateTime.TryParseExact(date, "yyyyMMddHHmmss", dtfi, DateTimeStyles.None, out dateTime); return dateTime.ToString("yyyy-MM-dd HH:mm:ss"); ; } /// /// 检查成品库存 /// /// 销售订单子表ID /// public async Task CheckFinishedProductInventory(long seorderentry_id) { //获取销售订单子表 var seorderentry = await _mysql_crm_seorderentry.FindAsync(x => x.Id == seorderentry_id); if (string.IsNullOrEmpty(seorderentry.bom_number)) { return false; } //物料BOM var ic_bom = _ic_bom.GetManyByCondition(x => x.bom_number == seorderentry.bom_number && x.tenant_id == seorderentry.tenant_id).Result.FirstOrDefault(); //物料库存表 var ic_Item_Stocks = await _ic_item_stock.GetManyByCondition(x => x.icitem_id == ic_bom.icitem_id && x.tenant_id == seorderentry.tenant_id); if (seorderentry.qty <= ic_Item_Stocks.Sum(x => x.sqty)) { return true; } else { return false; } } /// /// 检查在制工单 /// /// Bom编码 /// 需要数量 /// 交付日期 /// 销售订单子表ID /// public async Task> CheckMorder(string bomNumber, decimal? Quantity, DateTime DeliverDate, long seorderentry_id) { if (string.IsNullOrEmpty(bomNumber) || Quantity != null) { //TODO:入参异常; throw new NotImplementedException("BOM编码或需求数量不能为空!"); } //获取销售订单信息 //var seorder = await _crm_seorder.FindAsync(x => x.Id == OrderId); var seorderentry = await _mysql_crm_seorderentry.FindAsync(x => x.Id == seorderentry_id); //根据Bom编码查询出对应工单并且状态不为完成、关闭,非委外工单。 //TODO:工单类型; var morderList = await _mes_morder.GetManyByCondition(x => x.bom_number == bomNumber && (x.morder_state != "完成" || x.morder_state != "关闭" && x.morder_icitem_type != "相关委外工单") && x.IsDeleted == false && x.tenant_id == seorderentry.tenant_id); //获取物料详情 var mysql_ic_item = await _mysql_ic_item.FindAsync(x => x.number == bomNumber && x.tenant_id == seorderentry.tenant_id); //工单已被占用后要与占用表关联查询...减去占用量后 剩下生产数量可供下个销售工单使用。 var mes_mooccupyList = await _mes_mooccupy.GetManyByCondition(x => x.moo_state == 1 && x.IsDeleted == false && x.tenant_id == seorderentry.tenant_id); //首先满足需求数量工单其次判断是否满足交付日期、当数量不满足时继续查找最早交付日期订单 工单数量累加。 //当前工单计划日期-1天 小于交付日期 && 计算生产数量-入库数据并且大于需求产品数量。 var morderDataList = morderList.Where(x => x.planner_end_date.Value.AddDays(-1) < DeliverDate && (x.morder_production_number - x.inventory_number) > Quantity).ToList(); if (morderDataList.Count > 0) { //存在此数据满足当前BOM交付找到最早日期工单,则返回无需后续继续检查。 var morder = morderDataList.OrderByDescending(x => x.planner_end_date).FirstOrDefault(); var mooccupies = mes_mooccupyList.Where(x => x.moo_moid == morder.Id).ToList(); var mes_Mooccupy = GetMooccupies(seorderentry, mysql_ic_item, morder, mooccupies); await _mes_mooccupy.InsertOne(mes_Mooccupy); } else { // 寻找最早日期工单 && 计算生产数量-入库数据并且大于需求产品数量后累加直到满足需求产品数量 var morderListData = morderList.Where(x => x.planner_end_date.Value.AddDays(-1) < DeliverDate).OrderByDescending(x => x.planner_end_date).ToList(); if (morderListData.Count == 0) { //TODO:后期处理无在制工单返回内容 throw new NotImplementedException("无可用在制工单!"); } List mes_Mooccupies = new List(); decimal? number = Quantity; foreach (var item in morderListData) { //查询出工单已占用总数量 var mooccupies = mes_mooccupyList.Where(x => x.moo_moid == item.Id).ToList(); var mes_Mooccupy = GetMooccupies(seorderentry, mysql_ic_item, item, mooccupies); mes_Mooccupies.Add(mes_Mooccupy); //需求数量-占用量后小于或等于0 停止循环占用工单 if (number - mes_Mooccupy.moo_qty <= 0) { break; } } } return morderList; } /// /// 拼接工单占用表 /// /// 销售订单子表 /// 物料详情表 /// 工单表 /// 占用工单表 /// public mes_mooccupy GetMooccupies(crm_seorderentry seorderentry, ic_item mysql_ic_item, mes_morder item, List mes_mooccupy) { decimal? Sumqty = 0; if (mes_mooccupy.Count > 0) { Sumqty = mes_mooccupy.Sum(x => x.moo_qty); } //生成mes_mooccupy工单占用表数据,代表多个工单被某个销售订单已占用。 mes_mooccupy mes_Mooccupy = new mes_mooccupy(); mes_Mooccupy.GenerateNewId(); mes_Mooccupy.moo_id_type = "分配"; mes_Mooccupy.moo_id_billid = seorderentry.seorder_id;//销售订单ID mes_Mooccupy.fbill_no = seorderentry.bill_no;//销售订单号 mes_Mooccupy.fentry_id = seorderentry.entry_seq.Value;//销售订单行 mes_Mooccupy.fitem_name = mysql_ic_item.name;//物料名称 mes_Mooccupy.fitem_number = mysql_ic_item.number; mes_Mooccupy.fmodel = mysql_ic_item.model;//规格型号 mes_Mooccupy.moo_moid = item.Id; mes_Mooccupy.moo_mo = item.morder_no; //占用量=生产计划数量-入库数量-已被占用数量 mes_Mooccupy.moo_qty = item.morder_production_number - item.inventory_number - Sumqty; mes_Mooccupy.moo_stime = DateTime.Now; mes_Mooccupy.moo_etime = DateTime.Now;//日期来源需确定 mes_Mooccupy.moo_state = 1; mes_Mooccupy.moo_cbr = string.Empty; //mes_Mooccupy.moo_ctime = ; mes_Mooccupy.moo_creason = string.Empty; mes_Mooccupy.tenant_id = seorderentry.tenant_id;//取销售子表企业ID return mes_Mooccupy; } /// /// BOM预处理 /// /// /// /// public void BomPretreatment(long? orderid, long? BomId, int Quantity) { if (orderid == null) { //throw new bu } if (BomId == null) { //throw new bu } //var query = (await _ic_bom.GetQueryableAsync()).WhereIf(true, a => a.bom_id == BomId).ToList(); var help = new SnowFlake(); var bomlist = _ic_bom.GetAll().Result; var bomchildlist = _ic_bom_child.GetAll().Result; var icitemlist = _ic_item.GetAll().Result; List returnlist = new List(); var dto = new BomChildExamineDto(); dto.bom_id = BomId.Value; dto.level = 1; dto.id = help.NextId(); dto.parent_id = help.NextId(); dto.qty = 1; dto.num = "1"; dto.isbom = 1; dto.is_replace = 0; dto.haveicsubs = 0; dto.substitute_code = ""; dto.icitem_ids = ""; int type = 0; GetBomList(bomlist, bomchildlist, icitemlist, dto, returnlist, type); } /// /// BOM预处理层级组装 /// /// /// /// /// /// public void GetBomList(List bomlist, List bomchildlist, List icitemlist, BomChildExamineDto dto, List returnlist, int type) { int level = dto.level++;//初始化定义level层级 var help = new SnowFlake(); var bom = bomlist.WhereIf(true, s => s.Id == dto.bom_id).FirstOrDefault(); var item = icitemlist.WhereIf(true, a => a.Id == bom.icitem_id).FirstOrDefault(); if (bom == null || item == null) { } dto.item_id = bom.icitem_id; dto.item_name = bom.item_name; dto.item_code = bom.item_number; dto.model = item.model; dto.unit = bom.unit; dto.erp_cls = item.erp_cls; dto.erp_cls_name = item.erp_cls_name; dto.type = type; //var bdto = ObjectMapper.Map(bom); returnlist.Add(dto); var childlist = bomchildlist.WhereIf(true, a => a.bom_id == bom.Id).ToList(); int idx = 1; foreach (var c in childlist) { string childNum = dto.num + "." + idx.ToString(); var icitem = icitemlist.WhereIf(true, a => a.Id == c.icitem_id).FirstOrDefault(); var childBom = bomlist.WhereIf(true, a => a.icitem_id == c.icitem_id).FirstOrDefault(); //如果此明细查的到BOM信息,则代表此child是一个子BOM。 if (childBom != null) { var cdto = new BomChildExamineDto(); cdto.id = help.NextId(); cdto.level = level; cdto.parent_id = dto.id; cdto.bom_child_id = c.Id; cdto.qty = c.qty.Value; cdto.backflush = c.backflush; cdto.num = childNum; cdto.isbom = 1; cdto.is_replace = c.is_replace; cdto.haveicsubs = c.haveicsubs; cdto.substitute_code = c.substitute_code; cdto.icitem_ids = c.icitem_ids; cdto.type = type; //递归寻找子级 GetBomList(bomlist, bomchildlist, icitemlist, cdto, returnlist, type); } else { if (icitem != null) { var childDto = new BomChildExamineDto(); childDto.level = level++; childDto.bom_id = dto.bom_id; childDto.bom_child_id = c.Id; childDto.id = help.NextId(); childDto.parent_id = dto.id; childDto.item_id = icitem.Id; childDto.item_name = icitem.name; childDto.item_code = icitem.number; childDto.num = childNum; childDto.model = icitem.model; childDto.unit = c.unit; childDto.erp_cls = item.erp_cls; childDto.erp_cls_name = item.erp_cls_name; childDto.backflush = c.backflush; childDto.qty = c.qty.Value; childDto.isbom = 0; childDto.is_replace = c.is_replace; childDto.haveicsubs = c.haveicsubs; childDto.substitute_code = c.substitute_code; childDto.icitem_ids = c.icitem_ids; childDto.type = type; returnlist.Add(childDto); } } idx++; } } /// /// BOM替代关系预处理 /// public void BomSubstitute(List returnlist, List bomlist, List bomchildlist, List icitemlist) { var sublist = _ic_substitute.GetManyByCondition(s => s.substitute_code.IsIn(returnlist.Select(c => c.substitute_code))).Result.ToList(); var suballlist = _ic_substitute_all.GetManyByCondition(s => s.substitute_id.IsIn(sublist.Select(c => c.Id))).Result.ToList(); var subdtllist = _ic_substitute_all_dtl.GetManyByCondition(s => s.substitute_allid.IsIn(suballlist.Select(c => c.Id))).Result.ToList(); List childidList = new List(); var help = new SnowFlake(); int type = 1; //除顶级外,其他层级关系全带出来。生成平铺 foreach (var item in returnlist) { //最顶级、虚拟件 if (item.level != 1 && item.erp_cls != 4 && !childidList.Contains(item.bom_child_id.GetValueOrDefault())) { //有替代关系 if (item.haveicsubs == 1) { if (!string.IsNullOrEmpty(item.icitem_ids)) { long cid = 1; var cids = item.icitem_ids.Split(','); foreach (var c in cids) { if (long.TryParse(c, out cid)) { childidList.Add(cid); } } } //找到当前物料的替代群组关系集 var sl = sublist.Find(s => s.substitute_code == item.substitute_code); if (sl != null) { var sall = suballlist.Where(s => s.substitute_id == sl.Id).ToList(); foreach (var sal in sall) { var sadl = subdtllist.Where(s => s.substitute_allid == sal.Id).ToList(); foreach (var dtl in sadl) { if (dtl.ismain == 0) { //递归将替代关系组装出来。 SubstitutePretreatment(sl, sal, dtl, item, returnlist, icitemlist, bomlist, bomchildlist, type); } } } } } } } } /// /// 替代关系递归组装出来 /// /// /// /// /// /// /// /// public void SubstitutePretreatment(ic_substitute sl, ic_substitute_all sal, ic_substitute_all_dtl dtl, BomChildExamineDto toDto, List returnlist, List icitemlist, List bomlist, List bomchildlist, int type) { //循环生成dtl层级dto,明细 //如果dtl对应的icitem是BOM,还需要向下继续展开。 var help = new SnowFlake(); //List returnlist = new List(); var dto = new BomChildExamineDto(); var bom = bomlist.WhereIf(true,s => s.icitem_id == dtl.icitem_id).FirstOrDefault(); var icitem = icitemlist.Find(s => s.Id == dtl.icitem_id); if (icitem == null) { return; } dto.id = help.NextId(); dto.level = toDto.level; dto.parent_id = toDto.parent_id; dto.item_id = icitem.Id; dto.item_name = icitem.name; dto.item_code = icitem.number; dto.num = toDto.num; dto.model = icitem.model; dto.unit = icitem.unit; dto.erp_cls = icitem.erp_cls; dto.erp_cls_name = icitem.erp_cls_name; dto.backflush = toDto.backflush; dto.qty = toDto.qty; dto.replace_amount = dtl.replace_amount.Value; dto.is_replace = 0; dto.haveicsubs = 0; dto.substitute_code = ""; dto.icitem_ids = ""; dto.substitute_strategy = sl.substitute_strategy.Value;//替代策略 dto.substitute_mode = sl.substitute_mode.Value;//替代方式 dto.type = type; dto.substitute_all_num = sal.order_num;//群组优先级 if (bom != null) { dto.bom_id = bom.Id; dto.qty = dtl.replace_amount.Value; dto.isbom = 1; dto.is_replace = 0; dto.haveicsubs = 0; dto.substitute_code = ""; dto.icitem_ids = ""; GetBomList(bomlist, bomchildlist, icitemlist, dto, returnlist, type); } else { dto.bom_id = null; dto.isbom = 0; returnlist.Add(dto); } } /// /// 计算物料库存量 /// /// public void BomStock(List returnlist, long bangid, long orderid, long orderentryid, long factoryid) { returnlist = returnlist.OrderBy(s => s.num).ToList(); //获取当前工厂下物料库存数据 List icitemIds = returnlist.Select(c => c.item_id).ToList(); var stocklist = _ic_item_stock.GetManyByCondition(p => p.factory_id == factoryid && icitemIds.Contains(p.icitem_id)).Result; //取当前订单的物料库存占用记录 var occupylist = _ic_item_stockoccupy.GetManyByCondition(p => p.bang_id == bangid && p.order_id == orderid).Result; //计算剩余库存 foreach (var item in returnlist) { if (item.erp_cls == 4)//虚拟件不计算 { continue; } //非虚拟件 //当前物料的库存数量 decimal stockQty = stocklist.Where(s => s.icitem_id == item.item_id).Sum(p => p.sqty.GetValueOrDefault()); //获取当前订单其他订单行当前物料的占用数量 decimal otherStockQty = occupylist.Where(s => s.icitem_id == item.item_id).Sum(p => p.quantity); //当前订单行物料库存情况 item.sqty = stockQty - otherStockQty; } } /// /// 替代关系检查计算 /// public void CalcIcitemSubstitute(List returnlist, int count) { returnlist = returnlist.OrderBy(s => s.num).ToList(); //1.如果主料够的时候,不需要显示替代料的平铺视图,如果主料不够,显示替代料的平铺视图。 //2.替代策略和替代方式,影响到的是甲乙组概念,替代按主料有限,取代按组的优先级。A与B的替代,则A和B各自会存在一个组。 List calcIds = new List(); //先处理下最顶级的产品需要数量 returnlist[0].needCount = returnlist[0].qty * count; returnlist[0].satisfyNum = returnlist[0].sqty; returnlist[0].lack_qty = returnlist[0].needCount - returnlist[0].satisfyNum; returnlist[0].is_show = true; foreach (var item in returnlist) { //循环平铺整个资源检查的物料库存情况、缺料情况 CaclMaterialShortage(returnlist, item, count); } foreach (var item in returnlist) { //替代件不计算,替代件通过标准件的替代关系,去计算需要使用哪些物料 if (item.type == 1) { continue; } CaclBomChildUseShortage(returnlist, item); } } /// /// 物料计算 /// /// /// /// public void CaclBomChildUseShortage(List returnlist, BomChildExamineDto item) { //判断是否是BOM,如果是BOM,还需要向下展开 var bomchild = returnlist.Where(s => s.parent_id == item.id && s.type == 0).ToList(); if (bomchild.Count > 0) { foreach (var child in bomchild) { CaclBomChildUseShortage(returnlist, item); } } var tolist = returnlist.Where(s => s.parent_id == item.parent_id && s.num == item.num).ToList(); //有替代关系 if (item.haveicsubs == 1) { //首先判断标准件库存是否满足。 //如果是BOM,也需要向下展开,看子物料是否满足。 //不满足的情况下,则需要展开替代关系,根据替代策略和替代方式,来判定替代件的库存。 //假设子BOM有替代关系,则子BOM的子物料,也是有替代关系存在的,需要展开来看。 //1.假设标准件库存满足,则不计算替代件关系。 //2.如果标准件不满足,则替代件开始计算并展示。 //注意:不管是否需要替代件,标准件都需要展开。 var sublist = returnlist.Where(s => s.parent_id == item.parent_id && s.num == item.num && s.level == item.level).OrderBy(c => c.substitute_all_num).ToList(); //sublist找出当前含替代关系的标准件和替代件。 if (item.substitute_mode == 0) { //替代 } else { //取代 } } else { //无替代关系 if (item.stock_state == 0) { item.use_qty = item.needCount; item.is_show = true; item.stock_state = 0; } else if (item.stock_state == 1) { // 缺料数量 item.lack_qty // 使用数量将库存全部使用了 item.use_qty = item.sqty; if (item.erp_cls == 2 || item.erp_cls == 3) { //委外、外购 //生成委外工单、采购申请单 //得到单据到货时间。 //todo:初步设置为7天到货期,后期根据实际业务来补充修改。 item.kitting_time = DateTime.Now.AddDays(7); } else if (item.erp_cls == 1) { //自制 //调用产能计算,得到物料自制后的齐套时间。 //todo:初步设置为7天完成,等沟通调用方法,来修改此处。 item.kitting_time = DateTime.Now.AddDays(7); } } } } /// /// 平铺物料缺料情况,展示所有主料+替代料的库存情况、缺料情况 /// /// /// /// public void CaclMaterialShortage(List returnlist, BomChildExamineDto item, int count) { var parent = returnlist.Find(s => s.id == item.parent_id); //当前物料总共需要数量 item.needCount = parent.needCount * item.qty; item.satisfyNum = item.sqty;//5 item.lack_qty = item.needCount - item.satisfyNum; //如果不满足,计算子物料,或者计算替代料 if (item.lack_qty < 0) { //库存满足 item.stock_state = 0; item.lack_qty = 0; } else { //找出自己的子集,存在子集则是BOM,不存在子集,则自己非BOM。 var childList = returnlist.Where(s => s.parent_id == item.id && s.type == item.type).ToList(); if (childList.Count > 0) { //自己是BOM foreach (var child in childList) { //循环子集判断库存 CaclMaterialShortage(returnlist, child, count); } } else { item.stock_state = 1; } } } //根据物料id获取物料3个提前期 private Task> GetLeadTime(List returnlist,long factoryid) { //ToDo:企业Id ProjectionDefinitionBuilder project = new ProjectionDefinitionBuilder(); return _ic_factory_details.Find(p => returnlist.Select(x => x.item_id).Contains(p.icitem_id) && p.factory_id == factoryid, project.Include(p => p.icitem_id).Include(p => p.production_leadtime).Include(p => p.stock_leadtime).Include(p => p.transportation_leadtime)).Result. Select(x => new ICItemLeadTimeDto { item_id = x.icitem_id,transportation_leadtime=x.transportation_leadtime,stock_leadtime=x.stock_leadtime,production_leadtime=x.production_leadtime }).AsQueryable().ToListAsync(); } /// /// 生成委外工单 /// /// /// private void CreateMesOOder(List returnlist, long factoryid) { List oOderList = new List(); foreach (var item in returnlist) { mes_oorder oOrder = new mes_oorder(); oOrder.GenerateNewId(); oOrder.oorder_no =getOrderNum("WW");//生产工单编号 oOrder.oorder_type = "委外工单";//生产工单类型 oOrder.oorder_date = DateTime.Now;//委外订单日期 oOrder.oorder_state = "已提交";//订单状态 oOrder.ooentry_prd = 10000;//生产组织 oOrder.ooentry_prdname = "1000";//生产组织名称 oOrder.ooentry_wrkc = 10000;//工作中心id oOrder.ooentry_wrkcname = "10001";//工作中心名称 oOrder.planner_num = "wwww";//计划员工号 oOrder.planner_name = "qqq";//计划员名称 oOrder.ooentry_stime = DateTime.Now;//计划开工日期 oOrder.ooentry_etime = DateTime.Now;//计划完工日期 oOrder.product_code = "产品代码";//产品代码 oOrder.ffms_number = "1000";//fms旧料号 oOrder.product_name = "test";//产品名称 oOrder.specification_model ="";//规格型号 oOrder.bom_number = "";//bom编码 oOrder.unit ="";//单位 oOrder.morder_progress ="";//工单进度 oOrder.morder_production_number = 120;//工单生产数量(计划数量) oOrder.need_number = 11;//需求数量 oOrder.remaining_number = 11;//剩余可用数量 oOrder.work_number = 11;//报工数量 oOrder.inspection_number = 11;//报检数量 oOrder.qualified_number = 22;//合格数量 oOrder.inventory_number = 22;//入库数量 oOrder.notice_qty = 22;//已开通知单数量 oOrder.moentry_on = 22;//启动状态 oOrder.start_time =DateTime.Now;//开始时间 oOrder.pause_time = DateTime.Now;//最近暂停时间 oOrder.restart_time = DateTime.Now;//最近重启时间 oOrder.project_name = "22";//项目名称 oOrder.sent_status = 22;//发料状态 1-待发料 2-已发料 oOrder.production_unit = "ge";//加工单位 oOrder.production_unit_code = "元";//加工单位编码 oOrder.need_icitem_status =1;//所需物料是否充足 1-充足 0-缺料 oOderList.Add(oOrder); } _mes_oorder.InsertMany(oOderList); } /// /// 生成采购申请单 /// /// /// /// 1委外采购申请单,2采购申请单 private void CreateSRMPR(List returnlist, long factoryid,int orderType) { List prList=new List(); foreach(var item in returnlist) { srm_pr_main srm_Pr = new srm_pr_main(); srm_Pr.GenerateNewId(); srm_Pr.pr_billno = "";//pr单号 srm_Pr.pr_mono = "";//关联工单号 srm_Pr.entity_id = 1;//pr单号 srm_Pr.pr_purchaseid = 1001;//供应商id srm_Pr.pr_purchasenumber = "10000";//供应商编码 srm_Pr.pr_purchasename = "1000";//供应商名称 srm_Pr.pr_purchaser = "10000";//采购员 srm_Pr.pr_purchaser_num = "10001";//采购员工号(采购信息表) srm_Pr.pr_rqty = 20;//需求数量 srm_Pr.pr_aqty = 1000;//申请数量 srm_Pr.pr_sqty = 22;//建议数量 srm_Pr.icitem_id = 10001;//物料id srm_Pr.icitem_name = "test111";//物料名称 srm_Pr.pr_order_type = 1000;//单据类型 srm_Pr.pr_ssend_date = DateTime.Now;//系统建议下单日期 srm_Pr.pr_sarrive_date = DateTime.Now;//系统建议到达日期(建议到货日期) srm_Pr.pr_bsarrive_date = DateTime.Now;//采购员建议到货日期 srm_Pr.pr_oarrive_date = DateTime.Now;//订单到货日期 srm_Pr.pr_psend_date = DateTime.Now;//计划下单日期 srm_Pr.pr_parrive_date = DateTime.Now;//计划到达日期 srm_Pr.pr_rarrive_date = DateTime.Now;//需求到货日期 srm_Pr.pr_rparrive_date = DateTime.Now;//再计划到货日期 srm_Pr.pr_psend_date = DateTime.Now;//计划下单日期 srm_Pr.pr_pur_affirm_date = DateTime.Now;//采购确认到货日期 srm_Pr.pr_sysprice = 22;//系统价格(含税) srm_Pr.pr_orderprice = 22;//订单价格(含税) srm_Pr.pr_price = 22;//采购净价(不含税) srm_Pr.pr_rate = 22;//税率 srm_Pr.pr_unit = "元";//单位 srm_Pr.state = 22;//状态 srm_Pr.old_apply_aqty = 22;//已申请数量 srm_Pr.pr_type = 22;//申请类型 srm_Pr.currencytype = 22;//币种 srm_Pr.secInv_ratio = 22;//安全库存触发采购比例 srm_Pr.remark = "元";//备注 srm_Pr.pr_rreason = "元";//拒绝原因 prList.Add(srm_Pr); } _srm_pr_main.InsertMany(prList); } // 生成订单编号 字母+年月日+8位随机数+时间戳 private string getOrderNum(string preCode) { string Dates = DateTime.Now.ToString("yyyyMMdd");//获取当前时间 Random Rdm = new Random(Guid.NewGuid().GetHashCode());//随机数 TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);//时间戳 string newts = Convert.ToInt64(ts.TotalMilliseconds).ToString();//时间戳 string new_orderNum = preCode + Dates + Rdm.Next(0, 100000000) + newts; return new_orderNum; } } }