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.");