using System.Reflection; using JNPF; using JNPF.Common.Core.Manager; using JNPF.Common.Enums; using JNPF.Common.Extension; using JNPF.Common.Filter; using JNPF.Common.Security; using JNPF.DependencyInjection; using JNPF.DynamicApiController; using JNPF.Extras.CollectiveOAuth.Models; using JNPF.FriendlyException; using JNPF.Logging; using JNPF.Systems.Entitys.Permission; using JNPF.Systems.Entitys.System; using JNPF.Systems.Interfaces.System; using JNPF.VisualDev; using JNPF.VisualDev.Entitys.Dto.VisualDevModelData; using JNPF.VisualDev.Interfaces; using Mapster; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using SQLitePCL; using SqlSugar; using Tnb.BasicData; using Tnb.BasicData.Entities; using Tnb.BasicData.Entities.Dto; using Tnb.Common.Extension; using Tnb.EquipMgr.Entities; using Tnb.PerMgr.Entities; using Tnb.ProductionMgr.Entities; using Tnb.ProductionMgr.Entities.Dto; using Tnb.ProductionMgr.Entities.Dto.PrdManage; using Tnb.ProductionMgr.Entities.Enums; using Tnb.ProductionMgr.Interfaces; using Tnb.QcMgr.Entities; using Tnb.QcMgr.Entities.Enums; using Tnb.QcMgr.Interfaces; using Tnb.WarehouseMgr.Entities.Configs; using Tnb.Common.Utils; using Tnb.Common.Redis; using Tnb.WarehouseMgr.Entities.Consts; using JNPF.Extras.CollectiveOAuth.Utils; using JNPF.Systems.Interfaces.Permission; using Tnb.WarehouseMgr.Entities; using Tnb.WarehouseMgr.Entities.Dto; using Tnb.WarehouseMgr.Entities.Dto.Inputs; using Tnb.WarehouseMgr.Interfaces; using Tnb.WarehouseMgr; using Tnb.WarehouseMgr.Entities.Enums; using Tnb.ProductionMgr.Entities.Entity; using Tnb.ProductionMgr.Helpers; using Tnb.BasicData.Interfaces; // using Tnb.PerMgr.Entities; namespace Tnb.ProductionMgr { [ApiDescriptionSettings(Tag = ModuleConst.Tag, Area = ModuleConst.Area, Order = 700)] [Route("api/[area]/[controller]/[action]")] [OverideVisualDev(ModuleId)] public class PrdMoTaskService : IOverideVisualDevService, IPrdMoTaskService, IDynamicApiController, ITransient { private const string ModuleId = "25567924238373"; private const string MoModuleId = "25018860321301"; private readonly ISqlSugarRepository _repository; private readonly IUserManager _userManager; private readonly IDictionaryDataService _dictionaryDataService; private readonly IRunService _runService; private readonly IVisualDevService _visualDevService; private static Dictionary _dicDefect = new(); private static readonly Dictionary _dicWorkLine = new(); private static readonly Dictionary _dicProcess = new(); private readonly ISqlSugarClient _db; private ISqlSugarClient _db2; private ISqlSugarClient _db3; private readonly IBillRullService _billRuleService; private readonly IPrdInstockService _prdInstockService; private readonly WmsPrdInstockHService _wmsPrdInstockHService; private readonly IOrganizeService _organizeService; private readonly IQcCheckPlanService _qcCheckPlanService; private readonly IWmsCarryService _wmsCarryService; private readonly ElevatorControlConfiguration _eleCtlCfg = App.Configuration.Build(); private readonly RedisData _redisData; private static SemaphoreSlim prdreportSemaphore = new(1); private readonly IThirdApiRecordService _thirdApiRecordService; public OverideVisualDevFunc OverideFuncs { get; } = new OverideVisualDevFunc(); public PrdMoTaskService( ISqlSugarRepository repository, IUserManager userManager, IDictionaryDataService dictionaryDataService, IRunService runService, IWmsCarryService wmsCarryService, IBillRullService billRullService, IPrdInstockService prdInstockService, IOrganizeService organizeService, WmsPrdInstockHService wmsPrdInstockHService, IVisualDevService visualDevService, IThirdApiRecordService thirdApiRecordService, IQcCheckPlanService qcCheckPlanService ) { _repository = repository; _userManager = userManager; _dictionaryDataService = dictionaryDataService; _runService = runService; _visualDevService = visualDevService; _organizeService = organizeService; _db = _repository.AsSugarClient(); OverideFuncs.DeleteAsync = Delete; OverideFuncs.GetListAsync = GetList; _billRuleService = billRullService; _prdInstockService = prdInstockService; _qcCheckPlanService = qcCheckPlanService; _wmsCarryService = wmsCarryService; _thirdApiRecordService = thirdApiRecordService; _wmsPrdInstockHService = wmsPrdInstockHService; } #region Get /// /// 根据产品ID获取模具列表 /// /// /// ///
return results: ///
[ ///
{ ///
mold_code:模具编号 ///
mold_name:模具名称 ///
item_name:产品名称 ///
item_code:产品编号 ///
cavity_qty:模穴数 ///
} ///
] ///
[HttpGet("{materialId}")] public async Task GetMoldListByItemId(string materialId) { List result = new(); result = await _db.Queryable() .InnerJoin((a, b) => a.mold_id == b.id) .InnerJoin((a, b, c) => a.material_id == c.id) .LeftJoin((a,b,c,d)=>d.Id==b.mold_status) .LeftJoin(_db.SqlQueryable("select * from tool_mold_requisition where id in (select max(id) from tool_mold_requisition group by mold_id)"),(a,b,c,d,e)=>b.id==e.mold_id) .LeftJoin((a,b,c,d,e,f)=>e.equip_id==f.id) .LeftJoin((a,b,c,d,e,f,g)=>e.mo_task_id==g.id) .Where((a, b, c) => a.material_id == materialId) .OrderBy((a,b)=>b.mold_code) .Select((a, b, c,d,e,f,g) => new Tnb.ProductionMgr.Entities.Dto.MoldListOutput { mold_id = b.id, mold_code = b.mold_code, mold_name = b.mold_name, mold_type_code = b.mold_type_code, material_name = c.name, material_code = c.code, mold_status = d.FullName, available_stations = SqlFunc.Subqueryable().Where(it => it.mold_id == a.id).Count(), equip_name = f.name, complete_qty = SqlFunc.IsNull(g.reported_work_qty, 0) + SqlFunc.IsNull(g.scrap_qty, 0), scheduled_qty = SqlFunc.IsNull(g.scheduled_qty, 0) }).ToListAsync(); return result; } /// /// 根据模具Id获取设备列表 /// /// /// [HttpGet("{moldId}")] public async Task GetEquipmentListByMoldId(string moldId) { List items = await _db.Queryable().InnerJoin((a, b) => a.equipment_id == b.id) .Where((a, b) => a.mold_id == moldId) .OrderBy((a,b)=>b.code) .Select((a, b) => new Entities.Dto.EquipmentListOutput { eqp_id = b.id, eqp_code = b.code, eqp_type_code = SqlFunc.Subqueryable().Where(iit => iit.id == b.equip_type_id).Select(iit => iit.name), eqp_machine_num = b.eqp_machine_num, tonnage = b.tonnage, task_list_qty = SqlFunc.Subqueryable().Where(x => x.eqp_id == b.id && (x.mo_task_status==DictConst.ToBeStartedEnCode || x.mo_task_status==DictConst.ToBeScheduledEncode || x.mo_task_status==DictConst.InProgressEnCode || x.mo_task_status==DictConst.MoStatusPauseCode)).Count(), estimated_end_date = SqlFunc.Subqueryable().Where(x => x.eqp_id == b.id && (x.mo_task_status==DictConst.ToBeStartedEnCode || x.mo_task_status==DictConst.ToBeScheduledEncode || x.mo_task_status==DictConst.InProgressEnCode || x.mo_task_status==DictConst.MoStatusPauseCode)).Max(x=>x.create_time) }).Mapper(x => { x.first_date = x.estimated_end_date.HasValue ? x.estimated_end_date.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""; }).ToListAsync(); return items; } /// /// 工单调整-生产任务重新排序 /// /// 设备ID /// 排序后生产任务列表 /// /// returns: ///
[ ///
{ ///
no:生产序号 ///
mo_id:工单编号 ///
group_flag:同组标识 ///
plan_qty:计划生产数量 ///
comple_qty:完成数量 ///
item_name:产品名称 ///
mold_code:模具编号 ///
} ///
] ///
[HttpGet("{eqpId}")] public async Task PrdTaskSort(string eqpId) { Dictionary taskStatusDic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId); List list = await _repository.AsSugarClient().Queryable() .LeftJoin((a, b) => a.mo_id == b.id) .LeftJoin((a, b, c) => a.material_id == c.id) .LeftJoin((a, b, c, d) => a.mold_id == d.id) .Where((a, b, c, d) => a.eqp_id == eqpId) .OrderBy((a, b, c, d) => a.estimated_start_date) .Select((a, b, c, d) => new PrdTaskSortOutput { mo_status_code = a.mo_task_code, status = a.mo_task_status, group_flag = a.group_flag, plan_qty = b.plan_qty, comple_qty = a.complete_qty, item_name = c.name, mold_code = d.mold_code, }) .ToListAsync(); List data = list.Select((x, idx) => new PrdTaskSortOutput { no = idx + 1, mo_status_code = x.mo_status_code, status = taskStatusDic.ContainsKey(x.status) ? taskStatusDic[x.status].ToString() : "", group_flag = x.group_flag, plan_qty = x.plan_qty, comple_qty = x.comple_qty, item_name = x.item_name, mold_code = x.mold_code, }) .ToList(); return data; } /// /// 查看生产任务操作记录 /// /// 任务ID /// [HttpGet("{taskId}")] public async Task GetMoOperRecord(string taskId) { List list = await _repository.AsSugarClient().Queryable().Where(it => it.mo_task_id == taskId).ToListAsync(); List data = list.Adapt>(); Dictionary dic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId); _repository.AsSugarClient().ThenMapper(data, x => { x.statusName = dic.ContainsKey(x.status) ? dic[x.status].ToString() : x.status; x.schedule_type = _repository.AsSugarClient().Queryable().Single(y => y.id == x.mo_task_id).schedule_type; }); return data; } /// /// 获取自检报废批次记录 /// /// 任务单Id /// [HttpGet("{moTaskId}")] public async Task GetScarpStatRecord(string moTaskId) { PrdMoTaskDefectOutput output = new(); ISqlSugarClient db = _repository.AsSugarClient(); if (_dicDefect.Count < 1) { _dicDefect = await db.Queryable().ToDictionaryAsync(x => x.id, x => x.defect_type_name); } output.mo_task_code = (await db.Queryable().FirstAsync(it => it.id == moTaskId))?.mo_task_code; List defects = await db.Queryable().Where(it => it.mo_task_id == moTaskId).ToListAsync(); List users = await db.Queryable().ToListAsync(); if (defects?.Count > 0) { output.batchItems = defects.GroupBy(g => new { g.batch, g.create_id }).Select(t => new BatchItem { scrap_qty = t.Sum(d => d.defective_item_qty), batch = t.Key.batch, create_time = t.Key.batch.ParseToDateTime().ToString("yyyy-MM-dd HH:mm:ss"), create_name = users.First(x => x.Id == t.Key.create_id)?.RealName ?? "", categoryItems = t.GroupBy(g => g.defective_cagetory_id).Select(c => new CategoryItem { name = _dicDefect[c.Key]?.ToString(), qty = c.Sum(d => d.defective_item_qty), defectItems = c.Select(d => new DefectItem { name = d.defective_item, qty = d.defective_item_qty, }).ToList(), }).ToList(), }).ToList(); } return output; } /// /// 根据工单Id获取任务单列表 /// /// /// /// /// output: ///
{ ///
mo_task_code:生产任务单号 ///
material_code:物料编码 ///
mold_code:模具编码 ///
mold_name:模具名称 ///
eqp_code:设备编码 ///
eqp_name:设备名称 ///
eqp_type_code:设备型号 ///
mo_task_qty:任务单数量 ///
mo_task_status:任务状态 ///
scheduled_qty:计划生产数量 ///
complete_qty:完成数量 ///
estimated_start_date:预计开工时间 ///
estimated_end_date:预计完工时间 ///
} ///
[HttpGet("{moId}")] public async Task GetPrdTaskInfoByMoId(string moId, int schedType = 1) { List result = new(); Dictionary dic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId); result = schedType == 1 ? await _db.Queryable().LeftJoin((a, b) => a.mo_id == b.id) .LeftJoin((a, b, c) => a.material_id == c.id) .LeftJoin((a, b, c, d) => a.mold_id == d.id) .LeftJoin((a, b, c, d, e) => a.eqp_id == e.id) .Where((a, b, c, d, e) => a.mo_id == moId) .OrderByDescending((a, b, c, d, e) => a.create_time) .Select((a, b, c, d, e) => new PrdMoTaskOutput { mo_task_code = a.mo_task_code, mo_task_status = a.mo_task_status, mold_code = d.mold_code, mold_name = d.mold_name, material_code = c.code, material_name = c.name, eqp_code = e.code, eqp_name = e.name, eqp_type_code = SqlFunc.Subqueryable().Where(it => it.id == e.equip_type_id).Select(it => it.code), mo_task_qty = SqlFunc.Subqueryable().Where(a => a.mo_id == moId).Count(), estimated_start_date = a.estimated_start_date.Value.ToString(DbTimeFormat.SS), estimated_end_date = a.estimated_end_date.Value.ToString(DbTimeFormat.SS), plan_qty = a.scheduled_qty, complete_qty = SqlFunc.IsNull(a.reported_work_qty, 0) + SqlFunc.IsNull(a.scrap_qty, 0), process_code = SqlFunc.Subqueryable().Where(it => it.id == a.process_id).Select(it => it.process_code), process_name = SqlFunc.Subqueryable().Where(it => it.id == a.process_id).Select(it => it.process_name), create_time = a.create_time == null ? "" : a.create_time.Value.ToString(DbTimeFormat.SS), }) .Mapper(it => { it.mo_task_status = dic.ContainsKey(it.mo_task_status) ? dic[it.mo_task_status].ToString() : ""; }) .ToListAsync() : await _db.Queryable().LeftJoin((a, b) => a.mo_id == b.id) .LeftJoin((a, b, c) => a.material_id == c.id) .LeftJoin((a, b, c, d) => a.workline_id == d.Id) .LeftJoin((a, b, c, d, e) => a.process_id == e.id) .Where((a, b, c, d) => (b.id == moId || b.parent_id == moId) && SqlFunc.IsNullOrEmpty(a.parent_id)) .OrderByDescending((a, b, c, d, e) => a.create_time) .Select((a, b, c, d, e) => new PrdMoTaskOutput { mo_task_code = a.mo_task_code, mo_task_status = a.mo_task_status, workline_code = d.EnCode, workline_name = d.FullName, material_code = c.code, material_name = c.name, process_code = e.process_code, process_name = e.process_name, mo_task_qty = SqlFunc.Subqueryable().Where(a => a.mo_id == moId).Count(), estimated_start_date = a.estimated_start_date.Value.ToString(DbTimeFormat.SS), estimated_end_date = a.estimated_end_date.Value.ToString(DbTimeFormat.SS), plan_qty = a.scheduled_qty, complete_qty = SqlFunc.IsNull(a.reported_work_qty, 0) + SqlFunc.IsNull(a.scrap_qty, 0), create_time = a.create_time == null ? "" : a.create_time.Value.ToString(DbTimeFormat.SS), }) .Mapper(it => { it.mo_task_status = dic.ContainsKey(it.mo_task_status) ? dic[it.mo_task_status].ToString()! : ""; }) .ToListAsync(); return result; } /// ///组装、包装 获取待下发任务列表 /// /// [HttpGet] public async Task GetPackScheldToBeIssueList([FromQuery] PackScheldToBeIssueListInput input) { Dictionary dic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId); List result = await _db.Queryable() .LeftJoin((a, b) => a.workline_id == b.Id) .LeftJoin((a, b, c) => a.mo_id == c.id) .LeftJoin((a, b, c, d) => a.bom_id == d.id) .LeftJoin((a,b,c,d,e)=>a.material_id==e.id) .WhereIF(!string.IsNullOrEmpty(input.mo_task_code), (a, b, c, d) => a.mo_task_code.Contains(input.mo_task_code)) .Where((a, b, c, d) => a.schedule_type == 2 && string.IsNullOrEmpty(a.parent_id)) .OrderByDescending(a => a.create_time) .Select((a, b, c, d,e) => new PackSechelToBeIssueListOutput { mo_task_id = a.id, mo_task_code = a.mo_task_code, material_id = a.material_id, material_code = e.code, material_name = e.name, material_specification = e.material_specification, material_standard = e.material_standard, workline_id = a.workline_id, workline_code = b.EnCode, workline_name = b.FullName, mo_task_status = a.mo_task_status, // scheduled_qty = SqlFunc.Subqueryable().Where(it => it.mo_id == a.mo_id).Sum(it => it.scheduled_qty), scheduled_qty = a.scheduled_qty, plan_qty = SqlFunc.Subqueryable().Where(it => it.id == a.mo_id).Select(it => it.plan_qty), complete_qty = a.last_process_complete_qty, estimated_start_date = a.estimated_start_date == null ? null : a.estimated_start_date.Value.ToString(DbTimeFormat.SS), estimated_end_date = a.estimated_end_date == null ? null : a.estimated_end_date.Value.ToString(DbTimeFormat.SS), bom_id = d.id, bom_version = d.version, create_time = a.create_time==null ? "" : a.create_time.Value.ToString(DbTimeFormat.SS), dayshift_worker_id = a.dayshift_worker_id, dayshiftafter_worker_id = a.dayshiftafter_worker_id, nightshift_worker_id = a.nightshift_worker_id, nightshiftafter_worker_id = a.nightshiftafter_worker_id, }) .Mapper(it => it.mo_task_status = dic.ContainsKey(it.mo_task_status) ? dic[it.mo_task_status].ToString()! : "") .ToListAsync(); List userIdList = result.Select(x => x.dayshift_worker_id).Distinct().ToList(); userIdList.AddRange(result.Select(x => x.dayshiftafter_worker_id).Distinct().ToList()); userIdList.AddRange(result.Select(x => x.nightshift_worker_id).Distinct().ToList()); userIdList.AddRange(result.Select(x => x.nightshiftafter_worker_id).Distinct().ToList()); List userEntities = await _db.Queryable().Where(x=>userIdList.Contains(x.Id)).ToListAsync(); foreach (var item in result) { item.dayshift_worker_id = userEntities.Find(x=>x.Id==item.dayshift_worker_id)?.RealName ?? item.dayshift_worker_id; item.dayshiftafter_worker_id = userEntities.Find(x=>x.Id==item.dayshiftafter_worker_id)?.RealName ?? item.dayshiftafter_worker_id; item.nightshift_worker_id = userEntities.Find(x=>x.Id==item.nightshift_worker_id)?.RealName ?? item.nightshift_worker_id; item.nightshiftafter_worker_id = userEntities.Find(x=>x.Id==item.nightshiftafter_worker_id)?.RealName ?? item.nightshiftafter_worker_id; } return result; } /// /// 根据生产任务ID获取子任务列表 /// /// /// [HttpGet("{mo_task_id}")] public async Task GetSubMoTaskListByTaskId(string mo_task_id) { Dictionary dic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId); List result = await _db.Queryable() .LeftJoin((a, b) => a.material_id == b.id) .LeftJoin((a, b, c) => a.workline_id == c.Id) .LeftJoin((a, b, c, d) => a.mo_id == d.id) .LeftJoin((a, b, c, d, e) => a.process_id == e.id) .LeftJoin((a, b,c,d,e,f) => a.workstation_id == f.Id) // .LeftJoin((a, b,c,d,e,f,g)=>a.worker_id==g.Id) .Where((a, b, c, d) => a.parent_id == mo_task_id) .Select((a, b, c, d, e,f) => new PackSechelToBeIssueListOutput { mo_task_id = a.id, mo_task_code = a.mo_task_code, material_code = b.code, material_name = b.name, workline_code = c.EnCode, workline_name = c.FullName, mo_task_status = a.mo_task_status, batch = a.batch, workstation_name = f.FullName, // worker_name = g.RealName, scheduled_qty = a.scheduled_qty, plan_qty = d.plan_qty, process_task_qty = a.process_task_qty, complete_qty = SqlFunc.IsNull(a.reported_work_qty, 0) + SqlFunc.IsNull(a.scrap_qty, 0), estimated_start_date = a.estimated_start_date == null ? null : a.estimated_start_date.Value.ToString(DbTimeFormat.MM), estimated_end_date = a.estimated_end_date == null ? null : a.estimated_end_date.Value.ToString(DbTimeFormat.MM), process_name = e.process_name, bom_version = SqlFunc.Subqueryable().Where(it => it.material_id == a.material_id).Select(it => it.version), dayshift_worker_id = a.dayshift_worker_id, dayshiftafter_worker_id = a.dayshiftafter_worker_id, nightshift_worker_id = a.nightshift_worker_id, nightshiftafter_worker_id = a.nightshiftafter_worker_id, }) .Mapper(it => it.mo_task_status = dic.ContainsKey(it.mo_task_status) ? dic[it.mo_task_status].ToString()! : "") .OrderBy(a => a.mo_task_code, OrderByType.Asc) .ToListAsync(); List userIdList = result.Select(x => x.dayshift_worker_id).Distinct().ToList(); userIdList.AddRange(result.Select(x => x.dayshiftafter_worker_id).Distinct().ToList()); userIdList.AddRange(result.Select(x => x.nightshift_worker_id).Distinct().ToList()); userIdList.AddRange(result.Select(x => x.nightshiftafter_worker_id).Distinct().ToList()); List userEntities = await _db.Queryable().Where(x=>userIdList.Contains(x.Id)).ToListAsync(); foreach (var item in result) { item.dayshift_worker_id = userEntities.Find(x=>x.Id==item.dayshift_worker_id)?.RealName ?? item.dayshift_worker_id; item.dayshiftafter_worker_id = userEntities.Find(x=>x.Id==item.dayshiftafter_worker_id)?.RealName ?? item.dayshiftafter_worker_id; item.nightshift_worker_id = userEntities.Find(x=>x.Id==item.nightshift_worker_id)?.RealName ?? item.nightshift_worker_id; item.nightshiftafter_worker_id = userEntities.Find(x=>x.Id==item.nightshiftafter_worker_id)?.RealName ?? item.nightshiftafter_worker_id; } return result; } // /// // /// 获取组装、包装 待排产工单树形列表 // /// // /// // [HttpGet] // public async Task GetUnSchedulingList([FromQuery] VisualDevModelListQueryInput input) // { // List trees = new(); // VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(MoModuleId, true); // var data = await _runService.GetListResult(templateEntity, input); // // // if (data?.list?.Count > 0) // { // var parentIdField = nameof(PrdMo.parent_id); // var nodes = data.list.Where(it => it.ContainsKey(parentIdField) && it[parentIdField].IsNullOrEmpty()).ToList(); // foreach (var row in nodes) // { // var pkName = "material_id_id"; // var dic = row.ToDictionary(x => x.Key, x => x.Value); // // PrdMoTreeOutput node = DictionaryToObject(row); // node.parentId = "0"; // node.mo_id = node.id; // if (dic.ContainsKey(pkName)) // { // var materialId = dic[pkName]?.ToString(); // var material = await _db.Queryable().FirstAsync(it => it.id == materialId); // node.material_id_id = materialId; // node.material_code = material?.code; // node.material_name = material?.name; // node.material_standard = material?.material_standard; // } // // // var scheldQtyCol = nameof(PrdMo.scheduled_qty); // // node.scheduled_qty = _db.Queryable().Where(it => it.mo_id == dic["id"].ToString()).Sum(it => it.scheduled_qty)?.ToString(); // var queryObj = new { parent_id = node.id }; // input.superQueryJson = ""; // input.queryJson = queryObj.ToJsonString(); // var subData = await _runService.GetListResult(templateEntity, input); // if (subData?.list?.Count > 0) // { // var childNodes = new List(); // foreach (var item in subData.list) // { // dic = item.ToDictionary(x => x.Key, x => x.Value); // PrdMoTreeOutput subNode = DictionaryToObject(item); // subNode.parentId = node.id; // subNode.mo_id = subNode.id; // if (dic.ContainsKey(pkName)) // { // var materialId = dic[pkName]?.ToString(); // var material = await _db.Queryable().FirstAsync(it => it.id == materialId); // subNode.material_id_id = materialId; // subNode.material_code = material?.code; // subNode.material_name = material?.name; // subNode.material_standard = material?.material_standard; // } // node.scheduled_qty = _db.Queryable().Where(it => it.mo_id == dic["id"].ToString()).Sum(it => it.scheduled_qty)?.ToString(); // childNodes.Add(subNode); // } // trees.AddRange(childNodes); // } // trees.Add(node); // } // } // var treeList = trees.ToTree(); // var list = treeList.Skip(input.currentPage - 1).Take(input.pageSize).ToList(); // SqlSugarPagedList pagedList = new() // { // list = treeList, // pagination = new Pagination // { // CurrentPage = input.currentPage, // PageSize = input.pageSize, // Total = treeList.Count // } // }; // return PageResult.SqlSugarPageResult(pagedList); // } /// /// 获取组装、包装 待排产工单树形列表 /// /// [HttpGet] public async Task GetUnSchedulingList([FromQuery] VisualDevModelListQueryInput input) { Dictionary? queryJson = !string.IsNullOrEmpty(input.queryJson) ? JsonConvert.DeserializeObject>(input.queryJson) : new Dictionary(); List moStatusList = new(); if (queryJson != null && queryJson.ContainsKey("mo_stauts")) { moStatusList = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(queryJson["mo_status"])); } List moTypeList = new(); if (queryJson != null && queryJson.ContainsKey("mo_type")) { moTypeList = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(queryJson["mo_type"])); } string? moCode = queryJson != null && queryJson.ContainsKey("mo_code") ? queryJson["mo_code"].ToString() : ""; string? combineMoCode = queryJson != null && queryJson.ContainsKey("combine_mo_code") ? queryJson["combine_mo_code"].ToString() : ""; ISqlSugarClient db = _repository.AsSugarClient(); SqlSugarPagedList result = await db.Queryable() .LeftJoin((a, b) => a.material_id == b.id) .LeftJoin((a, b, c) => a.mo_type == c.Id) .LeftJoin((a, b, c, d) => a.mo_status == d.Id) .LeftJoin((a, b, c, d, e) => a.create_id == e.Id) .WhereIF(moStatusList != null && moStatusList.Count > 0, (a, b, c, d, e) => moStatusList.Contains(a.mo_status)) .WhereIF(moTypeList != null && moTypeList.Count > 0, (a, b, c, d, e) => moTypeList.Contains(a.mo_type)) .WhereIF(!string.IsNullOrEmpty(moCode), (a, b, c, d, e) => a.mo_code.Contains(moCode)) .WhereIF(!string.IsNullOrEmpty(combineMoCode), (a, b, c, d, e) => a.combine_mo_code.Contains(combineMoCode)) .Where((a, b, c, d, e) => SqlFunc.IsNullOrEmpty(a.parent_id)) .OrderByDescending((a, b, c, d, e) => a.create_time) .Select((a, b, c, d, e) => new PrdMoListTreeOutput { org_id = a.org_id, mo_id = a.id, mo_code = a.mo_code, material_code = b.code, material_name = b.name, material_specification = b.material_specification, material_standard = b.material_standard, mo_type = c.FullName, mo_status = d.FullName, plan_qty = a.plan_qty.Value.ToString(), input_qty = a.input_qty.Value.ToString(), complete_qty = a.complete_qty.Value.ToString(), scrap_qty = a.scrap_qty.Value.ToString(), plan_start_date = a.plan_start_date.Value.ToString("yyyy-MM-dd"), plan_end_date = a.plan_end_date.Value.ToString("yyyy-MM-dd"), is_create_dispatch = a.is_create_dispatch == 0 ? "否" : "是", production_linecode = a.production_linecode, is_merge = a.is_merge == 0 ? "否" : "是", combine_mo_code = a.combine_mo_code, time_stamp = a.time_stamp, create_id = e.RealName, create_time = a.create_time.Value.ToString("yyyy-MM-dd : HH:mm:ss"), material_id = b.code, material_id_id = a.material_id, scheduled_qty = a.scheduled_qty.Value.ToString(), parent_id = "0", id = a.id, hasChildren = SqlFunc.Subqueryable().Where(x => x.parent_id == a.id).Any(), num = SqlFunc.Subqueryable().Where(x => x.parent_id == a.id).Count(), isLeaf = SqlFunc.Subqueryable().Where(x => x.parent_id == a.id).Any(), children = SqlFunc.Subqueryable() .LeftJoin((h, i) => h.material_id == i.id) .LeftJoin((h, i, j) => h.mo_type == j.Id) .LeftJoin((h, i, j, k) => h.mo_status == k.Id) .LeftJoin((h, i, j, k, l) => h.create_id == l.Id) .Where((h, i, j, k, l) => a.id == h.parent_id).ToList((h, i, j, k, l) => new PrdMoListTreeOutput() { org_id = h.org_id, mo_id = h.id, mo_code = h.mo_code, material_code = i.code, material_name = i.name, material_standard = i.material_specification, mo_type = j.FullName, mo_status = k.FullName, plan_qty = h.plan_qty.Value.ToString(), input_qty = h.input_qty.Value.ToString(), complete_qty = h.complete_qty.Value.ToString(), scrap_qty = h.scrap_qty.Value.ToString(), plan_start_date = h.plan_start_date.Value.ToString("yyyy-MM-dd"), plan_end_date = h.plan_end_date.Value.ToString("yyyy-MM-dd"), is_create_dispatch = h.is_create_dispatch == 0 ? "否" : "是", production_linecode = h.production_linecode, is_merge = h.is_merge == 0 ? "否" : "是", combine_mo_code = h.combine_mo_code, time_stamp = h.time_stamp, create_id = l.RealName, create_time = h.create_time.Value.ToString("yyyy-MM-dd : HH:mm:ss"), material_id = i.code, material_id_id = h.material_id, scheduled_qty = h.scheduled_qty.Value.ToString(), parent_id = a.id, id = h.id, hasChildren = false, num = 0, isLeaf = true, }) }).ToPagedListAsync(input.currentPage, input.pageSize); return PageResult.SqlSugarPageResult(result); } #endregion #region Post /// /// 生产工单-生产排产 /// /// ///
{ ///
Id:生产任务主键Id ///
MoType:工单类型 1、注塑/挤出 2、组装/包装 ///
MoId:工单Id ///
ItemId:产品编号 ///
ItemName:产品名称 ///
MoldId:模具Id ///
MoldName:模具名称 ///
EqpId:设备Id ///
EqpName:设备名称 ///
LineId:产线编号 ///
LineName:产线名称 ///
} /// /// [HttpPost] public async Task ProductionScheduling(ProductionSchedulingCrInput input) { ISqlSugarClient db = _repository.AsSugarClient(); int row = -1; if (input.schedule_type.HasValue) { if (input.schedule_type.Value == 1) //注塑、基础排产 { PrdMo? mo = await db.Queryable().FirstAsync(it => it.id == input.mo_id); if (mo.mo_status == DictConst.MoCloseId || mo.mo_status == DictConst.MoCompleteId) throw Oops.Bah("状态错误"); BasMbomProcess? basMbomProcess = null; if (!string.IsNullOrEmpty(input.bom_id)) { basMbomProcess = await db.Queryable().FirstAsync(x => x.mbom_id == input.bom_id); } PrdMoTask moTask = input.Adapt(); moTask.id = SnowflakeIdHelper.NextId(); moTask.create_id = _userManager.UserId; moTask.create_time = DateTime.Now; moTask.mo_task_status = DictConst.ToBeScheduledEncode; moTask.scheduled_qty = input.scheduled_qty; moTask.unit_id = mo.unit_id; moTask.mbom_process_id = basMbomProcess?.id ?? ""; moTask.process_id = basMbomProcess.process_id; if (!string.IsNullOrEmpty(input.eqp_id)) { OrganizeRelationEntity organizeRelationEntity = await db.Queryable() .Where(x => x.ObjectId == input.eqp_id && x.ObjectType == "Eqp").FirstAsync(); if (organizeRelationEntity == null || organizeRelationEntity.OrganizeId == "") { throw Oops.Bah("该设备没绑定工位"); } moTask.workstation_id = organizeRelationEntity?.OrganizeId ?? ""; } string? moCode = mo?.mo_code; string taskCode = await _billRuleService.GetBillNumber(Tnb.BasicData.CodeTemplateConst.PRDMOTASK_CODE); moTask.mo_task_code = taskCode; // var taskCode = await db.Queryable().Where(it => !string.IsNullOrEmpty(it.mo_task_code) && it.mo_task_code.Contains(moCode)).OrderByDescending(it => it.mo_task_code).Select(it => it.mo_task_code).FirstAsync(); // if (taskCode.IsNullOrEmpty()) // { // moTask.mo_task_code = $"{moCode}-01"; // } // else // { // var pos = taskCode.IndexOf("-", StringComparison.Ordinal); // if (pos > -1) // { // var num = taskCode.AsSpan().Slice(pos + 1).ToString().ParseToInt(); // var code = taskCode.AsSpan().Slice(0, pos).ToString(); // var n = (num + 1).ToString().PadLeft(2, '0'); // moTask.mo_task_code = $"{code}-{n}"; // } // } try { await db.Ado.BeginTranAsync(); row = await db.Insertable(moTask).ExecuteCommandAsync(); #region 质检模块 //质检 // TriggerPlanEntity entity = new() // { // materialid = moTask.material_id, // processid = moTask.process_id, // workid = moTask.workstation_id, // triggerevent = EnumTriggerEvent.首件检新的生产任务 // }; // await _qcCheckPlanService.CreateTask(entity); #endregion //根据工单号获取当前工单包含的已排产数 decimal? schedQty = db.Queryable().Where(it => it.mo_id == input.mo_id)?.Sum(d => d.scheduled_qty); if (mo != null) {//判断如果当前 工单的已排产数大于工单计划数量则更新工单状态为 已排产 // if (schedQty.HasValue && schedQty.Value >= mo.plan_qty) // { // mo.mo_status = DictConst.AlreadyId; // } // else // { // if (schedQty.HasValue) // mo.scheduled_qty = schedQty.Value; // } // row = await db.Updateable(mo).ExecuteCommandAsync(); _ = mo.scheduled_qty == null ? await _db.Updateable() .SetColumns(x => x.mo_status == DictConst.AlreadyId) .SetColumns(x => x.scheduled_qty == input.scheduled_qty) .Where(x => x.id == mo.id) .ExecuteCommandAsync() : await _db.Updateable().SetColumns(x => x.scheduled_qty == x.scheduled_qty + input.scheduled_qty) .Where(x => x.id == mo.id) .ExecuteCommandAsync(); } BasMaterial? material = await db.Queryable().FirstAsync(it => it.id == moTask.material_id); PrdTaskLog taskLog = new() { id = SnowflakeIdHelper.NextId(), mo_code = (await db.Queryable().FirstAsync(it => it.id == input.mo_id))?.mo_code!, eqp_code = (await db.Queryable().FirstAsync(it => it.id == input.eqp_id))?.code!, mold_code = (await db.Queryable().FirstAsync(it => it.id == input.mold_id))?.mold_code!, item_code = material?.code!, item_standard = material?.material_specification!, status = DictConst.ToBeScheduledEncode, operator_name = _userManager.RealName, create_id = _userManager.UserId, create_time = DateTime.Now, mo_task_id = moTask.id, mo_task_code = moTask.mo_task_code }; _ = await db.Insertable(taskLog).ExecuteCommandAsync(); //将生产任务插入到自检报废记录表 //var sacipRecord = new PrdMoTaskDefectRecord(); //sacipRecord.id = SnowflakeIdHelper.NextId(); //sacipRecord.material_code = material?.code!; //sacipRecord.material_name = material?.name!; //sacipRecord.eqp_code = (await db.Queryable().FirstAsync(it => it.id == moTask.eqp_id))?.code!; //sacipRecord.mold_name = (await db.Queryable().FirstAsync(it => it.id == moTask.mold_id))?.mold_name!; //sacipRecord.estimated_start_date = moTask.plan_start_date; //sacipRecord.estimated_end_date = moTask.plan_end_date; //sacipRecord.plan_qty = moTask.plan_qty; //sacipRecord.scrap_qty = moTask.scrap_qty; //sacipRecord.status = moTask.mo_task_status; //sacipRecord.create_id = _userManager.UserId; //sacipRecord.create_time = DateTime.Now; //sacipRecord.mo_task_id = moTask.id; //sacipRecord.mo_task_code = moTask.mo_task_code; //await db.Insertable(sacipRecord).ExecuteCommandAsync(); await db.Ado.CommitTranAsync(); } catch (Exception e) { Log.Error(e.Message,e); await db.Ado.RollbackTranAsync(); throw Oops.Bah(e.Message); } } else if (input.schedule_type.Value == 2) //组装、包装排产 { } } return row > 0; } /// /// 组装包装排产 /// /// /// /// [HttpPost] public async Task PackSchedling(PackSchedlingCrInput input) { int row = -1; try { await _db.Ado.BeginTranAsync(); PrdMoTask moTask = input.Adapt(); moTask.id = SnowflakeIdHelper.NextId(); moTask.create_id = _userManager.UserId; moTask.bom_id = input.bom_id; moTask.workroute_id = (await _db.Queryable().FirstAsync(it => it.id == input.bom_id))?.route_id; moTask.workline_id = input.workline_id; moTask.create_time = DateTime.Now; moTask.schedule_type = 2; moTask.mo_task_status = DictConst.ToBeScheduledEncode; moTask.estimated_start_date = input.estimated_start_date; moTask.estimated_end_date = input.estimated_end_date; moTask.scheduled_qty = input.scheduled_qty; PrdMo? mo = await _db.Queryable().FirstAsync(it => it.id == input.mo_id); moTask.unit_id = mo.unit_id; if (mo.mo_status == DictConst.MoCloseId || mo.mo_status == DictConst.MoCompleteId) throw Oops.Bah("状态错误"); // moTask.unit_id = mo.unit_id; string? moCode = mo?.mo_code; // var taskCode = await _db.Queryable().Where(it => string.IsNullOrEmpty(it.parent_id) && !string.IsNullOrEmpty(it.mo_task_code) && it.mo_task_code.Contains(moCode)) // .OrderByDescending(it => it.mo_task_code) // .Select(it => it.mo_task_code) // .FirstAsync(); string taskCode = await _billRuleService.GetBillNumber(Tnb.BasicData.CodeTemplateConst.PRDMOTASK_CODE); moTask.mo_task_code = taskCode; // if (taskCode is null || taskCode.IsNullOrEmpty()) // { // moTask.mo_task_code = $"{moCode}-01"; // } // else // { // var pos = taskCode?.IndexOf("-", StringComparison.Ordinal); // if (pos.HasValue && pos.Value > -1) // { // var num = taskCode.AsSpan().Slice(pos.Value + 1).ToString().ParseToInt(); // var code = taskCode.AsSpan().Slice(0, pos.Value).ToString(); // var n = (num + 1).ToString().PadLeft(2, '0'); // moTask.mo_task_code = $"{code}-{n}"; // } // } row = await _db.Insertable(moTask).ExecuteCommandAsync(); #region 质检模块 //质检 // TriggerPlanEntity entity = new() // { // materialid = moTask.material_id, // processid = moTask.process_id, // workid = moTask.workstation_id, // triggerevent = EnumTriggerEvent.首件检新的生产任务 // }; // await _qcCheckPlanService.CreateTask(entity); #endregion BasMaterial? material_h = await _db.Queryable().FirstAsync(it => it.id == moTask.material_id); //添加生产任务操作记录日志 PrdTaskLog taskLog = new() { id = SnowflakeIdHelper.NextId(), mo_code = (await _db.Queryable().FirstAsync(it => it.id == input.mo_id))?.mo_code!, item_code = material_h?.code!, item_standard = material_h?.material_specification!, status = DictConst.ToBeScheduledEncode, operator_name = _userManager.RealName, create_id = _userManager.UserId, create_time = DateTime.Now, mo_task_id = moTask.id, mo_task_code = moTask.mo_task_code! }; row = await _db.Insertable(taskLog).ExecuteCommandAsync(); //将生产任务插入到自检报废记录表 //var sacipRecord = new PrdMoTaskDefectRecord(); //sacipRecord.id = SnowflakeIdHelper.NextId(); //sacipRecord.material_code = material?.code!; //sacipRecord.material_name = material?.name!; //sacipRecord.eqp_code = (await db.Queryable().FirstAsync(it => it.id == moTask.eqp_id))?.code!; //sacipRecord.mold_name = (await db.Queryable().FirstAsync(it => it.id == moTask.mold_id))?.mold_name!; //sacipRecord.estimated_start_date = moTask.plan_start_date; //sacipRecord.estimated_end_date = moTask.plan_end_date; //sacipRecord.plan_qty = moTask.plan_qty; //sacipRecord.scrap_qty = moTask.scrap_qty; //sacipRecord.status = moTask.mo_task_status; //sacipRecord.create_id = _userManager.UserId; //sacipRecord.create_time = DateTime.Now; //sacipRecord.mo_task_id = moTask.id; //sacipRecord.mo_task_code = moTask.mo_task_code; //await db.Insertable(sacipRecord).ExecuteCommandAsync(); //根据工单号获取当前工单包含的已排产数 decimal? schedQty = _db.Queryable().Where(it => it.mo_id == input.mo_id)?.Sum(d => d.scheduled_qty); // if (mo != null) // {//判断如果当前 工单的已排产数大于工单计划数量则更新工单状态为 已排产 // if (schedQty.HasValue && schedQty.Value >= mo.plan_qty) // { // mo.mo_status = DictConst.AlreadyId; // await _db.Updateable(mo).ExecuteCommandAsync(); // } // else // { // if (schedQty.HasValue) // { // mo.scheduled_qty += schedQty.Value; // await _db.Updateable(mo).ExecuteCommandAsync(); // } // } // } if (mo != null) { _ = mo.scheduled_qty == null ? await _db.Updateable() .SetColumns(x => x.mo_status == DictConst.AlreadyId) .SetColumns(x => x.scheduled_qty == input.scheduled_qty) .Where(x => x.id == mo.id) .ExecuteCommandAsync() : await _db.Updateable().SetColumns(x => x.scheduled_qty == x.scheduled_qty + input.scheduled_qty) .Where(x => x.id == mo.id) .ExecuteCommandAsync(); } List subTaskList = await _db.Queryable() .LeftJoin((a, b) => a.id == b.mbom_id) .LeftJoin((a, b, c) => a.route_id == c.id) // .LeftJoin((a, b, c, d) => b.process_id == d.process_id && c.id == d.route_id) .LeftJoin((a, b, c, d) => b.route_detail_id == d.id) .LeftJoin((a, b, c, d, e) => a.id == e.mbom_id && e.mbom_process_id == b.id) .Where((a, b, c, d, e) => a.id == input.bom_id) .OrderBy((a, b, c, d, e) => b.ordinal) .Select((a, b, c, d, e) => new SubBomListOutput { version = a.version, unit_id = e.unit_id, route_id = c.id, process_id = b.process_id, material_id = SqlFunc.Subqueryable().Where(it => it.id == e.material_id).Select(it => it.id), num = e.num, molecule = e.molecule, denominator = e.denominator, ordinal = d.ordinal, mbom_process_id = b.id, }) .Mapper(it => it.output_qty = it.num.ParseToInt()) .ToListAsync(); if (subTaskList?.Count > 0) { List workstationIds = await _db.Queryable().Where(x => x.Category == DictConst.RegionCategoryStationCode && x.OrganizeIdTree.Contains(input.workline_id)).Select(x => x.Id).ToListAsync(); List subMoTasks = new(); List subMoTaskLogs = new(); foreach (SubBomListOutput? item in subTaskList) { BasMbomProcess basMbomProcess = await _db.Queryable().SingleAsync(x => x.id == item.mbom_process_id); List mbomProcessStationIds = JsonConvert.DeserializeObject(basMbomProcess.station).Select(x => x[^1]).ToList(); List? resultList = workstationIds.Intersect(mbomProcessStationIds).ToList(); PrdMoTask subMoTask = new() { mo_id = input.mo_id, material_id = item.material_id, schedule_type = 2, parent_id = moTask.id, bom_id = input.bom_id, process_id = item.process_id, mbom_process_id = item.mbom_process_id, workstation_id = resultList?.FirstOrDefault() ?? "", mo_task_status = DictConst.ToBeScheduledEncode, workroute_id = item.route_id, // unit_id = item.unit_id, unit_id = mo.unit_id, workline_id = input.workline_id }; subMoTask.material_id = item.material_id; subMoTask.scheduled_qty = input.scheduled_qty; subMoTask.process_task_qty = item.output_qty * moTask.scheduled_qty; subMoTask.estimated_start_date = input.estimated_start_date; subMoTask.estimated_end_date = input.estimated_end_date; subMoTask.create_id = _userManager.UserId; subMoTask.create_time = DateTime.Now; subMoTasks.Add(subMoTask); PrdTaskLog subTaskLog = new(); BasMaterial? subMaterial = await _db.Queryable().SingleAsync(x => x.id == item.material_id); subTaskLog.id = SnowflakeIdHelper.NextId(); subTaskLog.mo_code = (await _db.Queryable().FirstAsync(it => it.id == input.mo_id))?.mo_code!; subTaskLog.item_code = subMaterial?.code!; subTaskLog.item_standard = subMaterial?.material_specification!; subTaskLog.status = DictConst.ToBeScheduledEncode; subTaskLog.operator_name = _userManager.RealName; subTaskLog.create_id = _userManager.UserId; subTaskLog.create_time = DateTime.Now; subTaskLog.mo_task_id = subMoTask.id; subTaskLog.mo_task_code = subMoTask.mo_task_code!; subMoTaskLogs.Add(subTaskLog); } //根据生产任务编号生成子任务编号 if (moTask.mo_task_code!.IsNotEmptyOrNull()) { for (int i = 1; i <= subMoTasks.Count; i++) { string n = i.ToString(); subMoTasks[i - 1].mo_task_code = $"{moTask.mo_task_code}-{n.PadLeft(2, '0')}"; } } row = await _db.Insertable(subMoTasks).ExecuteCommandAsync(); _ = await _db.Insertable(subMoTaskLogs).ExecuteCommandAsync(); } await _db.Ado.CommitTranAsync(); } catch (Exception ex) { JNPF.Logging.Log.Error("组装包装排产时报错", ex); await _db.Ado.RollbackTranAsync(); throw Oops.Bah(ex.Message); } return row > 0; } /// /// 生产任务下发,开始 、结束、完成 /// /// 输入参数 /// /// /// [HttpPost] public async Task PrdTaskRelease(PrdTaskReleaseUpInput input) { int row = -1; if (input is null) { throw new ArgumentNullException(nameof(input)); } if (input.TaskIds is null) { throw new ArgumentNullException(nameof(input.TaskIds)); } // if (input.Behavior.IsNullOrWhiteSpace()) if (input.Behavior==null || input.Behavior.IsEmpty()) { throw new ArgumentException($"{nameof(input.Behavior)} not be null or empty"); } bool tranFlag = true; ISqlSugarClient db = null; if (_db2!=null) { tranFlag = false; db = _db2; } else { db = _repository.AsSugarClient(); } try { if(tranFlag) await db.Ado.BeginTranAsync(); List prdTaskList = new List(); //var taskList = await _db.Queryable().Where(it => input.TaskIds.Contains(it.id) && it.mo_task_status == DictConst.ToBeScheduledEncode).ToListAsync(); //if (taskList?.Count > 0) { static string SetTaskStatus(PrdTaskBehavior behavior) { return behavior switch { PrdTaskBehavior.Release => DictConst.ToBeStartedEnCode, PrdTaskBehavior.Start => DictConst.InProgressEnCode, PrdTaskBehavior.Closed => DictConst.ClosedEnCode, PrdTaskBehavior.Compled => DictConst.ComplatedEnCode, PrdTaskBehavior.Pause => DictConst.MoStatusPauseCode, _ => throw new NotImplementedException(), }; } PrdTaskBehavior behavior = input.Behavior.ToEnum(); string status = SetTaskStatus(behavior); List? list = await db.Queryable().Where(it => input.TaskIds.Contains(it.id)).Select(it => it).ToListAsync(); if (behavior == PrdTaskBehavior.Release) { foreach(PrdMoTask item in list) { // if (string.IsNullOrEmpty(item.worker_id)) // { // throw Oops.Bah("请先分配员工"); // } if (item.scheduling_class_type == "1") { if (string.IsNullOrEmpty(item.dayshift_worker_id) || string.IsNullOrEmpty(item.nightshift_worker_id)) { throw Oops.Bah("请先分配员工"); } }else if (item.scheduling_class_type == "2") { if (string.IsNullOrEmpty(item.dayshift_worker_id) || string.IsNullOrEmpty(item.nightshift_worker_id) || string.IsNullOrEmpty(item.dayshiftafter_worker_id) || string.IsNullOrEmpty(item.nightshiftafter_worker_id) ) { throw Oops.Bah("请先分配员工"); } } } } if (behavior == PrdTaskBehavior.Compled) { // if (list?.Count > 0) // { // // var schedQtySum = list.Sum(x => x.scheduled_qty); // // var planQtySum = list.Sum(x => x.plan_qty); // // if (schedQtySum < planQtySum) // // { // // throw new AppFriendlyException("任务数量必须大于等于生产计划数量,才可完成", 500); // // } // // int reportedWorkQty = list.Sum(x => x.last_process_complete_qty) ?? 0; // int scrapQty = list.Sum(x => x.scrap_qty) ?? 0; // int scheduledQty = list.Sum(x => x.scheduled_qty) ?? 0; // if (scheduledQty >= reportedWorkQty+scrapQty) // { // throw new AppFriendlyException("已完成数量大于等于任务单数量,才可完成", 500); // } // } } List taskReportLogs = new(); prdTaskList = await db.Queryable().Where(it => input.TaskIds.Contains(it.id)).ToListAsync(); if (prdTaskList?.Count > 0) { #region 质检模块 //质检 // if (prdTaskList.Where(p => p.mo_task_status == "Pause").Count() > 0 && status == "InProgress") // { // foreach (PrdMoTask? task in prdTaskList.Where(p => p.mo_task_status == "Pause").ToList()) // { // TriggerPlanEntity entity = new() // { // materialid = task.material_id, // processid = task.process_id, // workid = task.workstation_id, // triggerevent = EnumTriggerEvent.首件检生产任务暂停 // }; // await _qcCheckPlanService.CreateTask(entity); // } // } #endregion foreach (PrdMoTask item in prdTaskList) { switch (behavior) { // case PrdTaskBehavior.Release: // if (item.mo_task_status == status) // { // throw Oops.Bah("已下发的不能再下发"); // } // break; case PrdTaskBehavior.Start: if (item.mo_task_status == status) { throw Oops.Bah("已开始的不能再开始"); } if (item.schedule_type == 2) { if (await db.Queryable().AnyAsync(x => x.workline_id == item.workline_id && x.mo_task_status == DictConst.InProgressEnCode && x.id != item.id)) { throw Oops.Bah("该产线已有生产中的任务单"); } } if (item.schedule_type == 1) { if (await db.Queryable().AnyAsync(x => x.eqp_id == item.eqp_id && x.mo_task_status == DictConst.InProgressEnCode && x.id != item.id)) { throw Oops.Bah("该设备已有生产中的任务单"); } } if (item.mo_task_status is not DictConst.ToBeStartedEnCode and not DictConst.MoStatusPauseCode) { throw Oops.Bah("状态错误无法开始"); } if (item.first_start_date == null) { item.first_start_date = DateTime.Now; } break; case PrdTaskBehavior.Pause: if (item.mo_task_status == status) { throw Oops.Bah("已暂停的不能再暂停"); } if (item.mo_task_status != DictConst.InProgressEnCode) { throw Oops.Bah("状态错误无法暂停"); } item.pause_reason = input.PauseReeson; break; case PrdTaskBehavior.Compled: if (item.mo_task_status == status) { throw Oops.Bah("已完成的不能再完成"); } if (item.mo_task_status is not DictConst.InProgressEnCode and not DictConst.MoStatusPauseCode) { throw Oops.Bah("状态错误无法完成"); } PrdMo prdMo = await db.Queryable().Where(x=>x.id==item.mo_id).FirstAsync(); if (prdMo.mo_type == DictConst.PrdMoTypeJC) { ///完工生成模具保养计划 ToolMaintainTemMoldH toolMaintainTemMoldH = await db.Queryable() .Where(x => x.is_start == "1" && x.plan_cycle_unit == "3" && x.mold_id==item.mold_id).FirstAsync(); ToolMolds toolMolds = await db.Queryable().Where(x=>x.id==item.mold_id).FirstAsync(); if (toolMaintainTemMoldH != null && toolMolds!=null) { string code = await _billRuleService.GetBillNumber(CodeTemplateConst.MOLDMAINTENANCE_CODE); ToolMoldMaintainRecordH toolMoldMaintainRecordH = new ToolMoldMaintainRecordH() { id = SnowflakeIdHelper.NextId(), code = code, // equip_type_id = item.equip_type_id, mold_id = toolMaintainTemMoldH.mold_id, maintain_tem_mold_id = toolMaintainTemMoldH.id, plan_run_notice = toolMaintainTemMoldH.plan_run_notice, plan_run_notice_unit = toolMaintainTemMoldH.plan_run_notice_unit, plan_delay = toolMaintainTemMoldH.plan_delay, plan_delay_unit = toolMaintainTemMoldH.plan_delay_unit, send_post_info_user_id = toolMaintainTemMoldH.send_post_info_user_id, is_repeat = toolMaintainTemMoldH.is_repeat, repeat_post_info_user_id = toolMaintainTemMoldH.repeat_post_info_user_id, is_send = toolMaintainTemMoldH.is_send, repeat_user_id = toolMaintainTemMoldH.repeat_user_id, // execute_user_id = toolMaintainTemMoldH.duty_user_id, execute_user_id = _userManager.UserId, create_time = DateTime.Now, status = Tnb.EquipMgr.SpotInsRecordExecutionStatus.TOBEEXECUTED }; List insertRecordDs = new List(); List spotInsItems = await db.Queryable() .Where(x => x.maintain_tem_mold_id == toolMaintainTemMoldH.id) .Select(x => x.maintain_item_id).ToListAsync(); List tobeCreateItems = await db.Queryable().Where(x => spotInsItems.Contains(x.id)).ToListAsync(); foreach (var tobeCreateItem in tobeCreateItems) { insertRecordDs.Add(new ToolMoldMaintainRecordD() { id = SnowflakeIdHelper.NextId(), maintain_record_id = toolMoldMaintainRecordH.id, maintain_tem_mold_id = toolMoldMaintainRecordH.maintain_tem_mold_id, maintain_item_id = tobeCreateItem.id, code = tobeCreateItem.code, name = tobeCreateItem.name, maintain_type = tobeCreateItem.maintain_type, maintain_content = tobeCreateItem.maintain_content, descrip = tobeCreateItem.descrip, remark = tobeCreateItem.remark }); } if (insertRecordDs.Count>0) { await db.Insertable(toolMoldMaintainRecordH).ExecuteCommandAsync(); await db.Insertable(insertRecordDs).ExecuteCommandAsync(); } } } break; case PrdTaskBehavior.Closed: if (item.mo_task_status == status) { throw Oops.Bah("已关闭的不能再关闭"); } break; } } prdTaskList.ForEach(x => x.mo_task_status = status); if (behavior == PrdTaskBehavior.Start) { prdTaskList.ForEach(x => x.act_start_date = DateTime.Now); } if (behavior == PrdTaskBehavior.Compled) { prdTaskList.ForEach(x => x.act_end_date = DateTime.Now); } row = await db.Updateable(prdTaskList).ExecuteCommandAsync(); foreach (PrdMoTask item in prdTaskList) { if (string.IsNullOrEmpty(item.parent_id)) { continue; } //子任务所有状态相同才修改父任务状态 int count1 = await db.Queryable().CountAsync(y => y.parent_id == item.parent_id); int count2 = await db.Queryable().CountAsync(y => y.parent_id == item.parent_id && y.mo_task_status == status); if (count1 == count2) { _ = await db.Updateable().SetColumns(x => x.mo_task_status == status) .Where(x => x.id == item.parent_id).ExecuteCommandAsync(); } } if (row > 0) { taskReportLogs.AddRange(prdTaskList); } } if (row > 0) { //更新子任务 List subMoTaskList = await db.Queryable().Where(it => input.TaskIds.Contains(it.parent_id)).ToListAsync(); if (subMoTaskList?.Count > 0) { List subTaskIds = subMoTaskList.Select(it => it.id).ToList(); row = await db.Updateable() .SetColumns(it => new PrdMoTask { mo_task_status = status }) .Where(it => subTaskIds.Contains(it.id)) .ExecuteCommandAsync(); if (row > 0) { taskReportLogs.AddRange(subMoTaskList); } } } //插入操作记录日志 List prdMOTasks = await _db.Queryable().Where(it => input.TaskIds.Contains(it.id) && string.IsNullOrEmpty(it.parent_id)).ToListAsync(); if (prdMOTasks?.Count > 0) { List taskLogEntities = new(); foreach (string taskId in input.TaskIds) { PrdTaskLog? taskLog = await db.Queryable().FirstAsync(it => it.mo_task_id == taskId); if (taskLog is null) { PrdMoTask? taskItem = list?.Find(x => x.id == taskId); taskLog = new PrdTaskLog { id = SnowflakeIdHelper.NextId() }; if (taskItem != null) { if (taskItem.mo_id!.IsNotEmptyOrNull()) { taskLog.mo_code = (await db.Queryable().FirstAsync(it => it.id == taskItem.mo_id))?.mo_code!; } if (taskItem.eqp_id!.IsNotEmptyOrNull()) { taskLog.eqp_code = (await db.Queryable().FirstAsync(it => it.id == taskItem.eqp_id))?.code!; } if (taskItem.mold_id!.IsNotEmptyOrNull()) { taskLog.mold_code = (await db.Queryable().FirstAsync(it => it.id == taskItem.mold_id))?.mold_code!; } if (taskItem.material_id!.IsNotEmptyOrNull()) { BasMaterial? material = await db.Queryable().FirstAsync(it => it.id == taskItem.material_id); taskLog.item_code = material?.code!; taskLog.item_standard = material?.material_specification!; } taskLog.operator_name = _userManager.RealName; taskLog.status = status; taskLog.create_id = _userManager.UserId; taskLog.create_time = DateTime.Now; taskLog.mo_task_id = taskItem.id; } taskLogEntities.Add(taskLog); } else { List records = await db.Queryable().Where(it => it.mo_task_id == taskLog.mo_task_id).ToListAsync(); if (records != null && !records.Select(x => x.status).Contains(status)) { taskLog.id = SnowflakeIdHelper.NextId(); taskLog.status = status; taskLogEntities.Add(taskLog); } } } if (taskLogEntities?.Count > 0) { row = await db.Insertable(taskLogEntities).ExecuteCommandAsync(); } List prdReportLogs = new(); List prdTaskDefectLogs = new(); if (taskReportLogs?.Count > 0) { foreach (PrdMoTask taskInfo in taskReportLogs) { //组装生产提报对象 BasMaterial? material = await db.Queryable().FirstAsync(it => it.id == taskInfo.material_id); PrdMo? mo = await db.Queryable().FirstAsync(it => it.id == taskInfo.mo_id); PrdReportRecord record = taskInfo.Adapt(); record.id = SnowflakeIdHelper.NextId(); record.masterial_code = material?.code; record.masterial_name = material?.name; record.plan_start_date = taskInfo.estimated_start_date; record.plan_end_date = taskInfo.estimated_end_date; record.plan_qty = taskInfo.plan_qty; record.eqp_code = (await db.Queryable().FirstAsync(it => it.id == taskInfo.eqp_id))?.code; record.mo_task_type = mo?.mo_type; record.status = taskInfo.mo_task_status; record.mo_task_id = taskInfo.id; record.mo_code = mo?.mo_code ?? ""; //record.completed_qty = (await db.Queryable().Where(it => it.mo_task_code == taskInfo.mo_task_code).SumAsync(it => it.reported_work_qty)).Value; prdReportLogs.Add(record); //组装自检报废对象 PrdMoTaskDefectRecord sacipRecord = new() { id = SnowflakeIdHelper.NextId(), material_code = material?.code!, material_name = material?.name!, eqp_code = (await db.Queryable().FirstAsync(it => it.id == taskInfo.eqp_id))?.code!, mold_name = (await db.Queryable().FirstAsync(it => it.id == taskInfo.mold_id))?.mold_name!, estimated_start_date = taskInfo.estimated_start_date, estimated_end_date = taskInfo.estimated_end_date, plan_qty = taskInfo.plan_qty, scrap_qty = taskInfo.scrap_qty.HasValue ? taskInfo.scrap_qty.Value : 0, status = taskInfo.mo_task_status, create_id = _userManager.UserId, create_time = DateTime.Now, mo_task_id = taskInfo.id, mo_task_code = taskInfo.mo_task_code, mo_task_type = mo?.mo_type, mo_code = mo?.mo_code ?? "", }; sacipRecord.status = taskInfo.mo_task_status; prdTaskDefectLogs.Add(sacipRecord); } } List reportTaskIds = prdReportLogs.Select(it => it.mo_task_id).ToList(); if (reportTaskIds?.Count > 0) { List items = await db.Queryable().Where(it => reportTaskIds.Contains(it.mo_task_id)).ToListAsync(); if (items == null || items.Count < 1) { row = await db.Insertable(prdReportLogs).ExecuteCommandAsync(); } } List defectTaskIds = prdTaskDefectLogs.Select(it => it.mo_task_id).ToList(); if (defectTaskIds?.Count > 0) { List items = await db.Queryable().Where(it => defectTaskIds.Contains(it.mo_task_id)).ToListAsync(); if (items == null || items.Count < 1) { row = await db.Insertable(prdTaskDefectLogs).ExecuteCommandAsync(); } } } foreach (var item in prdTaskList) { if (PrdTaskBehavior.Start==behavior && item.schedule_type == 2) { PrdMo prdMo = await db.Queryable().SingleAsync(x => x.id == item.mo_id); if (prdMo.mo_type == DictConst.PrdMoTypeBZ) { // if (await _db.Queryable().Where(x => // x.mo_task_code == item.mo_task_code && x.status == "0" && x.is_label == null && x.is_mark==0).AnyAsync()) // { // await _db.Updateable() // .SetColumns(x => x.is_label == 0) // .Where(x => x.mo_task_code == item.mo_task_code && x.status == "0" && x.is_label == null && // x.is_mark == 0) // .ExecuteCommandAsync(); // } // else // { // PrdOutPackMarkLabel prdOutPackMarkLabel = new PrdOutPackMarkLabel() // { // is_mark = null, // is_label = 0, // mo_task_code = item.mo_task_code, // material_code = item.material_code, // create_time = DateTime.Now, // }; // // await _db.Insertable(prdOutPackMarkLabel).ExecuteCommandAsync(); // } OrganizeEntity organizeEntity = await _db.Queryable().SingleAsync(x => x.Id == item.workline_id); string batch = $"{organizeEntity.EnCode.Substring(organizeEntity.EnCode.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}"; PrdMoTask parent = await _db.Queryable().SingleAsync(x => x.id == item.parent_id); BasMaterial basMaterial = await _db.Queryable().SingleAsync(x=>x.id==parent.material_id); BasMbom basMbom = await _db.Queryable().SingleAsync(x => x.id == item.bom_id); //string code = $"(01){basMaterial.di ?? ""}(11){DateTime.Now.ToString("yyMMdd")}(17){DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}(10){batch}#{basMaterial.material_specification}*{batch}*{DateTime.Now.ToString("yyyyMMdd")}*{DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyyyMMdd")}*{basMaterial.container_no}"; string code1 = $"(01){basMaterial.di ?? ""}*(11){item.act_start_date.Value.ToString("yyMMdd")}*(17){item.first_start_date.Value.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}*(10){batch}"; string code2 = $"{basMaterial.material_specification}*{batch}*{item.act_start_date.Value.ToString("yyyyMMdd")}*{item.first_start_date.Value.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyyyMMdd")}*{basMaterial.material_standard}"; Dictionary dicCommand1 = new(StringComparer.OrdinalIgnoreCase) { ["DevName"] = "外包装箱码垛线", ["token"] = _eleCtlCfg.token, ["TagName"] = "WBZX_tb_cs", ["Value"] = code1, }; Dictionary dicCommand2 = new(StringComparer.OrdinalIgnoreCase) { ["DevName"] = "外包装箱码垛线", ["token"] = _eleCtlCfg.token, ["TagName"] = "WBZX_pm_cs", ["Value"] = code2, }; Dictionary workLineDic = new Dictionary() { [WmsWareHouseConst.XUELUGUAN1XIAN] = "WBZX_x1_dy_quantity", [WmsWareHouseConst.XUELUGUAN2XIAN] = "WBZX_x2_dy_quantity", }; Dictionary dicCommand3 = new(StringComparer.OrdinalIgnoreCase) { ["DevName"] = "外包装箱码垛线", ["token"] = _eleCtlCfg.token, ["TagName"] = workLineDic[item.workline_id], ["Value"] = basMbom.full_qty.ToString(), }; Log.Information($"贴标写入参数:{JsonConvert.SerializeObject(dicCommand1)}"); string result1 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand1, false); Log.Information($"贴标写入返回结果:{JsonConvert.SerializeObject(result1)}"); Log.Information($"喷码写入参数:{JsonConvert.SerializeObject(dicCommand2)}"); string result2 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand2, false); Log.Information($"喷码写入返回结果:{JsonConvert.SerializeObject(result2)}"); Log.Information($"整托数写入参数:{JsonConvert.SerializeObject(dicCommand3)}"); string result3 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand3, false); Log.Information($"整托数写入返回结果:{JsonConvert.SerializeObject(result3)}"); } } } if (list.Where(p => p.mo_task_status == "Pause").Count() > 0 && behavior==PrdTaskBehavior.Start) { TimerPoolHelper.GetInstance().StartTimer(TimeCallback,list.Where(p => p.mo_task_status == "Pause").ToList(),TimeSpan.FromHours(1),Timeout.InfiniteTimeSpan); }else if (list.Where(p => p.mo_task_status == "ToBeStarted").Count() > 0 && behavior == PrdTaskBehavior.Start) { foreach (PrdMoTask? task in list.Where(p => p.mo_task_status == "ToBeStarted").ToList()) { ToolMolds toolMolds = await _db.Queryable().SingleAsync(x=>x.id==task.mold_id); TriggerPlanEntity entity = new() { materialid = task.material_id, processid = task.process_id, workid = task.workstation_id, triggerevent = EnumTriggerEvent.开工首件检, plan_check_type = WmsWareHouseConst.SHOUJIAN_ID, mo_task_code = task.mo_task_code, newpronum = toolMolds?.mold_cavity }; await _qcCheckPlanService.CreateTask(entity); } } if (behavior == PrdTaskBehavior.Start) { List qcCheckPlanAdds = await _db.Queryable ((a, b, c, d, e) => new object[] { JoinType.Inner, a.id == b.mainid, JoinType.Left, a.id == c.planid && c.materialid == prdTaskList[0].material_id, JoinType.Left, a.id == d.planid && d.processid == prdTaskList[0].process_id, JoinType.Left, a.id == e.planid && e.workid == prdTaskList[0].workstation_id, }).Where((a, b, c, d, e) => b.triggertype == "2" && a.checktype == WmsWareHouseConst.XUNJIAN_ID) .Where((a, b, c, d, e) => !SqlFunc.IsNullOrEmpty(c.id) || !SqlFunc.IsNullOrEmpty(d.id) || !SqlFunc.IsNullOrEmpty(e.id)) .Select((a, b) => b).ToListAsync(); if (qcCheckPlanAdds.Count == 1) { int hour = 0; int minute = 0; string hourStr = qcCheckPlanAdds[0].content.Split(" ")[2]; string minuteStr = qcCheckPlanAdds[0].content.Split(" ")[1]; if (hourStr.Contains("/")) { hour = int.Parse(hourStr.Split("/")[1]); } if (minuteStr.Contains("/")) { minute = int.Parse(minuteStr.Split("/")[1]); } int totalMonute = hour * 60 + minute; TimerPoolHelper.GetInstance().StartTimer(TimeCallback2,list.Where(p => p.mo_task_status == "Pause" || p.mo_task_status == "ToBeStarted").ToList(),TimeSpan.FromMinutes(totalMonute),TimeSpan.FromMinutes(totalMonute),false); } } if (behavior == PrdTaskBehavior.Pause) { foreach (PrdMoTask? task in list.Where(p => p.mo_task_status == "InProgress").ToList()) { TimerPoolHelper.GetInstance().DisposeTimer(new Dictionary() { ["key"] = task.timer_key }); } } } if(tranFlag) await db.Ado.CommitTranAsync(); } catch (Exception e) { Log.Error(e.Message,e); if(tranFlag) await db.Ado.RollbackTranAsync(); throw Oops.Bah(e.Message); } return "保存成功"; } public async Task PrdTaskRelease2(PrdTaskReleaseUpInput input,ISqlSugarClient db) { this._db2 = db; await PrdTaskRelease(input); return "保存成功"; } public async Task SelfTestScrapped2(SelfTestScrappedInput input, ISqlSugarClient db = null) { this._db3 = db; await SelfTestScrapped(input); return "保存成功"; } public async void TimeCallback(object args) { try { Dictionary dic = (Dictionary)args; List prdTaskList = (List)(dic["value"]); await _db.Ado.BeginTranAsync(); foreach (PrdMoTask? task in prdTaskList) { ToolMolds toolMolds = await _db.Queryable().SingleAsync(x=>x.id==task.mold_id); await _db.Updateable() .SetColumns(x => x.timer_key == dic["key"]) .Where(x => x.id == task.id) .ExecuteCommandAsync(); TriggerPlanEntity entity = new() { materialid = task.material_id, processid = task.process_id, workid = task.workstation_id, triggerevent = EnumTriggerEvent.开工首件检, mo_task_code = task.mo_task_code, newpronum = toolMolds?.mold_cavity, plan_check_type = WmsWareHouseConst.XUNJIAN_ID, triggertype = "2" // check_type = WmsWareHouseConst.FULLREVIEW_CODE }; await _qcCheckPlanService.CreateTask(entity); } await _db.Ado.CommitTranAsync(); Console.WriteLine("质检任务生成成功"); } catch (Exception e) { await _db.Ado.RollbackTranAsync(); Log.Error("质检任务生成失败:"+e.Message,e); } } public async void TimeCallback2(object args) { try { Dictionary dic = (Dictionary)args; List prdTaskList = (List)(dic["value"]); foreach (PrdMoTask? task in prdTaskList) { ToolMolds toolMolds = await _db.Queryable().SingleAsync(x=>x.id==task.mold_id); await _db.Updateable() .SetColumns(x => x.timer_key == dic["key"]) .Where(x => x.id == task.id) .ExecuteCommandAsync(); TriggerPlanEntity entity = new() { materialid = task.material_id, processid = task.process_id, workid = task.workstation_id, triggerevent = EnumTriggerEvent.巡检, mo_task_code = task.mo_task_code, newpronum = toolMolds?.mold_cavity, plan_check_type = WmsWareHouseConst.XUNJIAN_ID, triggertype = "2" // check_type = WmsWareHouseConst.FULLREVIEW_CODE }; await _qcCheckPlanService.CreateTask(entity); } Console.WriteLine("质检任务生成成功"); } catch (Exception e) { Log.Error("质检任务生成失败:"+e.Message,e); } } /// /// 生产任务单修改 /// /// 生产任务单修改输入参数 /// /// [HttpPost] public async Task IcmoModify(IcmoUpInput input) { int row = -1; ISqlSugarClient db = _repository.AsSugarClient(); if (input.icmo_id!=null && !input.mo_id.IsEmpty()) { throw new ArgumentNullException(nameof(input.icmo_id)); } PrdMoTask? icmoItem = await db.Queryable().FirstAsync(it => it.id == input.icmo_id); switch (input.category) { case 1: //设备 if (icmoItem != null) { EqpEquipment eqpItem = await db.Queryable().FirstAsync(it => it.id == icmoItem.eqp_id); icmoItem.eqp_id = eqpItem.id; icmoItem.eqp_type_code = db.Queryable().First(it => it.id == eqpItem.equip_type_id)?.code!; //if (input.scheduled_qty > icmoItem.plan_qty) //{ // throw new AppFriendlyException("任务单数量不能大于计划数量", 500); //} //row = await db.Updateable().SetColumns(it => new PrdMo { input_qty = input.scheduled_qty }).Where(it => it.id == input.mo_id).ExecuteCommandAsync(); } break; case 2: //模具 if (icmoItem != null) { ToolMolds moldItem = await db.Queryable().FirstAsync(it => it.id == icmoItem.mold_id); icmoItem.mold_id = moldItem.id; icmoItem.mold_code = moldItem.mold_code; icmoItem.mold_name = moldItem.mold_name; icmoItem.mold_cavity_qty = moldItem.cavity_qty; } break; } row = await db.Updateable(icmoItem).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync(); return row > 0; } /// /// 生产提报 /// /// /// /// input: ///
{ ///
icmo_id:生产任务ID ///
icmo_code:任务单号 ///
prd_qty:生产数量 ///
reported_work_qty:已报工数量 ///
reported_qty:提报数量 ///
icmo_qty:生产任务量 ///
} ///
[HttpPost] public async Task PrdReport(PrdReportCrInput input) { await prdreportSemaphore.WaitAsync(); try { Log.Information($"生产提报参数:{JsonConvert.SerializeObject(input)}"); ISqlSugarClient db = _repository.AsSugarClient(); PrdMoTask? prdMoTask = await db.Queryable().SingleAsync(x => x.id == input.mo_task_id); EqpEquipment equip = await db.Queryable().SingleAsync(x => x.id == prdMoTask.eqp_id); BasMaterial basMaterial = await db.Queryable().SingleAsync(x => x.id == prdMoTask.material_id); PrdReport report = await db.Queryable().FirstAsync(it => it.mo_task_id == input.mo_task_id); if (basMaterial == null) { throw Oops.Bah($"未找到物料{prdMoTask.material_id}"); } Dictionary dic = new Dictionary() { ["30019971917589"] = "外包装箱码垛线" }; Dictionary dic2 = new Dictionary() { [WmsWareHouseConst.XUELUGUAN1XIAN] = "WBZX_x1_Enquantity", [WmsWareHouseConst.XUELUGUAN2XIAN] = "WBZX_x2_Enquantity" }; string materialBoxCode = input.material_box_code; BasLocation location = null; await _db.Ado.BeginTranAsync(); int row = -1; PrdMo prdMo = await db.Queryable().SingleAsync(x => x.id == prdMoTask.mo_id); BasMbomProcess? mbomProcess = await db.Queryable().SingleAsync(x => x.id == prdMoTask.mbom_process_id); if (prdMoTask.mo_task_status == DictConst.MoStatusPauseCode) { throw Oops.Bah("暂停的任务单无法提报"); } if (mbomProcess == null) { throw Oops.Bah("未找到生产bom对应工序"); } BasMbom mbom = await db.Queryable().SingleAsync(x => x.id == mbomProcess.mbom_id); if (mbom == null) { throw Oops.Bah("未找到生产bom"); } if ((prdMoTask.reported_work_qty ?? 0) + input.reported_qty > prdMoTask.scheduled_qty) { BasFactoryConfig config1 = await db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.IS_SURPASS); if (config1?.value == "1") { // BasFactoryConfig? config2 = await db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.IS_SURPASS_PERCENTAGE); // if (!string.IsNullOrEmpty(config2?.value)) // { // if ((prdMoTask.reported_work_qty ?? 0) + input.reported_qty > prdMoTask.scheduled_qty * (100 + Convert.ToDecimal(config2?.value ?? "1")) / 100) // { // throw Oops.Bah($"提报数量不能大于{100 + Convert.ToDecimal(config2?.value ?? "0")}%排产数量"); // } // } if ((prdMoTask.reported_work_qty ?? 0) + input.reported_qty > prdMoTask.scheduled_qty * (100 + basMaterial.intolerance) / 100) { throw Oops.Bah($"提报数量不能大于{100 + basMaterial.intolerance}%排产数量"); } } else { throw Oops.Bah("提报数量不能大于排产数量"); } } // bool flag = (prdMoTask.reported_work_qty ?? 0) + (prdMoTask.scrap_qty ?? 0) + input.reported_qty == prdMoTask.scheduled_qty; // if ((prdMoTask.reported_work_qty ?? 0) + (prdMoTask.scrap_qty ?? 0) + input.reported_qty > prdMoTask.scheduled_qty) // { // throw Oops.Bah("已完成数量不能大于任务单数量"); // } if (string.IsNullOrEmpty((input.material_box_code))) { throw Oops.Bah("载具不能为空"); } // if (string.IsNullOrEmpty((input.location_code))) // { // throw Oops.Bah("入库库位不能为空"); // } if (input.reported_qty<=0) { throw Oops.Bah("提报数量为正数"); } report = input.Adapt(); report.id = SnowflakeIdHelper.NextId(); report.org_id = WmsWareHouseConst.AdministratorOrgId; report.reported_qty = input.reported_qty; report.weight = input.weight; report.material_box_code = input.material_box_code; if (prdMoTask.schedule_type == 2) { report.material_box_code = input.material_box_code; report.warehouse_id = WmsWareHouseConst.WAREHOUSE_DMJC_ID; Dictionary worklineWarehouseDic = new Dictionary() { [WmsWareHouseConst.XUELUGUAN1XIAN] = "ZZ-01-02", [WmsWareHouseConst.XUELUGUAN2XIAN] = "ZZ-02-02", }; report.location_code = worklineWarehouseDic.GetOrDefault(prdMoTask.workline_id); if (string.IsNullOrEmpty(report.location_code)) { report.location_code = "ZZ-01-02"; } location = await db.Queryable().SingleAsync(x=>x.location_code==report.location_code); if (location == null) { throw Oops.Bah($"未找到库位编号{report.location_code}"); } } else { report.warehouse_id = equip.instock_warehouse_id; if (equip.downmat_location_id == null || equip.downmat_location_id.IsEmpty()) { throw Oops.Bah("设备未绑定下料库位"); } location = await db.Queryable().SingleAsync(x=>x.id==equip.downmat_location_id); if (location == null) { throw Oops.Bah($"未找到库位id{equip.downmat_location_id}"); } report.location_code = location.location_code; } string batch = ""; PrdMo mo = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.mo_id); bool changeBatchFlag = false; int changeCountNumByDay = 0; int changeCountNumByQty = 0; if (prdMoTask.is_hand_set_batch==0 && (mo.mo_type == DictConst.PrdMoTypeZS || mo.mo_type == DictConst.PrdMoTypeJC)) { BasFactoryConfig changeBatchNum = await _db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.CHANGEBATCHNUM); BasFactoryConfig changeBatchDay = await _db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.CHANGEBATCHDAY); DateTime date1 = new DateTime(prdMoTask.first_start_date.Value.Year,prdMoTask.first_start_date.Value.Month,prdMoTask.first_start_date.Value.Day); DateTime date2 = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day); TimeSpan diff = date2.Subtract(date1); int diffDays = diff.Days + 1; changeCountNumByDay = (diffDays + 1) / int.Parse(changeBatchDay.value) - 1; changeCountNumByQty = ((int)(prdMoTask.reported_work_qty ?? 0 + prdMoTask.scrap_qty ?? 0) + 1) / int.Parse(changeBatchNum.value) - 1; if (changeCountNumByDay > prdMoTask.change_batch_count_by_day ) { changeBatchFlag = true; } if (changeCountNumByQty > prdMoTask.change_batch_count_by_qty) { changeBatchFlag = true; } } if (mo.mo_type == DictConst.PrdMoTypeZS && prdMoTask.is_hand_set_batch==0) { if (changeBatchFlag) { EqpEquipment equipment = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.eqp_id); batch = $"{equipment.code.Substring(equipment.code.Length - 2, 2)}{prdMoTask.act_start_date.Value.ToString("yyMMdd")}"; await db.Updateable() .SetColumns(x => x.batch == batch) .SetColumns(x=>x.change_batch_count_by_day==changeCountNumByDay) .SetColumns(x=>x.change_batch_count_by_qty==changeCountNumByQty) .Where(x => x.id == prdMoTask.id) .ExecuteCommandAsync(); } else { batch = prdMoTask.batch; } }else if (mo.mo_type == DictConst.PrdMoTypeJC && prdMoTask.is_hand_set_batch==0) { EqpEquipment equipment = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.eqp_id); ToolMolds toolMolds = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.mold_id); batch = $"6{toolMolds.mold_code.Substring(toolMolds.mold_code.Length - 4, 2)}{equipment.code.Substring(equipment.code.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}"; await db.Updateable() .SetColumns(x => x.batch == batch) .Where(x => x.id == prdMoTask.id) .ExecuteCommandAsync(); }else { // OrganizeEntity organizeEntity = await _db.Queryable().SingleAsync(x => x.Id == prdMoTask.workline_id); // batch = $"{organizeEntity.EnCode.Substring(organizeEntity.EnCode.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}"; batch = prdMoTask.batch; } if (string.IsNullOrEmpty(batch)) { throw Oops.Bah($"任务单{prdMoTask.mo_task_code}批次号为空,无法提报"); } if (prdMoTask.has_last_check == 0) { if ((prdMoTask.reported_work_qty ?? 0) + input.reported_qty >= prdMoTask.scheduled_qty * 90 / 100) { await _db.Updateable() .SetColumns(x => x.has_last_check==1) .Where(x => x.id == prdMoTask.id) .ExecuteCommandAsync(); TimerPoolHelper.GetInstance().DisposeTimer(new Dictionary() { ["key"] = prdMoTask.timer_key }); ToolMolds toolMolds = await db.Queryable().SingleAsync(x=>x.id==prdMoTask.mold_id); TriggerPlanEntity entity = new() { materialid = prdMoTask.material_id, processid = prdMoTask.process_id, workid = prdMoTask.workstation_id, triggerevent = EnumTriggerEvent.末检质检方案, mo_task_code = prdMoTask.mo_task_code, carry_code = report.material_box_code, report_id = report.id, batch = report.batch, plan_check_type = WmsWareHouseConst.MOJIAN_ID, newpronum = toolMolds?.mold_cavity, }; await _qcCheckPlanService.CreateTask(entity); } } // report.location_code = input.location_code; report.create_id = _userManager?.UserId ?? WmsWareHouseConst.AdministratorUserId; report.create_time = DateTime.Now; report.batch = batch; report.barcode = input.mo_task_code + DateTimeOffset.Now.ToUnixTimeSeconds().ToString(); report.barqty = mbom.full_qty; // report.barcode = input.mo_task_code+"0001"; report.equip_id = prdMoTask.eqp_id; report.mbom_process_id = prdMoTask.mbom_process_id; report.station = input.station; report.status = 0; report.material_id = prdMoTask.material_id; report.unit_id = prdMoTask.unit_id; report.process_id = mbomProcess?.process_id ?? ""; row = await db.Insertable(report).ExecuteCommandAsync(); WmsCarryH wmsCarryH = await db.Queryable().SingleAsync((x => x.carry_code == materialBoxCode)); if (wmsCarryH == null) throw Oops.Bah($"未找到{materialBoxCode}载具"); if (wmsCarryH.carry_status == ((int)EnumCarryStatus.占用).ToString()) { throw Oops.Bah($"提报失败,载具已绑定"); } List wmsCarryCodes = await db.Queryable().Where(x=>x.carry_id==wmsCarryH.id).ToListAsync(); if (wmsCarryCodes != null && wmsCarryCodes.Count > 0) { Log.Error($"载具{materialBoxCode}状态为{wmsCarryH.carry_status},但有条码{JsonConvert.SerializeObject(wmsCarryCodes)}"); throw Oops.Bah($"提报失败,载具异常"); } // bool isCheckFlag = !basMaterial.category_id.Contains("ZZCP"); bool isCheckFlag = basMaterial.category_id.Contains("ZSJ"); #region 质检模块 //质检模块 if (isCheckFlag && wmsCarryH.is_check == EnumCheckConclusion.待检.ParseToInt().ToString()) { TriggerPlanEntity entity = new() { materialid = prdMoTask.material_id, processid = prdMoTask.process_id, workid = prdMoTask.workstation_id, mo_task_code = prdMoTask.mo_task_code, carry_code = report.material_box_code, report_id = report.id, batch = report.batch, check_type = WmsWareHouseConst.FULLREVIEW_CODE, plan_check_type = WmsWareHouseConst.LINGBUJIANZUIZHONGJIANYAN_ID, }; decimal? reported = prdMoTask.reported_work_qty == null ? 0 : prdMoTask.reported_work_qty; decimal? scrap = prdMoTask.scrap_qty == null ? 0 : prdMoTask.scrap_qty; entity.oldpronum = reported + scrap; entity.newpronum = input.reported_qty; // entity.triggerevent = EnumTriggerEvent.生产检定量; entity.triggerevent = EnumTriggerEvent.零部件最终检验; await _qcCheckPlanService.CreateTask(entity); await _db.Updateable() .SetColumns(x => x.is_check == EnumCheckConclusion.检验中.ParseToInt().ToString()) .Where(x => x.id == wmsCarryH.id) .ExecuteCommandAsync(); isCheckFlag = true; } if ( wmsCarryH.is_check != EnumCheckConclusion.待检.ParseToInt().ToString()) { throw Oops.Bah("提交失败,载具状态不是待检"); } #endregion _ = prdMoTask.reported_work_qty == null ? await db.Updateable() // .SetColumns(x => x.complete_qty == x.complete_qty + input.reported_qty) .SetColumns(x => x.reported_work_qty == input.reported_qty) // .SetColumnsIF(flag,x=>x.mo_task_status==DictConst.ComplatedEnCode) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync() : await db.Updateable() // .SetColumns(x => x.complete_qty == x.complete_qty + input.reported_qty) .SetColumns(x => x.reported_work_qty == x.reported_work_qty + input.reported_qty) // .SetColumnsIF(flag,x=>x.mo_task_status==DictConst.ComplatedEnCode) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); if (prdMoTask.schedule_type == 1) { _ = prdMo.reported_work_qty == null ? await db.Updateable() .SetColumns(x => x.reported_work_qty == input.reported_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync() : await db.Updateable() .SetColumns(x => x.reported_work_qty == x.reported_work_qty + input.reported_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync(); _ = prdMo.complete_qty == null ? await db.Updateable() .SetColumns(x => x.complete_qty == input.reported_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync() : await db.Updateable() .SetColumns(x => x.complete_qty == x.complete_qty + input.reported_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync(); PerProcessStandardsH processStandardsH = await db.Queryable() .Where(x => x.equip_id == prdMoTask.eqp_id && x.molds_id == prdMoTask.mold_id && x.output_material_id == prdMoTask.material_id && x.enabled == 1) .OrderByDescending(x => x.create_time).FirstAsync(); ToolMolds toolMolds = await db.Queryable().SingleAsync(x => x.id == prdMoTask.mold_id); if (toolMolds != null && toolMolds?.mold_cavity > 0 && processStandardsH != null && processStandardsH?.moulding_cycle > 0) { decimal? addTime = ((((prdMoTask.scheduled_qty - input.reported_qty - (prdMoTask.scrap_qty ?? 0)) * processStandardsH?.moulding_cycle) - 1) / toolMolds.mold_cavity) + 1; if (prdMoTask.act_start_date != null && addTime != null && addTime > 0) { DateTime cal_plan_end_date = prdMoTask.act_start_date.Value.AddSeconds((double)addTime); _ = await db.Updateable() .SetColumns(x => x.plan_end_date == cal_plan_end_date) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); } } } if (prdMoTask.schedule_type == 2 && !string.IsNullOrEmpty(prdMoTask.mbom_process_id)) { if (mbomProcess.is_last == 1 && prdMoTask != null && !string.IsNullOrEmpty(prdMoTask.parent_id)) { PrdMoTask parentMoTask = await db.Queryable().SingleAsync(x => x.id == prdMoTask.parent_id); if (parentMoTask?.last_process_complete_qty == null) { _ = await db.Updateable() .SetColumns(x => x.last_process_complete_qty == input.reported_qty) // .SetColumnsIF(flag,x=>x.mo_task_status==DictConst.ComplatedEnCode) .Where(x => x.id == prdMoTask.parent_id).ExecuteCommandAsync(); } else if (parentMoTask?.last_process_complete_qty != null) { _ = await db.Updateable() .SetColumns(x => x.last_process_complete_qty == x.last_process_complete_qty + input.reported_qty) // .SetColumnsIF(flag,x=>x.mo_task_status==DictConst.ComplatedEnCode) .Where(x => x.id == prdMoTask.parent_id).ExecuteCommandAsync(); } _ = prdMo.reported_work_qty == null ? await db.Updateable() .SetColumns(x => x.reported_work_qty == input.reported_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync() : await db.Updateable() .SetColumns(x => x.reported_work_qty == x.reported_work_qty + input.reported_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync(); _ = prdMo.complete_qty == null ? await db.Updateable() .SetColumns(x => x.complete_qty == input.reported_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync() : await db.Updateable() .SetColumns(x => x.complete_qty == x.complete_qty + input.reported_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync(); } List list = await db.Queryable() .LeftJoin((a, b) => a.process_id == b.process_id && b.enabled == 1) .Where((a, b) => a.process_id == prdMoTask.process_id).Select((a, b) => b).ToListAsync(); decimal max = list.Select(x => Convert.ToDecimal(x.standard_time)).Max(x => x); decimal? addTime = (prdMoTask.scheduled_qty - input.reported_qty - (prdMoTask.scrap_qty ?? 0)) * max; if (prdMoTask.act_start_date != null && addTime != null && addTime > 0) { DateTime cal_plan_end_date = prdMoTask.act_start_date.Value.AddSeconds((double)addTime); _ = await db.Updateable() .SetColumns(x => x.plan_end_date == cal_plan_end_date) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); } } PrdReportRecord master = await db.Queryable().FirstAsync(it => it.mo_task_id == input.mo_task_id); if (master != null) { master.reported_work_qty += input.reported_qty; master.completed_qty += input.reported_qty; _ = await db.Updateable(master).ExecuteCommandAsync(); } //扣除生产投料 按最先投入的依次扣除 // List prdFeedingDs = await db.Queryable() // .LeftJoin((a,b)=>a.id==b.feeding_id) // .Where((a,b) => a.workline_id == prdMoTask.workline_id && (b.status=="0" || b.status=="1")) // .OrderBy((a,b) => b.create_time) // .Select((a,b)=>b) // .ToListAsync(); // // if (prdFeedingDs != null && prdFeedingDs.Count>0) // { // // BasMbom basMbom = await db.Queryable().SingleAsync(x => x.id == prdMoTask.bom_id); // List basMbomInputs = await db.Queryable().Where(x => // x.mbom_id == prdMoTask.bom_id && x.mbom_process_id == prdMoTask.mbom_process_id).ToListAsync(); // // foreach (var item in basMbomInputs) // { // var details = prdFeedingDs.Where(x => x.material_id == item.material_id).OrderBy(x=>x.create_time).ToList(); // if (details?.Count>0) // { // decimal deductNum = input.reported_qty * item.num / basMbom.num; // decimal? notUseNum = details.Sum(x => x.num - x.use_num); // if (notUseNum > deductNum) // { // // foreach (var detail in details) // { // // if (deductNum - (detail.num - detail.use_num) < 0) // { // await db.Updateable().SetColumns(x => x.use_num == x.use_num+deductNum) // .SetColumns(x=>x.status=="1") // .Where(x => x.id == detail.id).ExecuteCommandAsync(); // // } // else // { // await db.Updateable().SetColumns(x => x.use_num == x.num) // .SetColumns(x=>x.status=="2") // .Where(x => x.id == detail.id).ExecuteCommandAsync(); // // } // // deductNum = deductNum - (detail.num - detail.use_num); // // if (deductNum <= 0) // break; // } // // if (deductNum > 0) // { // throw new Exception("投入物料不足"); // } // } // else if(notUseNum == deductNum) // { // foreach (var detail in details) // { // await db.Updateable().SetColumns(x => x.use_num == x.num) // .SetColumns(x=>x.status=="2") // .Where(x => x.id == detail.id).ExecuteCommandAsync(); // // } // } // else // { // throw new Exception("投入物料不足"); // } // // } // else // { // throw new Exception("无投入物料"); // } // } // } if(!isCheckFlag) { int takeNum = (int)report.reported_qty.Value; List prdVisionResultRecords = await _db.Queryable() .Where(x => x.status == 0 && x.result.ToUpper()=="OK").OrderByDescending(x => x.create_time).Take(takeNum).ToListAsync(); List ids = prdVisionResultRecords.Select(x => x.id).ToList(); await db.Updateable().SetColumns(x => x.status == 1).Where(x => ids.Contains(x.id)).ExecuteCommandAsync(); await ReportInstock(new CheckCompleteInput() { report_id = report.id, pqty = report.reported_qty.ParseToDecimal(), rqty = 0, records = prdVisionResultRecords, }); } await _db.Ado.CommitTranAsync(); } catch (Exception ex) { Log.Error("提报失败", ex); await _db.Ado.RollbackTranAsync(); throw Oops.Bah("提报失败:"+ex.Message); } finally{ prdreportSemaphore.Release(); } return "提报成功"; } public async Task ReportInstock(CheckCompleteInput input,PrdReport report = null, ISqlSugarClient db = null) { try { if (db == null) db = _repository.AsSugarClient(); if (report == null) report = await db.Queryable() .FirstAsync(it => it.id == input.report_id && !SqlFunc.IsNullOrEmpty(it.id)); PrdMoTask? prdMoTask = await db.Queryable() .FirstAsync(x => x.id == report.mo_task_id && !SqlFunc.IsNullOrEmpty(x.id)); EqpEquipment equip = await db.Queryable().SingleAsync(x => x.id == prdMoTask.eqp_id); BasMaterial basMaterial = await db.Queryable().SingleAsync(x => x.id == prdMoTask.material_id); WmsCarryH wmsCarryH = await db.Queryable() .FirstAsync(x => x.carry_code == report.material_box_code); BasLocation location = await db.Queryable() .FirstAsync(x => x.location_code == report.location_code); PrdMo prdMo = await db.Queryable().SingleAsync(x => x.id == prdMoTask.mo_id); await db.Updateable() .SetColumns(x => x.check_result == input.check_result) .SetColumns(x => x.pqty == input.pqty) .SetColumns(x => x.rqty == input.rqty) .Where(x => x.id == input.report_id) .ExecuteCommandAsync(); if (prdMo.mo_type == DictConst.PrdMoTypeZS && input.rqty>0) { await _db.Updateable() .SetColumns(x => x.reported_work_qty == x.reported_work_qty - input.rqty) .SetColumns(x => x.scrap_qty == x.scrap_qty + input.rqty) .Where(x => x.id == prdMoTask.id) .ExecuteCommandAsync(); await _db.Updateable() .SetColumns(x => x.reported_work_qty == x.reported_work_qty - input.rqty) .SetColumns(x => x.scrap_qty == x.scrap_qty + input.rqty) .Where(x => x.id == prdMoTask.mo_id) .ExecuteCommandAsync(); } BindCarryCodeInput bindCarryCodeInput = new BindCarryCodeInput(); bindCarryCodeInput.carry_id = wmsCarryH.id; bindCarryCodeInput.barcode = report.barcode; bindCarryCodeInput.codeqty = report.reported_qty.Value; bindCarryCodeInput.material_id = prdMoTask.material_id; bindCarryCodeInput.material_code = basMaterial.code; bindCarryCodeInput.material_name = basMaterial.name; bindCarryCodeInput.material_specification = basMaterial.material_specification; bindCarryCodeInput.container_no = basMaterial.material_standard; bindCarryCodeInput.location_id = location.id; bindCarryCodeInput.location_code = location.location_code; bindCarryCodeInput.code_batch = report.batch; bindCarryCodeInput.create_id = _userManager?.UserId ?? WmsWareHouseConst.AdministratorUserId; Log.Information($"载具绑定参数:${JsonConvert.SerializeObject(bindCarryCodeInput)}"); Tnb.WarehouseMgr.Entities.Dto.Outputs.Result result1 = await _wmsCarryService.BindCarryMaterial(bindCarryCodeInput); if (result1.code != HttpStatusCode.OK) { throw Oops.Bah(result1.msg); } WmsPrdInstockInput wmsPrdInstockInput = new WmsPrdInstockInput(); wmsPrdInstockInput.prd_bill_code = prdMo.mo_code; wmsPrdInstockInput.material_id = prdMoTask.material_id; wmsPrdInstockInput.material_code = prdMoTask.material_code; wmsPrdInstockInput.material_name = basMaterial.name; wmsPrdInstockInput.material_spec = basMaterial.material_specification; wmsPrdInstockInput.planqty = prdMoTask.scheduled_qty.Value; wmsPrdInstockInput.pqty = input.pqty; wmsPrdInstockInput.rqty = input.rqty; wmsPrdInstockInput.type = prdMo.mo_type; wmsPrdInstockInput.create_id = report.create_id; wmsPrdInstockInput.prd_report_id = report.id; wmsPrdInstockInput.prdInstockCodes = new List(); wmsPrdInstockInput.prdInstockD = new WmsPrdInstockDInput() { task_bill_code = prdMoTask.mo_task_code, warehouse_id = report.warehouse_id, startlocation_id = location.id, carry_id = wmsCarryH.id, }; if (prdMoTask.schedule_type == 1) { wmsPrdInstockInput.prdInstockCodes.Add(new WmsPrdInstockCodeInput() { planqty = prdMoTask.scheduled_qty.Value, pqty = input.pqty, code_batch = report.batch, code = report.barcode, unit_id = prdMoTask.unit_id, carry_id = wmsCarryH.id, }); } if (input.records != null) { foreach (var record in input.records) { wmsPrdInstockInput.prdInstockCodes.Add(new WmsPrdInstockCodeInput() { planqty = prdMoTask.scheduled_qty.Value, pqty = 1, code_batch = report.batch, code = record.info, unit_id = prdMoTask.unit_id, carry_id = wmsCarryH.id, }); } } Log.Information($"生产入库参数:${JsonConvert.SerializeObject(wmsPrdInstockInput)}"); Tnb.WarehouseMgr.Entities.Dto.Outputs.Result result2 = await _wmsPrdInstockHService.PrdInstock(wmsPrdInstockInput, db); if (result2 != null) { Log.Information($"生产入库接口返回参数:${JsonConvert.SerializeObject(result2)}"); } else { Log.Information($"生产入库接口返回参数为null"); } if (result2.code != HttpStatusCode.OK) { throw Oops.Bah(result2.msg != null ? result2.msg : "生产入库接口报错"); } //来源erp需要调接口 if (prdMo.mo_source == "1") { List unitDatas = await db.Queryable() .LeftJoin((x, y) => x.Id == y.DictionaryTypeId) .Where((x, y) => x.EnCode == DictConst.MeasurementUnit && y.EnCode == report.unit_id) .Select((x, y) => y) .ToListAsync(); List erpExtendIds = new List(); // erpExtendIds.Add(report.create_id); erpExtendIds.Add(WmsWareHouseConst.AdministratorOrgId); erpExtendIds.Add(report.material_id); erpExtendIds.Add(prdMo.dept_id); // erpExtendIds.Add(report.unit_id); erpExtendIds.AddRange(unitDatas.Select(x => x.Id).ToList()); string userId = report.create_id ?? WmsWareHouseConst.AdministratorUserId; erpExtendIds.Add(userId); List erpExtendFields = await _db.Queryable().Where(x => erpExtendIds.Contains(x.table_id)).ToListAsync(); //string erpCreateId = erpExtendFields.Find(x => x.table_id == userId)?.user_id ?? WmsWareHouseConst.ERPUSERID; string erpCreateId = WmsWareHouseConst.ERPUSERID; ErpExtendField erpOrg = erpExtendFields.Find(x => x.table_id == (WmsWareHouseConst.AdministratorOrgId)); string nowStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ErpExtendField deptExtendField = null; if (!string.IsNullOrEmpty(prdMo.dept_id)) { deptExtendField = await _db.Queryable().Where(x => x.cdptid==prdMo.dept_id).FirstAsync(); } List> requestData = new List>(); Dictionary erpRequestData = new Dictionary(); erpRequestData.Add("auditer", erpCreateId); erpRequestData.Add("billmaker", erpCreateId); erpRequestData.Add("cdeptid", prdMo.dept_id); //部门先写死1001A1100000001JFOPQ erpRequestData.Add("cdeptvid", deptExtendField?.cdptvid); //部门先写死 erpRequestData.Add("taudittime", nowStr); erpRequestData.Add("creationtime", nowStr); erpRequestData.Add("creator", erpCreateId); erpRequestData.Add("dbilldate", nowStr); erpRequestData.Add("dmakedate", nowStr); erpRequestData.Add("pk_org", erpOrg.pk_org); erpRequestData.Add("pk_org_v", erpOrg.pk_org_v); erpRequestData.Add("vtrantypecode", "55A4-01"); erpRequestData.Add("vtrantypeid", "0001A11000000002LVX8"); erpRequestData.Add("vdef1", null); //todo 倒冲日期 erpRequestData.Add("vdef2", null); erpRequestData.Add("report_id", report.id); List> erpRequestDataDetails = new List>(); erpRequestDataDetails.Add(new Dictionary() { ["cbdeptid"] = prdMo.dept_id, ["cbdeptvid"] = deptExtendField?.cdptvid, ["cbmainmaterialid"] = erpExtendFields.Find(x => x.table_id == report.material_id)?.cmaterialoid ?? "", ["cbmainmaterialvid"] = erpExtendFields.Find(x => x.table_id == report.material_id)?.cmaterialvid ?? "", ["cbmaterialid"] = erpExtendFields.Find(x => x.table_id == report.material_id)?.cmaterialvid ?? "", ["cbmaterialvid"] = erpExtendFields.Find(x => x.table_id == report.material_id)?.cmaterialvid ?? "", ["cbmobid"] = prdMo.erp_line_pk, ["cbmoid"] = prdMo.erp_mo_pk, // ["cbunitid"] = erpExtendFields.Find(x=>x.table_id==report.unit_id)?.cunitid ?? "", // ["cbastunitid"] = erpExtendFields.Find(x=>x.table_id==report.unit_id)?.cunitid ?? "", ["cbunitid"] = erpExtendFields.Find(x => x.table_id == (unitDatas.Find(x => x.EnCode == report.unit_id)?.Id ?? ""))?.cunitid ?? "", ["cbastunitid"] = erpExtendFields.Find(x =>x.table_id == (unitDatas.Find(x => x.EnCode == report.unit_id)?.Id ?? ""))?.cunitid ?? "", ["nbplanwrnum"] = input.pqty, ["nbwrnum"] = input.pqty, ["tbendtime"] = nowStr, ["tbstarttime"] = prdMoTask.act_start_date != null ? prdMoTask.act_start_date.Value.ToString("yyyy-MM-dd HH:mm:ss") : "", ["vbinbatchcode"] = report.batch, ["vbmobillcode"] = prdMo.mo_code.Split("-")[0], ["vbmorowno"] = prdMo.erp_lineno, ["vbrowno"] = prdMo.erp_lineno, ["vbdef2"] = null,//todo 工时后续要改 }); erpRequestData.Add("AggWrDtl", erpRequestDataDetails); requestData.Add(erpRequestData); BasFactoryConfig config = await _db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.BIPURL); BasFactoryConfig callErp = await _db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.CALLERP); ThirdWebapiRecord thirdWebapiRecord = new ThirdWebapiRecord(); thirdWebapiRecord.id = SnowflakeIdHelper.NextId(); thirdWebapiRecord.third_name = WmsWareHouseConst.BIP; thirdWebapiRecord.name = "生产报告"; thirdWebapiRecord.method = "POST"; // thirdWebapiRecord.url = config.value + "uapws/rest/pwrnew/save"; thirdWebapiRecord.url = WmsWareHouseConst.BIP_DOMAIN+"uapws/rest/pwrnew/save"; thirdWebapiRecord.request_data = JsonConvert.SerializeObject(erpRequestData); thirdWebapiRecord.create_time = DateTime.Now; thirdWebapiRecord.remark = $"【PrdMoTaskService ReportInstock】载具编号:{report?.material_box_code ?? ""}"; await _db.Insertable(thirdWebapiRecord).ExecuteCommandAsync(); if(callErp.value=="1"){ await _thirdApiRecordService.Send(new List { thirdWebapiRecord }, "自动", _db); } } if (prdMoTask.schedule_type == 2) { // Dictionary dicCommand2 = new(StringComparer.OrdinalIgnoreCase) // { // ["DevName"] = dic[prdMoTask.workline_id], // ["token"] = _eleCtlCfg.token, // ["TagName"] = "WBZX_x1_ok", // ["Value"] = "true", // }; // Log.Information($"提拔确认完成参数:{JsonConvert.SerializeObject(dicCommand2)}"); // string responseresult = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand2); // Log.Information($"提拔确认完成参数成返回结果:{responseresult}"); // X2ServerResult x2ServerResult = JsonConvert.DeserializeObject(responseresult); // if (x2ServerResult.Result != X2ServerResult.Ok) // { // throw Oops.Bah(x2ServerResult.Msg); // } // Dictionary dicCommand4 = new(StringComparer.OrdinalIgnoreCase) // { // ["DevName"] = "外包装箱码垛线", // ["token"] = _eleCtlCfg.token, // ["TagName"] = dic2[prdMoTask.workline_id], // ["Value"] = "0", // }; // // Log.Information($"清除提报码垛数参数:{JsonConvert.SerializeObject(dicCommand4)}"); // string responseresult2 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand4); // Log.Information($"清除提报码垛数返回结果:{responseresult2}"); // X2ServerResult x2ServerResult2 = JsonConvert.DeserializeObject(responseresult2); // if (x2ServerResult2.Result != X2ServerResult.Ok) // { // throw Oops.Bah(x2ServerResult2.Msg); // } } // if (basMaterial.category_id.Contains("CGJCJ")) // { // EqpEquipment equipment = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.eqp_id); // if (!string.IsNullOrEmpty(equipment.downmat_location_id)) // { // BasLocation downmatLocation = await _db.Queryable().SingleAsync(x=>x.id==equipment.downmat_location_id); // await _db.Updateable() // .SetColumns(x => x.location_code == downmatLocation.location_code) // .SetColumns(x => x.location_id == downmatLocation.id) // .Where(x => x.carry_code == report.material_box_code) // .ExecuteCommandAsync(); // } // } if (basMaterial.category_id.Contains("ZSJ") || basMaterial.category_id.Contains("DGJCJ")) { EqpEquipment equipment = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.eqp_id); EqpDaq eqpDaq3 = await _repository.AsSugarClient().Queryable(). LeftJoin((x,y)=>x.equip_id==y.id). Where((x,y) => y.code == equipment.code && x.label_name.Contains("称重完成")).FirstAsync(); if (eqpDaq3 == null) { throw Oops.Bah("未在数据采集中设置称重完成标签点"); } Dictionary dicCommand3 = new(StringComparer.OrdinalIgnoreCase) { ["DevName"] = eqpDaq3.equip_code, ["token"] = _eleCtlCfg.token, ["TagName"] = eqpDaq3.label_name, ["Value"] = "true", }; Log.Information($"称重完成参数:{JsonConvert.SerializeObject(dicCommand3)}"); string responseresult = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand3,false); Log.Information($"{eqpDaq3.equip_code},{eqpDaq3.label_name}称重完成返回结果:{responseresult}"); X2ServerResult x2ServerResult = JsonConvert.DeserializeObject(responseresult); if (x2ServerResult.Result != X2ServerResult.Ok) { throw Oops.Bah(x2ServerResult.Msg); } } } catch (Exception e) { Log.Error("提报入库任务下发失败:"+e.Message, e); throw new Exception("提报入库任务下发失败:"+e.Message); } return "入库任务下发成功"; } [HttpPost] public async Task DelPrdReport(string id) { PrdReport prdReport = await _db.Queryable().SingleAsync(x => x.id == id); PrdMoTask prdMoTask = await _db.Queryable().SingleAsync(x => x.id == prdReport.mo_task_id); DbResult result = await _db.Ado.UseTranAsync(async () => { await _db.Updateable() .SetColumns(x => x.reported_work_qty == x.reported_work_qty - prdReport.reported_qty) .Where(x => x.id == prdMoTask.id) .ExecuteCommandAsync(); await _db.Updateable() .SetColumns(x => x.reported_work_qty == x.reported_work_qty - prdReport.reported_qty) .Where(x => x.id == prdMoTask.mo_id) .ExecuteCommandAsync(); await _db.Deleteable().Where(x => x.id == id).ExecuteCommandAsync(); }); return !result.IsSuccess ? throw Oops.Oh(ErrorCode.COM1008) : (dynamic)(result.IsSuccess ? "保存成功" : result.ErrorMessage); } /// /// 自检报废提交 /// /// 自检报废输入参数 /// true/false /// /// input: ///
{ ///
"icmo_code": 任务单号, ///
"scrap_qty": 报废数量, ///
"remark": 备注, ///
"categoryItems": [ ///
{ ///
"defective_category":次品分类, ///
"category_qty": 分类数量, ///
"items": [ ///
{ ///
"defective_item": 次品项, ///
"defective_item_qty": 次品项数量 ///
} ///
] ///
} ///
] ///
} ///
[HttpPost] public async Task SelfTestScrapped(SelfTestScrappedInput input) { bool tranFlag = true; ISqlSugarClient db = null; if (_db3!=null) { tranFlag = false; db = _db3; } else { db = _repository.AsSugarClient(); } if (await db.Queryable().AnyAsync(x => x.id == input.mo_task_id && x.mo_task_status == DictConst.MoStatusPauseCode)) { throw Oops.Bah("暂停的任务单无法报废"); } if(tranFlag) await db.Ado.BeginTranAsync(); try { List destDefects = new(); string batch = DateTime.Now.ToString("yyyyMMddHHmmss"); PrdMoTask prdMoTask = await db.Queryable().SingleAsync(x => x.id == input.mo_task_id); foreach (SelfTestScrappedInputItem categoryItem in input.categoryItems) { foreach (defectItem dItem in categoryItem.items) { PrdMoTaskDefect defect = new() { id = SnowflakeIdHelper.NextId(), mo_task_id = input.mo_task_id, material_id = prdMoTask.material_id, org_id = WmsWareHouseConst.AdministratorOrgId, batch = batch, defective_cagetory_id = categoryItem.category_id, defective_item = dItem.defective_item, defective_item_qty = dItem.defective_item_qty, create_id = _userManager.UserId, create_time = DateTime.Now, scrap_qty = input.scrap_qty }; destDefects.Add(defect); } } _ = await db.Insertable(destDefects).ExecuteCommandAsync(); int? scrapQty = db.Queryable().Where(it => it.mo_task_id == input.mo_task_id)?.Sum(d => d.defective_item_qty); if (scrapQty.HasValue && scrapQty.Value > 0)//更新生产任务表报废数量 { #region 质检模块 //质检模块 TriggerPlanEntity entity = new() { materialid = prdMoTask.material_id, processid = prdMoTask.process_id, workid = prdMoTask.workstation_id }; decimal? reported = prdMoTask.reported_work_qty == null ? 0 : prdMoTask.reported_work_qty; decimal? scrap = prdMoTask.scrap_qty == null ? 0 : prdMoTask.scrap_qty; entity.oldpronum = reported + scrap; entity.newpronum = input.scrap_qty; entity.triggerevent = EnumTriggerEvent.生产检定量; await _qcCheckPlanService.CreateTask(entity); #endregion _ = await db.Updateable().SetColumns(it => new PrdMoTask { scrap_qty = scrapQty.Value }).Where(it => it.id == input.mo_task_id).ExecuteCommandAsync(); } PrdMoTaskDefectRecord defectRecord = await db.Queryable().FirstAsync(it => it.mo_task_id == input.mo_task_id); if (defectRecord != null) { defectRecord.scrap_qty += input.scrap_qty; _ = await db.Updateable(defectRecord).ExecuteCommandAsync(); } PrdReportRecord reportMaster = await db.Queryable().FirstAsync(it => it.mo_task_id == input.mo_task_id); PrdMo prdMo = await db.Queryable().SingleAsync(x => x.id == prdMoTask.mo_id); _ = prdMo.reported_work_qty == null ? await db.Updateable() .SetColumns(x => x.scrap_qty == input.scrap_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync() : await db.Updateable() .SetColumns(x => x.scrap_qty == x.scrap_qty + input.scrap_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync(); _ = prdMo.complete_qty == null ? await db.Updateable() .SetColumns(x => x.complete_qty == input.scrap_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync() : await db.Updateable() .SetColumns(x => x.complete_qty == x.complete_qty + input.scrap_qty) .Where(x => x.id == prdMo.id).ExecuteCommandAsync(); if (reportMaster != null) { reportMaster.completed_qty += input.scrap_qty; _ = await db.Updateable(reportMaster).ExecuteCommandAsync(); } if (prdMoTask.schedule_type == 1) { PerProcessStandardsH processStandardsH = await db.Queryable() .Where(x => x.equip_id == prdMoTask.eqp_id && x.molds_id == prdMoTask.mold_id && x.output_material_id == prdMoTask.material_id && x.enabled == 1) .OrderByDescending(x => x.create_time).FirstAsync(); ToolMolds toolMolds = await db.Queryable().SingleAsync(x => x.id == prdMoTask.mold_id); if (toolMolds != null && toolMolds?.mold_cavity > 0 && processStandardsH != null && processStandardsH?.moulding_cycle > 0) { decimal? addTime = ((((prdMoTask.scheduled_qty - prdMoTask.reported_work_qty - input.scrap_qty) * processStandardsH?.moulding_cycle) - 1) / toolMolds.mold_cavity) + 1; if (prdMoTask.act_start_date != null && addTime != null && addTime > 0) { DateTime cal_plan_end_date = prdMoTask.act_start_date.Value.AddSeconds((double)addTime); _ = await db.Updateable() .SetColumns(x => x.plan_end_date == cal_plan_end_date) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); } } } else { List list = await db.Queryable() .LeftJoin((a, b) => a.process_id == b.process_id && b.enabled == 1) .Where((a, b) => a.process_id == prdMoTask.process_id).Select((a, b) => b).ToListAsync(); decimal max = list.Select(x => Convert.ToDecimal(x.standard_time)).Max(x => x); decimal? addTime = (prdMoTask.scheduled_qty - prdMoTask.reported_work_qty - input.scrap_qty) * max; if (prdMoTask.act_start_date != null && addTime != null && addTime > 0) { DateTime cal_plan_end_date = prdMoTask.act_start_date.Value.AddSeconds((double)addTime); _ = await db.Updateable() .SetColumns(x => x.plan_end_date == cal_plan_end_date) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); } } if(tranFlag) await db.Ado.CommitTranAsync(); } catch (Exception e) { if(tranFlag) await db.Ado.RollbackTranAsync(); Log.Error(e.Message,e); throw Oops.Bah(e.Message); } return true; } /// /// 修改组装、包装,生产任务信息 /// /// [HttpPost] public async Task UpdatePackMoTask(PackPrdTaskUpInput input) { if (input == null) { throw new ArgumentNullException("input"); } int row = await _db.Updateable().SetColumns(it => new PrdMoTask { workline_id = input.workline_id, bom_id = input.bom_id, estimated_start_date = input.estimated_start_date, estimated_end_date = input.estimated_end_date, scheduled_qty = input.scheduled_qty, }) .Where(it => it.id == input.mo_task_id).ExecuteCommandAsync(); return row > 0; } /// /// 生成子工单 /// /// [HttpPost] public async Task GenSubMo(GenSubMoCrInput input) { if (input is null) { throw new ArgumentNullException("input"); } if (input.ids is null || input.ids.Count == 0) { throw new ArgumentException($"{nameof(input.ids)} not be null or count zero"); } PrdMo curMo = await _db.Queryable().FirstAsync(it => it.id == input.mo_id); if (curMo == null) { throw new ArgumentNullException("创建子工单时的父工单不能为null"); } var outMaterials = await _db.Queryable().InnerJoin((a, b) => a.id == b.mbom_id) .InnerJoin((a, b, c) => a.id == c.mbom_id && b.id == c.mbom_process_id) .Where((a, b, c) => a.id == input.bom_id && input.ids.Contains(b.process_id)) .Select((a, b, c) => new { c.material_id, c.num, }) .ToListAsync(); if (outMaterials?.Count > 0) { List ids = outMaterials.Select(x => x.material_id).ToList(); _ = await _db.Deleteable().Where(it => it.parent_id == input.mo_id).ExecuteCommandAsync(); if (ids?.Count > 0) { Dictionary dicOutMaterialNum = outMaterials.DistinctBy(x => x.material_id).ToDictionary(x => x.material_id, x => x.num.ParseToInt()); List subMoList = new(); List outputMaterials = await _db.Queryable().Where(it => ids.Contains(it.id)).ToListAsync(); foreach (BasMaterial om in outputMaterials) { PrdMo subMo = new() { material_id = om.id, material_code = om.code, plan_qty = dicOutMaterialNum.ContainsKey(om.id) ? dicOutMaterialNum[om.id] * curMo.plan_qty : 0, mo_type = curMo.mo_type, parent_id = curMo.id, plan_start_date = curMo.plan_start_date, plan_end_date = curMo.plan_end_date, create_id = _userManager.UserId, create_time = DateTime.Now, mo_status = DictConst.WaitProductId }; subMoList.Add(subMo); } //生成子工单编码 for (int i = 0; i < subMoList.Count; i++) { string num = (i + 1).ToString().PadLeft(2, '0'); subMoList[i].mo_code = $"{curMo.mo_code}-{num}"; } int row = await _db.Insertable(subMoList).ExecuteCommandAsync(); if (row < 1) { throw Oops.Oh(ErrorCode.COM1000); } } } } #endregion private static readonly Dictionary dicProperties = new(StringComparer.OrdinalIgnoreCase); private static T DictionaryToObject(IDictionary dictionary) where T : class, new() { string name = typeof(T).Name; T instance = new(); if (!dicProperties.TryGetValue(name, out string[] properies)) { properies = instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Select(p => p.Name).ToArray(); dicProperties[name] = properies; } foreach (string pn in properies) { if (dictionary.ContainsKey(pn)) { instance.PropertySetValue(pn, dictionary[pn]); } } return instance; } // private async Task GetList(VisualDevModelListQueryInput input) // { // var db = _repository.AsSugarClient(); // VisualDevEntity? templateEntity = await _visualDevService.GetInfoById(ModuleId, true); // var data = await _runService.GetListResult(templateEntity, input); // if (data?.list?.Count > 0) // { // foreach (var row in data.list) // { // var dic = row.ToDictionary(x => x.Key, x => x.Value); // var pkName = "material_id_id"; // if (dic.ContainsKey(pkName)) // { // var materialId = dic[pkName]?.ToString(); // var material = await db.Queryable().FirstAsync(it => it.id == materialId); // if (material != null) // { // row["material_id"] = $"{material.code}/{material.name}"; // } // } // //模具 // if (dic.ContainsKey("mold_id")) // { // var moldId = dic["mold_id"]?.ToString(); // var mold = await db.Queryable().FirstAsync(it => it.id == moldId); // if (mold != null) // { // row["mold_id"] = $"{mold.mold_code}/{mold.mold_name}"; // } // } // //设备 // if (dic.ContainsKey("eqp_id")) // { // var eqpId = dic["eqp_id"]?.ToString(); // var eqp = await db.Queryable().FirstAsync(it => it.id == eqpId); // if (eqp != null) // { // row["eqp_id"] = $"{eqp.code}/{eqp.name}"; // } // } // } // } // return data!; // } private async Task GetList(VisualDevModelListQueryInput input) { ISqlSugarClient db = _repository.AsSugarClient(); Dictionary? queryJson = !string.IsNullOrEmpty(input.queryJson) ? JsonConvert.DeserializeObject>(input.queryJson) : new Dictionary(); string moTaskCode = queryJson.ContainsKey("mo_task_code") ? queryJson["mo_task_code"].ToString() : ""; string eqpId = queryJson.ContainsKey("eqp_id") ? queryJson["eqp_id"].ToString() : ""; List worklineIds = new(); List equipIds = new(); if (!string.IsNullOrEmpty(eqpId)) { worklineIds = await db.Queryable().Where(x => x.ParentId == eqpId && x.Category == DictConst.RegionCategoryWorklineCode && x.DeleteMark == null).Select(x => x.Id).ToListAsync(); equipIds = await db.Queryable().Where(x => x.equip_type_id == eqpId).Select(x => x.id).ToListAsync(); if (equipIds == null || equipIds.IsEmpty()) { equipIds.Add(eqpId); } } SqlSugarPagedList result = await db.Queryable() .LeftJoin((a, b) => a.material_id == b.id) .LeftJoin((a, b, c) => c.EnCode == DictConst.TaskStatus) .LeftJoin((a, b, c, d) => c.Id == d.DictionaryTypeId && a.mo_task_status == d.EnCode) .LeftJoin((a, b, c, d, e) => a.mold_id == e.id) .LeftJoin((a, b, c, d, e, f) => a.mo_id == f.id) .LeftJoin((a, b, c, d, e, f, g) => a.workline_id == g.Id) .LeftJoin((a, b, c, d, e, f, g, h) => a.eqp_id == h.id) // .LeftJoin((a, b, c, d, e, f, g, h,i)=>a.worker_id==i.Id) .WhereIF(!string.IsNullOrEmpty(moTaskCode), (a, b, c, d) => a.mo_task_code.Contains(moTaskCode)) .WhereIF(!string.IsNullOrEmpty(eqpId) && equipIds.Count <= 0 && worklineIds.Count <= 0, (a, b, c, d) => a.workline_id == eqpId || a.eqp_id == eqpId) .WhereIF(worklineIds.Count > 0, (a, b, c, d) => worklineIds.Contains(a.workline_id)) .WhereIF(equipIds.Count > 0, (a, b, c, d) => equipIds.Contains(a.eqp_id)) .Where((a) => a.mo_task_status == DictConst.ToBeStartedEnCode || a.mo_task_code == DictConst.ToBeScheduledEncode || a.mo_task_code == DictConst.MoStatusPauseCode) .Select((a, b, c, d, e, f, g, h) => new WorkOrderAdjustmentListOutput { id = a.id, mo_task_code = a.mo_task_code, material_id = b.code + "/" + b.name, material_id_id = a.material_id, mold_id = e.mold_code + "/" + e.mold_name, mold_id_id = a.mold_id, mo_task_status = d.FullName, plan_qty = f.plan_qty, complete_qty = SqlFunc.IsNull(a.reported_work_qty, 0) + SqlFunc.IsNull(a.scrap_qty, 0), scheduled_qty = a.scheduled_qty, workline_id = a.workline_id == null ? "" : g.EnCode + "/" + g.FullName, workline_id_id = a.workline_id, estimated_start_date = a.estimated_start_date == null ? "" : a.estimated_start_date.Value.ToString("yyyy-MM-dd"), estimated_end_date = a.estimated_end_date == null ? "" : a.estimated_end_date.Value.ToString("yyyy-MM-dd"), eqp_id = a.eqp_id == null ? "" : h.code + "/" + h.name, eqp_id_id = a.eqp_id, create_time = a.create_time == null ? "" : a.create_time.Value.ToString(DbTimeFormat.SS), schedule_type = a.schedule_type, // worker_id = i.RealName dayshift_worker_id = a.dayshift_worker_id, dayshiftafter_worker_id = a.dayshiftafter_worker_id, nightshift_worker_id = a.nightshift_worker_id, nightshiftafter_worker_id = a.nightshiftafter_worker_id, }).OrderByDescending(a => a.create_time).ToPagedListAsync(input.currentPage, input.pageSize); List userIdList = result.list.Select(x => x.dayshift_worker_id).Distinct().ToList(); userIdList.AddRange(result.list.Select(x => x.dayshiftafter_worker_id).Distinct().ToList()); userIdList.AddRange(result.list.Select(x => x.nightshift_worker_id).Distinct().ToList()); userIdList.AddRange(result.list.Select(x => x.nightshiftafter_worker_id).Distinct().ToList()); List userEntities = await db.Queryable().Where(x=>userIdList.Contains(x.Id)).ToListAsync(); foreach (var item in result.list) { item.dayshift_worker_id = userEntities.Find(x=>x.Id==item.dayshift_worker_id)?.RealName ?? item.dayshift_worker_id; item.dayshiftafter_worker_id = userEntities.Find(x=>x.Id==item.dayshiftafter_worker_id)?.RealName ?? item.dayshiftafter_worker_id; item.nightshift_worker_id = userEntities.Find(x=>x.Id==item.nightshift_worker_id)?.RealName ?? item.nightshift_worker_id; item.nightshiftafter_worker_id = userEntities.Find(x=>x.Id==item.nightshiftafter_worker_id)?.RealName ?? item.nightshiftafter_worker_id; } return PageResult.SqlSugarPageResult(result); } /// /// 删除 /// /// /// private async Task Delete(string id) { ISqlSugarClient db = _repository.AsSugarClient(); DbResult result = await db.Ado.UseTranAsync(async () => { int row = -1; PrdMoTask prdTask = await db.Queryable().FirstAsync(it => it.id == id); row = await db.Deleteable().Where(it => it.id == id).ExecuteCommandAsync(); if (row > 0) { PrdMo? prdMo = await db.Queryable().FirstAsync(it => it.id == prdTask.mo_id); if (prdMo is not null) { prdMo.scheduled_qty += prdTask.scheduled_qty; prdMo.mo_status = DictConst.ScheduledId; row = await db.Updateable(prdMo).ExecuteCommandAsync(); } } return row > 0; }); if (!result.IsSuccess) { throw Oops.Oh(ErrorCode.COM1002); } } public async Task> GetListByEqpId(string eqpId) { return await _db.Queryable().Where(it => it.eqp_id == eqpId && it.mo_task_status == DictConst.InProgressEnCode).ToListAsync(); } /// /// 计算预计结束日期 /// /// /// /// [HttpPost] public async Task GetEstimatedEndTime(CountEstimatedEndTimeInput input) { ISqlSugarClient db = _repository.AsSugarClient(); if (input.type == 1) { PerProcessStandardsH processStandardsH = await db.Queryable() .Where(x => x.equip_id == input.equip_id && x.molds_id == input.molds_id && x.output_material_id == input.material_id && x.enabled == 1) .OrderByDescending(x => x.create_time).FirstAsync(); ToolMolds toolMolds = await db.Queryable().SingleAsync(x => x.id == input.molds_id); if (toolMolds == null) { throw Oops.Bah("没找到模具,预计完成时间无法计算"); } if (toolMolds?.mold_cavity <= 0) { throw Oops.Bah("模穴数错误,预计完成时间无法计算"); } if (processStandardsH == null) { throw Oops.Bah("工艺标准成型周期错误,预计完成时间无法计算"); } if (processStandardsH?.moulding_cycle <= 0) { throw Oops.Bah("工艺标准成型周期错误,预计完成时间无法计算"); } decimal? addTime = (((input.scheduled_qty * processStandardsH?.moulding_cycle) - 1) / toolMolds.mold_cavity) + 1; return input.estimated_start_date.AddSeconds((double)addTime.Value).ToString("yyyy-MM-dd HH:mm:ss"); } else { List list = await db.Queryable() .LeftJoin((a, b) => a.process_id == b.process_id && b.enabled == 1) .Where((a, b) => a.mbom_id == input.mbom_id).Select((a, b) => b).ToListAsync(); if (list.IsEmpty()) { throw Oops.Bah("无标准工时,预计完成时间无法计算"); } decimal max = list.Select(x => Convert.ToDecimal(x.standard_time)).Max(x => x); decimal? addTime = input.scheduled_qty * max; return input.estimated_start_date.AddSeconds((double)addTime.Value).ToString("yyyy-MM-dd HH:mm:ss"); } } /// /// 获取这个产线生产中的任务单 /// /// [HttpPost] public async Task GetMoTaskByWorklineId(Dictionary dic) { string id = dic["id"]; return await _repository.AsSugarClient().Queryable() .Where(x => x.workline_id == id && x.mo_task_status == DictConst.InProgressEnCode).FirstAsync(); } /// /// 更换机台 /// /// [HttpPost] public async Task ChangeEquip(ChangeEquipInput input) { ISqlSugarClient db = _repository.AsSugarClient(); DbResult result = await db.Ado.UseTranAsync(async () => { PrdMoTask moTask = await db.Queryable().SingleAsync(x => x.id == input.mo_task_id); if (moTask.eqp_id == input.equip_id) { throw new Exception("与原机台相同"); } _ = await db.Updateable().SetColumns(x => x.eqp_id == input.equip_id) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); PrdMo mo = await db.Queryable().SingleAsync(x => x.id == moTask.mo_id); BasMaterial? material = await db.Queryable().SingleAsync(x => x.id == moTask.material_id); BasMaterial process = await db.Queryable().SingleAsync(x => x.id == moTask.process_id); PrdTaskLog taskLog = new() { id = SnowflakeIdHelper.NextId(), mo_code = mo?.mo_code!, eqp_code = (await db.Queryable().FirstAsync(it => it.id == input.equip_id))?.code!, mold_code = "", item_code = material?.code!, item_standard = material?.material_specification!, status = "更换机台", operator_name = _userManager.RealName, create_id = _userManager.UserId, create_time = DateTime.Now, mo_task_id = moTask.id, mo_task_code = moTask.mo_task_code, station_code = "", process_code = process?.code }; _ = await db.Insertable(taskLog).ExecuteCommandAsync(); }); return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "更换成功" : result.ErrorMessage); } /// /// 更换模具 /// /// [HttpPost] public async Task ChangeMold(ChangeMoldInput input) { ISqlSugarClient db = _repository.AsSugarClient(); DbResult result = await db.Ado.UseTranAsync(async () => { PrdMoTask moTask = await db.Queryable().SingleAsync(x => x.id == input.mo_task_id); if (moTask.mold_id == input.mold_id) { throw new Exception("与原模具相同"); } _ = await db.Updateable().SetColumns(x => x.mold_id == input.mold_id) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); PrdMo mo = await db.Queryable().SingleAsync(x => x.id == moTask.mo_id); ToolMolds mold = await db.Queryable().SingleAsync(x => x.id == input.mold_id); BasMaterial? material = await db.Queryable().SingleAsync(x => x.id == moTask.material_id); BasMaterial process = await db.Queryable().SingleAsync(x => x.id == moTask.process_id); PrdTaskLog taskLog = new() { id = SnowflakeIdHelper.NextId(), mo_code = mo?.mo_code!, eqp_code = "", mold_code = mold?.mold_code, item_code = material?.code!, item_standard = material?.material_specification!, status = "更换模具", operator_name = _userManager.RealName, create_id = _userManager.UserId, create_time = DateTime.Now, mo_task_id = moTask.id, mo_task_code = moTask.mo_task_code, station_code = "", process_code = process?.code }; _ = await db.Insertable(taskLog).ExecuteCommandAsync(); }); return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "更换成功" : result.ErrorMessage); } /// /// 更换产线 /// /// [HttpPost] public async Task ChangeWorkline(ChangeWorklineInput input) { ISqlSugarClient db = _repository.AsSugarClient(); DbResult result = await db.Ado.UseTranAsync(async () => { PrdMoTask moTask = await db.Queryable().SingleAsync(x => x.id == input.mo_task_id); if (moTask.workline_id == input.workline_id) { throw new Exception("与原产线相同"); } _ = await db.Updateable().SetColumns(x => x.workline_id == input.workline_id) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); PrdMo mo = await db.Queryable().SingleAsync(x => x.id == moTask.mo_id); BasMaterial? material = await db.Queryable().SingleAsync(x => x.id == moTask.material_id); BasMaterial process = await db.Queryable().SingleAsync(x => x.id == moTask.process_id); PrdTaskLog taskLog = new() { id = SnowflakeIdHelper.NextId(), mo_code = mo?.mo_code!, eqp_code = "", mold_code = "", item_code = material?.code!, item_standard = material?.material_specification!, status = "更换产线", operator_name = _userManager.RealName, create_id = _userManager.UserId, create_time = DateTime.Now, mo_task_id = moTask.id, mo_task_code = moTask.mo_task_code, station_code = "", process_code = process?.code }; _ = await db.Insertable(taskLog).ExecuteCommandAsync(); }); return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "更换成功" : result.ErrorMessage); } /// /// 更换员工 /// /// [HttpPost] public async Task ChangeWorker(ChangeWorkerInput input) { ISqlSugarClient db = _repository.AsSugarClient(); DbResult result = await db.Ado.UseTranAsync(async () => { PrdMoTask moTask = await db.Queryable().SingleAsync(x => x.id == input.mo_task_id); // if (moTask.worker_id == input.worker_id) // { // throw new Exception("与原员工相同"); // } _ = await db.Updateable() .SetColumns(x => x.dayshift_worker_id == input.dayshift_worker_id) .SetColumns(x => x.nightshift_worker_id == input.nightshift_worker_id) .SetColumns(x => x.dayshiftafter_worker_id == input.dayshiftafter_worker_id) .SetColumns(x => x.nightshiftafter_worker_id == input.nightshiftafter_worker_id) .Where(x => x.id == input.mo_task_id).ExecuteCommandAsync(); PrdMo mo = await db.Queryable().SingleAsync(x => x.id == moTask.mo_id); BasMaterial? material = await db.Queryable().SingleAsync(x => x.id == moTask.material_id); BasMaterial process = await db.Queryable().SingleAsync(x => x.id == moTask.process_id); PrdTaskLog taskLog = new() { id = SnowflakeIdHelper.NextId(), mo_code = mo?.mo_code!, eqp_code = "", mold_code = "", item_code = material?.code!, item_standard = material?.material_specification!, status = "更换员工", operator_name = _userManager.RealName, create_id = _userManager.UserId, create_time = DateTime.Now, mo_task_id = moTask.id, mo_task_code = moTask.mo_task_code, station_code = "", process_code = process?.code }; _ = await db.Insertable(taskLog).ExecuteCommandAsync(); }); return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "更换成功" : result.ErrorMessage); } /// /// 根据id获取任务单相关信息 /// /// [HttpPost] public async Task GetPrdMoTaskInfoById(Dictionary dic) { string id = dic.ContainsKey("id") ? dic["id"] : ""; if (string.IsNullOrEmpty(id)) { return null; } ISqlSugarClient db = _repository.AsSugarClient(); return await db.Queryable() .LeftJoin((a, b) => a.material_id == b.id) .LeftJoin((a, b, c) => a.mold_id == c.id) .LeftJoin((a, b, c, d) => a.eqp_id == d.id) .LeftJoin((a, b, c, d, e) => e.EnCode == a.mo_task_status && e.DictionaryTypeId == DictConst.PrdTaskStatusTypeId) .LeftJoin((a, b, c, d, e, f) => a.process_id == f.id) .LeftJoin((a, b, c, d, e, f, g) => a.workstation_id == g.Id) .Where((a, b, c, d) => a.id == id) .Select((a, b, c, d, e, f, g) => new { a.id, a.mo_task_code, mo_task_status = e.FullName, a.material_id, material_code = b.code, material_name = b.name, a.mold_id, c.mold_code, c.mold_name, a.schedule_type, equip_code = d.code, equip_name = d.name, a.workstation_id, workstation_code = g.EnCode, workstation_name = g.FullName, a.scheduled_qty, a.reported_work_qty, a.scrap_qty, a.process_id, f.process_name, }).FirstAsync(); } /// /// 获取组装包装生产排产甘特图信息 /// /// [HttpPost] public async Task GetGanntInfo1() { ISqlSugarClient db = _repository.AsSugarClient(); Dictionary result = new(); var listRows = await db.Queryable() .LeftJoin((a, b) => a.equip_type_id == b.id) .Where((a, b) => b.code == "ZSJ" || b.code == "005") .OrderBy((a, b) => b.code) .Select((a, b) => new { a.id, expanded = true, label = a.name, parentId = "" }).ToListAsync(); DateTime startTime = Convert.ToDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-15).ToString("yyyy-MM-dd 00:00:00")); DateTime endTime = Convert.ToDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).AddDays(15).ToString("yyyy-MM-dd 23:59:59")); var charItems = await db.Queryable() .LeftJoin((a, b) => a.material_id == b.id) .LeftJoin((a, b, c) => c.DictionaryTypeId == DictConst.PrdTaskStatusTypeId && a.mo_task_status == c.EnCode) .Where((a, b) => a.mo_task_status == DictConst.ToBeStartedEnCode || a.mo_task_status == DictConst.ToBeScheduledEncode || a.mo_task_status == DictConst.MoStatusPauseCode || a.mo_task_status == DictConst.InProgressEnCode) .Where((a, b) => a.schedule_type == 1 && string.IsNullOrEmpty(a.parent_id)) .Where((a, b) => a.estimated_start_date != null && a.estimated_end_date != null) .Where((a, b) => a.estimated_start_date >= startTime && a.estimated_end_date <= endTime) .Select((a, b, c) => new { a.id, label = b.name, material_name = b.name, reported_work_qty = a.reported_work_qty == null ? 0 : a.reported_work_qty, a.scheduled_qty, mo_task_status = c.FullName, // label = b.name +" " +(a.reported_work_qty==null?0:a.reported_work_qty)+"/"+a.scheduled_qty + " " +c.FullName, rowId = a.eqp_id, time = new GanntTime { start = a.estimated_start_date, end = a.estimated_end_date }, //linkedWith = SqlFunc.Subqueryable().Where(x=>a.schedule_type==2 && string.IsNullOrEmpty(a.parent_id) && a.workline_id==x.workline_id && (x.mo_task_status==DictConst.ToBeStartedEnCode || x.mo_task_status==DictConst.MoStatusPauseCode || x.mo_task_status==DictConst.ToBeScheduledEncode)).ToList(x=>x.id), tips = new GanntTimeTips { // material_code = b.code, // material_name = b.name, mo_task_code = a.mo_task_code, // start_time = a.estimated_start_date==null ? "" : a.estimated_start_date.Value.ToString("yyyy-MM-dd HH:mm:ss"), // end_time = a.estimated_end_date==null ? "" : a.estimated_end_date.Value.ToString("yyyy-MM-dd HH:mm:ss"), start_time = a.estimated_start_date, end_time = a.estimated_end_date, } }) .ToListAsync(); // DateTime min = (DateTime)charItems.Min(x => x.time.start); TimeSpan ts1 = new(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).Ticks); TimeSpan ts2 = new(Convert.ToDateTime(startTime.ToString("yyyy-MM-dd")).Ticks); TimeSpan ts3 = ts1.Subtract(ts2).Duration(); result.Add("listRows", listRows); result.Add("charItems", charItems); result.Add("startTime", startTime); result.Add("endTime", endTime); result.Add("totalDays", ts3.TotalDays); return result; } /// /// 获取组装包装生产排产甘特图信息 /// /// [HttpPost] public async Task GetGanntInfo2() { ISqlSugarClient db = _repository.AsSugarClient(); Dictionary result = new(); var listRows = await db.Queryable() .Where(x => x.DeleteMark == null && (x.Category == DictConst.RegionCategoryWorklineCode || x.Category == DictConst.RegionCategoryWorkshopCode)) .OrderByDescending(x => x.Category) .Select(x => new { id = x.Id, expanded = true, label = x.FullName, parentId = x.Category == DictConst.RegionCategoryWorklineCode ? x.ParentId : "" }).ToListAsync(); DateTime startTime = Convert.ToDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-15).ToString("yyyy-MM-dd 00:00:00")); DateTime endTime = Convert.ToDateTime(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).AddDays(15).ToString("yyyy-MM-dd 23:59:59")); var charItems = await db.Queryable() .LeftJoin((a, b) => a.material_id == b.id) .LeftJoin((a, b, c) => c.DictionaryTypeId == DictConst.PrdTaskStatusTypeId && a.mo_task_status == c.EnCode) .Where((a, b) => a.mo_task_status == DictConst.ToBeStartedEnCode || a.mo_task_status == DictConst.ToBeScheduledEncode || a.mo_task_status == DictConst.MoStatusPauseCode || a.mo_task_status == DictConst.InProgressEnCode) .Where((a, b) => a.schedule_type == 2 && string.IsNullOrEmpty(a.parent_id)) .Where((a, b) => a.estimated_start_date != null && a.estimated_end_date != null) .Where((a, b) => a.estimated_start_date >= startTime && a.estimated_end_date <= endTime) .Select((a, b, c) => new { a.id, label = b.name, material_name = b.name, reported_work_qty = a.reported_work_qty == null ? 0 : a.reported_work_qty, a.scheduled_qty, mo_task_status = c.FullName, // label = b.name +" " +(a.reported_work_qty==null?0:a.reported_work_qty)+"/"+a.scheduled_qty + " " +c.FullName, rowId = a.workline_id, time = new GanntTime { start = a.estimated_start_date, end = a.estimated_end_date }, //linkedWith = SqlFunc.Subqueryable().Where(x=>a.schedule_type==2 && string.IsNullOrEmpty(a.parent_id) && a.workline_id==x.workline_id && (x.mo_task_status==DictConst.ToBeStartedEnCode || x.mo_task_status==DictConst.MoStatusPauseCode || x.mo_task_status==DictConst.ToBeScheduledEncode)).ToList(x=>x.id), tips = new GanntTimeTips { // material_code = b.code, // material_name = b.name, mo_task_code = a.mo_task_code, // start_time = a.estimated_start_date==null ? "" : a.estimated_start_date.Value.ToString("yyyy-MM-dd HH:mm:ss"), // end_time = a.estimated_end_date==null ? "" : a.estimated_end_date.Value.ToString("yyyy-MM-dd HH:mm:ss"), start_time = a.estimated_start_date, end_time = a.estimated_end_date, } }) .ToListAsync(); // DateTime min = (DateTime)charItems.Min(x => x.time.start); TimeSpan ts1 = new(Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd")).Ticks); TimeSpan ts2 = new(Convert.ToDateTime(startTime.ToString("yyyy-MM-dd")).Ticks); TimeSpan ts3 = ts1.Subtract(ts2).Duration(); result.Add("listRows", listRows); result.Add("charItems", charItems); result.Add("startTime", startTime); result.Add("endTime", endTime); result.Add("totalDays", ts3.TotalDays); return result; } /// /// 保存注塑挤出生产排产甘特图信息 /// /// [HttpPost] public async Task SaveData1(List input) { ISqlSugarClient db = _repository.AsSugarClient(); DbResult result = await db.Ado.UseTranAsync(async () => { foreach (GanntSaveInput item in input) { // if(await db.Queryable().Where(x=>x.Id==item.row_id && x.Category==DictConst.RegionCategoryWorkshopCode).AnyAsync()) // throw Oops.Bah("不能排在车间上"); PrdMoTask prdMoTask = await db.Queryable().SingleAsync(x => x.id == item.id); if (prdMoTask.eqp_id != item.row_id) { _ = await db.Updateable() .SetColumns(x => x.workline_id == item.row_id) .Where(x => x.id == item.id).ExecuteCommandAsync(); } if (prdMoTask.estimated_start_date.Value.ToString("yyyy-MM-dd HH:mm") != item.time.start.Value.ToString("yyyy-MM-dd HH:mm")) { _ = await db.Updateable() .SetColumns(x => x.estimated_start_date == item.time.start) .Where(x => x.id == item.id).ExecuteCommandAsync(); } if (prdMoTask.estimated_end_date.Value.ToString("yyyy-MM-dd HH:mm") != item.time.end.Value.ToString("yyyy-MM-dd HH:mm")) { _ = await db.Updateable() .SetColumns(x => x.estimated_end_date == item.time.end) .Where(x => x.id == item.id).ExecuteCommandAsync(); } } }); return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "排产成功" : result.ErrorMessage); } /// /// 保存组装包装生产排产甘特图信息 /// /// [HttpPost] public async Task SaveData2(List input) { ISqlSugarClient db = _repository.AsSugarClient(); DbResult result = await db.Ado.UseTranAsync(async () => { foreach (GanntSaveInput item in input) { if (await db.Queryable().Where(x => x.Id == item.row_id && x.Category == DictConst.RegionCategoryWorkshopCode).AnyAsync()) { throw Oops.Bah("不能排在车间上"); } PrdMoTask prdMoTask = await db.Queryable().SingleAsync(x => x.id == item.id); if (prdMoTask.workline_id != item.row_id) { _ = await db.Updateable() .SetColumns(x => x.workline_id == item.row_id) .Where(x => x.id == item.id).ExecuteCommandAsync(); } if (prdMoTask.estimated_start_date.Value.ToString("yyyy-MM-dd HH:mm") != item.time.start.Value.ToString("yyyy-MM-dd HH:mm")) { _ = await db.Updateable() .SetColumns(x => x.estimated_start_date == item.time.start) .Where(x => x.id == item.id).ExecuteCommandAsync(); } if (prdMoTask.estimated_end_date.Value.ToString("yyyy-MM-dd HH:mm") != item.time.end.Value.ToString("yyyy-MM-dd HH:mm")) { _ = await db.Updateable() .SetColumns(x => x.estimated_end_date == item.time.end) .Where(x => x.id == item.id).ExecuteCommandAsync(); } } }); return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "排产成功" : result.ErrorMessage); } /// /// 获取工单各个状态数量 /// /// [HttpPost] public async Task GetMoTaskStatusNum() { return await _db.Queryable(). LeftJoin((a, b) => a.Id == b.DictionaryTypeId) .LeftJoin((a, b, c) => b.Id == c.mo_status) .Where((a, b, c) => a.EnCode == DictConst.MoTaskStatusCode) .GroupBy((a, b, c) => new { mo_status_code = b.EnCode, mo_status_name = b.FullName }) .Select((a, b, c) => new { mo_status_code = b.EnCode, mo_status_name = b.FullName, count = SqlFunc.AggregateCount(c.mo_status) }).ToListAsync(); } /// /// 获取备料计划 /// /// [HttpPost] public async Task GetMaterialPreparationPlan() { string now = DateTime.Now.ToString("yyyy-MM-dd"); List childrenList = await _db.Queryable() .LeftJoin((a, b) => a.id == b.parent_id) .LeftJoin((a, b, c) => b.material_id == c.id) .Where((a, b) => a.schedule_type == 2 && string.IsNullOrEmpty(a.parent_id) && a.estimated_start_date.Value.ToString("yyyy-MM-dd") == now) .Select((a, b, c) => new MaterialPreparationPlanDOutput { mo_task_id = b.id, mo_task_code = b.mo_task_code, rate_num = SqlFunc.Subqueryable().Where(o => o.id == a.bom_id) .OrderByDesc(o => o.create_time).Select(o => o.num), parent_id = b.parent_id, workstation_id = b.workstation_id, material_id = b.material_id, material_code = c.code, children = SqlFunc.Subqueryable() .LeftJoin((x, y) => x.material_id == y.id) .Where((x, y) => x.mbom_process_id == b.mbom_process_id) .ToList((x, y) => new MaterialPreparationPlanDDOutput() { material_id = x.material_id, material_code = y.code, category_id = y.category_id, num = x.num, molecule = x.molecule, denominator = x.denominator, }) }).ToListAsync(); List prdMoTaskList = await _db.Queryable() .LeftJoin((a, b) => a.material_id == b.id) .Where(a => a.schedule_type == 2 && string.IsNullOrEmpty(a.parent_id) && a.estimated_start_date.Value.ToString("yyyy-MM-dd") == now && (a.mo_task_status == DictConst.MoStatusPauseCode || a.mo_task_status == DictConst.ToBeScheduledEncode || a.mo_task_status == DictConst.ToBeStartedEnCode || a.mo_task_status == DictConst.InProgressEnCode)) .Select((a, b) => new MaterialPreparationPlanOutput() { mo_task_id = a.id, mo_task_code = a.mo_task_code, material_id = b.id, material_code = b.code, num = a.scheduled_qty, }) .ToListAsync(); foreach (MaterialPreparationPlanOutput? item in prdMoTaskList) { item.children = childrenList.Where(x => x.parent_id == item.mo_task_id).ToList(); foreach (MaterialPreparationPlanDOutput itemChild in item.children) { foreach (MaterialPreparationPlanDDOutput itemChildChild in itemChild.children) { if (itemChildChild.num > 0 && itemChild.rate_num != null && itemChild.rate_num > 0) { itemChildChild.num = item.num * itemChildChild.num / itemChild.rate_num; } } } } return prdMoTaskList; } /// /// 根据工位获取进行中的任务单信息 /// /// /// [HttpPost] public async Task GetPrdMoTaskInfoByStationId(Dictionary dic) { string station_id = dic.ContainsKey("station_id") ? dic["station_id"] : ""; if (string.IsNullOrEmpty(station_id)) { throw Oops.Bah("工位错误"); } OrganizeEntity workline = await _organizeService.GetAnyParentByWorkstationId(station_id, DictConst.RegionCategoryWorklineCode); if (workline==null) { throw Oops.Bah($"未找到该工位{station_id}的车间"); } PrdMoTask? prdMoTask = await _db.Queryable().Where(x => x.workline_id==workline.Id && x.parent_id != null && x.mo_task_status == DictConst.InProgressEnCode).FirstAsync(); if (prdMoTask != null) { BasMaterial basMaterial = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.material_id); prdMoTask.material_name = basMaterial.name; } return prdMoTask; } /// /// 根据chanxian 获取进行中的任务单信息 /// /// /// [HttpPost] public async Task GetPrdMoTaskInfoByWorklineId(Dictionary dic) { string workline_id = dic.ContainsKey("workline_id") ? dic["workline_id"] : ""; if (string.IsNullOrEmpty(workline_id)) { throw Oops.Bah("产线错误"); } PrdMoTask? prdMoTask = await _db.Queryable().Where(x => x.workline_id == workline_id && x.mo_task_status == DictConst.InProgressEnCode && x.parent_id == null).FirstAsync(); if (prdMoTask != null) { BasMaterial basMaterial = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.material_id); prdMoTask.material_name = basMaterial.name; } return prdMoTask; } /// /// 根据工位获取进行中待开工暂停的任务单信息 /// /// /// [HttpPost] public async Task> GetPrdMoTaskListByStationId(Dictionary dic) { string station_id = dic.ContainsKey("station_id") ? dic["station_id"] : ""; if (string.IsNullOrEmpty(station_id)) { throw Oops.Bah("工位错误"); } List list = await _db.Queryable().Where(x => x.workstation_id == station_id && x.parent_id != null && (x.mo_task_status == DictConst.InProgressEnCode || x.mo_task_status == DictConst.ToBeStartedEnCode || x.mo_task_status == DictConst.MoStatusPauseCode )).ToListAsync(); if (list != null && list.Count>0) { foreach (var prdMoTask in list) { BasMaterial basMaterial = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.material_id); if (basMaterial == null) { throw Oops.Bah($"找不到物料{prdMoTask.material_id}"); } prdMoTask.material_name = basMaterial.name; } } return list; } /// /// 外包装根据工位id获取喷码数据 /// /// /// // [HttpPost] // public async Task GetMarkingInfoByStationId(MarkingLabelInput input) // { // PrdMoTask prdMoTask = await GetPrdMoTaskInfoByStationId(new Dictionary() // { // { "station_id", input.station_id } // }); // if (prdMoTask == null) throw Oops.Bah("没找到对应任务单"); // // if (await _db.Queryable().Where(x => // x.mo_task_code == prdMoTask.mo_task_code && x.status == "0" && x.is_label == 0 && x.is_mark==null).AnyAsync()) // { // await _db.Updateable() // .SetColumns(x => x.is_mark == 0) // .Where(x => x.mo_task_code == prdMoTask.mo_task_code && x.status == "0" && x.is_label == 0 && // x.is_mark == null) // .ExecuteCommandAsync(); // } // else // { // PrdOutPackMarkLabel prdOutPackMarkLabel = new PrdOutPackMarkLabel() // { // is_mark = 0, // is_label = null, // mo_task_code = prdMoTask.mo_task_code, // material_code = prdMoTask.material_code, // create_time = DateTime.Now, // }; // // await _db.Insertable(prdOutPackMarkLabel).ExecuteCommandAsync(); // } // // PrdMoTask parent = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.parent_id); // BasMaterial basMaterial = await _db.Queryable().SingleAsync(x=>x.id==parent.material_id); // // string code = $"(01){basMaterial.di ?? ""}\\n(11){DateTime.Now.ToString("yyMMdd")}\\n(17){DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}\\n(10){parent.batch??""}"; // // return code; // } /// /// 外包装根据工位id获取贴标数据 /// /// /// // [HttpPost] // public async Task GetLabelInfoByStationId(MarkingLabelInput input) // { // PrdMoTask prdMoTask = await GetPrdMoTaskInfoByStationId(new Dictionary() // { // { "station_id", input.station_id } // }); // if (prdMoTask == null) throw Oops.Bah("没找到对应任务单"); // // if (await _db.Queryable().Where(x => // x.mo_task_code == prdMoTask.mo_task_code && x.status == "0" && x.is_label == null && x.is_mark==0).AnyAsync()) // { // await _db.Updateable() // .SetColumns(x => x.is_label == 0) // .Where(x => x.mo_task_code == prdMoTask.mo_task_code && x.status == "0" && x.is_label == null && // x.is_mark == 0) // .ExecuteCommandAsync(); // } // else // { // PrdOutPackMarkLabel prdOutPackMarkLabel = new PrdOutPackMarkLabel() // { // is_mark = null, // is_label = 0, // mo_task_code = prdMoTask.mo_task_code, // material_code = prdMoTask.material_code, // create_time = DateTime.Now, // }; // // await _db.Insertable(prdOutPackMarkLabel).ExecuteCommandAsync(); // } // // PrdMoTask parent = await _db.Queryable().SingleAsync(x => x.id == prdMoTask.parent_id); // BasMaterial basMaterial = await _db.Queryable().SingleAsync(x=>x.id==parent.material_id); // // string code = $"(01){basMaterial.di ?? ""}\\n(11){DateTime.Now.ToString("yyMMdd")}\\n(17){DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}\\n(10){parent.batch??""}"; // // return code; // } /// /// 获取喷码贴标信息 /// /// [HttpPost] [AllowAnonymous] public async Task GetLabelInfo(MarkingLabelInput input) { Log.Information($"获取喷码贴标信息参数:{JsonConvert.SerializeObject(input)}"); //TODO 之后要改 Dictionary dic = new Dictionary() { ["WBZ1"] = WmsWareHouseConst.XUELUGUAN1XIAN,//血路管自动生产线1线 ["WBZ2"] = WmsWareHouseConst.XUELUGUAN2XIAN, }; if (dic.TryGetValue(input.result, out string worklineId)) { if (worklineId != null && !worklineId.IsEmpty()) { PrdMoTask prdMoTask = await _db.Queryable().Where(x => x.workline_id == worklineId && x.mo_task_status == DictConst.InProgressEnCode && x.parent_id != null).FirstAsync(); if (prdMoTask == null) throw Oops.Bah("没找到对应任务单"); BasMaterial basMaterial = await _db.Queryable().SingleAsync(x=>x.id==prdMoTask.material_id); string batch = prdMoTask.batch; string code = $"(01){basMaterial.di ?? ""}*(11){prdMoTask.act_start_date.Value.ToString("yyMMdd")}*(17){prdMoTask.first_start_date.Value.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}*(10){batch}#{basMaterial.material_specification}*{batch}*{prdMoTask.act_start_date.Value.ToString("yyyyMMdd")}*{prdMoTask.first_start_date.Value.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyyyMMdd")}*{basMaterial.material_standard}"; return code; } } // return "(01)16945155732691(11)240510(17)270510(10)24053026#TX-JB-12*24053026*202405*1020270510RJ-A1F3NC2"; return ""; } /// /// 视觉设备判定 /// /// [HttpPost] [AllowAnonymous] public async Task VisionResult(MarkingLabelInput input) { Log.Information($"视觉设备判定参数:{JsonConvert.SerializeObject(input)}"); PrdVisionResultRecord reocrd = new PrdVisionResultRecord(); reocrd.id = SnowflakeIdHelper.NextId(); reocrd.info = input.mark_code; reocrd.result = input.result; reocrd.create_time = DateTime.Now; reocrd.num = int.Parse(input.station_id); reocrd.status = 0; await _db.Insertable(reocrd).ExecuteCommandAsync(); return $"接收到参数:{JsonConvert.SerializeObject(input)}"; } /// /// 分配员工 /// /// /// [HttpPost] public async Task BindUser(Dictionary input) { string ids = input.GetOrDefault("ids"); string[] idList = ids.Split(","); // string workerId = input.GetOrDefault("worker_id"); string schedulingClassType = input.GetOrDefault("scheduling_class_type"); string dayshiftWorkerId = input.GetOrDefault("dayshift_worker_id"); string nightshiftWorkerId = input.GetOrDefault("nightshift_worker_id"); string dayshiftafterWorkerId = input.GetOrDefault("dayshiftafter_worker_id"); string nightshiftafterWorkerId = input.GetOrDefault("nightshiftafter_worker_id"); int row = await _db.Updateable() .SetColumns(x => x.scheduling_class_type == schedulingClassType) .SetColumns(x => x.dayshift_worker_id == dayshiftWorkerId) .SetColumns(x => x.nightshift_worker_id == nightshiftWorkerId) .SetColumns(x => x.dayshiftafter_worker_id == dayshiftafterWorkerId) .SetColumns(x => x.nightshiftafter_worker_id == nightshiftafterWorkerId) .Where(x => idList.Contains(x.id)) .ExecuteCommandAsync(); return row>0 ? "分配成功" : "分配失败"; } /// /// 设置批号 /// /// /// [HttpPost] public async Task SetBatch(Dictionary input) { string ids = input.GetOrDefault("ids"); string[] idList = ids.Split(","); string batch = input.GetOrDefault("batch"); int row = await _db.Updateable() .SetColumns(x => x.batch == batch) .SetColumns(x => x.is_hand_set_batch == 1) .Where(x => idList.Contains(x.id)) .ExecuteCommandAsync(); foreach (var id in idList) { PrdMoTask prdMoTask = await _db.Queryable().Where(x => x.id == id).SingleAsync(); if (prdMoTask.mo_task_status == DictConst.InProgressEnCode && prdMoTask.schedule_type==2) { BasMaterial basMaterial = await _db.Queryable().Where(x=>x.id==prdMoTask.material_id).SingleAsync(); string code1 = $"(01){basMaterial.di ?? ""}*(11){prdMoTask.act_start_date.Value.ToString("yyMMdd")}*(17){prdMoTask.first_start_date.Value.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}*(10){batch}"; string code2 = $"{basMaterial.material_specification}*{batch}*{prdMoTask.act_start_date.Value.ToString("yyyyMMdd")}*{prdMoTask.first_start_date.Value.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyyyMMdd")}*{basMaterial.material_standard}"; Dictionary dicCommand1 = new(StringComparer.OrdinalIgnoreCase) { ["DevName"] = "外包装箱码垛线", ["token"] = _eleCtlCfg.token, ["TagName"] = "WBZX_tb_cs", ["Value"] = code1, }; Dictionary dicCommand2 = new(StringComparer.OrdinalIgnoreCase) { ["DevName"] = "外包装箱码垛线", ["token"] = _eleCtlCfg.token, ["TagName"] = "WBZX_pm_cs", ["Value"] = code2, }; Log.Information($"贴标写入参数:{JsonConvert.SerializeObject(dicCommand1)}"); string result1 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand1, false); Log.Information($"贴标写入返回结果:{JsonConvert.SerializeObject(result1)}"); Log.Information($"喷码写入参数:{JsonConvert.SerializeObject(dicCommand2)}"); string result2 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand2, false); Log.Information($"喷码写入返回结果:{JsonConvert.SerializeObject(result2)}"); } } return row>0 ? "设置成功" : "设置失败"; } /// /// 末检 /// /// /// [HttpPost] public async Task LastCheck(Dictionary input) { string moTaskId = input.GetOrDefault("mo_task_id"); PrdMoTask task = await _db.Queryable().SingleAsync(x => x.id == moTaskId); if (task.has_last_check == 1) { throw Oops.Bah("已经生成过质检任务"); } DbResult result = await _db.Ado.UseTranAsync(async () => { await _db.Updateable() .SetColumns(x => x.has_last_check==1) .Where(x => x.id == moTaskId) .ExecuteCommandAsync(); ToolMolds toolMolds = await _db.Queryable().SingleAsync(x=>x.id==task.mold_id); TriggerPlanEntity entity = new() { materialid = task.material_id, processid = task.process_id, workid = task.workstation_id, triggerevent = EnumTriggerEvent.末检质检方案, mo_task_code = task.mo_task_code, newpronum = toolMolds?.mold_cavity }; await _qcCheckPlanService.CreateTask(entity); }); return !result.IsSuccess ? throw Oops.Oh(ErrorCode.COM1008) : (dynamic)(result.IsSuccess ? "操作成功" : result.ErrorMessage); } [HttpPost] public async Task GetSchedulingInfo(string id) { return await _db.Queryable().SingleAsync(x => x.id == id); } [HttpPost] public async Task GetWorkstationByPosition(string id) { return await _db.Queryable() .LeftJoin((a,b)=>a.OrganizeId==b.Id && b.Category==DictConst.RegionCategoryWorkstationCode) .Select((a,b)=>b) .FirstAsync(x => x.Id == id); } } }