Files
tnb.server/ProductionMgr/Tnb.ProductionMgr/PrdMoTaskService.cs
2024-07-22 17:04:38 +08:00

3693 lines
196 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Reflection;
using JNPF;
using JNPF.Common.Core.Manager;
using JNPF.Common.Enums;
using JNPF.Common.Extension;
using JNPF.Common.Filter;
using JNPF.Common.Security;
using JNPF.DependencyInjection;
using JNPF.DynamicApiController;
using JNPF.Extras.CollectiveOAuth.Models;
using JNPF.FriendlyException;
using JNPF.Logging;
using JNPF.Systems.Entitys.Permission;
using JNPF.Systems.Entitys.System;
using JNPF.Systems.Interfaces.System;
using JNPF.VisualDev;
using JNPF.VisualDev.Entitys.Dto.VisualDevModelData;
using JNPF.VisualDev.Interfaces;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SQLitePCL;
using SqlSugar;
using Tnb.BasicData;
using Tnb.BasicData.Entities;
using Tnb.BasicData.Entities.Dto;
using Tnb.Common.Extension;
using Tnb.EquipMgr.Entities;
using Tnb.PerMgr.Entities;
using Tnb.ProductionMgr.Entities;
using Tnb.ProductionMgr.Entities.Dto;
using Tnb.ProductionMgr.Entities.Dto.PrdManage;
using Tnb.ProductionMgr.Entities.Enums;
using Tnb.ProductionMgr.Interfaces;
using Tnb.QcMgr.Entities;
using Tnb.QcMgr.Entities.Enums;
using Tnb.QcMgr.Interfaces;
using Tnb.WarehouseMgr.Entities.Configs;
using Tnb.Common.Utils;
using Tnb.Common.Redis;
using Tnb.WarehouseMgr.Entities.Consts;
using JNPF.Extras.CollectiveOAuth.Utils;
using Tnb.WarehouseMgr.Entities;
using Tnb.WarehouseMgr.Entities.Dto;
using Tnb.WarehouseMgr.Entities.Dto.Inputs;
using Tnb.WarehouseMgr.Interfaces;
using Tnb.WarehouseMgr;
using Tnb.WarehouseMgr.Entities.Enums;
using Tnb.ProductionMgr.Entities.Entity;
// using Tnb.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<PrdTask> _repository;
private readonly IUserManager _userManager;
private readonly IDictionaryDataService _dictionaryDataService;
private readonly IRunService _runService;
private readonly IVisualDevService _visualDevService;
private static Dictionary<string, object> _dicDefect = new();
private static readonly Dictionary<string, object> _dicWorkLine = new();
private static readonly Dictionary<string, object> _dicProcess = new();
private readonly ISqlSugarClient _db;
private readonly IBillRullService _billRuleService;
private readonly IPrdInstockService _prdInstockService;
private readonly WmsPrdInstockHService _wmsPrdInstockHService;
private readonly IQcCheckPlanService _qcCheckPlanService;
private readonly IWmsCarryService _wmsCarryService;
private readonly ElevatorControlConfiguration _eleCtlCfg = App.Configuration.Build<ElevatorControlConfiguration>();
private readonly RedisData _redisData;
private static SemaphoreSlim prdreportSemaphore = new(1);
public OverideVisualDevFunc OverideFuncs { get; } = new OverideVisualDevFunc();
public PrdMoTaskService(
ISqlSugarRepository<PrdTask> repository,
IUserManager userManager,
IDictionaryDataService dictionaryDataService,
IRunService runService,
IWmsCarryService wmsCarryService,
IBillRullService billRullService,
IPrdInstockService prdInstockService,
WmsPrdInstockHService wmsPrdInstockHService,
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;
_wmsCarryService = wmsCarryService;
_wmsPrdInstockHService = wmsPrdInstockHService;
}
#region Get
/// <summary>
/// 根据产品ID获取模具列表
/// </summary>
/// <returns></returns>
/// <remarks>
/// <br/>return results:
/// <br/>[
/// <br/> {
/// <br/> mold_code:模具编号
/// <br/> mold_name:模具名称
/// <br/> item_name:产品名称
/// <br/> item_code:产品编号
/// <br/> cavity_qty:模穴数
/// <br/> }
/// <br/>]
/// </remarks>
[HttpGet("{materialId}")]
public async Task<dynamic> GetMoldListByItemId(string materialId)
{
List<MoldListOutput> result = new();
result = await _db.Queryable<ToolMoldsMaterial>()
.InnerJoin<ToolMolds>((a, b) => a.mold_id == b.id)
.InnerJoin<BasMaterial>((a, b, c) => a.material_id == c.id)
.LeftJoin<DictionaryDataEntity>((a,b,c,d)=>d.Id==b.mold_status)
.Where((a, b, c) => a.material_id == materialId)
.Select((a, b, c,d) => new Tnb.ProductionMgr.Entities.Dto.MoldListOutput
{
mold_id = b.id,
mold_code = b.mold_code,
mold_name = b.mold_name,
mold_type_code = b.mold_type_code,
material_name = c.name,
material_code = c.code,
mold_status = d.FullName,
available_stations = SqlFunc.Subqueryable<EqpEquipment>().Where(it => it.mold_id == a.id).Count(),
}).ToListAsync();
return result;
}
/// <summary>
/// 根据模具Id获取设备列表
/// </summary>
/// <param name="moldId"></param>
/// <returns></returns>
[HttpGet("{moldId}")]
public async Task<dynamic> GetEquipmentListByMoldId(string moldId)
{
List<EquipmentListOutput> items = await _db.Queryable<ToolMoldsEquipment>().InnerJoin<EqpEquipment>((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<EqpEquipType>().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<PrdMoTask>().Where(x => x.eqp_id == b.id && (x.mo_task_status==DictConst.ToBeStartedEnCode || x.mo_task_status==DictConst.ToBeScheduledEncode || x.mo_task_status==DictConst.InProgressEnCode || x.mo_task_status==DictConst.MoStatusPauseCode)).Count(),
estimated_end_date = SqlFunc.Subqueryable<PrdMoTask>().Where(x => x.eqp_id == b.id && (x.mo_task_status==DictConst.ToBeStartedEnCode || x.mo_task_status==DictConst.ToBeScheduledEncode || x.mo_task_status==DictConst.InProgressEnCode || x.mo_task_status==DictConst.MoStatusPauseCode)).Max(x=>x.create_time)
}).Mapper(x =>
{
x.first_date = x.estimated_end_date.HasValue ? x.estimated_end_date.Value.ToString("yyyy-MM-dd HH:mm:ss") : "";
}).ToListAsync();
return items;
}
/// <summary>
/// 工单调整-生产任务重新排序
/// </summary>
/// <param name="eqpId">设备ID</param>
/// <returns>排序后生产任务列表</returns>
/// <remarks>
/// returns:
/// <br/>[
/// <br/> {
/// <br/> no:生产序号
/// <br/> mo_id工单编号
/// <br/> group_flag同组标识
/// <br/> plan_qty:计划生产数量
/// <br/> comple_qty:完成数量
/// <br/> item_name:产品名称
/// <br/> mold_code:模具编号
/// <br/> }
/// <br/>]
/// </remarks>
[HttpGet("{eqpId}")]
public async Task<dynamic> PrdTaskSort(string eqpId)
{
Dictionary<string, object> taskStatusDic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId);
List<PrdTaskSortOutput> list = await _repository.AsSugarClient().Queryable<PrdMoTask>()
.LeftJoin<PrdMo>((a, b) => a.mo_id == b.id)
.LeftJoin<BasMaterial>((a, b, c) => a.material_id == c.id)
.LeftJoin<ToolMolds>((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<PrdTaskSortOutput> 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;
}
/// <summary>
/// 查看生产任务操作记录
/// </summary>
/// <param name="taskId">任务ID</param>
/// <returns></returns>
[HttpGet("{taskId}")]
public async Task<dynamic> GetMoOperRecord(string taskId)
{
List<PrdTaskLog> list = await _repository.AsSugarClient().Queryable<PrdTaskLog>().Where(it => it.mo_task_id == taskId).ToListAsync();
List<PrdTaskOperOutput> data = list.Adapt<List<PrdTaskOperOutput>>();
Dictionary<string, object> 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<PrdMoTask>().Single(y => y.id == x.mo_task_id).schedule_type;
});
return data;
}
/// <summary>
/// 获取自检报废批次记录
/// </summary>
/// <param name="moTaskId">任务单Id</param>
/// <returns></returns>
[HttpGet("{moTaskId}")]
public async Task<dynamic> GetScarpStatRecord(string moTaskId)
{
PrdMoTaskDefectOutput output = new();
ISqlSugarClient db = _repository.AsSugarClient();
if (_dicDefect.Count < 1)
{
_dicDefect = await db.Queryable<BasDefectType>().ToDictionaryAsync(x => x.id, x => x.defect_type_name);
}
output.mo_task_code = (await db.Queryable<PrdMoTask>().FirstAsync(it => it.id == moTaskId))?.mo_task_code;
List<PrdMoTaskDefect> defects = await db.Queryable<PrdMoTaskDefect>().Where(it => it.mo_task_id == moTaskId).ToListAsync();
List<UserEntity> users = await db.Queryable<UserEntity>().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;
}
/// <summary>
/// 根据工单Id获取任务单列表
/// </summary>
/// <param name="moId"></param>
/// <param name="schedType"></param>
/// <remarks>
/// output:
/// <br/>{
/// <br/> mo_task_code:生产任务单号
/// <br/> material_code:物料编码
/// <br/> mold_code:模具编码
/// <br/> mold_name:模具名称
/// <br/> eqp_code:设备编码
/// <br/> eqp_name:设备名称
/// <br/> eqp_type_code:设备型号
/// <br/> mo_task_qty:任务单数量
/// <br/> mo_task_status:任务状态
/// <br/> scheduled_qty:计划生产数量
/// <br/> complete_qty:完成数量
/// <br/> estimated_start_date:预计开工时间
/// <br/> estimated_end_date:预计完工时间
/// <br/>}
/// </remarks>
[HttpGet("{moId}")]
public async Task<dynamic> GetPrdTaskInfoByMoId(string moId, int schedType = 1)
{
List<PrdMoTaskOutput> result = new();
Dictionary<string, object> dic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId);
result = schedType == 1
? await _db.Queryable<PrdMoTask>().LeftJoin<PrdMo>((a, b) => a.mo_id == b.id)
.LeftJoin<BasMaterial>((a, b, c) => a.material_id == c.id)
.LeftJoin<ToolMolds>((a, b, c, d) => a.mold_id == d.id)
.LeftJoin<EqpEquipment>((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<EqpEquipType>().Where(it => it.id == e.equip_type_id).Select(it => it.code),
mo_task_qty = SqlFunc.Subqueryable<PrdMoTask>().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<BasProcess>().Where(it => it.id == a.process_id).Select(it => it.process_code),
process_name = SqlFunc.Subqueryable<BasProcess>().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<PrdMoTask>().LeftJoin<PrdMo>((a, b) => a.mo_id == b.id)
.LeftJoin<BasMaterial>((a, b, c) => a.material_id == c.id)
.LeftJoin<OrganizeEntity>((a, b, c, d) => a.workline_id == d.Id)
.LeftJoin<BasProcess>((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<PrdMoTask>().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;
}
/// <summary>
///组装、包装 获取待下发任务列表
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<dynamic> GetPackScheldToBeIssueList([FromQuery] PackScheldToBeIssueListInput input)
{
Dictionary<string, object> dic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId);
List<PackSechelToBeIssueListOutput> result = await _db.Queryable<PrdMoTask>()
.LeftJoin<OrganizeEntity>((a, b) => a.workline_id == b.Id)
.LeftJoin<PrdMo>((a, b, c) => a.mo_id == c.id)
.LeftJoin<BasMbom>((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<BasMaterial>().Where(it => it.id == a.material_id).Select(it => it.code),
material_name = SqlFunc.Subqueryable<BasMaterial>().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<PrdMoTask>().Where(it => it.mo_id == a.mo_id).Sum(it => it.scheduled_qty),
scheduled_qty = a.scheduled_qty,
plan_qty = SqlFunc.Subqueryable<PrdMo>().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;
}
/// <summary>
/// 根据生产任务ID获取子任务列表
/// </summary>
/// <param name="mo_task_id"></param>
/// <returns></returns>
[HttpGet("{mo_task_id}")]
public async Task<dynamic> GetSubMoTaskListByTaskId(string mo_task_id)
{
Dictionary<string, object> dic = await _dictionaryDataService.GetDicByTypeId(DictConst.PrdTaskStatusTypeId);
List<PackSechelToBeIssueListOutput> result = await _db.Queryable<PrdMoTask>()
.LeftJoin<BasMaterial>((a, b) => a.material_id == b.id)
.LeftJoin<OrganizeEntity>((a, b, c) => a.workline_id == c.Id)
.LeftJoin<PrdMo>((a, b, c, d) => a.mo_id == d.id)
.LeftJoin<BasProcess>((a, b, c, d, e) => a.process_id == e.id)
.LeftJoin<OrganizeEntity>((a, b,c,d,e,f) => a.workstation_id == f.Id)
.LeftJoin<UserEntity>((a, b,c,d,e,f,g)=>a.worker_id==g.Id)
.Where((a, b, c, d) => a.parent_id == mo_task_id)
.Select((a, b, c, d, e,f,g) => 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,
workstation_name = f.FullName,
worker_name = g.RealName,
scheduled_qty = a.scheduled_qty,
plan_qty = d.plan_qty,
process_task_qty = a.process_task_qty,
complete_qty = SqlFunc.IsNull(a.reported_work_qty, 0) + SqlFunc.IsNull(a.scrap_qty, 0),
estimated_start_date = a.estimated_start_date == null ? null : a.estimated_start_date.Value.ToString(DbTimeFormat.MM),
estimated_end_date = a.estimated_end_date == null ? null : a.estimated_end_date.Value.ToString(DbTimeFormat.MM),
process_name = e.process_name,
bom_version = SqlFunc.Subqueryable<BasMbom>().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;
}
// /// <summary>
// /// 获取组装、包装 待排产工单树形列表
// /// </summary>
// /// <returns></returns>
// [HttpGet]
// public async Task<dynamic> GetUnSchedulingList([FromQuery] VisualDevModelListQueryInput input)
// {
// List<PrdMoTreeOutput> 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<PrdMoTreeOutput>(row);
// node.parentId = "0";
// node.mo_id = node.id;
// if (dic.ContainsKey(pkName))
// {
// var materialId = dic[pkName]?.ToString();
// var material = await _db.Queryable<BasMaterial>().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<PrdMoTask>().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<PrdMoTreeOutput>();
// foreach (var item in subData.list)
// {
// dic = item.ToDictionary(x => x.Key, x => x.Value);
// PrdMoTreeOutput subNode = DictionaryToObject<PrdMoTreeOutput>(item);
// subNode.parentId = node.id;
// subNode.mo_id = subNode.id;
// if (dic.ContainsKey(pkName))
// {
// var materialId = dic[pkName]?.ToString();
// var material = await _db.Queryable<BasMaterial>().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<PrdMoTask>().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<PrdMoTreeOutput> pagedList = new()
// {
// list = treeList,
// pagination = new Pagination
// {
// CurrentPage = input.currentPage,
// PageSize = input.pageSize,
// Total = treeList.Count
// }
// };
// return PageResult<PrdMoTreeOutput>.SqlSugarPageResult(pagedList);
// }
/// <summary>
/// 获取组装、包装 待排产工单树形列表
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<dynamic> GetUnSchedulingList([FromQuery] VisualDevModelListQueryInput input)
{
Dictionary<string, object>? queryJson = !string.IsNullOrEmpty(input.queryJson) ? JsonConvert.DeserializeObject<Dictionary<string, object>>(input.queryJson) : new Dictionary<string, object>();
List<string> moStatusList = new();
if (queryJson != null && queryJson.ContainsKey("mo_stauts"))
{
moStatusList = JsonConvert.DeserializeObject<List<string>>(JsonConvert.SerializeObject(queryJson["mo_status"]));
}
List<string> moTypeList = new();
if (queryJson != null && queryJson.ContainsKey("mo_type"))
{
moTypeList = JsonConvert.DeserializeObject<List<string>>(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<PrdMoListTreeOutput> result = await db.Queryable<PrdMo>()
.LeftJoin<BasMaterial>((a, b) => a.material_id == b.id)
.LeftJoin<DictionaryDataEntity>((a, b, c) => a.mo_type == c.Id)
.LeftJoin<DictionaryDataEntity>((a, b, c, d) => a.mo_status == d.Id)
.LeftJoin<UserEntity>((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_specification,
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<PrdMo>().Where(x => x.parent_id == a.id).Any(),
num = SqlFunc.Subqueryable<PrdMo>().Where(x => x.parent_id == a.id).Count(),
isLeaf = SqlFunc.Subqueryable<PrdMo>().Where(x => x.parent_id == a.id).Any(),
children = SqlFunc.Subqueryable<PrdMo>()
.LeftJoin<BasMaterial>((h, i) => h.material_id == i.id)
.LeftJoin<DictionaryDataEntity>((h, i, j) => h.mo_type == j.Id)
.LeftJoin<DictionaryDataEntity>((h, i, j, k) => h.mo_status == k.Id)
.LeftJoin<UserEntity>((h, i, j, k, l) => h.create_id == l.Id)
.Where((h, i, j, k, l) => a.id == h.parent_id).ToList((h, i, j, k, l) => new PrdMoListTreeOutput()
{
org_id = h.org_id,
mo_id = h.id,
mo_code = h.mo_code,
material_code = i.code,
material_name = i.name,
material_standard = i.material_specification,
mo_type = j.FullName,
mo_status = k.FullName,
plan_qty = h.plan_qty.Value.ToString(),
input_qty = h.input_qty.Value.ToString(),
complete_qty = h.complete_qty.Value.ToString(),
scrap_qty = h.scrap_qty.Value.ToString(),
plan_start_date = h.plan_start_date.Value.ToString("yyyy-MM-dd"),
plan_end_date = h.plan_end_date.Value.ToString("yyyy-MM-dd"),
is_create_dispatch = h.is_create_dispatch == 0 ? "否" : "是",
production_linecode = h.production_linecode,
is_merge = h.is_merge == 0 ? "否" : "是",
combine_mo_code = h.combine_mo_code,
time_stamp = h.time_stamp,
create_id = l.RealName,
create_time = h.create_time.Value.ToString("yyyy-MM-dd : HH:mm:ss"),
material_id = i.code,
material_id_id = h.material_id,
scheduled_qty = h.scheduled_qty.Value.ToString(),
parent_id = a.id,
id = h.id,
hasChildren = false,
num = 0,
isLeaf = true,
})
}).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<PrdMoListTreeOutput>.SqlSugarPageResult(result);
}
#endregion
#region Post
/// <summary>
/// 生产工单-生产排产
/// </summary>
/// <param name="input">
///<br/>{
///<br/> Id:生产任务主键Id
///<br/> MoType:工单类型 1、注塑/挤出 2、组装/包装
///<br/> MoId:工单Id
///<br/> ItemId:产品编号
///<br/> ItemName:产品名称
///<br/> MoldId:模具Id
///<br/> MoldName:模具名称
///<br/> EqpId:设备Id
///<br/> EqpName:设备名称
///<br/> LineId:产线编号
///<br/> LineName:产线名称
///<br/>}
/// </param>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> 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<PrdMo>().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<BasMbomProcess>().FirstAsync(x => x.mbom_id == input.bom_id);
}
PrdMoTask moTask = input.Adapt<PrdMoTask>();
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<OrganizeRelationEntity>()
.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<PrdMoTask>().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<PrdMoTask>().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<PrdMo>()
.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<PrdMo>().SetColumns(x => x.scheduled_qty == x.scheduled_qty + input.scheduled_qty)
.Where(x => x.id == mo.id)
.ExecuteCommandAsync();
}
BasMaterial? material = await db.Queryable<BasMaterial>().FirstAsync(it => it.id == moTask.material_id);
PrdTaskLog taskLog = new()
{
id = SnowflakeIdHelper.NextId(),
mo_code = (await db.Queryable<PrdMo>().FirstAsync(it => it.id == input.mo_id))?.mo_code!,
eqp_code = (await db.Queryable<EqpEquipment>().FirstAsync(it => it.id == input.eqp_id))?.code!,
mold_code = (await db.Queryable<ToolMolds>().FirstAsync(it => it.id == input.mold_id))?.mold_code!,
item_code = material?.code!,
item_standard = material?.material_specification!,
status = DictConst.ToBeScheduledEncode,
operator_name = _userManager.RealName,
create_id = _userManager.UserId,
create_time = DateTime.Now,
mo_task_id = moTask.id,
mo_task_code = moTask.mo_task_code
};
_ = await db.Insertable(taskLog).ExecuteCommandAsync();
//将生产任务插入到自检报废记录表
//var sacipRecord = new PrdMoTaskDefectRecord();
//sacipRecord.id = SnowflakeIdHelper.NextId();
//sacipRecord.material_code = material?.code!;
//sacipRecord.material_name = material?.name!;
//sacipRecord.eqp_code = (await db.Queryable<EqpEquipment>().FirstAsync(it => it.id == moTask.eqp_id))?.code!;
//sacipRecord.mold_name = (await db.Queryable<ToolMolds>().FirstAsync(it => it.id == moTask.mold_id))?.mold_name!;
//sacipRecord.estimated_start_date = moTask.plan_start_date;
//sacipRecord.estimated_end_date = moTask.plan_end_date;
//sacipRecord.plan_qty = moTask.plan_qty;
//sacipRecord.scrap_qty = moTask.scrap_qty;
//sacipRecord.status = moTask.mo_task_status;
//sacipRecord.create_id = _userManager.UserId;
//sacipRecord.create_time = DateTime.Now;
//sacipRecord.mo_task_id = moTask.id;
//sacipRecord.mo_task_code = moTask.mo_task_code;
//await db.Insertable(sacipRecord).ExecuteCommandAsync();
await db.Ado.CommitTranAsync();
}
catch (Exception e)
{
Log.Error(e.Message,e);
await db.Ado.RollbackTranAsync();
}
}
else if (input.schedule_type.Value == 2) //组装、包装排产
{
}
}
return row > 0;
}
/// <summary>
/// 组装包装排产
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
[HttpPost]
public async Task<dynamic> PackSchedling(PackSchedlingCrInput input)
{
int row = -1;
try
{
await _db.Ado.BeginTranAsync();
PrdMoTask moTask = input.Adapt<PrdMoTask>();
moTask.id = SnowflakeIdHelper.NextId();
moTask.create_id = _userManager.UserId;
moTask.bom_id = input.bom_id;
moTask.workroute_id = (await _db.Queryable<BasMbom>().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<PrdMo>().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<PrdMoTask>().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<BasMaterial>().FirstAsync(it => it.id == moTask.material_id);
//添加生产任务操作记录日志
PrdTaskLog taskLog = new()
{
id = SnowflakeIdHelper.NextId(),
mo_code = (await _db.Queryable<PrdMo>().FirstAsync(it => it.id == input.mo_id))?.mo_code!,
item_code = material_h?.code!,
item_standard = material_h?.material_specification!,
status = DictConst.ToBeScheduledEncode,
operator_name = _userManager.RealName,
create_id = _userManager.UserId,
create_time = DateTime.Now,
mo_task_id = moTask.id,
mo_task_code = moTask.mo_task_code!
};
row = await _db.Insertable(taskLog).ExecuteCommandAsync();
//将生产任务插入到自检报废记录表
//var sacipRecord = new PrdMoTaskDefectRecord();
//sacipRecord.id = SnowflakeIdHelper.NextId();
//sacipRecord.material_code = material?.code!;
//sacipRecord.material_name = material?.name!;
//sacipRecord.eqp_code = (await db.Queryable<EqpEquipment>().FirstAsync(it => it.id == moTask.eqp_id))?.code!;
//sacipRecord.mold_name = (await db.Queryable<ToolMolds>().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<PrdMoTask>().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<PrdMo>()
.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<PrdMo>().SetColumns(x => x.scheduled_qty == x.scheduled_qty + input.scheduled_qty)
.Where(x => x.id == mo.id)
.ExecuteCommandAsync();
}
List<SubBomListOutput> subTaskList = await _db.Queryable<BasMbom>()
.LeftJoin<BasMbomProcess>((a, b) => a.id == b.mbom_id)
.LeftJoin<BasRouteH>((a, b, c) => a.route_id == c.id)
// .LeftJoin<BasRouteD>((a, b, c, d) => b.process_id == d.process_id && c.id == d.route_id)
.LeftJoin<BasRouteD>((a, b, c, d) => b.route_detail_id == d.id)
.LeftJoin<BasMbomOutput>((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<BasMaterial>().Where(it => it.id == e.material_id).Select(it => it.id),
num = e.num,
molecule = e.molecule,
denominator = e.denominator,
ordinal = d.ordinal,
mbom_process_id = b.id,
})
.Mapper(it => it.output_qty = it.num.ParseToInt())
.ToListAsync();
if (subTaskList?.Count > 0)
{
List<string> workstationIds = await _db.Queryable<OrganizeEntity>().Where(x =>
x.Category == DictConst.RegionCategoryStationCode &&
x.OrganizeIdTree.Contains(input.workline_id)).Select(x => x.Id).ToListAsync();
List<PrdMoTask> subMoTasks = new();
List<PrdTaskLog> subMoTaskLogs = new();
foreach (SubBomListOutput? item in subTaskList)
{
BasMbomProcess basMbomProcess = await _db.Queryable<BasMbomProcess>().SingleAsync(x => x.id == item.mbom_process_id);
List<string> mbomProcessStationIds = JsonConvert.DeserializeObject<string[][]>(basMbomProcess.station).Select(x => x[^1]).ToList();
List<string>? 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<BasMaterial>().SingleAsync(x => x.id == item.material_id);
subTaskLog.id = SnowflakeIdHelper.NextId();
subTaskLog.mo_code = (await _db.Queryable<PrdMo>().FirstAsync(it => it.id == input.mo_id))?.mo_code!;
subTaskLog.item_code = subMaterial?.code!;
subTaskLog.item_standard = subMaterial?.material_specification!;
subTaskLog.status = DictConst.ToBeScheduledEncode;
subTaskLog.operator_name = _userManager.RealName;
subTaskLog.create_id = _userManager.UserId;
subTaskLog.create_time = DateTime.Now;
subTaskLog.mo_task_id = subMoTask.id;
subTaskLog.mo_task_code = subMoTask.mo_task_code!;
subMoTaskLogs.Add(subTaskLog);
}
//根据生产任务编号生成子任务编号
if (moTask.mo_task_code!.IsNotEmptyOrNull())
{
for (int i = 1; i <= subMoTasks.Count; i++)
{
string n = i.ToString();
subMoTasks[i - 1].mo_task_code = $"{moTask.mo_task_code}-{n.PadLeft(2, '0')}";
}
}
row = await _db.Insertable(subMoTasks).ExecuteCommandAsync();
_ = await _db.Insertable(subMoTaskLogs).ExecuteCommandAsync();
}
await _db.Ado.CommitTranAsync();
}
catch (Exception ex)
{
JNPF.Logging.Log.Error("组装包装排产时报错", ex);
await _db.Ado.RollbackTranAsync();
}
return row > 0;
}
/// <summary>
/// 生产任务下发,开始 、结束、完成
/// </summary>
/// <param name="input">输入参数</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="NotImplementedException"></exception>
[HttpPost]
public async Task<dynamic> PrdTaskRelease(PrdTaskReleaseUpInput input)
{
int row = -1;
if (input is null)
{
throw new ArgumentNullException(nameof(input));
}
if (input.TaskIds is null)
{
throw new ArgumentNullException(nameof(input.TaskIds));
}
// if (input.Behavior.IsNullOrWhiteSpace())
if (input.Behavior==null || input.Behavior.IsEmpty())
{
throw new ArgumentException($"{nameof(input.Behavior)} not be null or empty");
}
ISqlSugarClient db = _repository.AsSugarClient();
try
{
await db.Ado.BeginTranAsync();
List<PrdMoTask> prdTaskList = new List<PrdMoTask>();
//var taskList = await _db.Queryable<PrdMoTask>().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<PrdTaskBehavior>();
string status = SetTaskStatus(behavior);
List<PrdMoTask>? list = await db.Queryable<PrdMoTask>().Where(it => input.TaskIds.Contains(it.id)).Select(it => it).ToListAsync();
if (behavior == PrdTaskBehavior.Release)
{
foreach(PrdMoTask item in list)
{
if (string.IsNullOrEmpty(item.worker_id))
{
throw Oops.Bah("请先分配员工");
}
}
}
if (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<PrdMoTask> taskReportLogs = new();
prdTaskList = await db.Queryable<PrdMoTask>().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<PrdMoTask>().AnyAsync(x => x.workline_id == item.workline_id && x.mo_task_status == DictConst.InProgressEnCode && x.id != item.id))
{
throw Oops.Bah("该产线已有生产中的任务单");
}
}
if (item.schedule_type == 1)
{
if (await db.Queryable<PrdMoTask>().AnyAsync(x => x.eqp_id == item.eqp_id && x.mo_task_status == DictConst.InProgressEnCode && x.id != item.id))
{
throw Oops.Bah("该设备已有生产中的任务单");
}
}
if (item.mo_task_status is not DictConst.ToBeStartedEnCode and not DictConst.MoStatusPauseCode)
{
throw Oops.Bah("状态错误无法开始");
}
break;
case PrdTaskBehavior.Pause:
if (item.mo_task_status == status)
{
throw Oops.Bah("已暂停的不能再暂停");
}
if (item.mo_task_status != DictConst.InProgressEnCode)
{
throw Oops.Bah("状态错误无法暂停");
}
item.pause_reason = input.PauseReeson;
break;
case PrdTaskBehavior.Compled:
if (item.mo_task_status == status)
{
throw Oops.Bah("已完成的不能再完成");
}
if (item.mo_task_status is not DictConst.InProgressEnCode and not DictConst.MoStatusPauseCode)
{
throw Oops.Bah("状态错误无法完成");
}
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<PrdMoTask>().CountAsync(y => y.parent_id == item.parent_id);
int count2 = await db.Queryable<PrdMoTask>().CountAsync(y => y.parent_id == item.parent_id && y.mo_task_status == status);
if (count1 == count2)
{
_ = await db.Updateable<PrdMoTask>().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<PrdMoTask> subMoTaskList = await db.Queryable<PrdMoTask>().Where(it => input.TaskIds.Contains(it.parent_id)).ToListAsync();
if (subMoTaskList?.Count > 0)
{
List<string> subTaskIds = subMoTaskList.Select(it => it.id).ToList();
row = await db.Updateable<PrdMoTask>()
.SetColumns(it => new PrdMoTask { mo_task_status = status })
.Where(it => subTaskIds.Contains(it.id))
.ExecuteCommandAsync();
if (row > 0)
{
taskReportLogs.AddRange(subMoTaskList);
}
}
}
//插入操作记录日志
List<PrdMoTask> prdMOTasks = await _db.Queryable<PrdMoTask>().Where(it => input.TaskIds.Contains(it.id) && string.IsNullOrEmpty(it.parent_id)).ToListAsync();
if (prdMOTasks?.Count > 0)
{
List<PrdTaskLog> taskLogEntities = new();
foreach (string taskId in input.TaskIds)
{
PrdTaskLog? taskLog = await db.Queryable<PrdTaskLog>().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<PrdMo>().FirstAsync(it => it.id == taskItem.mo_id))?.mo_code!;
}
if (taskItem.eqp_id!.IsNotEmptyOrNull())
{
taskLog.eqp_code = (await db.Queryable<EqpEquipment>().FirstAsync(it => it.id == taskItem.eqp_id))?.code!;
}
if (taskItem.mold_id!.IsNotEmptyOrNull())
{
taskLog.mold_code = (await db.Queryable<ToolMolds>().FirstAsync(it => it.id == taskItem.mold_id))?.mold_code!;
}
if (taskItem.material_id!.IsNotEmptyOrNull())
{
BasMaterial? material = await db.Queryable<BasMaterial>().FirstAsync(it => it.id == taskItem.material_id);
taskLog.item_code = material?.code!;
taskLog.item_standard = material?.material_specification!;
}
taskLog.operator_name = _userManager.RealName;
taskLog.status = status;
taskLog.create_id = _userManager.UserId;
taskLog.create_time = DateTime.Now;
taskLog.mo_task_id = taskItem.id;
}
taskLogEntities.Add(taskLog);
}
else
{
List<PrdTaskLog> records = await db.Queryable<PrdTaskLog>().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<PrdReportRecord> prdReportLogs = new();
List<PrdMoTaskDefectRecord> prdTaskDefectLogs = new();
if (taskReportLogs?.Count > 0)
{
foreach (PrdMoTask taskInfo in taskReportLogs)
{
//组装生产提报对象
BasMaterial? material = await db.Queryable<BasMaterial>().FirstAsync(it => it.id == taskInfo.material_id);
PrdMo? mo = await db.Queryable<PrdMo>().FirstAsync(it => it.id == taskInfo.mo_id);
PrdReportRecord record = taskInfo.Adapt<PrdReportRecord>();
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<EqpEquipment>().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<PrdReport>().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<EqpEquipment>().FirstAsync(it => it.id == taskInfo.eqp_id))?.code!,
mold_name = (await db.Queryable<ToolMolds>().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<string> reportTaskIds = prdReportLogs.Select(it => it.mo_task_id).ToList();
if (reportTaskIds?.Count > 0)
{
List<PrdReportRecord> items = await db.Queryable<PrdReportRecord>().Where(it => reportTaskIds.Contains(it.mo_task_id)).ToListAsync();
if (items == null || items.Count < 1)
{
row = await db.Insertable(prdReportLogs).ExecuteCommandAsync();
}
}
List<string?> defectTaskIds = prdTaskDefectLogs.Select(it => it.mo_task_id).ToList();
if (defectTaskIds?.Count > 0)
{
List<PrdMoTaskDefectRecord> items = await db.Queryable<PrdMoTaskDefectRecord>().Where(it => defectTaskIds.Contains(it.mo_task_id)).ToListAsync();
if (items == null || items.Count < 1)
{
row = await db.Insertable(prdTaskDefectLogs).ExecuteCommandAsync();
}
}
}
foreach (var item in prdTaskList)
{
if (PrdTaskBehavior.Start==behavior && item.schedule_type == 2)
{
PrdMo prdMo = await db.Queryable<PrdMo>().SingleAsync(x => x.id == item.mo_id);
if (prdMo.mo_type == DictConst.PrdMoTypeBZ)
{
// if (await _db.Queryable<PrdOutPackMarkLabel>().Where(x =>
// x.mo_task_code == item.mo_task_code && x.status == "0" && x.is_label == null && x.is_mark==0).AnyAsync())
// {
// await _db.Updateable<PrdOutPackMarkLabel>()
// .SetColumns(x => x.is_label == 0)
// .Where(x => x.mo_task_code == item.mo_task_code && x.status == "0" && x.is_label == null &&
// x.is_mark == 0)
// .ExecuteCommandAsync();
// }
// else
// {
// PrdOutPackMarkLabel prdOutPackMarkLabel = new PrdOutPackMarkLabel()
// {
// is_mark = null,
// is_label = 0,
// mo_task_code = item.mo_task_code,
// material_code = item.material_code,
// create_time = DateTime.Now,
// };
//
// await _db.Insertable<PrdOutPackMarkLabel>(prdOutPackMarkLabel).ExecuteCommandAsync();
// }
OrganizeEntity organizeEntity = await _db.Queryable<OrganizeEntity>().SingleAsync(x => x.Id == item.workline_id);
string batch = $"{organizeEntity.EnCode.Substring(organizeEntity.EnCode.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}";
PrdMoTask parent = await _db.Queryable<PrdMoTask>().SingleAsync(x => x.id == item.parent_id);
BasMaterial basMaterial = await _db.Queryable<BasMaterial>().SingleAsync(x=>x.id==parent.material_id);
BasMbom basMbom = await _db.Queryable<BasMbom>().SingleAsync(x => x.id == item.bom_id);
//string code = $"(01){basMaterial.di ?? ""}(11){DateTime.Now.ToString("yyMMdd")}(17){DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}(10){batch}#{basMaterial.material_specification}*{batch}*{DateTime.Now.ToString("yyyyMMdd")}*{DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyyyMMdd")}*{basMaterial.container_no}";
string code1 = $"(01){basMaterial.di ?? ""}*(11){DateTime.Now.ToString("yyMMdd")}*(17){DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}*(10){batch}";
string code2 = $"{basMaterial.material_specification}*{batch}*{DateTime.Now.ToString("yyyyMMdd")}*{DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyyyMMdd")}*{basMaterial.container_no}";
Dictionary<string, string> dicCommand1 = new(StringComparer.OrdinalIgnoreCase)
{
["DevName"] = "外包装箱码垛线",
["token"] = _eleCtlCfg.token,
["TagName"] = "WBZX_tb_cs",
["Value"] = code1,
};
Dictionary<string, string> dicCommand2 = new(StringComparer.OrdinalIgnoreCase)
{
["DevName"] = "外包装箱码垛线",
["token"] = _eleCtlCfg.token,
["TagName"] = "WBZX_pm_cs",
["Value"] = code2,
};
Dictionary<String, String> workLineDic = new Dictionary<string, string>()
{
[WmsWareHouseConst.XUELUGUAN1XIAN] = "WBZX_x1_dy_quantity",
[WmsWareHouseConst.XUELUGUAN2XIAN] = "WBZX_x2_dy_quantity",
};
Dictionary<string, string> dicCommand3 = new(StringComparer.OrdinalIgnoreCase)
{
["DevName"] = "外包装箱码垛线",
["token"] = _eleCtlCfg.token,
["TagName"] = workLineDic[item.workline_id],
["Value"] = basMbom.full_qty.ToString(),
};
Log.Information($"贴标写入参数:{JsonConvert.SerializeObject(dicCommand1)}");
string result1 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand1, false);
Log.Information($"贴标写入返回结果:{JsonConvert.SerializeObject(result1)}");
Log.Information($"喷码写入参数:{JsonConvert.SerializeObject(dicCommand2)}");
string result2 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand2, false);
Log.Information($"喷码写入返回结果:{JsonConvert.SerializeObject(result2)}");
Log.Information($"整托数写入参数:{JsonConvert.SerializeObject(dicCommand3)}");
string result3 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand3, false);
Log.Information($"整托数写入返回结果:{JsonConvert.SerializeObject(result3)}");
}
}
}
}
await db.Ado.CommitTranAsync();
}
catch (Exception e)
{
Log.Error(e.Message,e);
await db.Ado.RollbackTranAsync();
throw Oops.Bah(e.Message);
}
return "保存成功";
}
/// <summary>
/// 生产任务单修改
/// </summary>
/// <param name="input">生产任务单修改输入参数</param>
/// <returns></returns>
/// <exception cref="AppFriendlyException"></exception>
[HttpPost]
public async Task<dynamic> IcmoModify(IcmoUpInput input)
{
int row = -1;
ISqlSugarClient db = _repository.AsSugarClient();
if (input.icmo_id!=null && !input.mo_id.IsEmpty())
{
throw new ArgumentNullException(nameof(input.icmo_id));
}
PrdMoTask? icmoItem = await db.Queryable<PrdMoTask>().FirstAsync(it => it.id == input.icmo_id);
switch (input.category)
{
case 1: //设备
if (icmoItem != null)
{
EqpEquipment eqpItem = await db.Queryable<EqpEquipment>().FirstAsync(it => it.id == icmoItem.eqp_id);
icmoItem.eqp_id = eqpItem.id;
icmoItem.eqp_type_code = db.Queryable<EqpEquipType>().First(it => it.id == eqpItem.equip_type_id)?.code!;
//if (input.scheduled_qty > icmoItem.plan_qty)
//{
// throw new AppFriendlyException("任务单数量不能大于计划数量", 500);
//}
//row = await db.Updateable<PrdMo>().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<ToolMolds>().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;
}
// /// <summary>
// /// 生产提报
// /// </summary>
// /// <param name="input"></param>
// /// <remarks>
// /// input:
// /// <br/>{
// /// <br/> icmo_id:生产任务ID
// /// <br/> icmo_code:任务单号
// /// <br/> prd_qty生产数量
// /// <br/> reported_work_qty已报工数量
// /// <br/> reported_qty提报数量
// /// <br/> icmo_qty生产任务量
// /// <br/>}
// /// </remarks>
// [HttpPost]
// public async Task<dynamic> PrdReport(PrdReportCrInput input)
// {
// var row = -1;
// var db = _repository.AsSugarClient();
// var report = await db.Queryable<PrdReport>().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<PrdReport>();
// 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<PrdReportRecord>().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;
// }
/// <summary>
/// 生产提报
/// </summary>
/// <param name="input"></param>
/// <remarks>
/// input:
/// <br/>{
/// <br/> icmo_id:生产任务ID
/// <br/> icmo_code:任务单号
/// <br/> prd_qty生产数量
/// <br/> reported_work_qty已报工数量
/// <br/> reported_qty提报数量
/// <br/> icmo_qty生产任务量
/// <br/>}
/// </remarks>
[HttpPost]
public async Task<dynamic> PrdReport(PrdReportCrInput input)
{
await prdreportSemaphore.WaitAsync();
try
{
Log.Information($"生产提报参数:{JsonConvert.SerializeObject(input)}");
ISqlSugarClient db = _repository.AsSugarClient();
PrdMoTask? prdMoTask = await db.Queryable<PrdMoTask>().SingleAsync(x => x.id == input.mo_task_id);
EqpEquipment equip = await db.Queryable<EqpEquipment>().SingleAsync(x => x.id == prdMoTask.eqp_id);
BasMaterial basMaterial = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == prdMoTask.material_id);
PrdReport report = await db.Queryable<PrdReport>().FirstAsync(it => it.mo_task_id == input.mo_task_id);
if (basMaterial == null)
{
throw Oops.Bah($"未找到物料{prdMoTask.material_id}");
}
Dictionary<String, String> dic = new Dictionary<string, string>()
{
["30019971917589"] = "外包装箱码垛线"
};
Dictionary<String, String> dic2 = new Dictionary<string, string>()
{
[WmsWareHouseConst.XUELUGUAN1XIAN] = "WBZX_x1_Enquantity",
[WmsWareHouseConst.XUELUGUAN2XIAN] = "WBZX_x2_Enquantity"
};
string materialBoxCode = input.material_box_code;
BasLocation location = null;
await _db.Ado.BeginTranAsync();
int row = -1;
PrdMo prdMo = await db.Queryable<PrdMo>().SingleAsync(x => x.id == prdMoTask.mo_id);
BasMbomProcess? mbomProcess = await db.Queryable<BasMbomProcess>().SingleAsync(x => x.id == prdMoTask.mbom_process_id);
if (prdMoTask.mo_task_status == DictConst.MoStatusPauseCode)
{
throw Oops.Bah("暂停的任务单无法提报");
}
if (mbomProcess == null)
{
throw Oops.Bah("未找到生产bom对应工序");
}
BasMbom mbom = await db.Queryable<BasMbom>().SingleAsync(x => x.id == mbomProcess.mbom_id);
if (mbom == null)
{
throw Oops.Bah("未找到生产bom");
}
if ((prdMoTask.reported_work_qty ?? 0) + input.reported_qty > prdMoTask.scheduled_qty)
{
BasFactoryConfig config1 = await db.Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.IS_SURPASS);
if (config1?.value == "1")
{
BasFactoryConfig? config2 = await db.Queryable<BasFactoryConfig>().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<PrdReport>();
report.id = SnowflakeIdHelper.NextId();
report.reported_qty = input.reported_qty;
report.weight = input.weight;
report.material_box_code = input.material_box_code;
if (prdMoTask.schedule_type == 2)
{
// if (dic.TryGetValue(prdMoTask.workline_id, out string value))
// {
// materialBoxCode = await _redisData.GetHash("value", "WBZX_x1_take_tp");
// if (materialBoxCode == null || materialBoxCode.IsEmpty())
// {
// throw Oops.Bah("托盘条码信息未空");
// }
report.material_box_code = input.material_box_code;
// }
// else
// {
// throw Oops.Bah("未找到对应产线");
// }
// report.warehouse_id = WmsWareHouseConst.WAREHOUSE_JXK_ID;
report.warehouse_id = WmsWareHouseConst.WAREHOUSE_DMJC_ID;
Dictionary<string, string> worklineWarehouseDic = new Dictionary<string, string>()
{
[WmsWareHouseConst.XUELUGUAN1XIAN] = "ZZ-01-02",
[WmsWareHouseConst.XUELUGUAN2XIAN] = "ZZ-02-02",
};
report.location_code = worklineWarehouseDic.GetOrDefault(prdMoTask.workline_id);
if (string.IsNullOrEmpty(report.location_code))
{
report.location_code = "ZZ-01-02";
}
location = await db.Queryable<BasLocation>().SingleAsync(x=>x.location_code==report.location_code);
if (location == null)
{
throw Oops.Bah($"未找到库位编号{report.location_code}");
}
}
else
{
report.warehouse_id = equip.instock_warehouse_id;
if (equip.downmat_location_id == null || equip.downmat_location_id.IsEmpty())
{
throw Oops.Bah("设备未绑定下料库位");
}
location = await db.Queryable<BasLocation>().SingleAsync(x=>x.id==equip.downmat_location_id);
if (location == null)
{
throw Oops.Bah($"未找到库位id{equip.downmat_location_id}");
}
report.location_code = location.location_code;
}
string batch = "";
PrdMo mo = await _db.Queryable<PrdMo>().SingleAsync(x => x.id == prdMoTask.mo_id);
if (mo.mo_type == DictConst.PrdMoTypeZS)
{
EqpEquipment equipment = await _db.Queryable<EqpEquipment>().SingleAsync(x => x.id == prdMoTask.eqp_id);
batch = $"{equipment.code.Substring(equipment.code.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}";
}else if (mo.mo_type == DictConst.PrdMoTypeJC)
{
EqpEquipment equipment = await _db.Queryable<EqpEquipment>().SingleAsync(x => x.id == prdMoTask.eqp_id);
ToolMolds toolMolds = await _db.Queryable<ToolMolds>().SingleAsync(x => x.id == prdMoTask.mold_id);
batch = $"{toolMolds.mold_code.Substring(toolMolds.mold_code.Length - 2, 2)}{equipment.code.Substring(equipment.code.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}";
}else
{
OrganizeEntity organizeEntity = await _db.Queryable<OrganizeEntity>().SingleAsync(x => x.Id == prdMoTask.workline_id);
batch = $"{organizeEntity.EnCode.Substring(organizeEntity.EnCode.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}";
}
// report.location_code = input.location_code;
report.create_id = _userManager?.UserId ?? WmsWareHouseConst.AdministratorUserId;
report.create_time = DateTime.Now;
report.batch = batch;
report.barcode = input.mo_task_code + DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
report.barqty = mbom.full_qty;
// report.barcode = input.mo_task_code+"0001";
report.equip_id = prdMoTask.eqp_id;
report.mbom_process_id = prdMoTask.mbom_process_id;
report.station = input.station;
report.status = 0;
report.material_id = prdMoTask.material_id;
report.unit_id = prdMoTask.unit_id;
report.process_id = mbomProcess?.process_id ?? "";
row = await db.Insertable(report).ExecuteCommandAsync();
#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<PrdMoTask>()
// .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<PrdMoTask>()
// .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<PrdMo>()
.SetColumns(x => x.reported_work_qty == input.reported_qty)
.Where(x => x.id == prdMo.id).ExecuteCommandAsync()
: await db.Updateable<PrdMo>()
.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<PrdMo>()
.SetColumns(x => x.complete_qty == input.reported_qty)
.Where(x => x.id == prdMo.id).ExecuteCommandAsync()
: await db.Updateable<PrdMo>()
.SetColumns(x => x.complete_qty == x.complete_qty + input.reported_qty)
.Where(x => x.id == prdMo.id).ExecuteCommandAsync();
PerProcessStandardsH processStandardsH = await db.Queryable<PerProcessStandardsH>()
.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<ToolMolds>().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<PrdMoTask>()
.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<PrdMoTask>().SingleAsync(x => x.id == prdMoTask.parent_id);
if (parentMoTask?.last_process_complete_qty == null)
{
_ = await db.Updateable<PrdMoTask>()
.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<PrdMoTask>()
.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<PrdMo>()
.SetColumns(x => x.reported_work_qty == input.reported_qty)
.Where(x => x.id == prdMo.id).ExecuteCommandAsync()
: await db.Updateable<PrdMo>()
.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<PrdMo>()
.SetColumns(x => x.complete_qty == input.reported_qty)
.Where(x => x.id == prdMo.id).ExecuteCommandAsync()
: await db.Updateable<PrdMo>()
.SetColumns(x => x.complete_qty == x.complete_qty + input.reported_qty)
.Where(x => x.id == prdMo.id).ExecuteCommandAsync();
}
List<BasStandardTime> list = await db.Queryable<BasMbomProcess>()
.LeftJoin<BasStandardTime>((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<PrdMoTask>()
.SetColumns(x => x.plan_end_date == cal_plan_end_date)
.Where(x => x.id == input.mo_task_id).ExecuteCommandAsync();
}
}
PrdReportRecord master = await db.Queryable<PrdReportRecord>().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<PrdFeedingD> prdFeedingDs = await db.Queryable<PrdFeedingH>()
// .LeftJoin<PrdFeedingD>((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<BasMbom>().SingleAsync(x => x.id == prdMoTask.bom_id);
// List<BasMbomInput> basMbomInputs = await db.Queryable<BasMbomInput>().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<PrdFeedingD>().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<PrdFeedingD>().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<PrdFeedingD>().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("无投入物料");
// }
// }
// }
// Dictionary<string, object> header = new()
// {
// ["Authorization"] = App.HttpContext != null ? App.HttpContext.Request.Headers["Authorization"] : ""
// };
// BasFactoryConfig config = await _repository.AsSugarClient().Queryable<BasFactoryConfig>().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DOMAIN);
WmsCarryH wmsCarryH = await db.Queryable<WmsCarryH>().SingleAsync((x => x.carry_code == materialBoxCode));
if (wmsCarryH == null)
throw Oops.Bah($"未找到{materialBoxCode}载具");
if (wmsCarryH.carry_status == ((int)EnumCarryStatus.).ToString())
{
throw Oops.Bah($"提报失败,载具已绑定");
}
List<WmsCarryCode> wmsCarryCodes = await db.Queryable<WmsCarryCode>().Where(x=>x.carry_id==wmsCarryH.id).ToListAsync();
if (wmsCarryCodes != null && wmsCarryCodes.Count > 0)
{
Log.Error($"载具{materialBoxCode}状态为{wmsCarryH.carry_status},但有条码{JsonConvert.SerializeObject(wmsCarryCodes)}");
throw Oops.Bah($"提报失败,载具异常");
}
BindCarryCodeInput bindCarryCodeInput = new BindCarryCodeInput();
bindCarryCodeInput.carry_id = wmsCarryH.id;
bindCarryCodeInput.barcode = report.barcode;
bindCarryCodeInput.codeqty = report.reported_qty.Value;
bindCarryCodeInput.material_id = prdMoTask.material_id;
bindCarryCodeInput.material_code = basMaterial.code;
bindCarryCodeInput.material_name = basMaterial.name;
bindCarryCodeInput.location_id = location.id;
bindCarryCodeInput.location_code = location.location_code;
bindCarryCodeInput.code_batch = report.batch;
bindCarryCodeInput.create_id = _userManager?.UserId ?? WmsWareHouseConst.AdministratorUserId;
Log.Information($"载具绑定参数:${JsonConvert.SerializeObject(bindCarryCodeInput)}");
Tnb.WarehouseMgr.Entities.Dto.Outputs.Result result1 = await _wmsCarryService.BindCarryMaterial(bindCarryCodeInput);
if (result1.code != HttpStatusCode.OK)
{
throw Oops.Bah(result1.msg);
}
WmsPrdInstockInput wmsPrdInstockInput = new WmsPrdInstockInput();
wmsPrdInstockInput.prd_bill_code = prdMo.mo_code;
wmsPrdInstockInput.material_id = prdMoTask.material_id;
wmsPrdInstockInput.material_code = prdMoTask.material_code;
wmsPrdInstockInput.material_name = basMaterial.name;
wmsPrdInstockInput.material_spec = basMaterial.material_specification;
wmsPrdInstockInput.planqty = prdMoTask.scheduled_qty.Value;
wmsPrdInstockInput.pqty = input.reported_qty;
wmsPrdInstockInput.rqty = 0;
wmsPrdInstockInput.type = prdMo.mo_type;
wmsPrdInstockInput.create_id = report.create_id;
wmsPrdInstockInput.prdInstockDs = new List<WmsPrdInstockDInput>();
wmsPrdInstockInput.prdInstockCodes = new List<WmsPrdInstockCodeInput>();
wmsPrdInstockInput.prdInstockDs.Add(new WmsPrdInstockDInput()
{
task_bill_code = prdMoTask.mo_task_code,
warehouse_id = report.warehouse_id,
startlocation_id = location.id,
carry_id = wmsCarryH.id,
});
if (prdMoTask.schedule_type == 1)
{
wmsPrdInstockInput.prdInstockCodes.Add(new WmsPrdInstockCodeInput()
{
planqty = prdMoTask.scheduled_qty.Value,
pqty = input.reported_qty,
code_batch = batch,
code = report.barcode,
unit_id = prdMoTask.unit_id,
carry_id = wmsCarryH.id,
});
}
else
{
List<PrdVisionResultRecord> prdVisionResultRecords = await _db.Queryable<PrdVisionResultRecord>()
.Where(x => x.status == 0 && x.result.ToUpper()=="OK").OrderByDescending(x => x.create_time).Take(report.reported_qty.Value).ToListAsync();
List<string> ids = prdVisionResultRecords.Select(x => x.id).ToList();
foreach (var record in prdVisionResultRecords)
{
wmsPrdInstockInput.prdInstockCodes.Add(new WmsPrdInstockCodeInput()
{
planqty = prdMoTask.scheduled_qty.Value,
pqty = 1,
code_batch = batch,
code = record.info,
unit_id = prdMoTask.unit_id,
carry_id = wmsCarryH.id,
});
}
await db.Updateable<PrdVisionResultRecord>()
.SetColumns(x => x.status == 1).Where(x => ids.Contains(x.id)).ExecuteCommandAsync();
}
Log.Information($"生产入库参数:${JsonConvert.SerializeObject(wmsPrdInstockInput)}");
Tnb.WarehouseMgr.Entities.Dto.Outputs.Result result2 = await _wmsPrdInstockHService.PrdInstock(wmsPrdInstockInput, _db);
if (result2 != null)
{
Log.Information($"生产入库接口返回参数:${JsonConvert.SerializeObject(result2)}");
}
else
{
Log.Information($"生产入库接口返回参数为null");
}
if (result2.code != HttpStatusCode.OK)
{
throw Oops.Bah(result2.msg !=null ? result2.msg : "生产入库接口报错");
}
List<string> erpExtendIds = new List<string>();
erpExtendIds.Add(_userManager.UserId);
erpExtendIds.Add(WmsWareHouseConst.AdministratorOrgId);
erpExtendIds.Add(report.material_id);
erpExtendIds.Add(report.unit_id);
List<ErpExtendField> erpExtendFields = await _db.Queryable<ErpExtendField>().Where(x=>erpExtendIds.Contains(x.table_id)).ToListAsync();
string erpCreateId = erpExtendFields.Find(x=>x.table_id==_userManager.UserId)?.user_id ?? "";
ErpExtendField erpOrg = erpExtendFields.Find(x => x.table_id == (WmsWareHouseConst.AdministratorOrgId));
string nowStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
List<Dictionary<string, object>> requestData = new List<Dictionary<string, object>>();
Dictionary<string, object> erpRequestData = new Dictionary<string, object>();
erpRequestData.Add("auditer",erpCreateId);
erpRequestData.Add("billmaker",erpCreateId);
erpRequestData.Add("cdeptid","");
erpRequestData.Add("cdeptvid","");
erpRequestData.Add("creationtime",nowStr);
erpRequestData.Add("creator",erpCreateId);
erpRequestData.Add("cshiftid","");
erpRequestData.Add("cteamid","");
erpRequestData.Add("cwkid","");
erpRequestData.Add("cworkmanid",erpCreateId);
erpRequestData.Add("dbilldate",nowStr);
erpRequestData.Add("dmakedate",nowStr);
erpRequestData.Add("fbillstatus",1);
erpRequestData.Add("fprodmode",1);
erpRequestData.Add("pk_org",erpOrg.pk_org);
erpRequestData.Add("pk_org_v",erpOrg.pk_org_v);
erpRequestData.Add("pk_group",erpOrg.pk_group);
erpRequestData.Add("pk_wr","");
erpRequestData.Add("vbillcode","");
erpRequestData.Add("vnote","");
erpRequestData.Add("vtrantypecode","55A4-01");
erpRequestData.Add("vtrantypeid","0001A11000000002LVX8");
List<Dictionary<string, object>> erpRequestDataDetails = new List<Dictionary<string, object>>();
erpRequestDataDetails.Add(new Dictionary<string, object>()
{
["bbchkflag"] = false,
["bbhasbckfled"] = false,
["bbhaspicked"] = false,
["bbinstock"] = false,
["bbisempass"] = false,
["bbotherreject"] = false,
["bbsetmark"] = false,
["bbstockbycheck"] = false,
["cbastunitid"] = "",
["cbbomversionid"] = "",
["cbdeptid"] = "",
["cbdeptvid"] = "",
["cbfirstmobid"] = "",
["cbfirstmoid"] = "",
["cbmainbomid"] = "",
["cbmainmaterialid"] = erpExtendFields.Find(x=>x.table_id==report.material_id)?.cmaterialoid ?? "",
["cbmainmaterialvid"] = erpExtendFields.Find(x=>x.table_id==report.material_id)?.cmaterialvid ?? "",
["cbmaterialid"] = erpExtendFields.Find(x=>x.table_id==report.material_id)?.cmaterialvid ?? "",
["cbmaterialvid"] = erpExtendFields.Find(x=>x.table_id==report.material_id)?.cmaterialvid ?? "",
["cbmobid"] = prdMo.erp_lineno,
["cbmoid"] = prdMo.erp_mo_pk,
["cbsrctranstype"] = "",
["cbsrctype"] = "",
["cbunitid"] = erpExtendFields.Find(x=>x.table_id==report.unit_id)?.cunitid ?? "",
["cbworkmanid"] = erpCreateId,
["fbproducttype"] = 1,
["fbsourcetype"] = 2,
// ["nbplanwrastnum"] = "",
["nbplanwrnum"] = report.reported_qty,
["nbwrnum"] = report.reported_qty,
["pk_wr"] = "",
["pk_wr_product"] = "",
["pseudocolumn"] = 10,
["tbendtime"] = "",
["tbstarttime"] = "",
["vbbatchcode"] = report.batch,
["vbbatchid"] = "",
["vbchangerate"] = "",
["vbfirstcode"] = "",
["vbfirstid"] = "",
["vbfirstmocode"] = "",
["vbfirstmorowno"] = "",
["vbfirsttype"] = "",
["vbidentify"] = "",
["vbinbatchcode"] = report.batch,
["vbinbatchid"] = "",
["vbmainbomcode"] = "",
["vbmainidentify"] = "",
["vbmainmorowno"] = "",
["vbmobillcode"] = prdMo.mo_code,
["vbrowno"] = prdMo.erp_lineno,
["vbsrccode"] = "",
["vbsrcid"] = "",
["vbsrcrowid"] = "",
["vbsrcrowno"] = "",
["vbsrctranstype"] = "",
["vbdef2"] = 10,
});
erpRequestData.Add("AggWrDtl",erpRequestDataDetails);
requestData.Add(erpRequestData);
ThirdWebapiRecord thirdWebapiRecord = new ThirdWebapiRecord();
thirdWebapiRecord.id = SnowflakeIdHelper.NextId();
thirdWebapiRecord.third_name = WmsWareHouseConst.BIP;
thirdWebapiRecord.name = "生产报告";
thirdWebapiRecord.method = "POST";
thirdWebapiRecord.url = WmsWareHouseConst.BIP_DOMAIN+"uapws/rest/pwrnew/save";
thirdWebapiRecord.request_data = JsonConvert.SerializeObject(erpRequestData);
thirdWebapiRecord.create_time = DateTime.Now;
await _db.Insertable(thirdWebapiRecord).ExecuteCommandAsync();
if (prdMoTask.schedule_type == 2)
{
// Dictionary<string, string> dicCommand2 = new(StringComparer.OrdinalIgnoreCase)
// {
// ["DevName"] = dic[prdMoTask.workline_id],
// ["token"] = _eleCtlCfg.token,
// ["TagName"] = "WBZX_x1_ok",
// ["Value"] = "true",
// };
// Log.Information($"提拔确认完成参数:{JsonConvert.SerializeObject(dicCommand2)}");
// string responseresult = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand2);
// Log.Information($"提拔确认完成参数成返回结果:{responseresult}");
// X2ServerResult x2ServerResult = JsonConvert.DeserializeObject<X2ServerResult>(responseresult);
// if (x2ServerResult.Result != X2ServerResult.Ok)
// {
// throw Oops.Bah(x2ServerResult.Msg);
// }
// Dictionary<string, string> dicCommand4 = new(StringComparer.OrdinalIgnoreCase)
// {
// ["DevName"] = "外包装箱码垛线",
// ["token"] = _eleCtlCfg.token,
// ["TagName"] = dic2[prdMoTask.workline_id],
// ["Value"] = "0",
// };
//
// Log.Information($"清除提报码垛数参数:{JsonConvert.SerializeObject(dicCommand4)}");
// string responseresult2 = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand4);
// Log.Information($"清除提报码垛数返回结果:{responseresult2}");
// X2ServerResult x2ServerResult2 = JsonConvert.DeserializeObject<X2ServerResult>(responseresult2);
// if (x2ServerResult2.Result != X2ServerResult.Ok)
// {
// throw Oops.Bah(x2ServerResult2.Msg);
// }
}
if (basMaterial.category_id.Contains("ZSJ") || basMaterial.category_id.Contains("DGJCJ"))
{
EqpEquipment equipment = await _db.Queryable<EqpEquipment>().SingleAsync(x => x.id == prdMoTask.eqp_id);
EqpDaq eqpDaq3 = await _repository.AsSugarClient().Queryable<EqpDaq>().
LeftJoin<EqpEquipment>((x,y)=>x.equip_id==y.id).
Where((x,y) => y.code == equipment.code && x.label_name.Contains("称重完成")).FirstAsync();
if (eqpDaq3 == null)
{
throw Oops.Bah("未在数据采集中设置称重完成标签点");
}
Dictionary<string, string> dicCommand3 = new(StringComparer.OrdinalIgnoreCase)
{
["DevName"] = eqpDaq3.equip_code,
["token"] = _eleCtlCfg.token,
["TagName"] = eqpDaq3.label_name,
["Value"] = "true",
};
Log.Information($"称重完成参数:{JsonConvert.SerializeObject(dicCommand3)}");
string responseresult = await HttpClientHelper.GetRequestAsync(_eleCtlCfg.WriteTagUrl, dicCommand3,false);
Log.Information($"{eqpDaq3.equip_code},{eqpDaq3.label_name}称重完成返回结果:{responseresult}");
X2ServerResult x2ServerResult = JsonConvert.DeserializeObject<X2ServerResult>(responseresult);
if (x2ServerResult.Result != X2ServerResult.Ok)
{
throw Oops.Bah(x2ServerResult.Msg);
}
}
await _db.Ado.CommitTranAsync();
}
catch (Exception ex)
{
Log.Error("提报失败", ex);
await _db.Ado.RollbackTranAsync();
throw Oops.Bah("提报失败:"+ex.Message);
}
finally{
prdreportSemaphore.Release();
}
// DbResult<bool> result = await _repository.AsSugarClient().Ado.UseTranAsync(async () =>
// {
//
//
//
// });
// if (result.IsSuccess)
// {
// if (!string.IsNullOrEmpty(basMaterial.category_id))
// {
// string[] arr = JsonConvert.DeserializeObject<string[]>(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 true;
}
/// <summary>
/// 自检报废提交
/// </summary>
/// <param name="input">自检报废输入参数</param>
/// <returns>true/false</returns>
/// <remarks>
/// input:
///<br/>{
///<br/> "icmo_code": 任务单号,
///<br/> "scrap_qty": 报废数量,
///<br/> "remark": 备注,
///<br/> "categoryItems": [
///<br/> {
///<br/> "defective_category":次品分类,
///<br/> "category_qty": 分类数量,
///<br/> "items": [
///<br/> {
///<br/> "defective_item": 次品项,
///<br/> "defective_item_qty": 次品项数量
///<br/> }
///<br/> ]
///<br/> }
///<br/> ]
///<br/>}
/// </remarks>
[HttpPost]
public async Task<dynamic> SelfTestScrapped(SelfTestScrappedInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
if (await db.Queryable<PrdMoTask>().AnyAsync(x => x.id == input.mo_task_id && x.mo_task_status == DictConst.MoStatusPauseCode))
{
throw Oops.Bah("暂停的任务单无法报废");
}
DbResult<bool> result = await db.Ado.UseTranAsync(async () =>
{
List<PrdMoTaskDefect> destDefects = new();
string batch = DateTime.Now.ToString("yyyyMMddHHmmss");
PrdMoTask prdMoTask = await db.Queryable<PrdMoTask>().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<PrdMoTaskDefect>().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<PrdMoTask>().SetColumns(it => new PrdMoTask { scrap_qty = scrapQty.Value }).Where(it => it.id == input.mo_task_id).ExecuteCommandAsync();
}
PrdMoTaskDefectRecord defectRecord = await db.Queryable<PrdMoTaskDefectRecord>().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<PrdReportRecord>().FirstAsync(it => it.mo_task_id == input.mo_task_id);
PrdMo prdMo = await db.Queryable<PrdMo>().SingleAsync(x => x.id == prdMoTask.mo_id);
_ = prdMo.reported_work_qty == null
? await db.Updateable<PrdMo>()
.SetColumns(x => x.scrap_qty == input.scrap_qty)
.Where(x => x.id == prdMo.id).ExecuteCommandAsync()
: await db.Updateable<PrdMo>()
.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<PrdMo>()
.SetColumns(x => x.complete_qty == input.scrap_qty)
.Where(x => x.id == prdMo.id).ExecuteCommandAsync()
: await db.Updateable<PrdMo>()
.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<PerProcessStandardsH>()
.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<ToolMolds>().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<PrdMoTask>()
.SetColumns(x => x.plan_end_date == cal_plan_end_date)
.Where(x => x.id == input.mo_task_id).ExecuteCommandAsync();
}
}
}
else
{
List<BasStandardTime> list = await db.Queryable<BasMbomProcess>()
.LeftJoin<BasStandardTime>((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<PrdMoTask>()
.SetColumns(x => x.plan_end_date == cal_plan_end_date)
.Where(x => x.id == input.mo_task_id).ExecuteCommandAsync();
}
}
});
return result.IsSuccess;
}
/// <summary>
/// 修改组装、包装,生产任务信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> UpdatePackMoTask(PackPrdTaskUpInput input)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
int row = await _db.Updateable<PrdMoTask>().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;
}
/// <summary>
/// 生成子工单
/// </summary>
/// <returns></returns>
[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<PrdMo>().FirstAsync(it => it.id == input.mo_id);
if (curMo == null)
{
throw new ArgumentNullException("创建子工单时的父工单不能为null");
}
var outMaterials = await _db.Queryable<BasMbom>().InnerJoin<BasMbomProcess>((a, b) => a.id == b.mbom_id)
.InnerJoin<BasMbomOutput>((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<string> ids = outMaterials.Select(x => x.material_id).ToList();
_ = await _db.Deleteable<PrdMo>().Where(it => it.parent_id == input.mo_id).ExecuteCommandAsync();
if (ids?.Count > 0)
{
Dictionary<string, int> dicOutMaterialNum = outMaterials.DistinctBy(x => x.material_id).ToDictionary(x => x.material_id, x => x.num.ParseToInt());
List<PrdMo> subMoList = new();
List<BasMaterial> outputMaterials = await _db.Queryable<BasMaterial>().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<string, string[]> dicProperties = new(StringComparer.OrdinalIgnoreCase);
private static T DictionaryToObject<T>(IDictionary<string, object> 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<dynamic> 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<BasMaterial>().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<ToolMolds>().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<EqpEquipment>().FirstAsync(it => it.id == eqpId);
// if (eqp != null)
// {
// row["eqp_id"] = $"{eqp.code}/{eqp.name}";
// }
// }
// }
// }
// return data!;
// }
private async Task<dynamic> GetList(VisualDevModelListQueryInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
Dictionary<string, string>? queryJson = !string.IsNullOrEmpty(input.queryJson) ? JsonConvert.DeserializeObject<Dictionary<string, string>>(input.queryJson) : new Dictionary<string, string>();
string moTaskCode = queryJson.ContainsKey("mo_task_code") ? queryJson["mo_task_code"].ToString() : "";
string eqpId = queryJson.ContainsKey("eqp_id") ? queryJson["eqp_id"].ToString() : "";
List<string> worklineIds = new();
List<string> equipIds = new();
if (!string.IsNullOrEmpty(eqpId))
{
worklineIds = await db.Queryable<OrganizeEntity>().Where(x => x.ParentId == eqpId && x.Category == DictConst.RegionCategoryWorklineCode && x.DeleteMark == null).Select(x => x.Id).ToListAsync();
equipIds = await db.Queryable<EqpEquipment>().Where(x => x.equip_type_id == eqpId).Select(x => x.id).ToListAsync();
if (equipIds == null || equipIds.IsEmpty())
{
equipIds.Add(eqpId);
}
}
SqlSugarPagedList<WorkOrderAdjustmentListOutput> result = await db.Queryable<PrdMoTask>()
.LeftJoin<BasMaterial>((a, b) => a.material_id == b.id)
.LeftJoin<DictionaryTypeEntity>((a, b, c) => c.EnCode == DictConst.TaskStatus)
.LeftJoin<DictionaryDataEntity>((a, b, c, d) =>
c.Id == d.DictionaryTypeId && a.mo_task_status == d.EnCode)
.LeftJoin<ToolMolds>((a, b, c, d, e) => a.mold_id == e.id)
.LeftJoin<PrdMo>((a, b, c, d, e, f) => a.mo_id == f.id)
.LeftJoin<OrganizeEntity>((a, b, c, d, e, f, g) => a.workline_id == g.Id)
.LeftJoin<EqpEquipment>((a, b, c, d, e, f, g, h) => a.eqp_id == h.id)
.LeftJoin<UserEntity>((a, b, c, d, e, f, g, h,i)=>a.worker_id==i.Id)
.WhereIF(!string.IsNullOrEmpty(moTaskCode), (a, b, c, d) => a.mo_task_code.Contains(moTaskCode))
.WhereIF(!string.IsNullOrEmpty(eqpId) && equipIds.Count <= 0 && worklineIds.Count <= 0,
(a, b, c, d) => a.workline_id == eqpId || a.eqp_id == eqpId)
.WhereIF(worklineIds.Count > 0, (a, b, c, d) => worklineIds.Contains(a.workline_id))
.WhereIF(equipIds.Count > 0, (a, b, c, d) => equipIds.Contains(a.eqp_id))
.Where((a) => a.mo_task_status == DictConst.ToBeStartedEnCode || a.mo_task_code == DictConst.ToBeScheduledEncode || a.mo_task_code == DictConst.MoStatusPauseCode)
.Select((a, b, c, d, e, f, g, h,i) => new WorkOrderAdjustmentListOutput
{
id = a.id,
mo_task_code = a.mo_task_code,
material_id = b.code + "/" + b.name,
material_id_id = a.material_id,
mold_id = e.mold_code + "/" + e.mold_name,
mold_id_id = a.mold_id,
mo_task_status = d.FullName,
plan_qty = f.plan_qty,
complete_qty = SqlFunc.IsNull(a.reported_work_qty, 0) + SqlFunc.IsNull(a.scrap_qty, 0),
scheduled_qty = a.scheduled_qty,
workline_id = a.workline_id == null ? "" : g.EnCode + "/" + g.FullName,
workline_id_id = a.workline_id,
estimated_start_date = a.estimated_start_date == null ? "" : a.estimated_start_date.Value.ToString("yyyy-MM-dd"),
estimated_end_date = a.estimated_end_date == null ? "" : a.estimated_end_date.Value.ToString("yyyy-MM-dd"),
eqp_id = a.eqp_id == null ? "" : h.code + "/" + h.name,
eqp_id_id = a.eqp_id,
create_time = a.create_time == null ? "" : a.create_time.Value.ToString(DbTimeFormat.SS),
schedule_type = a.schedule_type,
worker_id = i.RealName
}).OrderByDescending(a => a.create_time).ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult<WorkOrderAdjustmentListOutput>.SqlSugarPageResult(result);
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private async Task Delete(string id)
{
ISqlSugarClient db = _repository.AsSugarClient();
DbResult<bool> result = await db.Ado.UseTranAsync(async () =>
{
int row = -1;
PrdMoTask prdTask = await db.Queryable<PrdMoTask>().FirstAsync(it => it.id == id);
row = await db.Deleteable<PrdTask>().Where(it => it.id == id).ExecuteCommandAsync();
if (row > 0)
{
PrdMo? prdMo = await db.Queryable<PrdMo>().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<List<PrdMoTask>> GetListByEqpId(string eqpId)
{
return await _db.Queryable<PrdMoTask>().Where(it => it.eqp_id == eqpId && it.mo_task_status == DictConst.InProgressEnCode).ToListAsync();
}
/// <summary>
/// 计算预计结束日期
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="AppFriendlyException"></exception>
[HttpPost]
public async Task<dynamic> GetEstimatedEndTime(CountEstimatedEndTimeInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
if (input.type == 1)
{
PerProcessStandardsH processStandardsH = await db.Queryable<PerProcessStandardsH>()
.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<ToolMolds>().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<BasStandardTime> list = await db.Queryable<BasMbomProcess>()
.LeftJoin<BasStandardTime>((a, b) => a.process_id == b.process_id && b.enabled == 1)
.Where((a, b) => a.mbom_id == input.mbom_id).Select((a, b) => b).ToListAsync();
if (list.IsEmpty())
{
throw Oops.Bah("无标准工时,预计完成时间无法计算");
}
decimal max = list.Select(x => Convert.ToDecimal(x.standard_time)).Max(x => x);
decimal? addTime = input.scheduled_qty * max;
return input.estimated_start_date.AddSeconds((double)addTime.Value).ToString("yyyy-MM-dd HH:mm:ss");
}
}
/// <summary>
/// 获取这个产线生产中的任务单
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> GetMoTaskByWorklineId(Dictionary<string, string> dic)
{
string id = dic["id"];
return await _repository.AsSugarClient().Queryable<PrdMoTask>()
.Where(x => x.workline_id == id && x.mo_task_status == DictConst.InProgressEnCode).FirstAsync();
}
/// <summary>
/// 更换机台
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> ChangeEquip(ChangeEquipInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
DbResult<bool> result = await db.Ado.UseTranAsync(async () =>
{
PrdMoTask moTask = await db.Queryable<PrdMoTask>().SingleAsync(x => x.id == input.mo_task_id);
if (moTask.eqp_id == input.equip_id)
{
throw new Exception("与原机台相同");
}
_ = await db.Updateable<PrdMoTask>().SetColumns(x => x.eqp_id == input.equip_id)
.Where(x => x.id == input.mo_task_id).ExecuteCommandAsync();
PrdMo mo = await db.Queryable<PrdMo>().SingleAsync(x => x.id == moTask.mo_id);
BasMaterial? material = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == moTask.material_id);
BasMaterial process = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == moTask.process_id);
PrdTaskLog taskLog = new()
{
id = SnowflakeIdHelper.NextId(),
mo_code = mo?.mo_code!,
eqp_code = (await db.Queryable<EqpEquipment>().FirstAsync(it => it.id == input.equip_id))?.code!,
mold_code = "",
item_code = material?.code!,
item_standard = material?.material_specification!,
status = "更换机台",
operator_name = _userManager.RealName,
create_id = _userManager.UserId,
create_time = DateTime.Now,
mo_task_id = moTask.id,
mo_task_code = moTask.mo_task_code,
station_code = "",
process_code = process?.code
};
_ = await db.Insertable<PrdTaskLog>(taskLog).ExecuteCommandAsync();
});
return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "更换成功" : result.ErrorMessage);
}
/// <summary>
/// 更换模具
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> ChangeMold(ChangeMoldInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
DbResult<bool> result = await db.Ado.UseTranAsync(async () =>
{
PrdMoTask moTask = await db.Queryable<PrdMoTask>().SingleAsync(x => x.id == input.mo_task_id);
if (moTask.mold_id == input.mold_id)
{
throw new Exception("与原模具相同");
}
_ = await db.Updateable<PrdMoTask>().SetColumns(x => x.mold_id == input.mold_id)
.Where(x => x.id == input.mo_task_id).ExecuteCommandAsync();
PrdMo mo = await db.Queryable<PrdMo>().SingleAsync(x => x.id == moTask.mo_id);
ToolMolds mold = await db.Queryable<ToolMolds>().SingleAsync(x => x.id == input.mold_id);
BasMaterial? material = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == moTask.material_id);
BasMaterial process = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == moTask.process_id);
PrdTaskLog taskLog = new()
{
id = SnowflakeIdHelper.NextId(),
mo_code = mo?.mo_code!,
eqp_code = "",
mold_code = mold?.mold_code,
item_code = material?.code!,
item_standard = material?.material_specification!,
status = "更换模具",
operator_name = _userManager.RealName,
create_id = _userManager.UserId,
create_time = DateTime.Now,
mo_task_id = moTask.id,
mo_task_code = moTask.mo_task_code,
station_code = "",
process_code = process?.code
};
_ = await db.Insertable<PrdTaskLog>(taskLog).ExecuteCommandAsync();
});
return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "更换成功" : result.ErrorMessage);
}
/// <summary>
/// 更换产线
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> ChangeWorkline(ChangeWorklineInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
DbResult<bool> result = await db.Ado.UseTranAsync(async () =>
{
PrdMoTask moTask = await db.Queryable<PrdMoTask>().SingleAsync(x => x.id == input.mo_task_id);
if (moTask.workline_id == input.workline_id)
{
throw new Exception("与原产线相同");
}
_ = await db.Updateable<PrdMoTask>().SetColumns(x => x.workline_id == input.workline_id)
.Where(x => x.id == input.mo_task_id).ExecuteCommandAsync();
PrdMo mo = await db.Queryable<PrdMo>().SingleAsync(x => x.id == moTask.mo_id);
BasMaterial? material = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == moTask.material_id);
BasMaterial process = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == moTask.process_id);
PrdTaskLog taskLog = new()
{
id = SnowflakeIdHelper.NextId(),
mo_code = mo?.mo_code!,
eqp_code = "",
mold_code = "",
item_code = material?.code!,
item_standard = material?.material_specification!,
status = "更换产线",
operator_name = _userManager.RealName,
create_id = _userManager.UserId,
create_time = DateTime.Now,
mo_task_id = moTask.id,
mo_task_code = moTask.mo_task_code,
station_code = "",
process_code = process?.code
};
_ = await db.Insertable<PrdTaskLog>(taskLog).ExecuteCommandAsync();
});
return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "更换成功" : result.ErrorMessage);
}
/// <summary>
/// 更换员工
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> ChangeWorker(ChangeWorkerInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
DbResult<bool> result = await db.Ado.UseTranAsync(async () =>
{
PrdMoTask moTask = await db.Queryable<PrdMoTask>().SingleAsync(x => x.id == input.mo_task_id);
if (moTask.worker_id == input.worker_id)
{
throw new Exception("与原员工相同");
}
_ = await db.Updateable<PrdMoTask>().SetColumns(x => x.worker_id == input.worker_id)
.Where(x => x.id == input.mo_task_id).ExecuteCommandAsync();
PrdMo mo = await db.Queryable<PrdMo>().SingleAsync(x => x.id == moTask.mo_id);
BasMaterial? material = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == moTask.material_id);
BasMaterial process = await db.Queryable<BasMaterial>().SingleAsync(x => x.id == moTask.process_id);
PrdTaskLog taskLog = new()
{
id = SnowflakeIdHelper.NextId(),
mo_code = mo?.mo_code!,
eqp_code = "",
mold_code = "",
item_code = material?.code!,
item_standard = material?.material_specification!,
status = "更换员工",
operator_name = _userManager.RealName,
create_id = _userManager.UserId,
create_time = DateTime.Now,
mo_task_id = moTask.id,
mo_task_code = moTask.mo_task_code,
station_code = "",
process_code = process?.code
};
_ = await db.Insertable<PrdTaskLog>(taskLog).ExecuteCommandAsync();
});
return !result.IsSuccess ? throw Oops.Bah(result.ErrorMessage) : (dynamic)(result.IsSuccess ? "更换成功" : result.ErrorMessage);
}
/// <summary>
/// 根据id获取任务单相关信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic?> GetPrdMoTaskInfoById(Dictionary<string, string> dic)
{
string id = dic.ContainsKey("id") ? dic["id"] : "";
if (string.IsNullOrEmpty(id))
{
return null;
}
ISqlSugarClient db = _repository.AsSugarClient();
return await db.Queryable<PrdMoTask>()
.LeftJoin<BasMaterial>((a, b) => a.material_id == b.id)
.LeftJoin<ToolMolds>((a, b, c) => a.mold_id == c.id)
.LeftJoin<EqpEquipment>((a, b, c, d) => a.eqp_id == d.id)
.LeftJoin<DictionaryDataEntity>((a, b, c, d, e) => e.EnCode == a.mo_task_status && e.DictionaryTypeId == DictConst.PrdTaskStatusTypeId)
.LeftJoin<BasProcess>((a, b, c, d, e, f) => a.process_id == f.id)
.LeftJoin<OrganizeEntity>((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();
}
/// <summary>
/// 获取组装包装生产排产甘特图信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> GetGanntInfo1()
{
ISqlSugarClient db = _repository.AsSugarClient();
Dictionary<string, object> result = new();
var listRows = await db.Queryable<EqpEquipment>()
.LeftJoin<EqpEquipType>((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<PrdMoTask>()
.LeftJoin<BasMaterial>((a, b) => a.material_id == b.id)
.LeftJoin<DictionaryDataEntity>((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<PrdMoTask>().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;
}
/// <summary>
/// 获取组装包装生产排产甘特图信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> GetGanntInfo2()
{
ISqlSugarClient db = _repository.AsSugarClient();
Dictionary<string, object> result = new();
var listRows = await db.Queryable<OrganizeEntity>()
.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<PrdMoTask>()
.LeftJoin<BasMaterial>((a, b) => a.material_id == b.id)
.LeftJoin<DictionaryDataEntity>((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<PrdMoTask>().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;
}
/// <summary>
/// 保存注塑挤出生产排产甘特图信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> SaveData1(List<GanntSaveInput> input)
{
ISqlSugarClient db = _repository.AsSugarClient();
DbResult<bool> result = await db.Ado.UseTranAsync(async () =>
{
foreach (GanntSaveInput item in input)
{
// if(await db.Queryable<OrganizeEntity>().Where(x=>x.Id==item.row_id && x.Category==DictConst.RegionCategoryWorkshopCode).AnyAsync())
// throw Oops.Bah("不能排在车间上");
PrdMoTask prdMoTask = await db.Queryable<PrdMoTask>().SingleAsync(x => x.id == item.id);
if (prdMoTask.eqp_id != item.row_id)
{
_ = await db.Updateable<PrdMoTask>()
.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<PrdMoTask>()
.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<PrdMoTask>()
.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);
}
/// <summary>
/// 保存组装包装生产排产甘特图信息
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> SaveData2(List<GanntSaveInput> input)
{
ISqlSugarClient db = _repository.AsSugarClient();
DbResult<bool> result = await db.Ado.UseTranAsync(async () =>
{
foreach (GanntSaveInput item in input)
{
if (await db.Queryable<OrganizeEntity>().Where(x => x.Id == item.row_id && x.Category == DictConst.RegionCategoryWorkshopCode).AnyAsync())
{
throw Oops.Bah("不能排在车间上");
}
PrdMoTask prdMoTask = await db.Queryable<PrdMoTask>().SingleAsync(x => x.id == item.id);
if (prdMoTask.workline_id != item.row_id)
{
_ = await db.Updateable<PrdMoTask>()
.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<PrdMoTask>()
.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<PrdMoTask>()
.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);
}
/// <summary>
/// 获取工单各个状态数量
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> GetMoTaskStatusNum()
{
return await _db.Queryable<DictionaryTypeEntity>().
LeftJoin<DictionaryDataEntity>((a, b) => a.Id == b.DictionaryTypeId)
.LeftJoin<PrdMo>((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();
}
/// <summary>
/// 获取备料计划
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> GetMaterialPreparationPlan()
{
string now = DateTime.Now.ToString("yyyy-MM-dd");
List<MaterialPreparationPlanDOutput> childrenList = await _db.Queryable<PrdMoTask>()
.LeftJoin<PrdMoTask>((a, b) => a.id == b.parent_id)
.LeftJoin<BasMaterial>((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<BasMbom>().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<BasMbomInput>()
.LeftJoin<BasMaterial>((x, y) => x.material_id == y.id)
.Where((x, y) => x.mbom_process_id == b.mbom_process_id)
.ToList((x, y) => new MaterialPreparationPlanDDOutput()
{
material_id = x.material_id,
material_code = y.code,
category_id = y.category_id,
num = x.num,
molecule = x.molecule,
denominator = x.denominator,
})
}).ToListAsync();
List<MaterialPreparationPlanOutput> prdMoTaskList = await _db.Queryable<PrdMoTask>()
.LeftJoin<BasMaterial>((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;
}
/// <summary>
/// 根据工位获取进行中的任务单信息
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
[HttpPost]
public async Task<PrdMoTask> GetPrdMoTaskInfoByStationId(Dictionary<string, string> dic)
{
string station_id = dic.ContainsKey("station_id") ? dic["station_id"] : "";
if (string.IsNullOrEmpty(station_id))
{
throw Oops.Bah("工位错误");
}
PrdMoTask? prdMoTask = await _db.Queryable<PrdMoTask>().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<BasMaterial>().SingleAsync(x => x.id == prdMoTask.material_id);
prdMoTask.material_name = basMaterial.name;
}
return prdMoTask;
}
/// <summary>
/// 根据chanxian 获取进行中的任务单信息
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
[HttpPost]
public async Task<PrdMoTask> GetPrdMoTaskInfoByWorklineId(Dictionary<string, string> dic)
{
string workline_id = dic.ContainsKey("workline_id") ? dic["workline_id"] : "";
if (string.IsNullOrEmpty(workline_id))
{
throw Oops.Bah("产线错误");
}
PrdMoTask? prdMoTask = await _db.Queryable<PrdMoTask>().Where(x => x.workline_id == workline_id && x.mo_task_status == DictConst.InProgressEnCode && x.parent_id == null).FirstAsync();
if (prdMoTask != null)
{
BasMaterial basMaterial = await _db.Queryable<BasMaterial>().SingleAsync(x => x.id == prdMoTask.material_id);
prdMoTask.material_name = basMaterial.name;
}
return prdMoTask;
}
/// <summary>
/// 根据工位获取进行中待开工暂停的任务单信息
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
[HttpPost]
public async Task<List<PrdMoTask>> GetPrdMoTaskListByStationId(Dictionary<string, string> dic)
{
string station_id = dic.ContainsKey("station_id") ? dic["station_id"] : "";
if (string.IsNullOrEmpty(station_id))
{
throw Oops.Bah("工位错误");
}
List<PrdMoTask> list = await _db.Queryable<PrdMoTask>().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<BasMaterial>().SingleAsync(x => x.id == prdMoTask.material_id);
if (basMaterial == null)
{
throw Oops.Bah($"找不到物料{prdMoTask.material_id}");
}
prdMoTask.material_name = basMaterial.name;
}
}
return list;
}
/// <summary>
/// 外包装根据工位id获取喷码数据
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> GetMarkingInfoByStationId(MarkingLabelInput input)
{
PrdMoTask prdMoTask = await GetPrdMoTaskInfoByStationId(new Dictionary<string, string>()
{
{ "station_id", input.station_id }
});
if (prdMoTask == null) throw Oops.Bah("没找到对应任务单");
if (await _db.Queryable<PrdOutPackMarkLabel>().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<PrdOutPackMarkLabel>()
.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>(prdOutPackMarkLabel).ExecuteCommandAsync();
}
PrdMoTask parent = await _db.Queryable<PrdMoTask>().SingleAsync(x => x.id == prdMoTask.parent_id);
BasMaterial basMaterial = await _db.Queryable<BasMaterial>().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;
}
/// <summary>
/// 外包装根据工位id获取贴标数据
/// </summary>
/// <param name="dic"></param>
/// <returns></returns>
[HttpPost]
public async Task<dynamic> GetLabelInfoByStationId(MarkingLabelInput input)
{
PrdMoTask prdMoTask = await GetPrdMoTaskInfoByStationId(new Dictionary<string, string>()
{
{ "station_id", input.station_id }
});
if (prdMoTask == null) throw Oops.Bah("没找到对应任务单");
if (await _db.Queryable<PrdOutPackMarkLabel>().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<PrdOutPackMarkLabel>()
.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>(prdOutPackMarkLabel).ExecuteCommandAsync();
}
PrdMoTask parent = await _db.Queryable<PrdMoTask>().SingleAsync(x => x.id == prdMoTask.parent_id);
BasMaterial basMaterial = await _db.Queryable<BasMaterial>().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;
}
/// <summary>
/// 获取喷码贴标信息
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public async Task<dynamic> GetLabelInfo(MarkingLabelInput input)
{
Log.Information($"获取喷码贴标信息参数:{JsonConvert.SerializeObject(input)}");
//TODO 之后要改
Dictionary<String, String> dic = new Dictionary<string, string>()
{
["WBZ1"] = "30019971917589",//血路管自动生产线1线
["WBZ2"] = "123",
["WBZ3"] = "123",
};
if (dic.TryGetValue(input.result, out string worklineId))
{
if (worklineId != null && !worklineId.IsEmpty())
{
PrdMoTask prdMoTask = await GetPrdMoTaskInfoByWorklineId(new Dictionary<string, string>()
{
{ "workline_id", worklineId }
});
if (prdMoTask == null) throw Oops.Bah("没找到对应任务单");
// if (await _db.Queryable<PrdOutPackMarkLabel>().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<PrdOutPackMarkLabel>()
// .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
// {
// BasMaterial bm = await _db.Queryable<BasMaterial>().SingleAsync(x => x.id == prdMoTask.material_id);
// PrdOutPackMarkLabel prdOutPackMarkLabel = new PrdOutPackMarkLabel()
// {
// is_mark = null,
// is_label = 0,
// mo_task_code = prdMoTask.mo_task_code,
// material_code = bm.code,
// create_time = DateTime.Now,
// };
//
// await _db.Insertable<PrdOutPackMarkLabel>(prdOutPackMarkLabel).ExecuteCommandAsync();
// }
//PrdMoTask parent = await _db.Queryable<PrdMoTask>().SingleAsync(x => x.id == prdMoTask.parent_id);
BasMaterial basMaterial = await _db.Queryable<BasMaterial>().SingleAsync(x=>x.id==prdMoTask.material_id);
PrdMo mo = await _db.Queryable<PrdMo>().SingleAsync(x => x.id == prdMoTask.mo_id);
string batch = "";
if (mo.mo_type == DictConst.PrdMoTypeZS)
{
EqpEquipment equipment = await _db.Queryable<EqpEquipment>().SingleAsync(x => x.id == prdMoTask.eqp_id);
batch = $"{equipment.code.Substring(equipment.code.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}";
}else if (mo.mo_type == DictConst.PrdMoTypeJC)
{
EqpEquipment equipment = await _db.Queryable<EqpEquipment>().SingleAsync(x => x.id == prdMoTask.eqp_id);
ToolMolds toolMolds = await _db.Queryable<ToolMolds>().SingleAsync(x => x.id == prdMoTask.mold_id);
batch = $"{toolMolds.mold_code.Substring(toolMolds.mold_code.Length - 2, 2)}{equipment.code.Substring(equipment.code.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}";
}else
{
// LableRecord lableRecord = await _db.Queryable<LableRecord>().FirstAsync();
// if (lableRecord == null)
// {
// batch = $"{DateTime.Now.ToString("yyMMdd")}5{"1".PadLeft(3,'0')}";
// await _db.Insertable(new LableRecord()
// {
// id = SnowflakeIdHelper.NextId(),
// last_day = DateTime.Now.ToString("yyyyMMdd"),
// num = 1
// }).ExecuteCommandAsync();
// }
// else
// {
// int num = 1;
// if(DateTime.Now.ToString("yyyyMMdd") == lableRecord.last_day)
// {
// num = lableRecord.num+1;
// batch = $"{DateTime.Now.ToString("yyMMdd")}5{(lableRecord.num+1).ToString().PadLeft(3,'0')}";
// }
// else
// {
// batch = $"{DateTime.Now.ToString("yyMMdd")}5{"1".PadLeft(3,'0')}";
// }
//
// await _db.Updateable<LableRecord>()
// .SetColumns(x=>x.last_day==DateTime.Now.ToString("yyyyMMdd"))
// .SetColumns(x=>x.num==num)
// .Where(x=>x.id==lableRecord.id)
// .ExecuteCommandAsync();
// }
OrganizeEntity organizeEntity = await _db.Queryable<OrganizeEntity>().SingleAsync(x => x.Id == prdMoTask.workline_id);
batch = $"{organizeEntity.EnCode.Substring(organizeEntity.EnCode.Length - 2, 2)}{DateTime.Now.ToString("yyMMdd")}";
}
string code = $"(01){basMaterial.di ?? ""}*(11){DateTime.Now.ToString("yyMMdd")}*(17){DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyMMdd")}*(10){batch}#{basMaterial.material_specification}*{batch}*{DateTime.Now.ToString("yyyyMMdd")}*{DateTime.Now.AddMonths(basMaterial.quality_guarantee_period ?? 0).ToString("yyyyMMdd")}*{basMaterial.container_no}";
return code;
}
}
// return "(01)16945155732691(11)240510(17)270510(10)24053026#TX-JB-12*24053026*202405*1020270510RJ-A1F3NC2";
return "";
}
/// <summary>
/// 视觉设备判定
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public async Task<dynamic> VisionResult(MarkingLabelInput input)
{
Log.Information($"视觉设备判定参数:{JsonConvert.SerializeObject(input)}");
PrdVisionResultRecord reocrd = new PrdVisionResultRecord();
reocrd.id = SnowflakeIdHelper.NextId();
reocrd.info = input.mark_code;
reocrd.result = input.result;
reocrd.create_time = DateTime.Now;
reocrd.num = int.Parse(input.station_id);
reocrd.status = 0;
await _db.Insertable(reocrd).ExecuteCommandAsync();
return $"接收到参数:{JsonConvert.SerializeObject(input)}";
}
/// <summary>
/// 分配员工
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
public async Task<string> BindUser(Dictionary<String,String> input)
{
string ids = input.GetOrDefault("ids");
string[] idList = ids.Split(",");
string workerId = input.GetOrDefault("worker_id");
int row = await _db.Updateable<PrdMoTask>()
.SetColumns(x => x.worker_id == workerId)
.Where(x => idList.Contains(x.id))
.ExecuteCommandAsync();
return row>0 ? "分配成功" : "分配失败";
}
}
}