using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HHWMS.Web.Models;
using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
namespace HHWMS.Web.Support
{
/// 按钮拉取和ERP推送共用的发货通知单保存入口。
public class DispatchImportService
{
private readonly WTMContext _context;
private readonly IUnitWork _unitwork;
public DispatchImportService(WTMContext context, IUnitWork unitwork)
{
_context = context;
_unitwork = unitwork;
}
public async Task ImportAsync(List items, string operatorCode)
{
Validate(items);
using (var transaction = _context.DC.BeginTransaction())
{
try
{
// 按成品库区编码C加锁,使拉取和推送串行保存,不依赖库区ID。
// cp是ERP仓库标识,不是WMS的LocationZone.ZoneCode(现场为C)。
var zone = _context.DC.Set()
.FromSqlRaw("SELECT * FROM `LocationZone` WHERE `ZoneCode` = {0} FOR UPDATE", "C")
.AsNoTracking().FirstOrDefault();
if (zone == null)
throw new InvalidOperationException("当前数据库未配置成品库区编码C,不能导入发货通知单");
ProcessDispatchItems(items, operatorCode, zone.ZoneCode);
await transaction.CommitAsync();
return items.Count;
}
catch
{
await transaction.RollbackAsync();
throw;
}
}
}
public static void Validate(List items)
{
if (items == null || items.Count == 0)
throw new InvalidOperationException("data不能为空");
foreach (var item in items)
{
if (item == null)
throw new InvalidOperationException("data不能包含null明细");
if (item.ErpCode != "003")
throw new InvalidOperationException("仅支持ErpCode=003的成品发货通知单");
if (item.BReturnFlag)
throw new InvalidOperationException("不支持退货通知单,bReturnFlag必须为false");
if (string.IsNullOrWhiteSpace(item.DLCode) || item.DLCode != item.DLCode.Trim()
|| item.DLCode.Length > 50 || item.DLsID <= 0)
throw new InvalidOperationException("DLCode必须为不超过50字符且无首尾空格的单号,DLsID必须大于0");
if (string.IsNullOrWhiteSpace(item.InvCode) || item.InvCode.Length > 50
|| (item.InvName?.Length ?? 0) > 50 || (item.InvDefine1?.Length ?? 0) > 50
|| (item.CusCode?.Length ?? 0) > 50)
throw new InvalidOperationException($"DLsID {item.DLsID} 物料编码不能为空,物料/客户编码、名称、类型不能超过50字符");
if (item.DeliveryQty <= 0 || item.DeliveryQty > 99999999.9999m
|| decimal.Round(item.DeliveryQty, 4) != item.DeliveryQty)
throw new InvalidOperationException($"DLsID {item.DLsID} DeliveryQty必须大于0且符合decimal(12,4)");
}
if (items.GroupBy(x => x.DLsID).Any(x => x.Count() > 1))
throw new InvalidOperationException("同一请求中DLsID不能重复");
foreach (var group in items.GroupBy(x => x.DLCode))
{
if (group.Select(x => new { x.CusCode, x.CusName }).Distinct().Count() != 1)
throw new InvalidOperationException($"通知单 {group.Key} 的客户信息不一致");
if (group.Sum(x => x.DeliveryQty) > 99999999.9999m)
throw new InvalidOperationException($"通知单 {group.Key} 总数量超出decimal(12,4)范围");
}
}
private void SaveUpdate(T entity) where T : class
{
// UnitWork.Update会用登录用户覆盖UpdateBy;ERP调用没有登录用户,保留入口设置的审计人。
_context.DC.Set().Update(entity);
_context.DC.SaveChanges();
}
private void ProcessDispatchItems(List items, string operatorCode, string zoneCode)
{
var now = DateTime.Now;
foreach (var group in items.GroupBy(x => x.DLCode).OrderBy(x => x.Key))
{
if (_unitwork.IsExit(x => x.SourceCode == group.Key))
throw new InvalidOperationException($"通知单 {group.Key} 已归档,不能重复导入");
var header = _unitwork.FindSingle(x => x.SourceCode == group.Key);
if (header == null)
{
header = new ShipmentHeader
{
SourceCode = group.Key,
Code = _unitwork.GetSerialNumber("SO"),
BillType = "sout",
CompanyCode = group.First().CusCode,
SupplierCode = group.First().CusCode,
TotalQty = group.Sum(x => x.DeliveryQty),
TotalLines = group.Select(x => x.DLsID).Distinct().Count(),
FirstStatus = ShipStatusEnum.新建,
LastStatus = ShipStatusEnum.新建,
Remark = group.First().CusName,
UpdateVersion = 1,
CreateBy = operatorCode,
CreateTime = now
};
_unitwork.Add(header);
}
else
{
if (!_unitwork.IsExit(x => x.HeaderId == header.ID && x.DLsID.HasValue))
throw new InvalidOperationException($"通知单 {group.Key} 与非ERP出库单号冲突");
header.CompanyCode = group.First().CusCode;
header.SupplierCode = group.First().CusCode;
header.Remark = group.First().CusName;
header.UpdateVersion++;
header.UpdateBy = operatorCode;
header.UpdateTime = now;
SaveUpdate(header);
}
foreach (var item in group.OrderBy(x => x.DLsID))
{
var detail = _context.DC.Set()
.FromSqlRaw("SELECT * FROM `ShipmentDetail` WHERE `DLsID` = {0} FOR UPDATE", item.DLsID)
.AsNoTracking().SingleOrDefault();
if (detail == null)
{
detail = new ShipmentDetail
{
HeaderId = header.ID,
DLsID = item.DLsID,
ZoneCode = zoneCode,
MaterialCode = item.InvCode,
MaterialName = item.InvName,
MaterialType = item.InvDefine1,
Qty = item.DeliveryQty,
CompletedQty = 0,
DividedQty = 0,
Status = ShipStatusEnum.新建,
UpdateVersion = 1,
CreateBy = operatorCode,
CreateTime = now
};
_unitwork.Add(detail);
}
else
{
if (detail.HeaderId != header.ID)
throw new InvalidOperationException($"DLsID {item.DLsID} 已属于其他通知单");
if (((detail.CompletedQty ?? 0) > 0 || (detail.DividedQty ?? 0) > 0)
&& (detail.MaterialCode != item.InvCode || detail.Qty != item.DeliveryQty))
throw new InvalidOperationException($"DLsID {item.DLsID} 已分配或已出库,不能变更物料或数量");
detail.ZoneCode = zoneCode;
detail.MaterialCode = item.InvCode;
detail.MaterialName = item.InvName;
detail.MaterialType = item.InvDefine1;
if ((detail.CompletedQty ?? 0) == 0 && (detail.DividedQty ?? 0) == 0)
{
// ERP累计出库数量存在回写延迟,WMS执行量只使用发货通知数量和本地记录。
detail.Qty = item.DeliveryQty;
}
detail.UpdateVersion++;
detail.UpdateBy = operatorCode;
detail.UpdateTime = now;
SaveUpdate(detail);
}
}
var localDetails = _unitwork.Find(x => x.HeaderId == header.ID).ToList();
header.TotalQty = localDetails.Sum(x => x.Qty ?? 0);
if (header.TotalQty > 99999999.9999m)
throw new InvalidOperationException($"通知单 {group.Key} 累计总数量超出decimal(12,4)范围");
header.TotalLines = localDetails.Count;
// 增量新增明细或调整未执行数量后,重新汇总状态,避免单头保留旧的完成状态。
var status = localDetails.All(x => (x.CompletedQty ?? 0) >= (x.Qty ?? 0))
? ShipStatusEnum.拣货完成
: localDetails.Any(x => (x.CompletedQty ?? 0) > 0)
? ShipStatusEnum.拣货中
: localDetails.All(x => (x.CompletedQty ?? 0) + (x.DividedQty ?? 0) >= (x.Qty ?? 0))
? ShipStatusEnum.分配完成
: localDetails.Any(x => (x.DividedQty ?? 0) > 0)
? ShipStatusEnum.分配中
: ShipStatusEnum.新建;
header.FirstStatus = status;
header.LastStatus = status;
SaveUpdate(header);
}
}
}
}