|
|
@@ -1,10 +1,13 @@
|
|
|
+using System.Globalization;
|
|
|
using System.Security.Cryptography;
|
|
|
using System.Text;
|
|
|
using System.Text.Json;
|
|
|
using System.Text.Json.Nodes;
|
|
|
using System.Text.RegularExpressions;
|
|
|
+using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
|
|
|
using Admin.NET.Plugin.AiDOP.DataPlatform.Executors;
|
|
|
using Admin.NET.Plugin.AiDOP.DataPlatform;
|
|
|
+using Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
|
|
|
using Admin.NET.Plugin.AiDOP.Entity.DataPlatform;
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
@@ -13,6 +16,7 @@ namespace Admin.NET.Plugin.AiDOP.DataPlatform.Inbound;
|
|
|
/// <summary>入站接收主流水线。步骤顺序按任务书 §6.3 定死,勿换序。</summary>
|
|
|
public sealed class MdpInboundReceiveService : ITransient
|
|
|
{
|
|
|
+ private const string PurchaseOrderEntity = "S3_PURCHASE_ORDER";
|
|
|
private static readonly Regex TableNameRe = new(@"^[A-Za-z0-9_]+$", RegexOptions.Compiled);
|
|
|
private static readonly Regex IsoOffsetRe = new(@"[Zz]|[+\-]\d{2}:\d{2}", RegexOptions.Compiled);
|
|
|
private const int MaxRowBytes = 64 * 1024;
|
|
|
@@ -54,6 +58,7 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
{
|
|
|
var sw = System.Diagnostics.Stopwatch.StartNew();
|
|
|
var entityCode = (args.EntityCode ?? string.Empty).Trim().ToUpperInvariant();
|
|
|
+ var purchaseOrder = entityCode == PurchaseOrderEntity;
|
|
|
var hash = ToSha256Hex(args.RawBody);
|
|
|
var contractVersion = ContractVersion(args);
|
|
|
|
|
|
@@ -100,6 +105,7 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
|
|
|
var source = await _db.Queryable<MdpSource>()
|
|
|
.Where(s => s.SourceCode == grant.SourceCode && s.Status == 1)
|
|
|
+ .WhereIF(purchaseOrder, s => s.TenantId == args.TenantId || s.TenantId == 0)
|
|
|
.FirstAsync(ct);
|
|
|
if (source == null)
|
|
|
return Fail(500, "inbound source not configured");
|
|
|
@@ -119,46 +125,51 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
return Fail(ex.HttpStatus, ex.Message);
|
|
|
}
|
|
|
|
|
|
- MdpInboundRequest request;
|
|
|
+ MdpInboundRequest? request;
|
|
|
try
|
|
|
{
|
|
|
- request = await BeginRequestAsync(args, entity, hash, batch.SnapshotId, ct);
|
|
|
+ request = purchaseOrder
|
|
|
+ ? await FindCommittedPurchaseRequestAsync(args, entity.EntityCode, hash, ct)
|
|
|
+ : await BeginRequestAsync(args, entity, hash, batch.SnapshotId, ct);
|
|
|
}
|
|
|
catch (MdpInboundBatchException ex)
|
|
|
{
|
|
|
return Fail(ex.HttpStatus, ex.Message);
|
|
|
}
|
|
|
|
|
|
- if (request.Status == "COMMITTED" &&
|
|
|
+ if (request?.Status == "COMMITTED" &&
|
|
|
string.Equals(request.RequestHash, hash, StringComparison.OrdinalIgnoreCase) &&
|
|
|
!string.IsNullOrWhiteSpace(request.ReceiptJson))
|
|
|
{
|
|
|
return Receipt(request.ReceiptJson, replay: true);
|
|
|
}
|
|
|
|
|
|
- await TryArchiveEnvelopeAsync(args, request, hash, ct);
|
|
|
+ if (!purchaseOrder)
|
|
|
+ await TryArchiveEnvelopeAsync(args, request!, hash, ct);
|
|
|
|
|
|
try
|
|
|
{
|
|
|
var maps = await _mapper.LoadAsync(args.TenantId, entity.EntityCode, args.AccessKey, ct);
|
|
|
var accepted = new List<MdpInboundPreparedRow>();
|
|
|
+ var positions = new Dictionary<MdpInboundPreparedRow, int>();
|
|
|
var rejected = new List<MdpInboundRejectedRow>();
|
|
|
var staleRejected = 0;
|
|
|
var equalTsOverride = 0;
|
|
|
|
|
|
- foreach (var el in batch.Rows)
|
|
|
+ for (var ordinal = 0; ordinal < batch.Rows.Count; ordinal++)
|
|
|
{
|
|
|
var prepared = PrepareRow(
|
|
|
- el, entity, maps, contractVersion, grant, args.TenantId, rejected, out var batchDeny);
|
|
|
+ batch.Rows[ordinal], entity, maps, contractVersion, grant, args.TenantId, rejected, out var batchDeny);
|
|
|
if (batchDeny != null)
|
|
|
{
|
|
|
- await MarkFailedAsync(request.Id, batchDeny.Message, sw.ElapsedMilliseconds, ct);
|
|
|
+ if (request is not null)
|
|
|
+ await MarkFailedAsync(request.Id, batchDeny.Message, sw.ElapsedMilliseconds, ct);
|
|
|
return Fail(batchDeny.HttpStatus, batchDeny.Message);
|
|
|
}
|
|
|
if (prepared == null)
|
|
|
continue;
|
|
|
|
|
|
- if (entity.StaleGuardEnabled == 1)
|
|
|
+ if (!purchaseOrder && entity.StaleGuardEnabled == 1)
|
|
|
{
|
|
|
var decision = await GuardStaleAsync(
|
|
|
entity, args.TenantId, sourceTable, prepared, neutralSource, ct);
|
|
|
@@ -174,18 +185,107 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
}
|
|
|
|
|
|
accepted.Add(prepared);
|
|
|
+ if (purchaseOrder)
|
|
|
+ positions.Add(prepared, ordinal);
|
|
|
}
|
|
|
|
|
|
- var ctx = new MdpPullContext { TenantId = args.TenantId, BatchId = request.SyncBatchId };
|
|
|
var written = new List<MdpInboundPreparedRow>();
|
|
|
+ PurchaseMigrationScope? migration = null;
|
|
|
+ var replay = false;
|
|
|
var tran = await _db.Ado.UseTranAsync(async () =>
|
|
|
{
|
|
|
- foreach (var row in accepted)
|
|
|
+ if (purchaseOrder)
|
|
|
{
|
|
|
- await TransferIfNeededAsync(
|
|
|
- entity, args.TenantId, sourceTable, row.BizKey, neutralSource, ct);
|
|
|
+ migration = await MdpPurchaseMigrationStore.LockLegacyAsync(_db, args.TenantId,
|
|
|
+ grant.FactoryId.GetValueOrDefault(), grant.SourceCode);
|
|
|
+ if (migration is not null)
|
|
|
+ {
|
|
|
+ // 可能在等待作用域锁期间,原请求才完成提交;关闭写入不影响旧回执。
|
|
|
+ var prior = await FindCommittedPurchaseRequestAsync(args, entity.EntityCode, hash, ct, lockRow: true);
|
|
|
+ if (prior is not null)
|
|
|
+ {
|
|
|
+ request = prior;
|
|
|
+ replay = true;
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ MdpPurchaseMigrationStore.RequireAdmission(migration, MdpPurchaseMigrationStore.Legacy);
|
|
|
+ if (!string.IsNullOrWhiteSpace(batch.SnapshotId))
|
|
|
+ throw new MdpIngestHttpException(409, "PURCHASE_SNAPSHOT_UNAVAILABLE");
|
|
|
+ }
|
|
|
+ await RequireCurrentPurchaseGrantAsync(grant, source);
|
|
|
+ ct.ThrowIfCancellationRequested();
|
|
|
+ request = await BeginRequestAsync(args, entity, hash, batch.SnapshotId, ct);
|
|
|
+ if (request.Status == "COMMITTED")
|
|
|
+ {
|
|
|
+ if (string.IsNullOrWhiteSpace(request.ReceiptJson))
|
|
|
+ throw new MdpIngestHttpException(409, "PURCHASE_LEGACY_RECEIPT_UNAVAILABLE");
|
|
|
+ replay = true;
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ await TryArchiveEnvelopeAsync(args, request, hash, ct, required: migration is not null);
|
|
|
+ }
|
|
|
+
|
|
|
+ var current = request ?? throw new InvalidOperationException("Inbound request was not reserved.");
|
|
|
+ var ctx = new MdpPullContext { TenantId = args.TenantId, BatchId = current.SyncBatchId };
|
|
|
+ var rowsToWrite = migration is null ? accepted
|
|
|
+ : accepted.OrderBy(row => TryGetString(row.Dict, "PoNo"), StringComparer.Ordinal)
|
|
|
+ .ThenBy(row => TryGetString(row.Dict, "PoLine"), StringComparer.Ordinal).ToList();
|
|
|
+ var useFactoryKey = purchaseOrder && migration is null && grant.FactoryId is > 0
|
|
|
+ && await MdpPurchaseMigrationStore.HasFactoryOrderKeyAsync(_db);
|
|
|
+ foreach (var prepared in rowsToWrite)
|
|
|
+ {
|
|
|
+ var row = prepared;
|
|
|
+ string? storageKey = null;
|
|
|
+ if (migration is not null)
|
|
|
+ {
|
|
|
+ if (!TryMigrationLine(row, out var line))
|
|
|
+ {
|
|
|
+ rejected.Add(new MdpInboundRejectedRow { BizKey = row.BizKey, Reason = "INVALID_PURCHASE_LINE" });
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ var traceId = FormattableString.Invariant($"{current.Id}:{positions[row]}");
|
|
|
+ var result = await MdpPurchaseMigrationWriter.WriteAsync(_db, migration, MdpPurchaseMigrationStore.Legacy,
|
|
|
+ line!, current.SyncBatchId, traceId);
|
|
|
+ if (result.Status is "WRITTEN" or "REUSED")
|
|
|
+ written.Add(row);
|
|
|
+ else if (result.Status == "CONFLICT")
|
|
|
+ rejected.Add(new MdpInboundRejectedRow { BizKey = row.BizKey, Reason = "PURCHASE_ORDER_CONFLICT" });
|
|
|
+ else
|
|
|
+ throw new InvalidOperationException("Unexpected purchase migration write result.");
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (purchaseOrder)
|
|
|
+ {
|
|
|
+ // 旧贴源唯一键没有租户/工厂,先检查精确键,禁止旧通用逻辑转移别的来源。
|
|
|
+ var ownership = await LockLegacyPurchaseStageAsync(args.TenantId, row, sourceTable, neutralSource, useFactoryKey);
|
|
|
+ storageKey = ownership.Key;
|
|
|
+ if (ownership.Conflict)
|
|
|
+ {
|
|
|
+ rejected.Add(new MdpInboundRejectedRow { BizKey = row.BizKey, Reason = "PURCHASE_ORDER_CONFLICT" });
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (entity.StaleGuardEnabled == 1 && ownership.Row is not null)
|
|
|
+ {
|
|
|
+ var decision = CheckStale(row, ownership.Row);
|
|
|
+ if (decision.RejectStale)
|
|
|
+ {
|
|
|
+ staleRejected++;
|
|
|
+ rejected.Add(new MdpInboundRejectedRow { BizKey = row.BizKey, Reason = "stale" });
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (decision.EqualTsOverride)
|
|
|
+ equalTsOverride++;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ else
|
|
|
+ {
|
|
|
+ await TransferIfNeededAsync(entity, args.TenantId, sourceTable, row.BizKey, neutralSource, ct);
|
|
|
+ }
|
|
|
+
|
|
|
var n = await _writer.UpsertAsync(
|
|
|
- source, entity, sourceTable, row.Dict, row.RawJson, row.BizKey, ctx);
|
|
|
+ source, entity, sourceTable, row.Dict, row.RawJson, row.BizKey, ctx, storageKey);
|
|
|
if (n == 0)
|
|
|
{
|
|
|
rejected.Add(new MdpInboundRejectedRow
|
|
|
@@ -207,8 +307,8 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
Rejected = rejected.Count,
|
|
|
RejectedRows = rejected,
|
|
|
IdempotentReplay = false,
|
|
|
- SyncBatchId = request.SyncBatchId,
|
|
|
- RequestId = request.Id,
|
|
|
+ SyncBatchId = current.SyncBatchId,
|
|
|
+ RequestId = current.Id,
|
|
|
TransformEnqueued = false,
|
|
|
StaleRejected = staleRejected,
|
|
|
EqualTsOverride = equalTsOverride
|
|
|
@@ -232,7 +332,7 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
ElapsedMs = (int)sw.ElapsedMilliseconds,
|
|
|
UpdateTime = now
|
|
|
})
|
|
|
- .Where(r => r.Id == request.Id)
|
|
|
+ .Where(r => r.Id == current.Id)
|
|
|
.ExecuteCommandAsync(ct);
|
|
|
if (!string.IsNullOrWhiteSpace(batch.SnapshotId) && batch.Seq is > 0)
|
|
|
await _snapshots.AdvanceAsync(batch.SnapshotId, batch.Seq.Value, written.Count, ct);
|
|
|
@@ -240,25 +340,47 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
|
|
|
if (!tran.IsSuccess)
|
|
|
{
|
|
|
+ if (tran.ErrorException is MdpIngestHttpException admission)
|
|
|
+ {
|
|
|
+ if (request is not null)
|
|
|
+ await MarkFailedAsync(request.Id, admission.Code, sw.ElapsedMilliseconds, CancellationToken.None, admission.StatusCode);
|
|
|
+ return Fail(admission.StatusCode, admission.Code);
|
|
|
+ }
|
|
|
+ if (tran.ErrorException is MdpInboundBatchException batchError)
|
|
|
+ return Fail(batchError.HttpStatus, batchError.Message);
|
|
|
+
|
|
|
var err = tran.ErrorException?.Message ?? "transaction failed";
|
|
|
- await MarkFailedAsync(request.Id, Truncate(err, 1000), sw.ElapsedMilliseconds, ct);
|
|
|
- _logger.LogError(tran.ErrorException, "inbound write transaction failed requestId={Id}", request.Id);
|
|
|
+ if (request is not null)
|
|
|
+ await MarkFailedAsync(request.Id, Truncate(err, 1000), sw.ElapsedMilliseconds,
|
|
|
+ purchaseOrder ? CancellationToken.None : ct);
|
|
|
+ _logger.LogError(tran.ErrorException, "inbound write transaction failed requestId={Id}", request?.Id);
|
|
|
return Fail(500, "inbound write failed");
|
|
|
}
|
|
|
|
|
|
+ var finished = request ?? throw new InvalidOperationException("Inbound request was not reserved.");
|
|
|
+ if (replay)
|
|
|
+ return Receipt(finished.ReceiptJson, replay: true);
|
|
|
+
|
|
|
var committed = await _db.Queryable<MdpInboundRequest>()
|
|
|
- .Where(r => r.Id == request.Id)
|
|
|
+ .Where(r => r.Id == finished.Id)
|
|
|
.FirstAsync(ct);
|
|
|
var receiptJson = committed?.ReceiptJson;
|
|
|
+ if (migration is not null)
|
|
|
+ return Receipt(receiptJson, replay: false);
|
|
|
+
|
|
|
try
|
|
|
{
|
|
|
await _mirror.MirrorCommittedAsync(
|
|
|
entity.EntityCode, args.TenantId, grant.FactoryId, grant.SourceCode, written, ct);
|
|
|
- await _neutral.ProjectAsync(entity.EntityCode, args.TenantId, grant.SourceCode, ct);
|
|
|
+ if (purchaseOrder && written.Count > 0)
|
|
|
+ await _neutral.ProjectPurchaseBatchAsync(args.TenantId, grant.FactoryId, grant.SourceCode, neutralSource,
|
|
|
+ sourceTable, finished.SyncBatchId, ct);
|
|
|
+ else if (!purchaseOrder)
|
|
|
+ await _neutral.ProjectAsync(entity.EntityCode, args.TenantId, grant.SourceCode, ct);
|
|
|
}
|
|
|
catch (Exception ex)
|
|
|
{
|
|
|
- _logger.LogError(ex, "inbound mirror after commit failed requestId={Id}", request.Id);
|
|
|
+ _logger.LogError(ex, "inbound mirror after commit failed requestId={Id}", finished.Id);
|
|
|
}
|
|
|
|
|
|
var enqueued = false;
|
|
|
@@ -269,17 +391,19 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
}
|
|
|
catch (Exception ex)
|
|
|
{
|
|
|
- _logger.LogError(ex, "inbound trigger after commit failed requestId={Id}", request.Id);
|
|
|
+ _logger.LogError(ex, "inbound trigger after commit failed requestId={Id}", finished.Id);
|
|
|
}
|
|
|
|
|
|
if (enqueued)
|
|
|
- receiptJson = await PatchTransformEnqueuedAsync(request.Id, receiptJson, ct);
|
|
|
+ receiptJson = await PatchTransformEnqueuedAsync(finished.Id, receiptJson, ct);
|
|
|
return Receipt(receiptJson, replay: false);
|
|
|
}
|
|
|
catch (Exception ex)
|
|
|
{
|
|
|
- await MarkFailedAsync(request.Id, Truncate(ex.Message, 1000), sw.ElapsedMilliseconds, ct);
|
|
|
- _logger.LogError(ex, "inbound receive failed requestId={Id}", request.Id);
|
|
|
+ if (request is not null)
|
|
|
+ await MarkFailedAsync(request.Id, Truncate(ex.Message, 1000), sw.ElapsedMilliseconds,
|
|
|
+ purchaseOrder ? CancellationToken.None : ct);
|
|
|
+ _logger.LogError(ex, "inbound receive failed requestId={Id}", request?.Id);
|
|
|
return Fail(500, "inbound receive failed");
|
|
|
}
|
|
|
}
|
|
|
@@ -441,7 +565,7 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
return Fail(403, "entity not authorized");
|
|
|
|
|
|
var reqs = await _db.Queryable<MdpInboundRequest>()
|
|
|
- .Where(r => r.AccessKey == accessKey && r.CreateTime >= from && r.CreateTime < to)
|
|
|
+ .Where(r => r.TenantId == tenantId && r.AccessKey == accessKey && r.CreateTime >= from && r.CreateTime < to)
|
|
|
.Where("UPPER(entity_code) = @code", new { code })
|
|
|
.ToListAsync(ct);
|
|
|
|
|
|
@@ -458,9 +582,13 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
&& !string.IsNullOrWhiteSpace(entity.TargetTableName)
|
|
|
&& TableNameRe.IsMatch(entity.TargetTableName))
|
|
|
{
|
|
|
+ // 采购物理键带工厂前缀,旧入口的日对账摘要仍使用原始业务键。
|
|
|
+ var keyColumn = code == PurchaseOrderEntity
|
|
|
+ ? "IF(source_biz_key = CONCAT(tenant_id,'#',factory_id,'#',raw_data->>'$.PoNo','#',raw_data->>'$.PoLine'), CONCAT(raw_data->>'$.PoNo','#',raw_data->>'$.PoLine'), source_biz_key)"
|
|
|
+ : "source_biz_key";
|
|
|
keys = await _db.Ado.SqlQueryAsync<string>(
|
|
|
$"""
|
|
|
- SELECT source_biz_key FROM `{entity.TargetTableName}`
|
|
|
+ SELECT {keyColumn} FROM `{entity.TargetTableName}`
|
|
|
WHERE tenant_id=@t AND sync_batch_id IN ({string.Join(",", batchIds.Select((_, i) => "@b" + i))})
|
|
|
""",
|
|
|
new[] { new SugarParameter("@t", tenantId) }
|
|
|
@@ -468,6 +596,22 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
.ToArray());
|
|
|
}
|
|
|
|
|
|
+ if (code == "S3_PURCHASE_ORDER" && batchIds.Count > 0 && await MdpPurchaseMigrationStore.HasScopeTableAsync(_db))
|
|
|
+ {
|
|
|
+ ct.ThrowIfCancellationRequested();
|
|
|
+ // 跨入口复用沿用原贴源批次。旧日终对账从本次接收对应的观察记录取同一业务键。
|
|
|
+ keys.AddRange(await _db.Ado.SqlQueryAsync<string>(
|
|
|
+ """
|
|
|
+ SELECT CONCAT(o.po_no,'#',o.po_line)
|
|
|
+ FROM mdp_inbound_request r
|
|
|
+ JOIN mdp_purchase_migration_observation o ON o.batch_id=r.sync_batch_id AND o.writer='LEGACY'
|
|
|
+ JOIN mdp_purchase_migration_scope s ON s.id=o.scope_id AND s.tenant_id=r.tenant_id
|
|
|
+ WHERE r.tenant_id=@TenantId AND r.access_key=@AccessKey AND r.entity_code=@EntityCode
|
|
|
+ AND r.create_time>=@From AND r.create_time<@To AND r.status='COMMITTED'
|
|
|
+ AND o.resolution IN ('WRITTEN','REUSED')
|
|
|
+ """, new { TenantId = tenantId, AccessKey = accessKey, EntityCode = code, From = from, To = to }));
|
|
|
+ }
|
|
|
+
|
|
|
var sorted = keys
|
|
|
.Where(k => !string.IsNullOrWhiteSpace(k))
|
|
|
.Distinct(StringComparer.Ordinal)
|
|
|
@@ -641,16 +785,41 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ private async Task<MdpInboundRequest?> FindCommittedPurchaseRequestAsync(
|
|
|
+ MdpInboundReceiveArgs args, string entityCode, string hash, CancellationToken ct, bool lockRow = false)
|
|
|
+ {
|
|
|
+ ct.ThrowIfCancellationRequested();
|
|
|
+ const string statement = """
|
|
|
+ SELECT id AS Id, status AS Status, request_hash AS RequestHash, receipt_json AS ReceiptJson
|
|
|
+ FROM mdp_inbound_request
|
|
|
+ WHERE tenant_id = @TenantId AND access_key = @AccessKey AND entity_code = @EntityCode
|
|
|
+ AND idempotency_key = @IdempotencyKey AND status = 'COMMITTED'
|
|
|
+ """;
|
|
|
+ var existing = await _db.Ado.SqlQuerySingleAsync<MdpInboundRequest>(lockRow ? statement + " FOR UPDATE" : statement,
|
|
|
+ new { args.TenantId, args.AccessKey, EntityCode = entityCode, args.IdempotencyKey });
|
|
|
+ if (existing is null)
|
|
|
+ return null;
|
|
|
+ if (!string.Equals(existing.RequestHash, hash, StringComparison.OrdinalIgnoreCase))
|
|
|
+ throw new MdpInboundBatchException(409, "idempotency key conflict");
|
|
|
+ if (string.IsNullOrWhiteSpace(existing.ReceiptJson))
|
|
|
+ throw new MdpInboundBatchException(409, "PURCHASE_LEGACY_RECEIPT_UNAVAILABLE");
|
|
|
+ return existing;
|
|
|
+ }
|
|
|
+
|
|
|
private async Task TryArchiveEnvelopeAsync(
|
|
|
- MdpInboundReceiveArgs args, MdpInboundRequest request, string hash, CancellationToken ct)
|
|
|
+ MdpInboundReceiveArgs args, MdpInboundRequest request, string hash, CancellationToken ct, bool required = false)
|
|
|
{
|
|
|
try
|
|
|
{
|
|
|
- var exists = await _db.Queryable<MdpInboundEnvelope>()
|
|
|
+ var previous = await _db.Queryable<MdpInboundEnvelope>()
|
|
|
.Where(e => e.RequestId == request.Id)
|
|
|
- .AnyAsync(ct);
|
|
|
- if (exists)
|
|
|
+ .Select(e => e.BodySha256).FirstAsync(ct);
|
|
|
+ if (previous is not null)
|
|
|
+ {
|
|
|
+ if (required && !string.Equals(previous, hash, StringComparison.OrdinalIgnoreCase))
|
|
|
+ throw new MdpIngestHttpException(409, "LEGACY_ARCHIVE_CONFLICT");
|
|
|
return;
|
|
|
+ }
|
|
|
|
|
|
var headers = args.Headers
|
|
|
.Where(kv => !IsSensitiveHeader(kv.Key))
|
|
|
@@ -668,7 +837,7 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
CreateTime = DateTime.Now
|
|
|
}).ExecuteCommandAsync(ct);
|
|
|
}
|
|
|
- catch (Exception ex)
|
|
|
+ catch (Exception ex) when (!required)
|
|
|
{
|
|
|
_logger.LogError(ex, "inbound envelope archive failed requestId={Id}", request.Id);
|
|
|
}
|
|
|
@@ -687,6 +856,9 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
batchDeny = null;
|
|
|
var incoming = MdpInboundFieldMapper.ElementToDict(el);
|
|
|
var mapped = _mapper.MapRow(incoming, maps);
|
|
|
+ if (entity.EntityCode == PurchaseOrderEntity && grant.FactoryId is > 0
|
|
|
+ && !mapped.ContainsKey("factory_id") && !mapped.ContainsKey("FactoryId"))
|
|
|
+ mapped["factory_id"] = grant.FactoryId.Value;
|
|
|
var missing = _mapper.MissingRequired(mapped, maps, entity.EntityCode, contractVersion);
|
|
|
var previewKey = TryGetString(mapped, "bizKey");
|
|
|
|
|
|
@@ -738,6 +910,12 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ if (entity.EntityCode == PurchaseOrderEntity && !NormalizePurchaseFields(mapped))
|
|
|
+ {
|
|
|
+ rejected.Add(new MdpInboundRejectedRow { BizKey = previewKey, Reason = "INVALID_PURCHASE_DATE" });
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
if (string.Equals(entity.EntityCode, "S5_INVENTORY_TXN", StringComparison.OrdinalIgnoreCase))
|
|
|
{
|
|
|
var transType = FirstMapped(mapped, "TransType", "trans_type");
|
|
|
@@ -804,8 +982,12 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
CancellationToken ct)
|
|
|
{
|
|
|
var existing = await LoadGuardRowAsync(entity.TargetTableName, tenantId, sourceTable, incoming.BizKey, inboundSource, ct);
|
|
|
- if (existing == null)
|
|
|
- return (false, false, incoming);
|
|
|
+ return existing is null ? (false, false, incoming) : CheckStale(incoming, existing);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static (bool RejectStale, bool EqualTsOverride, MdpInboundPreparedRow Row) CheckStale(
|
|
|
+ MdpInboundPreparedRow incoming, MdpInboundStgGuardRow existing)
|
|
|
+ {
|
|
|
|
|
|
var oldHasVer = long.TryParse(existing.SourceVersion, out var oldVer);
|
|
|
var newHasVer = long.TryParse(incoming.SourceVersion, out var newVer);
|
|
|
@@ -833,6 +1015,118 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
return (false, !same, incoming);
|
|
|
}
|
|
|
|
|
|
+ private async Task RequireCurrentPurchaseGrantAsync(MdpInboundGrant grant, MdpSource source)
|
|
|
+ {
|
|
|
+ var id = await _db.Ado.SqlQuerySingleAsync<long?>(
|
|
|
+ """
|
|
|
+ SELECT id FROM mdp_inbound_grant WHERE id = @Id AND tenant_id = @TenantId AND access_key = @AccessKey
|
|
|
+ AND entity_code = @EntityCode AND source_code = @SourceCode AND factory_id <=> @FactoryId AND status = 1
|
|
|
+ FOR UPDATE
|
|
|
+ """, new { grant.Id, grant.TenantId, grant.AccessKey, grant.EntityCode, grant.SourceCode, grant.FactoryId });
|
|
|
+ if (id is null or <= 0)
|
|
|
+ throw new MdpIngestHttpException(403, "PURCHASE_LEGACY_GRANT_UNAVAILABLE");
|
|
|
+
|
|
|
+ var sourceId = await _db.Ado.SqlQuerySingleAsync<long?>(
|
|
|
+ """
|
|
|
+ SELECT id FROM mdp_source WHERE id = @Id AND tenant_id = @TenantId AND source_code = @SourceCode
|
|
|
+ AND system_code <=> @SystemCode AND status = 1
|
|
|
+ FOR UPDATE
|
|
|
+ """, new { source.Id, source.TenantId, source.SourceCode, source.SystemCode });
|
|
|
+ if (sourceId is null or <= 0)
|
|
|
+ throw new MdpIngestHttpException(403, "PURCHASE_LEGACY_SOURCE_UNAVAILABLE");
|
|
|
+ }
|
|
|
+
|
|
|
+ private async Task<(bool Conflict, MdpInboundStgGuardRow? Row, string Key)> LockLegacyPurchaseStageAsync(
|
|
|
+ long tenantId, MdpInboundPreparedRow row, string sourceTable, string sourceSystem, bool useFactoryKey)
|
|
|
+ {
|
|
|
+ if (!TryGetLong(row.Dict, "factory_id", out var factoryId))
|
|
|
+ TryGetLong(row.Dict, "FactoryId", out factoryId);
|
|
|
+ var factory = MdpStagingWriter.NormalizeFactoryId(tenantId, factoryId) ?? 1;
|
|
|
+ var physicalKey = useFactoryKey ? FormattableString.Invariant($"{tenantId}#{factory}#{row.BizKey}") : row.BizKey;
|
|
|
+ var candidates = await _db.Ado.SqlQueryAsync<LegacyPurchaseStageRow>(
|
|
|
+ """
|
|
|
+ SELECT tenant_id AS TenantId, factory_id AS FactoryId, source_biz_key AS StorageKey,
|
|
|
+ JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.sourceUpdatedAt')) AS SourceUpdatedAt,
|
|
|
+ JSON_UNQUOTE(JSON_EXTRACT(raw_data,'$.sourceVersion')) AS SourceVersion, raw_data AS RawData
|
|
|
+ FROM mdp_stg_purchase_order
|
|
|
+ WHERE source_system=@SourceSystem AND source_table=@SourceTable AND source_biz_key IN (@BizKey,@PhysicalKey)
|
|
|
+ FOR UPDATE
|
|
|
+ """, new { SourceSystem = sourceSystem, SourceTable = sourceTable, row.BizKey, PhysicalKey = physicalKey });
|
|
|
+ LegacyPurchaseStageRow? owned = null;
|
|
|
+ foreach (var candidate in candidates)
|
|
|
+ {
|
|
|
+ var historicalFactory = candidate.FactoryId.GetValueOrDefault();
|
|
|
+ if (candidate.TenantId == tenantId && (historicalFactory == factory ||
|
|
|
+ (!useFactoryKey && historicalFactory == 0 && factory == 1)))
|
|
|
+ {
|
|
|
+ if (owned is not null) return (true, null, physicalKey);
|
|
|
+ owned = candidate;
|
|
|
+ }
|
|
|
+ else if (!useFactoryKey || candidate.TenantId is null || historicalFactory <= 0 ||
|
|
|
+ !string.Equals(candidate.StorageKey, row.BizKey, StringComparison.Ordinal))
|
|
|
+ return (true, null, physicalKey);
|
|
|
+ }
|
|
|
+ if (owned is null) return (false, null, physicalKey);
|
|
|
+ return (false, new MdpInboundStgGuardRow
|
|
|
+ {
|
|
|
+ RawData = owned.RawData, SourceUpdatedAt = owned.SourceUpdatedAt, SourceVersion = owned.SourceVersion
|
|
|
+ }, owned.StorageKey);
|
|
|
+ }
|
|
|
+
|
|
|
+ private static bool NormalizePurchaseFields(Dictionary<string, object?> mapped)
|
|
|
+ {
|
|
|
+ foreach (var field in new[] { "OrderDate", "DueDate" })
|
|
|
+ {
|
|
|
+ if (!MdpPurchaseMigrationWriter.TryParseBusinessDate(TryGetString(mapped, field), out var date))
|
|
|
+ return false;
|
|
|
+ if (mapped.Remove(field))
|
|
|
+ mapped[field] = date?.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture);
|
|
|
+ }
|
|
|
+
|
|
|
+ foreach (var field in new[] { "PoNo", "PoLine", "ItemCode", "OrderQty", "SupplierCode", "Status" })
|
|
|
+ {
|
|
|
+ if (mapped.Remove(field, out var value))
|
|
|
+ mapped[field] = value;
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static bool TryMigrationLine(MdpInboundPreparedRow row, out PurchaseHandoffLine? line)
|
|
|
+ {
|
|
|
+ line = null;
|
|
|
+ var poNo = TryGetString(row.Dict, "PoNo");
|
|
|
+ var poLine = TryGetString(row.Dict, "PoLine");
|
|
|
+ var item = TryGetString(row.Dict, "ItemCode");
|
|
|
+ var supplier = TryGetString(row.Dict, "SupplierCode");
|
|
|
+ var status = TryGetString(row.Dict, "Status");
|
|
|
+ var operation = TryGetString(row.Dict, "op");
|
|
|
+ row.Dict.TryGetValue("OrderQty", out var rawQuantity);
|
|
|
+ if (string.IsNullOrWhiteSpace(poNo) || poNo.Length > 100 || poNo.Contains('#')
|
|
|
+ || string.IsNullOrWhiteSpace(poLine) || poLine.Length > 50 || poLine.Contains('#')
|
|
|
+ || string.IsNullOrWhiteSpace(item) || item.Length > 100 || supplier?.Length > 100 || status?.Length > 50
|
|
|
+ || (!string.IsNullOrWhiteSpace(operation) && !string.Equals(operation, "upsert", StringComparison.OrdinalIgnoreCase))
|
|
|
+ || !decimal.TryParse(Convert.ToString(rawQuantity, CultureInfo.InvariantCulture), NumberStyles.Float,
|
|
|
+ CultureInfo.InvariantCulture, out var quantity)
|
|
|
+ || quantity <= 0 || quantity >= 1_000_000_000_000m || decimal.Round(quantity, 6) != quantity
|
|
|
+ || !MdpPurchaseMigrationWriter.TryParseBusinessDate(TryGetString(row.Dict, "OrderDate"), out var orderDate)
|
|
|
+ || !MdpPurchaseMigrationWriter.TryParseBusinessDate(TryGetString(row.Dict, "DueDate"), out var dueDate)
|
|
|
+ || dueDate < orderDate)
|
|
|
+ return false;
|
|
|
+
|
|
|
+ line = new PurchaseHandoffLine(Guid.Empty, poNo, poLine, item, quantity, supplier, orderDate, dueDate, status, row.SourceUpdatedAt);
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+
|
|
|
+ private sealed class LegacyPurchaseStageRow
|
|
|
+ {
|
|
|
+ public long? TenantId { get; set; }
|
|
|
+ public long? FactoryId { get; set; }
|
|
|
+ public string StorageKey { get; set; } = string.Empty;
|
|
|
+ public string? SourceUpdatedAt { get; set; }
|
|
|
+ public string? SourceVersion { get; set; }
|
|
|
+ public string? RawData { get; set; }
|
|
|
+ }
|
|
|
+
|
|
|
private async Task<MdpInboundStgGuardRow> LoadGuardRowAsync(
|
|
|
string table, long tenantId, string sourceTable, string bizKey, string inboundSource, CancellationToken ct)
|
|
|
{
|
|
|
@@ -881,7 +1175,7 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
new SugarParameter("@id", existing.Id));
|
|
|
}
|
|
|
|
|
|
- private async Task MarkFailedAsync(long requestId, string error, long elapsedMs, CancellationToken ct)
|
|
|
+ private async Task MarkFailedAsync(long requestId, string error, long elapsedMs, CancellationToken ct, int status = 500)
|
|
|
{
|
|
|
try
|
|
|
{
|
|
|
@@ -889,13 +1183,13 @@ public sealed class MdpInboundReceiveService : ITransient
|
|
|
.SetColumns(r => new MdpInboundRequest
|
|
|
{
|
|
|
Status = "FAILED",
|
|
|
- HttpStatus = 500,
|
|
|
- ResultCode = 500,
|
|
|
+ HttpStatus = status,
|
|
|
+ ResultCode = status,
|
|
|
ErrorMsg = error,
|
|
|
ElapsedMs = (int)elapsedMs,
|
|
|
UpdateTime = DateTime.Now
|
|
|
})
|
|
|
- .Where(r => r.Id == requestId)
|
|
|
+ .Where(r => r.Id == requestId && r.Status != "COMMITTED")
|
|
|
.ExecuteCommandAsync(ct);
|
|
|
}
|
|
|
catch (Exception ex)
|