using System.Reflection; 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.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 SqlSugar; using Tnb.BasicData; using Tnb.BasicData.Entities; using Tnb.BasicData.Entities.Dto; 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.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 readonly IBillRullService _billRuleService; private readonly IPrdInstockService _prdInstockService; private readonly IQcCheckPlanService _qcCheckPlanService; public OverideVisualDevFunc OverideFuncs { get; } = new OverideVisualDevFunc(); public PrdMoTaskService( ISqlSugarRepository repository, IUserManager userManager, IDictionaryDataService dictionaryDataService, IRunService runService, IBillRullService billRullService, IPrdInstockService prdInstockService, IVisualDevService visualDevService, IQcCheckPlanService qcCheckPlanService ) { _repository = repository; _userManager = userManager; _dictionaryDataService = dictionaryDataService; _runService = runService; _visualDevService = visualDevService; _db = _repository.AsSugarClient(); OverideFuncs.DeleteAsync = Delete; OverideFuncs.GetListAsync = GetList; _billRuleService = billRullService; _prdInstockService = prdInstockService; _qcCheckPlanService = qcCheckPlanService; } #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) .Where((a, b, c) => a.material_id == materialId) .Select((a, b, c) => 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, available_stations = SqlFunc.Subqueryable().Where(it => it.mold_id == a.id).Count(), }).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) .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).Count(), estimated_end_date = SqlFunc.Subqueryable().Where(x => x.eqp_id == b.id).OrderByDesc(o => o.plan_end_date).Select(x => x.plan_end_date) }).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) .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) => new PackSechelToBeIssueListOutput { mo_task_id = a.id, mo_task_code = a.mo_task_code, material_id = a.material_id, material_code = SqlFunc.Subqueryable().Where(it => it.id == a.material_id).Select(it => it.code), material_name = SqlFunc.Subqueryable().Where(it => it.id == a.material_id).Select(it => it.name), 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) }) .Mapper(it => it.mo_task_status = dic.ContainsKey(it.mo_task_status) ? dic[it.mo_task_status].ToString()! : "") .ToListAsync(); 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) .Where((a, b, c, d) => a.parent_id == mo_task_id) .Select((a, b, c, d, e) => 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, 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) }) .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(); 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_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_standard, 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 //根据工单号获取当前工单包含的已排产数 int? 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_standard!, 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) { await db.Ado.RollbackTranAsync(); } } 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); 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_standard!, 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(); //根据工单号获取当前工单包含的已排产数 int? 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 = a.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, 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, 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_standard!; 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(); } 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()) { throw new ArgumentException($"{nameof(input.Behavior)} not be null or empty"); } //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); ISqlSugarClient db = _repository.AsSugarClient(); List? list = await db.Queryable().Where(it => input.TaskIds.Contains(it.id)).Select(it => it).ToListAsync(); 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(); List 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.workstation_id == item.workstation_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("状态错误无法开始"); } break; case PrdTaskBehavior.Pause: if (item.mo_task_status == status) { throw Oops.Bah("已暂停的不能再暂停"); } if (item.mo_task_status != DictConst.InProgressEnCode) { throw Oops.Bah("状态错误无法暂停"); } 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("状态错误无法完成"); } 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_standard!; } 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(); } } } } //else // throw new AppFriendlyException("只有待下发状态的任务才可下发", 500); return row > 0; } /// /// 生产任务单修改 /// /// 生产任务单修改输入参数 /// /// [HttpPost] public async Task IcmoModify(IcmoUpInput input) { int row = -1; ISqlSugarClient db = _repository.AsSugarClient(); if (input.icmo_id.IsNullOrWhiteSpace()) { 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) // { // var row = -1; // var db = _repository.AsSugarClient(); // var report = await db.Queryable().FirstAsync(it => it.mo_task_id == input.mo_task_id); // // //if (report is not null) // //{ // // report.mo_task_code = input.mo_task_code; // // report.mo_task_id = input.mo_task_id; // // report.reported_work_qty += input.reported_qty; // // report.prd_qty += input.reported_qty; // //} // //else // { // report = input.Adapt(); // report.id = SnowflakeIdHelper.NextId(); // report.reported_qty = input.reported_qty; // report.create_id = _userManager.UserId; // report.create_time = DateTime.Now; // // } // row = await db.Insertable(report).ExecuteCommandAsync(); // var 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(); // } // 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) { 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); DbResult result = await _repository.AsSugarClient().Ado.UseTranAsync(async () => { 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 ((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")}%排产数量"); } } } 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.reported_qty = input.reported_qty; report.material_box_code = input.material_box_code; report.location_code = input.location_code; report.create_id = _userManager.UserId; report.create_time = DateTime.Now; // report.batch = input.mo_task_code + DateTimeOffset.Now.ToUnixTimeSeconds().ToString(); report.barcode = input.mo_task_code + DateTimeOffset.Now.ToUnixTimeSeconds().ToString(); // 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(); #region 质检模块 //质检模块 TriggerPlanEntity entity = new() { materialid = prdMoTask.material_id, processid = prdMoTask.process_id, workid = prdMoTask.workstation_id }; int? reported = prdMoTask.reported_work_qty == null ? 0 : prdMoTask.reported_work_qty; int? scrap = prdMoTask.scrap_qty == null ? 0 : prdMoTask.scrap_qty; entity.oldpronum = reported + scrap; entity.newpronum = input.reported_qty; entity.triggerevent = EnumTriggerEvent.生产检定量; await _qcCheckPlanService.CreateTask(entity); #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 (result.IsSuccess) { if (!string.IsNullOrEmpty(basMaterial.category_id)) { string[] arr = JsonConvert.DeserializeObject(basMaterial.category_id); if (arr.Length > 0 && arr.Contains("DGJCJ"))//短管挤出件入库申请 { // string resultMsg = await _prdInstockService.InstockTubeOne(report); // return resultMsg == "true" ? (dynamic)true : throw Oops.Bah(resultMsg); return true; } if (arr.Length > 0 && arr.Contains("CGJCJ"))//短管挤出件入库申请 { string resultMsg = await _prdInstockService.InstockTubeThree(report); return resultMsg == "true" ? (dynamic)true : throw Oops.Bah(resultMsg); } } } return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)result.IsSuccess; } /// /// 自检报废提交 /// /// 自检报废输入参数 /// 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) { ISqlSugarClient db = _repository.AsSugarClient(); if (await db.Queryable().AnyAsync(x => x.id == input.mo_task_id && x.mo_task_status == DictConst.MoStatusPauseCode)) { throw Oops.Bah("暂停的任务单无法报废"); } DbResult result = await db.Ado.UseTranAsync(async () => { 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, 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 }; int? reported = prdMoTask.reported_work_qty == null ? 0 : prdMoTask.reported_work_qty; int? 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(); } } }); return result.IsSuccess; } /// /// 修改组装、包装,生产任务信息 /// /// [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(); } 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) .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, }).OrderByDescending(a => a.create_time).ToPagedListAsync(input.currentPage, input.pageSize); 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(); 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_standard!, 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_standard!, 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_standard!, 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 }) }).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("工位错误"); } PrdMoTask? prdMoTask = await _db.Queryable().Where(x => x.workstation_id == station_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; } /// /// 根据工位获取进行中待开工暂停的任务单信息 /// /// /// [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); 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)}"); return "(01)16945155732691(11)240510(17)270510(10)24053026#TX-JB-12*24053026*202405*1020270510RJ-A1F3NC2"; } /// /// 觉设备判定 /// /// [HttpPost] [AllowAnonymous] public async Task VisionResult(MarkingLabelInput input) { Log.Information($"视觉设备判定参数:{JsonConvert.SerializeObject(input)}"); return $"接收到参数:{JsonConvert.SerializeObject(input)}"; } } }