diff --git a/HHWMS.Web/Areas/Api/ErpController.cs b/HHWMS.Web/Areas/Api/ErpController.cs new file mode 100644 index 0000000..730c534 --- /dev/null +++ b/HHWMS.Web/Areas/Api/ErpController.cs @@ -0,0 +1,51 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using HHWMS.Web.Models; +using HHWMS.Web.Support; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using WalkingTec.Mvvm.Core; + +namespace HHWMS.Web +{ + [Public] + [ApiController] + [Route("api/erp")] + [ApiExplorerSettings(GroupName = "User")] + [ActionDescription("ERP发货通知单下发")] + public class ErpController : ApiController + { + private readonly DispatchImportService _import; + private readonly ILogger _logger; + + public ErpController(DispatchImportService import, ILogger logger) + { + _import = import; + _logger = logger; + } + + [HttpPost("dispatch-notices")] + [RequestSizeLimit(10 * 1024 * 1024)] + public async Task ReceiveDispatch([FromBody] ReceiveDispatchRequest request) + { + try + { + var count = await _import.ImportAsync(request?.Data, "ERP"); + var codes = request.Data.Select(x => x.DLCode).Distinct().ToArray(); + _logger.LogInformation("ERP下发发货通知单成功,单号{Codes},明细数{Count}", string.Join(",", codes), count); + return ApiResult(new { BillCount = codes.Length, DetailCount = count, DLCodes = codes }, "发货通知单接收成功"); + } + catch (InvalidOperationException ex) + { + _logger.LogWarning(ex, "ERP下发发货通知单校验失败"); + return ApiResultError(msg: ex.Message); + } + catch (Exception ex) + { + _logger.LogError(ex, "ERP下发发货通知单保存失败"); + return StatusCode(500, new ApiJsonResult { Msg = "发货通知单保存失败,请联系WMS管理员或稍后重试" }); + } + } + } +} diff --git a/HHWMS.Web/Areas/Shipment/Controllers/ShipmentHeaderController.Erp.cs b/HHWMS.Web/Areas/Shipment/Controllers/ShipmentHeaderController.Erp.cs index 4cf1e4d..da4eadd 100644 --- a/HHWMS.Web/Areas/Shipment/Controllers/ShipmentHeaderController.Erp.cs +++ b/HHWMS.Web/Areas/Shipment/Controllers/ShipmentHeaderController.Erp.cs @@ -698,7 +698,7 @@ namespace HHWMS.Web.Controllers if (apiResult.Data.Data != null) { fetchedCount += apiResult.Data.Data.Count; - items.AddRange(apiResult.Data.Data.Where(x => !x.BReturnFlag)); + items.AddRange(apiResult.Data.Data.Where(x => x == null || !x.BReturnFlag)); } page++; } while (fetchedCount < total && page <= 100); @@ -708,20 +708,12 @@ namespace HHWMS.Web.Controllers return new ApiJsonResult { Success = false, Msg = "未查询到发货通知单" }; } - using (var transaction = DC.BeginTransaction()) - { - try - { - ProcessDispatchItems(items); - await transaction.CommitAsync(); - } - catch - { - await transaction.RollbackAsync(); - throw; - } - } - return new ApiJsonResult { Success = true, Data = items.Count }; + if (fetchedCount < total) + return new ApiJsonResult { Success = false, Msg = "ERP分页数据未获取完整,请稍后重试" }; + if (items.Any(x => x == null || x.DLCode != dispatchCode)) + return new ApiJsonResult { Success = false, Msg = "ERP返回的通知单号与请求不一致" }; + var count = await _dispatchImport.ImportAsync(items, Wtm.LoginUserInfo?.ITCode ?? "WMS"); + return new ApiJsonResult { Success = true, Status = true, Data = count }; } catch (Exception ex) { @@ -731,93 +723,6 @@ namespace HHWMS.Web.Controllers } } - private void ProcessDispatchItems(List items) - { - var now = DateTime.Now; - var operatorCode = Wtm.LoginUserInfo?.ITCode ?? "WMS"; - foreach (var group in items.Where(x => !string.IsNullOrWhiteSpace(x.DLCode) && x.DLsID > 0) - .GroupBy(x => x.DLCode)) - { - 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 - { - header.CompanyCode = group.First().CusCode; - header.SupplierCode = group.First().CusCode; - header.Remark = group.First().CusName; - header.UpdateVersion++; - header.UpdateBy = operatorCode; - header.UpdateTime = now; - _unitwork.Update(header); - } - - foreach (var item in group.GroupBy(x => x.DLsID).Select(x => x.First())) - { - var detail = _unitwork.FindSingle(x => x.DLsID == item.DLsID); - if (detail == null) - { - detail = new ShipmentDetail - { - HeaderId = header.ID, - DLsID = item.DLsID, - ZoneCode = "cp", - 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 - { - detail.HeaderId = header.ID; - 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; - _unitwork.Update(detail); - } - } - - var localDetails = _unitwork.Find(x => x.HeaderId == header.ID).ToList(); - header.TotalQty = localDetails.Sum(x => x.Qty ?? 0); - header.TotalLines = localDetails.Count; - _unitwork.Update(header); - } - } - private void ReleasePendingPallet(TaskHeader task) { var operatorCode = Wtm.LoginUserInfo?.ITCode ?? "WMS"; diff --git a/HHWMS.Web/Areas/Shipment/Controllers/ShipmentHeaderController.cs b/HHWMS.Web/Areas/Shipment/Controllers/ShipmentHeaderController.cs index 09af8c2..b8b4888 100644 --- a/HHWMS.Web/Areas/Shipment/Controllers/ShipmentHeaderController.cs +++ b/HHWMS.Web/Areas/Shipment/Controllers/ShipmentHeaderController.cs @@ -19,9 +19,11 @@ namespace HHWMS.Web.Controllers public partial class ShipmentHeaderController : BaseController { private readonly IUnitWork _unitwork; - public ShipmentHeaderController(IUnitWork unitwork) + private readonly HHWMS.Web.Support.DispatchImportService _dispatchImport; + public ShipmentHeaderController(IUnitWork unitwork, HHWMS.Web.Support.DispatchImportService dispatchImport) { _unitwork = unitwork; + _dispatchImport = dispatchImport; } #region Search [ActionDescription("Sys.Search")] diff --git a/HHWMS.Web/Models/Request/Request/ReceiveDispatchRequest.cs b/HHWMS.Web/Models/Request/Request/ReceiveDispatchRequest.cs new file mode 100644 index 0000000..a5092b0 --- /dev/null +++ b/HHWMS.Web/Models/Request/Request/ReceiveDispatchRequest.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace HHWMS.Web.Models +{ + public class ReceiveDispatchRequest + { + // 与LoadDispatch返回的data结构一致;单张、批量均使用数组。 + public List Data { get; set; } + } +} diff --git a/HHWMS.Web/Program.cs b/HHWMS.Web/Program.cs index 9db063c..d68cd62 100644 --- a/HHWMS.Web/Program.cs +++ b/HHWMS.Web/Program.cs @@ -62,6 +62,7 @@ builder.Services.TryAddScoped(); builder.Services.AddSoapCore(); builder.Services.AddScoped(typeof(IUnitWork), typeof(UnitWork)); +builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddSignalR() diff --git a/HHWMS.Web/Support/DispatchImportService.cs b/HHWMS.Web/Support/DispatchImportService.cs new file mode 100644 index 0000000..aec986b --- /dev/null +++ b/HHWMS.Web/Support/DispatchImportService.cs @@ -0,0 +1,202 @@ +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); + } + } + + } +} diff --git a/docs/ERP发货通知单主动下发接口.md b/docs/ERP发货通知单主动下发接口.md new file mode 100644 index 0000000..154ee65 --- /dev/null +++ b/docs/ERP发货通知单主动下发接口.md @@ -0,0 +1,118 @@ +# ERP发货通知单主动下发接口 + +## 两种接单方式 + +1. 原有“获取ERP发货通知单”按钮:输入DLCode,WMS按ErpCode=003、BReturnFlag=0分页调用ERP的LoadDispatch。未取完整或返回其他单号时不保存。 +2. ERP主动下发:调用下面的POST接口,WMS直接接收明细,不再回查ERP。单张通知单的全部明细放在data中;批量下发时混合多个DLCode,WMS按DLCode分组。 + +两个入口共用DispatchImportService保存规则,仅创建/更新出库单;分配库存、下发WCS和人工确认发货仍走现有流程。 + +## 部署和数据库 + +接口地址:`POST https://成品库WMS地址/api/erp/dispatch-notices` + +接口在成品库和线边库实例均可直接访问,无启用开关,无API密钥校验,也不需要网页登录Cookie。程序使用当前部署实例的数据库连接,不根据请求的ErpCode、WhCode或单号切换数据库;ERP向成品库下发时调用成品库WMS地址。 + +保存服务按成品库区编码ZoneCode=C查询并加锁,以防止并发导入重复单据,不依赖库区ID;不存在编码C则拒绝导入。明细保存为C,不要求ZoneCode=cp。ERP接口的cp仓库标识与WMS库区编码是不同概念。若线边库也存在编码C的库区且报文通过业务校验,会按现有规则保存,不会自动忽略请求。 + +沿用现有DLsID字段和成品库索引,无新增字段。尚未实施之前ERP成品发货功能的环境,须先应用既有 `sql/20260717_add_sale_out.sql` 和成品库专用 `sql/20260717_add_sale_out_cp.sql`,不要在线边库执行成品库专用索引脚本。 + +请求头: + +```http +Content-Type: application/json +``` + +接口沿用项目Public API入口,ERP直接提交JSON即可。 + +## 单张通知单示例 + +```json +{ + "data": [ + { + "ErpCode": "003", + "bReturnFlag": false, + "DLCode": "202609161279", + "DLsID": 1000003782, + "CusCode": "SSPB", + "CusName": "上海史派博实业有限公司", + "InvCode": "3002057", + "InvName": "018带边同步轮", + "InvDefine1": "QG0409", + "DeliveryQty": 100 + }, + { + "ErpCode": "003", + "bReturnFlag": false, + "DLCode": "202609161279", + "DLsID": 1000003783, + "CusCode": "SSPB", + "CusName": "上海史派博实业有限公司", + "InvCode": "3002057", + "InvName": "018带边同步轮", + "InvDefine1": "QG0409", + "DeliveryQty": 100 + } + ] +} +``` + +仅一条明细时data只放一个对象。批量时继续放入其他DLCode的明细,DLsID不能重复。相同物料的两条ERP明细不会合并。 + +兼容实际LoadDispatch响应中的data结构,可携带count、code和其他多余字段;推送不使用分页count/code,也不会补拉其他页。ERP必须主动发送需要下发的所有明细。CreateDate支持案例的 `yyyy-MM-dd HH:mm:ss` 格式(沿用WTM JSON配置)。按钮查询参数中的BReturnFlag=0是ERP查询约定;推送明细使用JSON布尔值false。 + +| 字段 | 规则 / 用途 | +| --- | --- | +| ErpCode | 必填,003 | +| DLCode | 必填,最多50字符,无首尾空格,保存为SourceCode | +| DLsID | 必填,大于0的整数,ERP明细唯一标识 | +| InvCode | 必填,最多50字符,物料编码 | +| DeliveryQty | 必填,大于0,最多4位小数,最大99999999.9999 | +| bReturnFlag | false;true拒绝 | +| CusCode / CusName | 客户编码/名称,同单据内须一致;编码最多50字符 | +| InvName / InvDefine1 | 物料名称/类型,最多50字符 | +| fOutQuantity | 不覆盖WMS已出库数量 | + +零数、负数、退货单均不接收。用户已确认负数单据拒绝接收;案例中的DLsID=1000003443、DeliveryQty=-2500会导致整批失败,不静默过滤。 + +## 响应及重试 + +成功返回HTTP 200,沿用WMS响应格式(字段名保留项目默认大小写): + +```json +{ + "Status": true, + "Success": true, + "Msg": "发货通知单接收成功", + "Data": { + "BillCount": "1", + "DetailCount": "2", + "DLCodes": ["202609161279"] + } +} +``` + +WTM默认将数字序列化为字符串,因此BillCount、DetailCount按字符串返回。 + +业务校验失败返回HTTP 200、Success=false、Status=false、Msg为具体原因,Data=null。HTTP 400表示报文绑定错误,500表示保存异常。请求体上限10 MiB;超过上限可能由服务器返回413。ERP必须同时检查HTTP状态和Success,不能只判断HTTP 200。 + +- 整批事务:任意一条失败,整批回滚。超时或500后允许重试原报文;校验失败须修正数据后重试。 +- DLCode定位单头、DLsID定位明细;重复推送更新现有记录,不增加重复行。同一请求内重复DLsID直接拒绝。 +- 同一DLsID不能迁移到另一张通知单;不能覆盖同SourceCode的非ERP单据。归档单据拒绝重新导入。 +- 未执行的明细允许修改数量/物料;已有分配量或完成量时,数量/物料变更整批拒绝。相同数据重试保留本地执行量。 +- 增量提交不会删除本地未出现在报文中的明细;取消明细/删除通知单不在此接口范围。 +- 保存按成品库区行锁串行执行,并对现有明细加锁,与原有分配流程协调。单头数量、行数及状态按保存后的所有明细汇总。 +- 接收结果写应用日志;新增/修改记录保留ERP审计身份。按钮仍使用当前登录用户。 + +## 本地验证 + +构建:`dotnet build WMS.sln --no-restore` + +验证程序:`dotnet run --project tools/dispatch-tests/DispatchTests.csproj -- 样例JSON文件路径` + +不提供样例路径时跳过真实样例校验。不设置WMS_DISPATCH_TEST_CONNECTION时,仅运行报文校验测试。设置该环境变量为本地MySQL测试库连接后,会创建随机命名的临时数据库、只复制所需表结构,测试完成自动删除临时库;不修改来源数据库业务数据。 + +2026-09-16已验证:真实样例反序列化、正数明细、负数拒绝、单条/批量、重复推送、并发推送、跨单明细冲突、整批回滚、已分配/已完成明细保护、未执行数量更新、增量行汇总与状态、审计人、编码C使用其他ID时正常导入、存在ID=1028但编码不是C时拒绝导入、无配置、无密钥请求成功接收。 + +测试直接调用实际控制器方法和共用服务,并连接临时MySQL库;未启动完整WMS现场服务,也未进行ERP网络联调或设备联动。部署后由ERP验证实际HTTP链路,无需额外接口配置。 diff --git a/tools/dispatch-tests/DispatchTests.csproj b/tools/dispatch-tests/DispatchTests.csproj new file mode 100644 index 0000000..419e791 --- /dev/null +++ b/tools/dispatch-tests/DispatchTests.csproj @@ -0,0 +1,11 @@ + + + Exe + net6.0 + enable + + + + + + diff --git a/tools/dispatch-tests/Program.cs b/tools/dispatch-tests/Program.cs new file mode 100644 index 0000000..408b6c9 --- /dev/null +++ b/tools/dispatch-tests/Program.cs @@ -0,0 +1,152 @@ +using System.Text.Json; +using HHWMS.Web; +using HHWMS.Web.Models; +using HHWMS.Web.Support; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging.Abstractions; +using MySqlConnector; +using WalkingTec.Mvvm.Core; +using WalkingTec.Mvvm.Mvc; + +var checks = 0; +void Check(bool success, string name) +{ + if (!success) throw new Exception("FAIL: " + name); + Console.WriteLine("PASS: " + name); + checks++; +} +DispatchItem Row(string code = "TEST-A", long id = 1, decimal qty = 100) => new() +{ + ErpCode = "003", DLCode = code, DLsID = id, InvCode = "3002057", + InvName = "018带边同步轮", InvDefine1 = "QG0409", CusCode = "SSPB", + CusName = "测试客户", DeliveryQty = qty, FOutQuantity = 999 +}; +void Invalid(List rows, string name) +{ + try { DispatchImportService.Validate(rows); } + catch (InvalidOperationException) { Check(true, name); return; } + throw new Exception("FAIL: " + name); +} +DispatchImportService.Validate(new() { Row() }); +Check(true, "single notice valid"); +Invalid(null, "null data"); +Invalid(new(), "empty data"); +Invalid(new() { null }, "null row"); +Invalid(new() { Row(), Row() }, "duplicate DLsID"); +Invalid(new() { Row(qty: 0) }, "zero quantity"); +Invalid(new() { Row(qty: 0.00001m) }, "quantity precision"); +var invalid = Row(); invalid.BReturnFlag = true; Invalid(new() { invalid }, "return notice rejected"); +invalid = Row(); invalid.ErpCode = "002"; Invalid(new() { invalid }, "other ERP rejected"); +invalid = Row(); invalid.CusCode = "OTHER"; Invalid(new() { Row(id: 2), invalid }, "customer conflict"); +if (args.Length > 0) +{ + var jsonOptions = new JsonOptions(); + jsonOptions.UseWtmJsonOptions(); + var sample = JsonSerializer.Deserialize(File.ReadAllText(args[0]), jsonOptions.JsonSerializerOptions); + Check(sample.Data.Count == 10, "provided sample deserializes with WTM options"); + Invalid(sample.Data, "sample negative quantity rejected"); + DispatchImportService.Validate(sample.Data.Where(x => x.DeliveryQty > 0).ToList()); + Check(true, "positive sample rows accepted"); +} +ErpController Controller(DispatchImportService service) +{ + return new ErpController(service, NullLogger.Instance) + { ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() } }; +} + +// Clone schema only into a disposable database. Never write source data. +var connectionString = Environment.GetEnvironmentVariable("WMS_DISPATCH_TEST_CONNECTION"); +if (string.IsNullOrEmpty(connectionString)) +{ + Console.WriteLine($"{checks} checks passed; DB tests skipped (set WMS_DISPATCH_TEST_CONNECTION)."); + return; +} +var source = new MySqlConnectionStringBuilder(connectionString); +var schema = source.Database; +if (!System.Text.RegularExpressions.Regex.IsMatch(schema, "^[a-zA-Z0-9_]+$")) throw new Exception("Invalid source schema"); +var scratch = "wms_dispatch_test_" + Guid.NewGuid().ToString("N"); +source.Database = ""; +await using var admin = new MySqlConnection(source.ConnectionString); +await admin.OpenAsync(); +async Task Sql(string sql) { await using var cmd = new MySqlCommand(sql, admin); await cmd.ExecuteNonQueryAsync(); } +await Sql($"CREATE DATABASE `{scratch}` CHARACTER SET utf8mb4"); +source.Database = scratch; +DataContext Db() => new(source.ConnectionString, DBTypeEnum.MySql); +async Task Import(params DispatchItem[] rows) +{ + using var db = Db(); + var context = new WTMContext(null, dc: db); + return await new DispatchImportService(context, new UnitWork(context)).ImportAsync(rows.ToList(), "ERP"); +} +async Task RejectImport(string name, params DispatchItem[] rows) +{ + try { await Import(rows); } + catch (InvalidOperationException) { Check(true, name); return; } + throw new Exception("FAIL: " + name); +} +try +{ + foreach (var table in new[] { "LocationZone", "ShipmentHeader", "ShipmentDetail", "ShipmentHeaderHistory", "SysCount" }) + await Sql($"CREATE TABLE `{scratch}`.`{table}` LIKE `{schema}`.`{table}`"); + await Sql($"INSERT INTO `{scratch}`.`LocationZone` (ID, ZoneCode, Name) VALUES (2028, 'C', '成品库')"); + Check(await Import(Row(), Row(id: 2), Row("TEST-B", 3)) == 3, "batch import two notices"); + await Import(Row(), Row(id: 2)); + using (var db = Db()) + { + Check(db.ShipmentHeaders.Count() == 2 && db.ShipmentDetails.Count() == 3, "repeated push does not duplicate"); + Check(db.ShipmentHeaders.Single(x => x.SourceCode == "TEST-A").TotalQty == 200, "header totals"); + Check(db.ShipmentDetails.All(x => x.ZoneCode == "C"), "zone C with ID 2028 accepted and stored on repeated import"); + Check(db.ShipmentDetails.All(x => x.CompletedQty == 0 && x.Qty == 100), "ERP out quantity ignored"); + } + await RejectImport("cross-notice detail conflict", Row("TEST-C", 1)); + using (var db = Db()) Check(!db.ShipmentHeaders.Any(x => x.SourceCode == "TEST-C"), "new header rolled back"); + await Sql($"UPDATE `{scratch}`.`ShipmentDetail` SET DividedQty=10 WHERE DLsID=1"); + await RejectImport("allocated quantity protected", Row(qty: 110)); + await RejectImport("late failure rolls back earlier notice", Row("AAA-ROLLBACK", 10), Row(qty: 110)); + using (var db = Db()) Check(!db.ShipmentHeaders.Any(x => x.SourceCode == "AAA-ROLLBACK"), "whole batch rollback"); + await Import(Row()); + using (var db = Db()) Check(db.ShipmentDetails.Single(x => x.DLsID == 1).DividedQty == 10, "identical retry preserves allocations"); + await Import(Row("TEST-B", 3, 120)); + using (var db = Db()) Check(db.ShipmentDetails.Single(x => x.DLsID == 3).Qty == 120, + "unexecuted quantity can be updated"); + await Sql($"UPDATE `{scratch}`.`ShipmentDetail` SET CompletedQty=120 WHERE DLsID=3"); + await Import(Row("TEST-B", 3, 120)); + using (var db = Db()) Check(db.ShipmentHeaders.Single(x => x.SourceCode == "TEST-B").FirstStatus == ShipStatusEnum.拣货完成, + "completed status preserved"); + await Import(Row("TEST-B", 4)); + using (var db = Db()) + { + var header = db.ShipmentHeaders.Single(x => x.SourceCode == "TEST-B"); + Check(header.TotalLines == 2 && header.TotalQty == 220 && header.FirstStatus == ShipStatusEnum.拣货中, + "incremental lines retain old lines and recalculate totals/status"); + Check(db.ShipmentDetails.Single(x => x.DLsID == 3).UpdateBy == "ERP", "ERP update audit identity"); + } + var changedMaterial = Row("TEST-B", 3, 120); changedMaterial.InvCode = "OTHER"; + await RejectImport("completed material protected", changedMaterial); + await Task.WhenAll(Import(Row("CONCURRENT", 20)), Import(Row("CONCURRENT", 20))); + using (var db = Db()) Check(db.ShipmentHeaders.Count(x => x.SourceCode == "CONCURRENT") == 1 + && db.ShipmentDetails.Count(x => x.DLsID == 20) == 1, "concurrent import idempotency"); + using (var db = Db()) + { + var context = new WTMContext(null, dc: db); + var controller = Controller(new DispatchImportService(context, new UnitWork(context))); + var response = (JsonResult)await controller.ReceiveDispatch(new() { Data = new() { Row("API-SUCCESS", 40) } }); + var options = new JsonOptions(); options.UseWtmJsonOptions(); + var json = JsonSerializer.SerializeToElement(response.Value, options.JsonSerializerOptions); + Check(json.GetProperty("Success").GetBoolean() && json.GetProperty("Data").GetProperty("DetailCount").GetString() == "1", + "anonymous controller success without configuration or key and documented JSON shape"); + response = (JsonResult)await controller.ReceiveDispatch(new() { Data = new() { Row("API-NEGATIVE", 41, -1) } }); + Check(!((ApiJsonResult)response.Value).Success && !db.ShipmentHeaders.Any(x => x.SourceCode == "API-NEGATIVE"), + "anonymous controller rejects negative quantity without writes"); + } + await Sql($"DELETE FROM `{scratch}`.`LocationZone`"); + await Sql($"INSERT INTO `{scratch}`.`LocationZone` (ID, ZoneCode, Name) VALUES (1028, 'OTHER', '其他库区')"); + await RejectImport("missing finished-goods zone code C", Row("NO-CP", 30)); +} +finally +{ + // scratch is generated above, never supplied by callers. + await Sql($"DROP DATABASE `{scratch}`"); +} +Console.WriteLine($"{checks} checks passed, disposable database removed.");