using System.Diagnostics.CodeAnalysis;
using JNPF.Common.Core.Manager;
using JNPF.Common.Extension;
using JNPF.Common.Filter;
using JNPF.Common.Security;
using JNPF.EventBus;
using JNPF.FriendlyException;
using JNPF.Systems.Entitys.Permission;
using JNPF.Systems.Entitys.System;
using JNPF.Systems.Interfaces.System;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SqlSugar;
using Tnb.BasicData.Entities;
using Tnb.Common.Utils;
using Tnb.ProductionMgr.Interfaces;
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.Entities.Dto.Outputs;
using Tnb.WarehouseMgr.Entities.Dto.Queries;
using Tnb.WarehouseMgr.Entities.Enums;
using Tnb.WarehouseMgr.Interfaces;
using Tnb.ProductionMgr.Entities.Entity;
using Tnb.BasicData;
using Tnb.WarehouseMgr.Entities.Entity;
using Microsoft.Extensions.Logging;
using Tnb.BasicData.Interfaces;
namespace Tnb.WarehouseMgr
{
///
/// 入库申请服务
///
[ServiceModule(BizTypeId)]
public class WmsInStockService : BaseWareHouseService, IWmsInStockService
{
private const string BizTypeId = "26191496816421";
private readonly ISqlSugarClient _db;
private readonly IDictionaryDataService _dictionaryDataService;
private readonly IUserManager _userManager;
private readonly IWareHouseService _wareHouseService;
private readonly IBillRullService _billRullService;
private readonly IPrdInstockService _prdInstockService;
private readonly IThirdApiRecordService _thirdApiRecordService;
private static Dictionary _dicBillCodes = new();
public WmsInStockService(
ISqlSugarRepository repository,
IDictionaryDataService dictionaryDataService,
IUserManager userManager,
IBillRullService billRullService,
IWareHouseService wareHouseService,
IPrdInstockService prdInstockService,
IThirdApiRecordService thirdApiRecordService,
IEventPublisher eventPublisher
)
{
_db = repository.AsSugarClient();
_dictionaryDataService = dictionaryDataService;
_userManager = userManager;
_billRullService = billRullService;
_wareHouseService = wareHouseService;
_thirdApiRecordService = thirdApiRecordService;
_prdInstockService = prdInstockService;
}
///
/// 根据入库申请单ID获取申请单明细信息
///
///
///
[HttpGet]
public async Task GetInStockDetailsListById([FromRoute] string billId)
{
Dictionary dic = await _dictionaryDataService.GetDictionaryByTypeId(WmsWareHouseConst.WMS_INSTOCK_D_BILL_STATUS_TYPEID);
List items = await _db.Queryable().LeftJoin((a, b) => a.warehouse_id == b.id)
.Select((a, b) => new WmsInstockD
{
warehouse_name = b.whname
}, true)
.Where(a => a.bill_id == billId).ToListAsync();
_db.ThenMapper(items,
it => it.line_status = dic.ContainsKey(it.line_status) ? dic[it.line_status]?.ToString()! : "");
return items;
}
///
/// 条码打印
///
///
///
{
///
BillIds:入库申请单Id列表
///
}
///
///
///
///
[HttpPost]
public async Task BarCodePrint(BarCodePrintInput input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (input.BillIds == null || input.BillIds.Count == 0)
{
throw new ArgumentException($"parameter {nameof(input.BillIds)} not be null or zero");
}
List barcodes = new();
try
{
await _db.Ado.BeginTranAsync();
if (_dicBillCodes.Count < 1)
{
_dicBillCodes = await _db.Queryable().ToDictionaryAsync(x => x.id, x => x.bill_code);
}
List inStockDetails = await _db.Queryable().Where(it => input.BillIds.Contains(it.bill_id)).ToListAsync();
if (inStockDetails?.Count > 0)
{
List wmsTempCodes = new();
for (int i = 0; i < inStockDetails.Count; i++)
{
if (inStockDetails[i] is null)
{
continue;
}
decimal? minPacking = (await _db.Queryable().FirstAsync(it => it.id == inStockDetails[i].material_id))?.minpacking;
int codeNum = 0;
if (inStockDetails[i].pr_qty.HasValue && minPacking.HasValue && minPacking.Value > 0)
{
int mod = (int)(inStockDetails[i].pr_qty!.Value % minPacking.Value);
codeNum = (int)(mod > 0 ? (inStockDetails[i].pr_qty!.Value / minPacking.Value) + 1 : inStockDetails[i].pr_qty!.Value / minPacking.Value);
if (inStockDetails[i].pr_qty!.Value > minPacking.Value)
{
for (int j = 0; j < codeNum; j++)
{
int index = j + 1;
WmsTempCode barCode = await CreateInstock(inStockDetails[i], index);
if (minPacking.HasValue)
{
barCode.codeqty = index < codeNum ? minPacking : mod > 0 ? mod : minPacking;
}
wmsTempCodes.Add(barCode);
}
}
else if (inStockDetails[i].pr_qty!.Value <= minPacking.Value)
{
WmsTempCode barCode = await CreateInstock(inStockDetails[i], i + 1);
wmsTempCodes.Add(barCode);
}
}
else if (!minPacking.HasValue)
{
WmsTempCode barCode = await CreateInstock(inStockDetails[i], i + 1);
wmsTempCodes.Add(barCode);
}
}
int row = 0;
List<(string requireId, string barcode)> multi = wmsTempCodes.Select(x => (x.require_id, x.barcode)).ToList();
var printedTempCodes = await _db.Queryable().Where(it => multi.Select(x => x.requireId).Contains(it.require_id) && multi.Select(x => x.barcode).Contains(it.barcode)).ToListAsync();
if (printedTempCodes?.Count > 0)
{
var instocks = await _db.Queryable().Where(it => it.print_status == WmsWareHouseConst.BARCODE_PRINT_STATUS_COMPLETE_ID && printedTempCodes.Select(x => x.require_id).Contains(it.id)).ToListAsync();
if (instocks?.Count > 0)
{
wmsTempCodes = wmsTempCodes.Except(printedTempCodes, new CustomEqualityComparer()).ToList();
}
if (wmsTempCodes?.Count > 0)
row = await _db.Insertable(wmsTempCodes).ExecuteCommandAsync();
wmsTempCodes = wmsTempCodes.Concat(printedTempCodes).ToList();
}
else
{
row = await _db.Insertable(wmsTempCodes).ExecuteCommandAsync();
}
_ = await _db.Updateable().SetColumns(it => new WmsInstockH { print_status = WmsWareHouseConst.BARCODE_PRINT_STATUS_COMPLETE_ID }).Where(it => input.BillIds.Contains(it.id)).ExecuteCommandAsync();
barcodes = wmsTempCodes?.Select(x => x.barcode).ToList() ?? Enumerable.Empty().ToList();
}
if (barcodes?.Count > 0)
{
base.BarCodePrint(barcodes, 1, "192.167.14.253");
}
await _db.Ado.CommitTranAsync();
}
catch (Exception)
{
await _db.Ado.RollbackTranAsync();
}
return barcodes;
}
/* ///
/// 条码打印
///
///
///
[HttpPost]
public Task BarCodePrint()
{
try
{
if (barcodes?.Count > 0)
{
base.BarCodePrint(barcodes, 1);
barcodes.Clear();
}
else
{
throw new AppFriendlyException("没有可打印的条码", 500);
}
}
catch (AppFriendlyException ex)
{
throw ex;
}
catch (Exception)
{
throw new AppFriendlyException("打印失败", 500);
}
return Task.CompletedTask;
}*/
private Task CreateInstock(WmsInstockD detail, int no)
{
string code = $"{detail.material_code}{detail.code_batch}{no.ToString().PadLeft(4, '0')}";
WmsTempCode barCode = new()
{
org_id = detail.org_id,
material_id = detail.material_id,
material_code = detail.material_code,
barcode = code,
code_batch = detail.code_batch,
material_specification = detail.material_specification,
container_no = detail.container_no,
codeqty = detail.pr_qty!.Value,
unit_id = detail.unit_id,
is_lock = 0,
is_end = 0,
require_id = detail.bill_id,
require_code = _dicBillCodes.ContainsKey(detail.bill_id) ? _dicBillCodes[detail.bill_id]?.ToString() : "",
create_id = _userManager.UserId,
create_time = DateTime.Now
};
return Task.FromResult(barCode);
}
public override async Task ModifyAsync(WareHouseUpInput input)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
//更具distaskCode的barcode 更新 instockcode 的 is_end 为 1
try
{
await _db.Ado.BeginTranAsync();
if (input.distaskCodes?.Count > 0)
{
IEnumerable barCodes = input.distaskCodes.Select(x => x.barcode);
_ = await _db.Updateable().SetColumns(it => new WmsInstockCode { is_end = 1 }).Where(it => barCodes.Contains(it.barcode)).ExecuteCommandAsync();
var instockCodes = await _db.Queryable().Where(it => barCodes.Contains(it.barcode)).Select(it => new
{
id = it.bill_d_id,
barcode_qty = it.codeqty,
}).ToListAsync();
Dictionary> dic = instockCodes.GroupBy(g => g.id).ToDictionary(x => x.Key, x => x.Select(d => d.barcode_qty).ToList());
List ids = instockCodes.Select(it => it.id).ToList();
List instockDetails = await _db.Queryable().Where(it => ids.Contains(it.id)).ToListAsync();
foreach (WmsInstockD item in instockDetails)
{
if (dic.ContainsKey(item.id))
{
item.qty += dic[item.id].Sum(x => x);
if (item.qty >= item.pr_qty)
{
item.line_status = WmsWareHouseConst.BILLSTATUS_COMPLETE_ID;
}
}
}
_ = await _db.Updateable(instockDetails).ExecuteCommandAsync();
WmsInstockH instock = await _db.Queryable().SingleAsync(it => it.id == input.requireId);
if (instock.IsNull())
{
ArgumentNullException.ThrowIfNull(nameof(instock));
}
// 采购入库
if (instock.bill_type == WmsWareHouseConst.BILLTYPE_MATERIALINSTOCK_ID)
{
WmsPurchaseD wmsPurchaseD = await _db.Queryable().SingleAsync(x => x.id == input.wmsDistaskH.source_id);
string purchaseHId = wmsPurchaseD?.bill_id ?? "";
WmsPurchaseH wmsPurchaseH = await _db.Queryable().SingleAsync(x => x.id == purchaseHId);
int row =await _db.Updateable().SetColumns(r => new WmsCarryCode
{
auxprop_gys = wmsPurchaseD.auxprop_gys,
auxprop_xph = wmsPurchaseD.auxprop_xph
}).Where(r => r.carry_id == input.wmsDistaskH.carry_id).ExecuteCommandAsync();
if (wmsPurchaseH.make_method == "自制")
{
if (instock.sync_status != WmsWareHouseConst.SYNC_STATUS_NONEEDSYNC)
{
//如果是自动单据,需要回更上层系统
Dictionary pars = new() { { nameof(WmsInstockH.source_id), instock?.source_id ?? string.Empty } };
dynamic callBackRes = await _prdInstockService.SyncInstock(pars);
instock!.sync_status = callBackRes == true ? WmsWareHouseConst.SYNC_STATUS__SYNCCOMPLETE : WmsWareHouseConst.SYNC_STATUS__SYNCFAILED;
_ = await _db.Updateable(instock).UpdateColumns(it => it.sync_status).ExecuteCommandAsync();
}
List allInstockDetails = await _db.Queryable().Where(it => it.bill_id == input.requireId).OrderBy(x=>x.id).ToListAsync();
if (allInstockDetails.All(x => x.line_status == WmsWareHouseConst.BILLSTATUS_COMPLETE_ID))
{
instock.status = WmsWareHouseConst.BILLSTATUS_COMPLETE_ID;
}
else
{
//任务没有结束,更新状态为工作中
instock.status = WmsWareHouseConst.BILLSTATUS_ON_ID;
}
_ = await _db.Updateable(instock).UpdateColumns(it => it.status).ExecuteCommandAsync();
WmsTempCode wmsTempCode = await _db.Queryable()
.LeftJoin((a, b) => a.barcode == b.barcode)
.Where((a, b) => a.carry_id == input.wmsDistaskH.carry_id)
.Select((a, b) => b)
.FirstAsync();
string purchaseDId = wmsTempCode?.require_id ?? "";
//WmsPurchaseD wmsPurchaseD = await _db.Queryable().SingleAsync(x => x.id == purchaseDId);
string wmsPurchaseOrderHId = wmsPurchaseH?.erp_bill_code ?? "";
WmsPurchaseOrderH wmsPurchaseOrderH = await _db.Queryable().SingleAsync(x => x.id == wmsPurchaseOrderHId);
WmsPurchaseOrderD wmsPurchaseOrderDs = await _db.Queryable().FirstAsync(x => x.fk_wms_purchase_order_id == wmsPurchaseOrderHId);
BasWarehouse basWarehouse = await _db.Queryable().SingleAsync(x => x.id == instock.warehouse_id);
List materialIds = allInstockDetails.Select(x => x.material_id).Distinct().ToList();
List unitCodes = allInstockDetails.Select(x => x.unit_id).Distinct().ToList();
List unitDatas = await _db.Queryable()
.LeftJoin((x, y) => x.Id == y.DictionaryTypeId)
.Where((x, y) => x.EnCode == DictConst.MeasurementUnit && unitCodes.Contains(y.EnCode))
.Select((x, y) => y)
.ToListAsync();
List erpWarehouserelaHs = await _db.Queryable().Where(x => x.id != null).ToListAsync();
DictionaryDataEntity tranType = await _db.Queryable().Where(x => x.DictionaryTypeId == "25043925951909" && x.EnCode == wmsPurchaseH.transaction_type).FirstAsync();
string tranTypeId = tranType?.Id ?? "";
string supplierId = wmsPurchaseOrderH?.supplier_id ?? "";
List tableIds = new List();
tableIds.Add(_userManager.UserId);
tableIds.Add(WmsWareHouseConst.AdministratorOrgId);
tableIds.Add(instock.warehouse_id);
tableIds.AddRange(materialIds);
tableIds.Add(supplierId);
tableIds.Add(tranTypeId);
tableIds.AddRange(unitDatas.Select(x => x.Id).ToList());
List erpExtendFields = await _db.Queryable().Where(x => tableIds.Contains(x.table_id)).ToListAsync();
// string erpCreateId = erpExtendFields.Find(x => x.table_id == instock.create_id)?.user_id ?? "";
string erpCreateId = WmsWareHouseConst.ERPUSERID;
ErpExtendField erpOrg = erpExtendFields.Find(x => x.table_id == (WmsWareHouseConst.AdministratorOrgId));
string nowStr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
List> requestData = new List>();
Dictionary erpRequestData = new Dictionary();
erpRequestData.Add("approver", erpCreateId);
erpRequestData.Add("billmaker", erpCreateId);
erpRequestData.Add("cbiztype", wmsPurchaseH?.transaction_type ?? "");
erpRequestData.Add("bitinbill", false);
erpRequestData.Add("cgeneralhid", null);
erpRequestData.Add("corpoid", erpOrg.corpoid);
erpRequestData.Add("corpvid", erpOrg.corpvid);
erpRequestData.Add("creationtime", nowStr);
erpRequestData.Add("creator", erpCreateId);
erpRequestData.Add("ctrantypeid", erpExtendFields.Find(x => x.table_id == tranTypeId)?.transaction_type_id ?? "");
erpRequestData.Add("cvendorid", erpExtendFields.Find(x => x.table_id == supplierId)?.supplier_id ?? "");
erpRequestData.Add("cvendorvid", erpExtendFields.Find(x => x.table_id == supplierId)?.supplier_vid ?? "");
// erpRequestData.Add("cwarehouseid", erpExtendFields.Find(x => x.table_id == instock.warehouse_id)?.cotherwhid ?? "");//类型视图里取
// erpRequestData.Add("cwarehouseid", erpWarehouserelaHs.Find(x => x.erp_warehousecode == wmsPurchaseD.erp_wh_type)?.erp_warehouseid ?? "");//类型视图里取
// erpRequestData.Add("cwarehouseid", "1001A11000000002OOGU");//类型视图里取
erpRequestData.Add("cwarehouseid", wmsPurchaseD?.erp_wh_type ?? "1001A11000000002OOGU");
erpRequestData.Add("dbilldate", nowStr);
erpRequestData.Add("dmakedate", nowStr);
erpRequestData.Add("fbillflag", 2);
erpRequestData.Add("fbuysellflag", 2);
erpRequestData.Add("ntotalnum", allInstockDetails.Sum(x => x.qty));
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("vbillcode", instock.bill_code);
erpRequestData.Add("vtrantypecode", tranType?.EnCode ?? "");
erpRequestData.Add("csourcebillhid", wmsPurchaseH?.erp_arriveorder_pk ?? "");
erpRequestData.Add("vdef3", wmsPurchaseH?.service_num ?? "");
List> erpRequestDataDetails = new List>();
foreach (WmsInstockD item in allInstockDetails)
{
erpRequestDataDetails.Add(new Dictionary()
{
["castunitid"] = erpExtendFields.Find(x => x.table_id == (unitDatas.Find(x => x.EnCode == item.unit_id)?.Id ?? ""))?.cunitid ?? "",
["cbodytranstypecode"] = erpExtendFields.Find(x => x.table_id == tranTypeId)?.transaction_type_id ?? "",
// ["cbodywarehouseid"] = erpExtendFields.Find(x => x.table_id == instock.warehouse_id)?.cotherwhid ?? "",
// ["cbodywarehouseid"] = "1001A11000000002OOGU",
["cbodywarehouseid"] = wmsPurchaseD?.erp_wh_type ?? "1001A11000000002OOGU",
["cgeneralbid"] = null,
["cgeneralhid"] = null,
["cmaterialoid"] = erpExtendFields.Find(x => x.table_id == item.material_id)?.cmaterialoid ?? "",
["cmaterialvid"] = erpExtendFields.Find(x => x.table_id == item.material_id)?.cmaterialvid ?? "",
["corpoid"] = erpOrg.corpoid,
["corpvid"] = erpOrg.corpvid,
["crowno"] = (allInstockDetails.FindIndex(x => x.id == item.id) + 1) * 10,
["cunitid"] = erpExtendFields.Find(x => x.table_id == (unitDatas.Find(x => x.EnCode == item.unit_id)?.Id ?? ""))?.cunitid ?? "",
["cvendorid"] = erpExtendFields.Find(x => x.table_id == supplierId)?.supplier_id ?? "",
["cvendorvid"] = erpExtendFields.Find(x => x.table_id == supplierId)?.supplier_vid ?? "",
["dbizdate"] = instock.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
["nnum"] = item.qty,
["nshouldnum"] = item.pr_qty,
// ["pk_creqwareid"] = erpExtendFields.Find(x => x.table_id == instock.warehouse_id)?.cotherwhid ?? "",
// ["pk_creqwareid"] = erpWarehouserelaHs.Find(x => x.erp_warehousecode == basWarehouse.whcode)?.erp_warehouseid ?? "",
// ["pk_creqwareid"] = "1001A11000000002OOGU",
["pk_creqwareid"] = wmsPurchaseD?.erp_wh_type ?? "1001A11000000002OOGU",
["pk_group"] = erpOrg.pk_group,
["pk_org"] = erpOrg.pk_org,
["pk_org_v"] = erpOrg.pk_org_v,
["pseudocolumn"] = (allInstockDetails.FindIndex(x => x.id == item.id) + 1) * 10,
["vbatchcode"] = item.code_batch,
["csourcebillhid"] = wmsPurchaseH?.erp_arriveorder_pk ?? "",
["csourcebillbid"] = wmsPurchaseD?.erp_arriveorder_b_pk ?? "",
["vsourcebillcode"] = wmsPurchaseH?.bill_code ?? "",
["lineno"] = wmsPurchaseOrderDs?.lineno ?? "",
["vfree1"] = erpExtendFields.Find(x => x.table_id == supplierId)?.supplier_id ?? "",
["bpresent"] = wmsPurchaseD.gift == 1,
["ntaxprice"] = wmsPurchaseD.price,
});
}
erpRequestData.Add("dtls", erpRequestDataDetails);
requestData.Add(erpRequestData);
BasFactoryConfig config = await _db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.BIPURL);
ThirdWebapiRecord thirdWebapiRecord = new ThirdWebapiRecord();
thirdWebapiRecord.id = SnowflakeIdHelper.NextId();
thirdWebapiRecord.third_name = WmsWareHouseConst.BIP;
thirdWebapiRecord.name = "采购入库";
thirdWebapiRecord.method = "POST";
// thirdWebapiRecord.url = config.value + "uapws/rest/purchaseIn/save";
thirdWebapiRecord.url = WmsWareHouseConst.BIP_DOMAIN + "uapws/rest/purchaseIn/save";
thirdWebapiRecord.request_data = JsonConvert.SerializeObject(requestData);
thirdWebapiRecord.create_time = DateTime.Now;
thirdWebapiRecord.remark = "【WmsInStockService ModifyAsync】采购收货单号:" + (wmsPurchaseH?.bill_code ?? "") + ",erp采购订单号:" + (wmsPurchaseOrderH?.erp_bill_code ?? "");
await _db.Insertable(thirdWebapiRecord).ExecuteCommandAsync();
BasFactoryConfig callErp = await _db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.CALLERP);
if (callErp.value == "1")
{
await _thirdApiRecordService.Send(new List { thirdWebapiRecord }, "自动", _db);
}
}
}
// 委外入库
else if (instock.bill_type == WmsWareHouseConst.BILLTYPE_OUTSOURCEINSTOCK_ID)
{
WmsOutsourceD wmsOutsourceD = await _db.Queryable().SingleAsync(x => x.id == input.wmsDistaskH.source_id);
//string wmsOutsourceDId = wmsOutsourceD?.fk_wms_outsource_order_id ?? "";
//WmsOutsourceH wWmsOutsourceH = await _db.Queryable().SingleAsync(x => x.id == wmsOutsourceDId);
int row = await _db.Updateable().SetColumns(r => new WmsCarryCode
{
auxprop_gys = wmsOutsourceD.auxprop_gys,
auxprop_xph = wmsOutsourceD.auxprop_xph
}).Where(r => r.carry_id == input.wmsDistaskH.carry_id).ExecuteCommandAsync();
}
// 调拨入库
else if (instock.bill_type == WmsWareHouseConst.BILLTYPE_RAWMATTRANSFERINSTOCK_ID)
{
WmsRawmatTransferinstockD wmsRawmatTransferinstockD = await _db.Queryable().SingleAsync(x => x.id == input.wmsDistaskH.source_id);
await _db.Updateable().SetColumns(r => new WmsCarryCode
{
auxprop_gys = wmsRawmatTransferinstockD.auxprop_gys,
auxprop_xph = wmsRawmatTransferinstockD.auxprop_xph
}).Where(r => r.carry_id == input.wmsDistaskH.carry_id).ExecuteCommandAsync();
// List allInstockDetails = await _db.Queryable().Where(it => it.bill_id == input.requireId).ToListAsync();
//
// WmsTempCode wmsTempCode = await _db.Queryable()
// .LeftJoin((a, b) => a.barcode == b.barcode)
// .Where((a, b) => a.carry_id == input.wmsDistaskH.carry_id)
// .Select((a, b) => b)
// .FirstAsync();
//
// string rawmatTransferinstockDId = wmsTempCode?.require_id ?? "";
// WmsRawmatTransferinstockD wmsRawmatTransferinstockD = await _db.Queryable().SingleAsync(x => x.id == rawmatTransferinstockDId);
// string rawmatTransferinstockHId = wmsRawmatTransferinstockD?.bill_id ?? "";
// WmsRawmatTransferinstockH wmsRawmatTransferinstockH = await _db.Queryable().SingleAsync(x => x.id == rawmatTransferinstockHId);
//
// List materialIds = allInstockDetails.Select(x => x.material_id).Distinct().ToList();
// List unitCodes = allInstockDetails.Select(x => x.unit_id).Distinct().ToList();
// List unitDatas = await _db.Queryable()
// .LeftJoin((x, y) => x.Id == y.DictionaryTypeId)
// .Where((x, y) => x.EnCode == DictConst.MeasurementUnit && unitCodes.Contains(y.EnCode))
// .Select((x, y) => y)
// .ToListAsync();
// List erpWarehouserelaHs = await _db.Queryable().Where(x=>x.id!=null).ToListAsync();
// BasWarehouse basWarehouse = await _db.Queryable().SingleAsync(x=>x.id==instock.warehouse_id);
//
// string supplierId = WmsWareHouseConst.TIANYIGONGYINGSHANG_ID;
// List tableIds = new List();
// tableIds.Add(_userManager.UserId);
// tableIds.Add(WmsWareHouseConst.AdministratorOrgId);
// tableIds.Add(instock.warehouse_id);
// tableIds.AddRange(materialIds);
// tableIds.Add(supplierId);
// tableIds.AddRange(unitDatas.Select(x => x.Id).ToList());
//
// List erpExtendFields = await _db.Queryable().Where(x => tableIds.Contains(x.table_id)).ToListAsync();
// string userAccount = wmsRawmatTransferinstockH?.biller ?? "";
// string deptCode = wmsRawmatTransferinstockH?.dept_code ?? "";
// UserEntity userEntity = await _db.Queryable().Where(x=>x.Account==userAccount).FirstAsync();
// string userId = userEntity?.Id ?? "";
// string erpCreateId = erpExtendFields.Find(x => x.table_id == 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> requestData = new List>();
// Dictionary erpRequestData = new Dictionary();
// erpRequestData.Add("billmaker", erpCreateId);
// erpRequestData.Add("cbiztype", "");
// erpRequestData.Add("cdptid","1001A1100000001JFOPQ");//部门先写死
// erpRequestData.Add("cdptvid","0001A1100000000AOMIQ");//部门先写死
// erpRequestData.Add("corpoid", erpOrg.corpoid);
// erpRequestData.Add("corpvid", erpOrg.corpvid);
// erpRequestData.Add("creationtime", nowStr);
// erpRequestData.Add("creator", erpCreateId);
// // erpRequestData.Add("cwarehouseid", erpExtendFields.Find(x => x.table_id == instock.warehouse_id)?.cotherwhid ?? "");//类型视图里取
// erpRequestData.Add("cwarehouseid", erpWarehouserelaHs.Find(x => x.erp_warehousecode == basWarehouse.whcode)?.erp_warehouseid ?? "");//类型视图里取
// erpRequestData.Add("dbilldate", nowStr);
// erpRequestData.Add("dmakedate", nowStr);
// erpRequestData.Add("fbillflag", 1);
// erpRequestData.Add("ntotalnum", allInstockDetails.Sum(x => x.qty));
// 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("vdef1", null);
// erpRequestData.Add("vbillcode", instock.bill_code);
// erpRequestData.Add("ctrantypeid", "0001H11000000000D31E");//先写死
// erpRequestData.Add("vtrantypecode", "4E-01");//先写死
// erpRequestData.Add("csourcebillhid", wmsRawmatTransferinstockH?.erp_pk ?? "");
//
//
// List> erpRequestDataDetails = new List>();
// foreach (WmsInstockD item in allInstockDetails)
// {
// erpRequestDataDetails.Add(new Dictionary()
// {
// ["cbodytranstypecode"] = "4E-01",
// // ["cbodywarehouseid"] = erpExtendFields.Find(x => x.table_id == instock.warehouse_id)?.cotherwhid ?? "",
// ["cbodywarehouseid"] = erpWarehouserelaHs.Find(x => x.erp_warehousecode == basWarehouse.whcode)?.erp_warehouseid ?? "",
// ["cmaterialoid"] = erpExtendFields.Find(x => x.table_id == item.material_id)?.cmaterialoid ?? "",
// ["cmaterialvid"] = erpExtendFields.Find(x => x.table_id == item.material_id)?.cmaterialvid ?? "",
// ["corpoid"] = erpOrg.corpoid,
// ["corpvid"] = erpOrg.corpvid,
// ["crowno"] = (allInstockDetails.FindIndex(x => x.id == item.id) + 1) * 10,
// ["csourcebillhid"] = wmsRawmatTransferinstockH?.erp_pk ?? "",
// ["csourcebillbid"] = wmsRawmatTransferinstockD?.erp_line_pk ?? "",
// ["cunitid"] = erpExtendFields.Find(x => x.table_id == (unitDatas.Find(x => x.EnCode == item.unit_id)?.Id ?? ""))?.cunitid ?? "",
// ["cvendorid"] = erpExtendFields.Find(x => x.table_id == supplierId)?.supplier_id ?? "",
// ["cvendorvid"] = erpExtendFields.Find(x => x.table_id == supplierId)?.supplier_vid ?? "",
// ["dbizdate"] = instock.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
// ["dplanarrivedate"] = instock.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
// ["dplanoutdate"] = instock.create_time.ToString("yyyy-MM-dd HH:mm:ss"),
// ["nnum"] = item.qty,
// ["nshouldnum"] = item.pr_qty,
// ["pk_group"] = erpOrg.pk_group,
// ["pk_org"] = erpOrg.pk_org,
// ["pk_org_v"] = erpOrg.pk_org_v,
// ["vbatchcode"] = item.code_batch,
// });
// }
// erpRequestData.Add("dtls", erpRequestDataDetails);
// requestData.Add(erpRequestData);
// BasFactoryConfig config = await _db.Queryable().FirstAsync(x => x.enabled == 1 && x.key == FactoryConfigConst.BIPURL);
// ThirdWebapiRecord thirdWebapiRecord = new ThirdWebapiRecord();
// thirdWebapiRecord.id = SnowflakeIdHelper.NextId();
// thirdWebapiRecord.third_name = WmsWareHouseConst.BIP;
// thirdWebapiRecord.name = "调拨入库";
// thirdWebapiRecord.method = "POST";
// thirdWebapiRecord.url = config.value + "uapws/rest/transIn/save";
// // thirdWebapiRecord.url = WmsWareHouseConst.BIP_DOMAIN + "uapws/rest/transIn/save";
// thirdWebapiRecord.request_data = JsonConvert.SerializeObject(requestData);
// thirdWebapiRecord.create_time = DateTime.Now;
// await _db.Insertable(thirdWebapiRecord).ExecuteCommandAsync();
}
}
await _db.Ado.CommitTranAsync();
}
catch (Exception ex)
{
Logger.LogWarning($"【WmsInStockService Modify】 {ex.Message}");
Logger.LogWarning($"【WmsInStockService Modify】 {ex.StackTrace}");
await _db.Ado.RollbackTranAsync();
throw;
}
}
///
/// 入库申请-MES对接功能
/// MES系统下发时,需要有对应的入库申请数据,和载具信息,起始库位ID,入库仓库
///
///
///
[HttpPost]
[AllowAnonymous]
public async Task MESCreateInstock(MESCreateInstockInput input)
{
bool isSuccessFul = false;
try
{
await _db.Ado.BeginTranAsync();
//入库申请主表
WmsInstockH instock = input.instock.Adapt();
//入库申请物料明细表
List instockds = input.instockds.Adapt>();
//入库申请条码明细表
List instockcodes = input.instockcodes.Adapt>();
//入库取终点 //出库起点
InStockStrategyQuery inStockStrategyInput = new() { warehouse_id = instock?.warehouse_id!, Size = 1 };
List endLocations = await _wareHouseService.InStockStrategy(inStockStrategyInput);
WmsPointH sPoint = await _db.Queryable().FirstAsync(it => it.location_code == input.instock.location_code);
WmsPointH ePoint = await _db.Queryable().FirstAsync(it => it.location_id == endLocations[0].id);
WmsCarryH carry = await _db.Queryable().SingleAsync(it => it.carry_code == input.instock.carry_code);
BasLocation loc = await _db.Queryable().FirstAsync(it => it.id == endLocations[0].id);
bool isMatch = await IsCarryAndLocationMatchByCarryStd(carry, loc);
if (!isMatch)
{
throw new AppFriendlyException("库位与载具规格不匹配", 500);
}
loc = await _db.Queryable().FirstAsync(it => it.location_code == input.instock.location_code && it.is_type != EnumLocationType.存储库位.ToString());
//如果数据不全或有误,
if (carry.IsNull() || loc.IsNull() || instockds?.Count < 1 || instockcodes?.Count < 1)
{
//报错, 提示数据不全或有误。
throw new AppFriendlyException("数据不全或有误!", 500);
}
// 生成入库申请数据,添加其他数据 主表
instock.id = SnowflakeIdHelper.NextId();
instock.carry_id = carry.id;
instock.location_id = loc.id;
instock.biz_type = WmsWareHouseConst.BIZTYPE_WMSINSTOCK_ID;
instock.bill_code = _billRullService.GetBillNumber(WmsWareHouseConst.WMS_INSTOCK_ENCODE).GetAwaiter().GetResult();
instock.generate_type = "0";// 人工
instock.sync_status = WmsWareHouseConst.SYNC_STATUS_NONEEDSYNC;//无需同步
instock.print_status = WmsWareHouseConst.PRINT_STATUS_PRINTCOMPLETE;//已打印
instock.status = WmsWareHouseConst.BILLSTATUS_ADD_ID;// 新增
instock.create_time = DateTime.Now;
_ = await _db.Insertable(instock).ExecuteCommandAsync();
//明细表
foreach (WmsInstockD instockd in instockds!)
{
instockd.id = SnowflakeIdHelper.NextId();
instockd.bill_id = instock.id;
instockd.line_status = WmsWareHouseConst.BILLSTATUS_ADD_ID;
instockd.qty = 0;
instock.create_time = instock.create_time;
instock.create_id = instock.create_id;
}
_ = await _db.Insertable(instockds).ExecuteCommandAsync();
List items = instockds.Adapt>();
List instockCOdes = new();
//条码表
foreach (WmsInstockCode instockcode in instockcodes!)
{
instockcode.id = SnowflakeIdHelper.NextId();
string materialCode = instockcode.material_code;
string? codeBatch = instockcode.code_batch;
string? materialSpecification = instockcode.material_specification;
string? containerNo = instockcode.container_no;
WmsInstockCode? b = items.Find(x => x.material_code == materialCode && x.code_batch == codeBatch && x.material_specification == materialSpecification && x.container_no == containerNo);
if (b != null)
{
WmsInstockCode c = DeepCopyHelper.DeepCopy(b);
c.id = SnowflakeIdHelper.NextId();
c.bill_d_id = instockds?.Find(x => x.material_code == materialCode && x.code_batch == codeBatch && x.material_specification == materialSpecification && x.container_no == containerNo)?.id ?? "";
c.barcode = instockcode.barcode;
c.codeqty = instockcode.codeqty;
c.is_end = 0;// 未结束
c.create_time = instock.create_time;
c.create_id = instock.create_id;
instockCOdes.Add(c);
}
}
string orgId = _userManager.User?.OrganizeId ?? input.instock.org_id;
_ = await _db.Insertable(instockCOdes).CallEntityMethod(it => it.Create(orgId)).ExecuteCommandAsync();
//生成预任务申请
if (sPoint != null && ePoint != null)
{
List points = await _wareHouseService.PathAlgorithms(sPoint.id, ePoint.id);
//根据获取的路径点生成预任务,生成顺序必须预路径算法返回的起终点的顺序一致(预任务顺序)
if (points?.Count > 0)
{
if (points.Count <= 2)
{
throw new AppFriendlyException($"sPoint {sPoint.point_code} ePoint{ePoint.point_code}该路径不存在", 500);
}
List preTasks = points.Where(it => !it.location_id.IsNullOrEmpty()).GroupBy(g => g.area_code).Select(it =>
{
WmsPointH? sPoint = it.FirstOrDefault();
WmsPointH? ePoint = it.LastOrDefault();
WmsPretaskH preTask = new()
{
org_id = orgId,
startlocation_id = sPoint?.location_id ?? string.Empty,
startlocation_code = sPoint?.location_code ?? string.Empty,
endlocation_id = ePoint?.location_id ?? string.Empty,
endlocation_code = ePoint?.location_code ?? string.Empty,
start_floor = sPoint?.floor.ToString(),
end_floor = ePoint?.floor.ToString(),
bill_code = _billRullService.GetBillNumber(WmsWareHouseConst.WMS_PRETASK_H_ENCODE).GetAwaiter().GetResult(),
status = WmsWareHouseConst.PRETASK_BILL_STATUS_DXF_ID,
biz_type = instock?.biz_type ?? string.Empty,
task_type = WmsWareHouseConst.WMS_PRETASK_INSTOCK_TYPE_ID,
carry_id = instock?.carry_id ?? string.Empty,
carry_code = instock?.carry_code ?? string.Empty,
area_id = sPoint?.area_id ?? string.Empty,
area_code = it.Key,
require_id = instock?.id ?? string.Empty,
require_code = instock?.bill_code ?? string.Empty,
create_id = instock.create_id,
create_time = DateTime.Now
};
return preTask;
}).ToList();
//生成预任务条码信息
List pretaskCodes = new();
foreach (WmsPretaskH? pt in preTasks)
{
if (instockCOdes.Count > 0)
{
foreach (WmsInstockCode jo in instockCOdes)
{
WmsPretaskCode ptc = pt.Adapt();
ptc.id = SnowflakeIdHelper.NextId();
ptc.bill_id = pt.id;
ptc.material_id = jo.material_id;
ptc.material_code = jo.material_code;
ptc.barcode = jo.barcode;
ptc.codeqty = jo.codeqty;
ptc.unit_id = jo.unit_id!;
ptc.code_batch = jo.code_batch;
ptc.material_specification = jo.material_specification;
ptc.container_no = jo.container_no;
pretaskCodes.Add(ptc);
}
}
}
//生成预任务,同时如果包含条码信息同时插入条码记录
bool isOk = await _wareHouseService.GenPreTask(preTasks, pretaskCodes);
if (isOk)
{
GenPreTaskUpInput preTaskUpInput = new()
{
RquireId = instock?.id,
CarryId = instock?.carry_id!,
CarryStartLocationId = points.FirstOrDefault()?.location_id,
CarryStartLocationCode = points.FirstOrDefault()?.location_code,
LocationIds = (points?.Select(x => x.location_id)?.ToList() ?? Enumerable.Empty().ToList()) as List
};
//创建预任务操作记录
string operBillId = string.Empty;
if (instock != null)
{
WmsHandleH handleH = instock.Adapt();
operBillId = handleH.id = SnowflakeIdHelper.NextId();
handleH.startlocation_id = instock.location_id!;
handleH.carry_id = instock.carry_id!;
handleH.carry_code = instock.carry_code!;
preTaskUpInput.PreTaskRecord = handleH;
}
//创建预任务条码操作记录
if (instockcodes?.Count > 0)
{
foreach (WmsInstockCode jo in instockcodes)
{
WmsHandleCode handleCode = jo.Adapt();
handleCode.id = SnowflakeIdHelper.NextId();
handleCode.org_id = orgId;
handleCode.bill_id = operBillId;
handleCode.create_id = instock.create_id;
handleCode.create_time = DateTime.Now;
preTaskUpInput.PreTaskHandleCodes.Add(handleCode);
}
}
//生成载具条码记录
List carryCodes = preTaskUpInput.PreTaskHandleCodes.Adapt>();
carryCodes.ForEach(x =>
{
x.id = SnowflakeIdHelper.NextId();
x.is_out = 0;
x.carry_id = instock!.carry_id!;
x.warehouse_id = instock!.warehouse_id!;
});
_ = await _db.Insertable(carryCodes).ExecuteCommandAsync();
await _wareHouseService.GenInStockTaskHandleAfter(preTaskUpInput,
it => new WmsCarryH { carry_code = instock!.carry_code!, is_lock = 1, carry_status = ((int)EnumCarryStatus.占用).ToString(), location_id = preTaskUpInput.CarryStartLocationId, location_code = preTaskUpInput.CarryStartLocationCode },
it => new BasLocation { is_lock = 1 });
if (instockCOdes?.Count > 0)
{
_ = await _db.Updateable().SetColumns(it => new WmsInstockD { line_status = WmsWareHouseConst.BILLSTATUS_ON_ID }).Where(it => instockCOdes.Select(x => x.bill_d_id).Contains(it.id)).ExecuteCommandAsync();
_ = await _db.Updateable().SetColumns(it => new WmsInstockH { status = WmsWareHouseConst.BILLSTATUS_ON_ID }).Where(it => it.id == instock!.id).ExecuteCommandAsync();
}
isSuccessFul = true;
}
}
}
await _db.Ado.CommitTranAsync();
}
catch (Exception ex)
{
isSuccessFul = false;
JNPF.Logging.Log.Error(ex.Message);
await _db.Ado.RollbackTranAsync();
//return await ToApiResult(JNPF.Common.Enums.HttpStatusCode.InternalServerError, ex.Message);
}
finally
{
await InvokeGenPretaskExcute();
}
return isSuccessFul;
}
///
/// 物料标签查询
///
///
///
[HttpPost]
[AllowAnonymous]
public async Task MesFetchInOutStockInfoByBarCode(MaterialLabelQuery input)
{
if (input.IsNull())
{
_ = new ArgumentException(nameof(input));
}
if (input.barcode?.Count < 1)
{
_ = new ArgumentException(nameof(input.barcode));
}
SqlSugarPagedList pagedList = await _db.Queryable().InnerJoin((a, b) => a.id == b.bill_id)
.LeftJoin((a, b, c) => b.barcode == c.barcode)
.WhereIF(!string.IsNullOrEmpty(input.org_id), (a, b, c) => a.org_id == input.org_id)
.Where((a, b, c) => input.barcode.Contains(b.barcode))
.Select((a, b, c) => new MaterailLabelOutput
{
barcode_qty = b.codeqty,
in_bill_code = a.bill_code,
instock_time = a.create_time,
out_bill_code = SqlFunc.Subqueryable().Where(it => it.id == c.bill_id).Select(it => it.bill_code),
outstock_time = SqlFunc.Subqueryable().Where(it => it.id == c.bill_id).Select(it => it.create_time),
}, true)
.ToPagedListAsync(input.currentPage, input.pageSize);
return PageResult.SqlSugarPageResult(pagedList);
}
}
public class CustomEqualityComparer : EqualityComparer
{
public override bool Equals(WmsTempCode? x, WmsTempCode? y)
{
// 判断两个对象是否相等的逻辑
return x?.barcode == y?.barcode && x?.require_id == y?.require_id;
}
public override int GetHashCode([DisallowNull] WmsTempCode obj)
{
// 使用多个属性来计算哈希码
int hashCode = obj.barcode?.GetHashCode() ?? 0;
hashCode = (hashCode * 397) ^ obj.require_id.GetHashCode();
return hashCode;
}
}
}