using JNPF;
using JNPF.ClayObject.Extensions;
using JNPF.Common.Core.Manager;
using JNPF.Common.Enums;
using JNPF.Common.Extension;
using JNPF.DependencyInjection;
using JNPF.DynamicApiController;
using JNPF.Extras.CollectiveOAuth.Models;
using JNPF.Extras.CollectiveOAuth.Utils;
using JNPF.FriendlyException;
using JNPF.Logging;
using JNPF.Systems.Entitys.Permission;
using JNPF.Systems.Interfaces.Permission;
using JNPF.Systems.Interfaces.System;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using Tnb.BasicData;
using Tnb.BasicData.Entities;
using Tnb.ProductionMgr.Entities;
using Tnb.ProductionMgr.Entities.Dto;
using Tnb.ProductionMgr.Interfaces;
using Tnb.WarehouseMgr;
using Tnb.WarehouseMgr.Entities;
using Tnb.WarehouseMgr.Entities.Attributes;
using Tnb.WarehouseMgr.Entities.Consts;
using Tnb.WarehouseMgr.Entities.Dto;
using Tnb.WarehouseMgr.Entities.Dto.Inputs;
using Tnb.WarehouseMgr.Interfaces;
using Tnb.WarehouseMgr.Entities.Dto.Outputs;
using Tnb.BasicData.Interfaces;
using Tnb.WarehouseMgr.Entities.Enums;
namespace Tnb.ProductionMgr
{
///
/// 业务实现:物料签收
///
[ApiDescriptionSettings(Tag = ModuleConst.Tag, Area = ModuleConst.Area, Order = 700)]
[Route("api/[area]/[controller]/[action]")]
[ServiceModule(BizTypeId)]
public class PrdMaterialReceiptService : BaseWareHouseService,IPrdMaterialReceiptService, IDynamicApiController, ITransient
{
private const string BizTypeId = "FloorCallMaterial";
private readonly ISqlSugarRepository _repository;
private readonly ISqlSugarClient _db;
private readonly IUserManager _userManager;
private readonly IOrganizeService _organizeService;
private readonly IBillRullService _billRullService;
private readonly IPrdMoTaskService _prdMoTaskService;
private readonly IWmsCarryQueryService _wmsCarryQueryService;
private readonly IBasWorkgroupService _basWorkgroupService;
private readonly IWmsCarryUnbindService _wmsCarryUnbindService;
public PrdMaterialReceiptService(
ISqlSugarRepository repository,
IBillRullService billRullService,
IOrganizeService organizeService,
IPrdMoTaskService prdMoTaskService,
IWmsCarryQueryService wmsCarryQueryService,
IBasWorkgroupService basWorkgroupService,
IWmsCarryUnbindService wmsCarryUnbindService,
IUserManager userManager
)
{
_repository = repository;
_db = _repository.AsSugarClient();
_userManager = userManager;
_organizeService = organizeService;
_billRullService = billRullService;
_prdMoTaskService = prdMoTaskService;
_wmsCarryQueryService = wmsCarryQueryService;
_basWorkgroupService = basWorkgroupService;
_wmsCarryUnbindService = wmsCarryUnbindService;
}
[HttpPost]
public async Task GetInfoByQrCode(Dictionary dic)
{
string qrCode = dic["qrcode"];
string station_id = dic["station_id"];
ISqlSugarClient db = _repository.AsSugarClient();
// var result = await db.Queryable()
// .Where((a) => a.carry_code == qrCode)
// .Select(a => new
// {
// carry_id = a.id,
// carry_name = a.carry_name,
// children = SqlFunc.Subqueryable()
// .LeftJoin((b,c)=>b.material_id==c.id)
// .Where((b,c)=>a.id==b.carry_id).ToList((b,c)=>new CarryCodeDetailOutput()
// {
// unit_id = c.unit_id,
// barcode = b.barcode,
// code_batch = b.code_batch,
// codeqty = b.codeqty,
// material_id = b.material_id,
// material_code = c.code,
// material_name = c.name
// })
// }).FirstAsync();
//OrganizeEntity workline = await _organizeService.GetAnyParentByWorkstationId(station_id, DictConst.RegionCategoryWorklineCode);
// PrdMoTask prdMoTask = await db.Queryable().Where(x => x.workline_id == workline.Id && x.worker_id == _userManager.UserId && x.mo_task_status==DictConst.InProgressEnCode)
// .FirstAsync();
string nowTime = DateTime.Now.ToString("HH:mm");
string nowHour = DateTime.Now.ToString("HH");
if (int.Parse(nowHour) < 7)
{
nowTime = int.Parse(nowHour) + 24 +":"+ DateTime.Now.ToString("mm");
}
BasFactoryConfig config = await db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.DAYNIGHTWORKTIME);
Dictionary dayNightWorkTime = JsonConvert.DeserializeObject>(config.value);
string dayStime = dayNightWorkTime["白班"].Split("-")[0];
string dayEtime = dayNightWorkTime["白班"].Split("-")[1];
string nightStime = dayNightWorkTime["夜班"].Split("-")[0];
string nightEtime = dayNightWorkTime["夜班"].Split("-")[1];
string dayBeforeStime = dayNightWorkTime["白班前"].Split("-")[0];
string dayBeforeEtime = dayNightWorkTime["白班前"].Split("-")[1];
string dayAfterStime = dayNightWorkTime["白班后"].Split("-")[0];
string dayAfterEtime = dayNightWorkTime["白班后"].Split("-")[1];
string nightBeforeStime = dayNightWorkTime["夜班前"].Split("-")[0];
string nightBeforeEtime = dayNightWorkTime["夜班前"].Split("-")[1];
string nightAfterStime = dayNightWorkTime["夜班后"].Split("-")[0];
string nightAfterEtime = dayNightWorkTime["夜班后"].Split("-")[1];
OrganizeEntity workline = await _organizeService.GetAnyParentByWorkstationId(_userManager.User.OrganizeId,DictConst.RegionCategoryWorklineCode);
string userWorklineId = workline?.Id ?? "";
bool twoDayFlag = string.Compare(nowTime, dayStime) >= 0 && string.Compare(nowTime, dayEtime) <= 0;
bool twoNightFlag = string.Compare(nowTime,nightStime)>=0 && string.Compare(nowTime,nightEtime)<=0;
bool fourDayBeforeFlag = (string.Compare(nowTime,dayBeforeStime)>=0 && string.Compare(nowTime,dayBeforeEtime)<=0) ;
bool fourDayAfterFlag = (string.Compare(nowTime,dayAfterStime)>=0 && string.Compare(nowTime,dayAfterEtime)<=0) ;
bool fourNightBeforeFlag = (string.Compare(nowTime,nightBeforeStime)>=0 && string.Compare(nowTime,nightBeforeEtime)<=0) ;
bool fourNightAfterFlag = (string.Compare(nowTime,nightAfterStime)>=0 && string.Compare(nowTime,nightAfterEtime)<=0) ;
string userId = _userManager.UserId;
PrdMoTask prdMoTask = await db.Queryable().
LeftJoin((x,y)=>x.mo_id==y.id)
.Where(x => x.mo_task_status==DictConst.InProgressEnCode)
.Where((x, y) => x.schedule_type==2 && x.parent_id!=null)
.Where((x,y)=>(x.scheduling_class_type=="1" && twoDayFlag && x.dayshift_worker_id==userId)
|| (y.mo_type==DictConst.PrdMoTypeBZ && !SqlFunc.IsNullOrEmpty(userWorklineId) && x.workline_id==userWorklineId)
|| (x.scheduling_class_type=="1" && twoNightFlag && x.nightshift_worker_id==userId)
|| (x.scheduling_class_type=="2" && fourDayBeforeFlag && x.dayshift_worker_id==userId)
|| (x.scheduling_class_type=="2" && fourDayAfterFlag && x.dayshiftafter_worker_id==userId)
|| (x.scheduling_class_type=="2" && fourNightBeforeFlag && x.nightshift_worker_id==userId)
|| (x.scheduling_class_type=="2" && fourNightAfterFlag && x.nightshiftafter_worker_id==userId))
.FirstAsync();
if (prdMoTask == null)
{
throw Oops.Bah("未找到进行中的任务单");
}
List ids = await db.Queryable()
.Where(x => x.mo_task_id == prdMoTask.id).Select(x=>x.id).ToListAsync();
WmsCarryH wmsCarryH = await db.Queryable().SingleAsync(x => x.carry_code == qrCode);
if (wmsCarryH == null)
{
throw Oops.Bah($"未找到该载具{qrCode}");
}
List inPrdMoTask = await db.Queryable().
LeftJoin((x,y)=>x.mo_id==y.id)
.Where(x => x.mo_task_status==DictConst.InProgressEnCode)
.Where((x, y) => x.schedule_type==2 && x.parent_id!=null)
.Where((x,y)=>(x.scheduling_class_type=="1" && twoDayFlag && x.dayshift_worker_id==userId)
|| (y.mo_type==DictConst.PrdMoTypeBZ && !SqlFunc.IsNullOrEmpty(userWorklineId) && x.workline_id==userWorklineId)
|| (x.scheduling_class_type=="1" && twoNightFlag && x.nightshift_worker_id==userId)
|| (x.scheduling_class_type=="2" && fourDayBeforeFlag && x.dayshift_worker_id==userId)
|| (x.scheduling_class_type=="2" && fourDayAfterFlag && x.dayshiftafter_worker_id==userId)
|| (x.scheduling_class_type=="2" && fourNightBeforeFlag && x.nightshift_worker_id==userId)
|| (x.scheduling_class_type=="2" && fourNightAfterFlag && x.nightshiftafter_worker_id==userId))
.ToListAsync();
Log.Information($"生产投料任务单id:${prdMoTask.id}");
Log.Information($"生产投料载具id:${wmsCarryH.id}");
if (!ids.IsEmpty())
{
Log.Information($"生产签收ids:${JsonConvert.SerializeObject(ids)}");
}
if (!inPrdMoTask.IsEmpty())
{
Log.Information($"找到的进行中的任务单:${JsonConvert.SerializeObject(inPrdMoTask)}");
}
if (wmsCarryH.carrystd_id==WmsWareHouseConst.CARRY_ZYXCSTD_ID || wmsCarryH.carrystd_id==WmsWareHouseConst.CARRY_ZYLJSTD_ID)
{
FeedingDetailOutput result = await db.Queryable()
.LeftJoin((a, b) => b.id==a.carry_id)
.Where((a,b) => b.carry_code == qrCode && a.is_all_feeding == 0 && ids.Contains(a.material_receipt_id))
.Select((a, b) => new FeedingDetailOutput
{
carry_id = b.id,
carry_name = b.carry_name,
children = SqlFunc.Subqueryable()
.LeftJoin((c, d) => c.material_id == d.id)
.Where((c, d) => a.carry_id == c.carry_id && c.is_all_feeding == 0 && ids.Contains(c.material_receipt_id))
.ToList((c, d) => new CarryCodeDetailOutput()
{
unit_id = d.unit_id,
// barcode = c.barcode,
// code_batch = c.code_batch,
code_batch = c.batch,
codeqty = c.num - SqlFunc.IsNull(c.feeding_num,0),
material_id = c.material_id,
material_code = d.code,
material_name = d.name
})
}).FirstAsync();
return result;
}
else
{
FeedingDetailOutput result = await db.Queryable()
.LeftJoin((a, b) => b.carry_code==a.member_carry_code)
.Where((a) => a.member_carry_code == qrCode && a.is_all_feeding == 0 && ids.Contains(a.material_receipt_id))
.Select((a, b) => new FeedingDetailOutput
{
carry_id = b.id,
carry_name = b.carry_name,
children = SqlFunc.Subqueryable()
.LeftJoin((c, d) => c.material_id == d.id)
.Where((c, d) => a.member_carry_code == c.member_carry_code && c.is_all_feeding == 0 && ids.Contains(c.material_receipt_id))
.ToList((c, d) => new CarryCodeDetailOutput()
{
unit_id = d.unit_id,
// barcode = c.barcode,
// code_batch = c.code_batch,
code_batch = c.batch,
codeqty = c.num - SqlFunc.IsNull(c.feeding_num,0),
material_id = c.material_id,
material_code = d.code,
material_name = d.name
})
}).FirstAsync();
return result;
}
}
[HttpPost]
public async Task GetInfoByQrCodeForBackMaterial(Dictionary dic)
{
string qrCode = dic["qrcode"];
ISqlSugarClient db = _repository.AsSugarClient();
WmsCarryH wmsCarryH = await db.Queryable().SingleAsync(x => x.carry_code == qrCode);
if (wmsCarryH == null)
{
throw Oops.Bah($"未找到该载具{qrCode}");
}
if (wmsCarryH.carrystd_id==WmsWareHouseConst.CARRY_ZYXCSTD_ID || wmsCarryH.carrystd_id==WmsWareHouseConst.CARRY_ZYLJSTD_ID)
{
List result = await db.Queryable()
.LeftJoin((a, b) => b.id==a.carry_id)
.Where((a,b) => b.carry_code == qrCode && a.is_all_feeding == 0 )
.Select((a, b) => new FeedingDetailOutput
{
carry_id = b.id,
carry_name = b.carry_name,
children = SqlFunc.Subqueryable()
.LeftJoin((c, d) => c.material_id == d.id)
.Where((c, d) => a.carry_id == c.carry_id && c.is_all_feeding == 0 )
.ToList((c, d) => new CarryCodeDetailOutput()
{
unit_id = d.unit_id,
// barcode = c.barcode,
// code_batch = c.code_batch,
code_batch = c.batch,
codeqty = c.num - SqlFunc.IsNull(c.feeding_num,0),
material_id = c.material_id,
material_code = d.code,
material_name = d.name
})
}).ToListAsync();
if (result.Count > 1)
{
throw Oops.Bah("找到多条签收记录");
}else if (result.Count == 1)
{
return result[0];
}
}
else
{
List result = await db.Queryable()
.LeftJoin((a, b) => b.carry_code==a.member_carry_code)
.Where((a) => a.member_carry_code == qrCode && a.is_all_feeding == 0 )
.Select((a, b) => new FeedingDetailOutput
{
carry_id = b.id,
carry_name = b.carry_name,
children = SqlFunc.Subqueryable()
.LeftJoin((c, d) => c.material_id == d.id)
.Where((c, d) => a.member_carry_code == c.member_carry_code && c.is_all_feeding == 0)
.ToList((c, d) => new CarryCodeDetailOutput()
{
unit_id = d.unit_id,
// barcode = c.barcode,
// code_batch = c.code_batch,
code_batch = c.batch,
codeqty = c.num - SqlFunc.IsNull(c.feeding_num,0),
material_id = c.material_id,
material_code = d.code,
material_name = d.name
})
}).ToListAsync();
if (result.Count > 1)
{
throw Oops.Bah("找到多条签收记录");
}else if (result.Count == 1)
{
return result[0];
}
}
return null;
}
[HttpPost]
public async Task SaveData(MaterialReceiptInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
DbResult result2 = new();
PrdMaterialReceiptH? prdMaterialReceiptH = null;
List list = new();
DbResult result = await db.Ado.UseTranAsync(async () =>
{
PrdMoTask moTask = await db.Queryable().FirstAsync(x => x.id == input.mo_task_id);
List inputMaterials = await db.Queryable()
.Where(x => x.mbom_id == moTask.bom_id)
.WhereIF(!string.IsNullOrEmpty(input.mbom_process_id), x => x.mbom_process_id == input.mbom_process_id)
.Select(x => x.material_id)
.ToListAsync();
string code = await _billRullService.GetBillNumber(Tnb.BasicData.CodeTemplateConst.MATERIAL_RECEIPT_CODE);
OrganizeEntity workline = await _organizeService.GetAnyParentByWorkstationId(input.station_id, DictConst.RegionCategoryWorklineCode);
OrganizeEntity workshop = await _organizeService.GetAnyParentByWorkstationId(input.station_id, DictConst.RegionCategoryWorkshopCode);
prdMaterialReceiptH = new PrdMaterialReceiptH()
{
code = code,
station_id = input.station_id,
mo_task_id = input.mo_task_id,
process_id = input.process_id,
equip_id = input.equip_id,
workshop_id = workshop?.Id ?? "",
carry_id = input.carry_id,
workline_id = workline?.Id ?? "",
carry_code = input.carry_code,
remark = input.remark,
mbom_process_id = input.mbom_process_id,
create_id = _userManager.UserId,
create_time = DateTime.Now,
org_id = _userManager.GetUserInfo().Result.organizeId
};
if (input.details != null && input.details.Count > 0)
{
foreach (Dictionary item in input.details)
{
// if (!inputMaterials.Contains(item["material_id"]))
// {
// throw new Exception("该物料不是生产bom投入物料,不能签收");
// }
list.Add(new PrdMaterialReceiptD
{
material_receipt_id = prdMaterialReceiptH.id,
material_id = item["material_id"]?.ToString(),
num = Convert.ToDecimal(item["num"]),
batch = item["batch"]?.ToString(),
unit_id = item["unit_id"]?.ToString(),
carry_id = input.carry_id,
barcode = item["barcode"]?.ToString(),
is_all_feeding = 0,
member_carry_id = item["member_carry_id"]?.ToString(),
member_carry_code = item["member_carry_code"]?.ToString(),
feeding_num = 0,
supplier_id = item.ContainsKey("supplier_id") ? item["supplier_id"]?.ToString() : "",
instock_time = item.ContainsKey("instock_time") ? (DateTime)item["instock_time"] : DateTime.Now,
check_conclusion = item.ContainsKey("check_conclusion") ? item["check_conclusion"]?.ToString() : "",
});
}
}
else
{
throw new Exception("没有签收物料");
}
// await db.Insertable(prdMaterialReceiptH).ExecuteCommandAsync();
// await db.Insertable(list).ExecuteCommandAsync();
});
if (result.IsSuccess)
{
//签收后调用载具签收接口
// await _wmsSignForDeliveryService.MESCarrySign(new MESCarrySignInput()
// {
// org_id = _userManager.GetUserInfo().Result.organizeId,
// create_id = _userManager.UserId,
// carry_code = input.carry_code ?? "",
// });
MESCarrySignInput mesCarrySignInput = new()
{
org_id = _userManager.GetUserInfo().Result.organizeId,
create_id = _userManager.UserId,
carry_code = input.carry_code ?? "",
};
string domain = _userManager.Domain;
Dictionary header = new()
{
["Authorization"] = App.HttpContext!=null ? App.HttpContext.Request.Headers["Authorization"] : ""
};
string sendResult = HttpUtils.RequestPost(domain + WebApiConst.MES_CARRY_SIGN, JsonConvert.SerializeObject(mesCarrySignInput), header);
Log.Information(sendResult);
AuthResponse authResponse = JsonConvert.DeserializeObject(sendResult);
result2 = authResponse.code != 200
? throw Oops.Bah(authResponse.msg)
: await db.Ado.UseTranAsync(async () =>
{
_ = await db.Insertable(prdMaterialReceiptH).ExecuteCommandAsync();
_ = await db.Insertable(list).ExecuteCommandAsync();
});
}
return !result.IsSuccess
? throw Oops.Bah(result.ErrorMessage)
: !result2.IsSuccess ? throw Oops.Bah(result2.ErrorMessage) : (dynamic)"签收成功";
}
[HttpPost]
public async Task SaveDataNew(NewMaterialReceiptInput input)
{
ISqlSugarClient db = _repository.AsSugarClient();
PrdMoTask moTask = await _prdMoTaskService.GetPrdMoTaskInfoByStationId(new Dictionary(){
{"station_id",input.station_id}
});
DbResult result2 = new();
PrdMaterialReceiptH? prdMaterialReceiptH = null;
List list = new();
DbResult result = await db.Ado.UseTranAsync(async () =>
{
List inputMaterials = await db.Queryable()
.Where(x => x.mbom_id == moTask.bom_id)
.WhereIF(!string.IsNullOrEmpty(moTask.mbom_process_id), x => x.mbom_process_id == moTask.mbom_process_id)
.Select(x => x.material_id)
.ToListAsync();
string code = await _billRullService.GetBillNumber(Tnb.BasicData.CodeTemplateConst.MATERIAL_RECEIPT_CODE);
OrganizeEntity workline = await _organizeService.GetAnyParentByWorkstationId(input.station_id, DictConst.RegionCategoryWorklineCode);
OrganizeEntity workshop = await _organizeService.GetAnyParentByWorkstationId(input.station_id, DictConst.RegionCategoryWorkshopCode);
WmsCarryH carry = await db.Queryable().Where(x=>x.carry_code==input.carry_code).FirstAsync();
prdMaterialReceiptH = new PrdMaterialReceiptH()
{
code = code,
station_id = input.station_id,
mo_task_id = moTask.id,
process_id = moTask.process_id,
equip_id = moTask.eqp_id,
workshop_id = workshop?.Id ?? "",
carry_id = carry.id,
workline_id = workline?.Id ?? "",
carry_code = input.carry_code,
mbom_process_id = moTask.mbom_process_id,
create_id = _userManager.UserId,
create_time = DateTime.Now,
org_id = _userManager.GetUserInfo().Result.organizeId
};
if (input.details != null && input.details.Count > 0)
{
foreach (var item in input.details)
{
PrdMaterialReceiptD existD = await db.Queryable()
.LeftJoin((x, y) => x.material_receipt_id == y.id)
.Where((x, y) => x.carry_id == carry.id && y.mo_task_id == moTask.id && x.is_all_feeding == 0)
.Select((x,y)=>x)
.FirstAsync();
if (existD != null)
{
throw new Exception($"{moTask.mo_task_code}任务单存在未投完的签收物料,物料签收子表id{existD.id}");
}
if (!inputMaterials.Contains(item.material_id) && !input.sure)
{
throw new Exception("存在不属于生产bom的投入物料,确认签收吗");
}
list.Add(new PrdMaterialReceiptD
{
material_receipt_id = prdMaterialReceiptH.id,
material_id = item.material_id,
num = item.codeqty,
batch = item.code_batch,
unit_id = item.unit_id,
carry_id = carry.id,
barcode = item.barcode,
is_all_feeding = 0,
member_carry_id = item.member_carryid,
member_carry_code = item.member_carrycode,
feeding_num = 0,
supplier_id = item.supplier_id,
instock_time = item.instock_time,
check_conclusion = item.check_conclusion,
create_time = DateTime.Now,
});
}
}
else
{
throw new Exception("没有签收物料");
}
// await db.Insertable(prdMaterialReceiptH).ExecuteCommandAsync();
// await db.Insertable(list).ExecuteCommandAsync();
});
if (result.IsSuccess)
{
//签收后调用载具签收接口
// await _wmsSignForDeliveryService.MESCarrySign(new MESCarrySignInput()
// {
// org_id = _userManager.GetUserInfo().Result.organizeId,
// create_id = _userManager.UserId,
// carry_code = input.carry_code ?? "",
// });
MESCarrySignInput mesCarrySignInput = new()
{
org_id = _userManager.GetUserInfo().Result.organizeId,
create_id = _userManager.UserId,
carry_code = input.carry_code ?? "",
};
// string domain = _userManager.Domain;
string domain = _userManager.Domain;
Dictionary header = new()
{
// ["Authorization"] = App.HttpContext!=null ? App.HttpContext.Request.Headers["Authorization"] : ""
};
string sendResult = HttpUtils.RequestPost(domain + WebApiConst.MES_CARRY_SIGN, JsonConvert.SerializeObject(mesCarrySignInput), header);
Log.Information(sendResult);
AuthResponse authResponse = JsonConvert.DeserializeObject(sendResult);
result2 = authResponse.code != 200
? throw Oops.Bah(authResponse.msg)
: await db.Ado.UseTranAsync(async () =>
{
_ = await db.Insertable(prdMaterialReceiptH).ExecuteCommandAsync();
_ = await db.Insertable(list).ExecuteCommandAsync();
});
}
if (result.ErrorMessage == "存在不属于生产bom的投入物料,确认签收吗")
{
return "存在不属于生产bom的投入物料,确认签收吗";
}
return !result.IsSuccess
? throw Oops.Bah(result.ErrorMessage)
: !result2.IsSuccess ? throw Oops.Bah(result2.ErrorMessage) : (dynamic)"签收成功";
}
///
/// 自动签收
///
///
///
///
///
public override async Task ModifyAsync(WareHouseUpInput input)
{
Log.Information($"物料呼叫完成回更参数:{JsonConvert.SerializeObject(input)}");
try
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (string.IsNullOrEmpty(input.requireId))
{
throw Oops.Bah("来源id为空");
}
// var db = _repository.AsSugarClient();
PrdMoTask moTask = await _db.Queryable().SingleAsync(x => x.id == input.requireId);
if (moTask == null)
{
throw Oops.Bah($"未找到来源id为{input.requireId}的生产任务单");
}
OrganizeEntity workshop = await _organizeService.GetAnyParentByWorkstationId(moTask.workstation_id, DictConst.RegionCategoryWorkshopCode);
List insertHList = new List();
List insertDList = new List();
List insertFHList = new List();
List insertFDList = new List();
List clearCarryIds = new List();
List deleteCarryCodeIds = new List();
List deleteCarryDIds = new List();
string orgId = WmsWareHouseConst.AdministratorOrgId;
// string userId = moTask.worker_id;
string userId = WmsWareHouseConst.AdministratorUserId;
if (_userManager != null && !string.IsNullOrEmpty(_userManager.UserId))
{
userId = _userManager.UserId;
}
foreach(string carryId in input.carryIds)
{
clearCarryIds.Add(carryId);
WmsCarryH carry = await _db.Queryable().SingleAsync(x => x.id == carryId);
string code = await _billRullService.GetBillNumber(CodeTemplateConst.MATERIAL_RECEIPT_CODE);
PrdMaterialReceiptH prdMaterialReceiptH = new PrdMaterialReceiptH()
{
code = code,
station_id = moTask.workstation_id,
mo_task_id = moTask.id,
process_id = moTask.process_id,
equip_id = moTask.eqp_id,
workshop_id = workshop?.Id ?? "",
carry_id = carry.id,
workline_id = moTask.workline_id,
carry_code = carry.carry_code,
mbom_process_id = moTask.mbom_process_id,
create_id = userId,
create_time = DateTime.Now,
org_id = orgId
};
insertHList.Add(prdMaterialReceiptH);
string feedCode = await _billRullService.GetBillNumber(CodeTemplateConst.FEEDING_CODE);
PrdFeedingH prdFeedingH = new PrdFeedingH()
{
code = feedCode,
station_id = moTask.workstation_id,
mo_task_id = moTask.id,
process_id = moTask.process_id,
// equip_id = input.equip_id,
workshop_id = workshop?.Id,
carry_id = carry.id,
workline_id = moTask.workline_id,
carry_code = carry.carry_code,
// remark = input.remark,
mbom_process_id = moTask.mbom_process_id,
create_id = userId,
create_time = DateTime.Now,
org_id = orgId
};
insertFHList.Add(prdFeedingH);
List carryCodes = new List();
List memberCarryIds = new List();
List memberCarrys = new List();
if (carry.carrystd_id == WmsWareHouseConst.CARRY_ZYXCSTD_ID ||
carry.carrystd_id == WmsWareHouseConst.CARRY_ZYLJSTD_ID)
{
carryCodes = await _db.Queryable().Where(x=>x.carry_id==carry.id).ToListAsync();
}
else
{
//CarryQueryOutput carryQueryOutput = await _wmsCarryQueryService.MESCarryQueryResult(new MESCarryQueryResultInput(){carry_code = carry.carry_code});
memberCarryIds = await _db.Queryable().Where(x=>x.carry_id==carry.id).Select(x=>x.membercarry_id).ToListAsync();
if (memberCarryIds == null || memberCarryIds.IsEmpty())
{
throw Oops.Bah($"未找到载具编号{carry.carry_code}的子载具");
}
memberCarrys = await _db.Queryable().Where(x=>memberCarryIds.Contains(x.id)).ToListAsync();
carryCodes = await _db.Queryable().Where(x=>memberCarryIds.Contains(x.carry_id)).ToListAsync();
clearCarryIds.AddRange(memberCarryIds);
}
if (carryCodes != null && carryCodes.Count > 0)
{
Log.Information($"签收载具信息{JsonConvert.SerializeObject(carryCodes)}");
foreach (var item in carryCodes)
{
// 自动签收不校验
// PrdMaterialReceiptD existD = await db.Queryable()
// .LeftJoin((x, y) => x.material_receipt_id == y.id)
// .Where((x, y) => x.carry_id == carry.id && y.mo_task_id == moTask.id && x.is_all_feeding == 0)
// .Select((x,y)=>x)
// .FirstAsync();
// if (existD != null)
// {
// throw new Exception($"{moTask.mo_task_code}任务单存在未投完的签收物料,物料签收子表id{existD.id}");
// }
PrdMaterialReceiptD detail = new PrdMaterialReceiptD
{
material_receipt_id = prdMaterialReceiptH.id,
material_id = item.material_id,
num = item.codeqty,
batch = item.code_batch,
unit_id = item.unit_id,
carry_id = carry.id,
barcode = item.barcode,
is_all_feeding = 1,
member_carry_id = item.carry_id,
member_carry_code = memberCarrys.Find(x => x.id == item.carry_id)?.carry_code ?? "",
feeding_num = item.codeqty,
supplier_id = item.supplier_id,
instock_time = item.instock_time,
check_conclusion = item.check_conclusion + "",
create_time = DateTime.Now,
};
insertDList.Add(detail);
decimal num = item.codeqty;
insertFDList.Add(new PrdFeedingD
{
feeding_id = prdFeedingH.id,
material_receipt_detail_id = detail?.id,
material_id = item.material_id,
num = num,
batch = item.code_batch,
unit_id = item.unit_id,
carry_id = carry.id,
status = "0",
use_num = 0,
});
if (carry.carrystd_id == WmsWareHouseConst.CARRY_ZYXCSTD_ID || carry.carrystd_id == WmsWareHouseConst.CARRY_ZYLJSTD_ID)
{
}
else
{
// Result result = await _wmsCarryUnbindService.CarryCodeUnbindWithoutTran(new CarryCodeUnbindInput()
// {
// carry_id = detail.member_carry_id
// },_db);
//
//
// if (result.code != HttpStatusCode.OK)
// {
// throw Oops.Bah(result.msg);
// }
//deleteCarryCodeIds.Add(detail.member_carry_id);
// int row = await db.Deleteable().Where(r => r.carry_id == detail.member_carry_id).ExecuteCommandAsync();
// Log.Information($"载具{detail.member_carry_id}已解绑,解绑条数{row}");
}
}
if (carry.carrystd_id == WmsWareHouseConst.CARRY_ZYXCSTD_ID || carry.carrystd_id == WmsWareHouseConst.CARRY_ZYLJSTD_ID)
{
// Result result = await _wmsCarryUnbindService.CarryCodeUnbindWithoutTran(new CarryCodeUnbindInput()
// {
// carry_id = carry.id
// },_db);
//
//
// if (result.code != HttpStatusCode.OK)
// {
// throw Oops.Bah(result.msg);
// }
//deleteCarryCodeIds.Add(carry.id);
// int row = await db.Deleteable().Where(r => r.carry_id == carry.id).ExecuteCommandAsync();
// Log.Information($"载具{carry.id}已解绑,解绑条数{row}");
}
}
else
{
throw Oops.Bah($"{carry.carry_code}未找到物料明细");
}
if (carry.carrystd_id==WmsWareHouseConst.CARRY_LXSTD_ID || carry.carrystd_id==WmsWareHouseConst.CARRY_LJSTD_ID)
{
Result result2 = await _wmsCarryUnbindService.CarryUnbindWithoutTran(new CarryBindInput()
{
org = prdFeedingH.org_id,
create_id = prdFeedingH.create_id,
carry_id = prdMaterialReceiptH.carry_id,
carry_code = prdMaterialReceiptH.carry_code,
carrystd_id = carry.carrystd_id,
membercarry_code = "",
membercarry_id = "",
},_db);
if (result2.code != HttpStatusCode.OK)
{
throw Oops.Bah(result2.msg);
}
//deleteCarryDIds.Add(prdMaterialReceiptH.carry_id);
// int row = await db.Deleteable().Where(r => r.carry_id == prdMaterialReceiptH.carry_id).ExecuteCommandAsync();
// Log.Information($"载具{prdMaterialReceiptH.carry_id}已解绑,解绑条数{row}");
}
}
// Log.Information($"清空载具信息:{JsonConvert.SerializeObject(clearCarryIds)}");
// string carryStatus = ((int)EnumCarryStatus.空闲).ToString();
// string isCheck = ((int)EnumCheckConclusion.待检).ToString();
// foreach(string carryId in clearCarryIds)
// {
// await _db.Updateable()
// .SetColumns(x => x.carry_status == carryStatus)
// .SetColumns(x => x.is_check == isCheck)
// .Where(x => x.id==carryId)
// .ExecuteCommandAsync();
// Log.Information($"更新载具{carryId}状态为空闲{carryStatus},检验为{isCheck}成功");
// }
if (insertHList.Count <= 0 || insertDList.Count <= 0)
{
throw Oops.Bah(ErrorCode.COM1000);
}
// int dRow1 = await _db.Deleteable().Where(r => deleteCarryDIds.Contains(r.carry_id)).ExecuteCommandAsync();
// Log.Information($"子载具{JsonConvert.SerializeObject(deleteCarryDIds)}已解绑,解绑条数{dRow1}");
//
// int dRow2 = await _db.Deleteable().Where(r => deleteCarryCodeIds.Contains(r.carry_id)).ExecuteCommandAsync();
// Log.Information($"载具条码{JsonConvert.SerializeObject(deleteCarryDIds)}已解绑,解绑条数{dRow2}");
int row1 = await _db.Insertable(insertHList).ExecuteCommandAsync();
int row2 = await _db.Insertable(insertDList).ExecuteCommandAsync();
int row3 = await _db.Insertable(insertFHList).ExecuteCommandAsync();
int row4 = await _db.Insertable(insertFDList).ExecuteCommandAsync();
if (row1 <= 0 || row2 <= 0 || row3<=0 || row4<=0)
{
throw Oops.Bah(ErrorCode.COM1000);
}
}
catch (Exception e)
{
Logger.Error("自动签收投料失败:"+e.Message,e);
throw Oops.Bah(e.Message,e);
}
}
}
}