| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267 |
- using System.Globalization;
- using System.Security.Cryptography;
- using System.Text.Json;
- using Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.UnifiedIngress;
- internal sealed record PurchaseMigrationLineResult(string Status, long? StageId, long? StandardId);
- /// <summary>在调用方持有范围行锁的事务中,用同一份业务对照处理两个入口。</summary>
- internal static class MdpPurchaseMigrationWriter
- {
- private static readonly string[] LocalDateFormats =
- ["yyyy-MM-dd'T'HH:mm:ss", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFF", "yyyy-MM-dd HH:mm:ss.FFFFFFF"];
- private static readonly string[] OffsetDateFormats =
- ["yyyy-MM-dd'T'HH:mm:sszzz", "yyyy-MM-dd HH:mm:sszzz", "yyyy-MM-dd'T'HH:mm:ss.FFFFFFFzzz", "yyyy-MM-dd HH:mm:ss.FFFFFFFzzz"];
- internal static async Task<PurchaseMigrationLineResult> WriteAsync(
- ISqlSugarClient db, PurchaseMigrationScope scope, string writer, PurchaseHandoffLine line, string batchId, string traceId)
- {
- MdpPurchaseMigrationStore.RequireWriter(scope, writer);
- var identity = new { ScopeId = scope.Id, line.PoNo, line.PoLine };
- var content = OrderContent.From(line);
- var digest = Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(content))).ToLowerInvariant();
- var existing = await db.Ado.SqlQuerySingleAsync<LedgerRow>(
- """
- SELECT content_sha256 AS Digest, stage_id AS StageId, standard_id AS StandardId
- FROM mdp_purchase_migration_line WHERE scope_id=@ScopeId AND po_no=@PoNo AND po_line=@PoLine FOR UPDATE
- """, identity);
- var result = existing is not null && existing.Digest != digest
- ? new PurchaseMigrationLineResult("CONFLICT", null, null)
- : await ResolveAsync(db, scope, writer, line, batchId, traceId, content, existing);
- if (result.StageId is long stageId && result.StandardId is long standardId)
- {
- if (existing is null)
- await db.Ado.ExecuteCommandAsync(
- """
- INSERT INTO mdp_purchase_migration_line
- (scope_id, po_no, po_line, content_sha256, stage_id, standard_id, created_at)
- VALUES (@ScopeId, @PoNo, @PoLine, @Digest, @StageId, @StandardId, UTC_TIMESTAMP(6))
- """, new { identity.ScopeId, line.PoNo, line.PoLine, Digest = digest, StageId = stageId, StandardId = standardId });
- else if (existing.StandardId != standardId)
- await db.Ado.ExecuteCommandAsync(
- """
- UPDATE mdp_purchase_migration_line SET standard_id=@StandardId
- WHERE scope_id=@ScopeId AND po_no=@PoNo AND po_line=@PoLine AND stage_id=@StageId
- """, new { identity.ScopeId, line.PoNo, line.PoLine, StageId = stageId, StandardId = standardId });
- }
- await db.Ado.ExecuteCommandAsync(
- """
- INSERT INTO mdp_purchase_migration_observation
- (scope_id, writer, trace_id, batch_id, po_no, po_line, content_sha256, resolution, stage_id, standard_id, created_at)
- VALUES (@ScopeId,@Writer,@TraceId,@BatchId,@PoNo,@PoLine,@Digest,@Status,@StageId,@StandardId,UTC_TIMESTAMP(6))
- """, new { identity.ScopeId, Writer = writer, TraceId = traceId, BatchId = batchId, line.PoNo, line.PoLine,
- Digest = digest, result.Status, result.StageId, result.StandardId });
- return result;
- }
- private static async Task<PurchaseMigrationLineResult> ResolveAsync(
- ISqlSugarClient db, PurchaseMigrationScope scope, string writer, PurchaseHandoffLine line, string batchId, string traceId,
- OrderContent content, LedgerRow? existing)
- {
- var scopedKey = FormattableString.Invariant($"{scope.TenantId}#{scope.FactoryId}#{line.BusinessKey}");
- var stageCandidates = await db.Ado.SqlQueryAsync<StoredStage>(
- """
- SELECT id AS Id, factory_id AS FactoryId, source_system AS SourceCode, source_biz_key AS BusinessKey,
- sync_batch_id AS BatchId, raw_data AS RawData
- FROM mdp_stg_purchase_order
- WHERE tenant_id=@TenantId AND source_table='S3_PURCHASE_ORDER'
- AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0)
- AND source_biz_key IN (@LegacyKey,@ScopedKey)
- FOR SHARE
- """, new { scope.TenantId, scope.FactoryId, LegacyKey = line.BusinessKey, ScopedKey = scopedKey });
- var standards = await db.Ado.SqlQueryAsync<StoredStandard>(
- """
- SELECT id AS Id, factory_id AS FactoryId, source_system AS SourceCode, source_biz_key AS BusinessKey,
- sync_batch_id AS BatchId, po_no AS PoNo, po_line AS PoLine, item_code AS ItemCode, supplier_code AS SupplierCode,
- order_qty AS OrderQty, order_date AS OrderDate, due_date AS DueDate, status AS Status
- FROM mdp_std_purchase_order WHERE tenant_id=@TenantId AND po_no=@PoNo AND po_line=@PoLine
- AND (factory_id=@FactoryId OR factory_id IS NULL OR factory_id=0
- OR (factory_id=1 AND source_system=@LegacySourceCode AND source_biz_key=@LegacyKey AND sync_batch_id=@StageBatch))
- FOR UPDATE
- """, new { scope.TenantId, scope.FactoryId, line.PoNo, line.PoLine, scope.LegacySourceCode,
- LegacyKey = line.BusinessKey, StageBatch = stageCandidates.Count == 1 ? stageCandidates[0].BatchId : null });
- if (standards.Count > 1)
- return new("CONFLICT", null, null);
- var standard = standards.SingleOrDefault();
- if (stageCandidates.Count == 0 && standard is null && existing is null)
- {
- var legacy = writer == MdpPurchaseMigrationStore.Legacy;
- var package = new PurchaseHandoffPackage(Guid.Empty, string.Empty, scope.TenantId, scope.FactoryId, scope.NewSourceId,
- scope.DatasetId, PurchaseOrderSchemaRegistry.DatasetKey, legacy ? scope.LegacySourceCode : scope.NewSourceCode,
- PurchaseHandoffPackage.Version, PurchaseOrderSchemaRegistry.SourceVersion, "po-map-v1", [line]);
- return await MdpPurchaseHandoffService.WriteLineAsync(db, package, batchId, line, scopedKey, traceId);
- }
- var conflict = new PurchaseMigrationLineResult("CONFLICT", null, null);
- if (stageCandidates is not [var stage] || stage.FactoryId != scope.FactoryId
- || (stage.SourceCode != scope.LegacySourceCode && stage.SourceCode != scope.NewSourceCode)
- || (existing is not null && stage.Id != existing.StageId) || !stage.Matches(content))
- return conflict;
- var oldStage = string.Equals(stage.SourceCode, scope.LegacySourceCode, StringComparison.Ordinal);
- if (existing is null && !await HasCustodyEvidenceAsync(db, scope, stage, oldStage, writer))
- return conflict;
- if (standard is null)
- {
- var standardId = await MdpPurchaseHandoffService.InsertStandardAsync(db, scope.TenantId, scope.FactoryId,
- stage.SourceCode, stage.BusinessKey, stage.BatchId, line);
- return standardId.HasValue ? new("WRITTEN", stage.Id, standardId) : conflict;
- }
- if ((existing is not null && standard.Id != existing.StandardId)
- || standard.SourceCode != stage.SourceCode || standard.BusinessKey != stage.BusinessKey
- || standard.BatchId != stage.BatchId || standard.Content() != content)
- return conflict;
- if (standard.FactoryId != scope.FactoryId)
- {
- // 老投影用过默认工厂。只有证据已证明同一授权、贴源行及原批次时才认领。
- if (!oldStage || standard.FactoryId != 1)
- return conflict;
- await db.Ado.ExecuteCommandAsync(
- """
- UPDATE mdp_std_purchase_order SET factory_id=@FactoryId
- WHERE id=@Id AND tenant_id=@TenantId AND factory_id=1
- AND source_system=@SourceCode AND sync_batch_id=@BatchId
- """, new { scope.FactoryId, standard.Id, scope.TenantId, stage.SourceCode, stage.BatchId });
- }
- return new("REUSED", stage.Id, standard.Id);
- }
- private static async Task<bool> HasCustodyEvidenceAsync(
- ISqlSugarClient db, PurchaseMigrationScope scope, StoredStage stage, bool legacy, string writer)
- {
- if (legacy && writer == MdpPurchaseMigrationStore.Unified)
- return await db.Ado.GetIntAsync(
- """
- SELECT COUNT(*) FROM mdp_purchase_legacy_custody
- WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND source_code=@SourceCode AND sync_batch_id=@BatchId
- """, new { scope.TenantId, scope.FactoryId, stage.SourceCode, stage.BatchId }) == 1;
- if (legacy)
- return await db.Ado.GetIntAsync(
- """
- SELECT COUNT(*)
- FROM mdp_inbound_request r
- JOIN mdp_inbound_grant g ON g.tenant_id=r.tenant_id AND g.access_key=r.access_key
- AND g.entity_code=r.entity_code AND g.source_code=@SourceCode AND g.factory_id=@FactoryId
- WHERE r.tenant_id=@TenantId AND r.entity_code='S3_PURCHASE_ORDER'
- AND r.sync_batch_id=@BatchId AND r.status='COMMITTED' AND r.accepted>0
- """, new { scope.TenantId, scope.FactoryId, stage.SourceCode, stage.BatchId }) == 1;
- return await db.Ado.GetIntAsync(
- """
- SELECT COUNT(*)
- FROM mdp_ingest_handoff_receipt r
- JOIN JSON_TABLE(r.line_results, '$[*]' COLUMNS (stage_id BIGINT PATH '$.stageId' NULL ON EMPTY NULL ON ERROR)) line
- ON line.stage_id=@StageId
- WHERE r.batch_id=@BatchId AND r.tenant_id=@TenantId AND r.factory_id=@FactoryId
- AND r.dataset_id=@DatasetId AND r.source_id=@NewSourceId
- """, new { scope.TenantId, scope.FactoryId, scope.DatasetId, scope.NewSourceId, StageId = stage.Id, stage.BatchId }) == 1;
- }
- internal static bool TryParseBusinessDate(string? text, out DateTime? result)
- {
- result = null;
- if (string.IsNullOrWhiteSpace(text))
- return true;
- DateTime date;
- if (text.EndsWith('Z'))
- text = text[..^1] + "+00:00";
- if (DateTimeOffset.TryParseExact(text, OffsetDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out var offset))
- {
- var ticks = offset.UtcTicks + TimeSpan.FromHours(8).Ticks;
- if (ticks > DateTime.MaxValue.Ticks)
- return false;
- date = new DateTime(ticks);
- }
- else if (!DateTime.TryParseExact(text, LocalDateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
- return false;
- if (date.Year < 1000)
- return false;
- result = new DateTime(date.Ticks - date.Ticks % TimeSpan.TicksPerSecond, DateTimeKind.Unspecified);
- return true;
- }
- private sealed record OrderContent(string PoNo, string PoLine, string ItemCode, string? SupplierCode,
- string Quantity, DateTime? OrderDate, DateTime? DueDate, string? Status)
- {
- public static OrderContent From(PurchaseHandoffLine line) =>
- new(line.PoNo, line.PoLine, line.ItemCode, line.SupplierCode, QuantityOf(line.OrderQty),
- Clock(line.OrderDate), Clock(line.DueDate), line.Status);
- public static string QuantityOf(decimal quantity) => quantity.ToString("0.############################", CultureInfo.InvariantCulture);
- private static DateTime? Clock(DateTime? date) =>
- date.HasValue ? DateTime.SpecifyKind(date.Value, DateTimeKind.Unspecified) : null;
- }
- private sealed class LedgerRow
- {
- public string Digest { get; set; } = string.Empty;
- public long StageId { get; set; }
- public long StandardId { get; set; }
- }
- private sealed class StoredStage
- {
- public long Id { get; set; }
- public long? FactoryId { get; set; }
- public string SourceCode { get; set; } = string.Empty;
- public string BusinessKey { get; set; } = string.Empty;
- public string BatchId { get; set; } = string.Empty;
- public string RawData { get; set; } = string.Empty;
- public bool Matches(OrderContent expected)
- {
- try
- {
- using var json = JsonDocument.Parse(RawData);
- var row = json.RootElement;
- if (!row.TryGetProperty("OrderQty", out var qty)
- || !decimal.TryParse(qty.ValueKind == JsonValueKind.String ? qty.GetString() : qty.GetRawText(),
- NumberStyles.Float, CultureInfo.InvariantCulture, out var quantity)
- || !TryParseBusinessDate(Text("OrderDate"), out var orderDate)
- || !TryParseBusinessDate(Text("DueDate"), out var dueDate))
- return false;
- return new OrderContent(Text("PoNo") ?? "", Text("PoLine") ?? "", Text("ItemCode") ?? "", Text("SupplierCode"),
- OrderContent.QuantityOf(quantity), orderDate, dueDate, Text("Status")) == expected;
- string? Text(string name) => row.TryGetProperty(name, out var item) && item.ValueKind == JsonValueKind.String
- ? item.GetString() : null;
- }
- catch (JsonException)
- {
- return false;
- }
- }
- }
- private sealed class StoredStandard
- {
- public long Id { get; set; }
- public long? FactoryId { get; set; }
- public string SourceCode { get; set; } = string.Empty;
- public string BusinessKey { get; set; } = string.Empty;
- public string BatchId { get; set; } = string.Empty;
- public string PoNo { get; set; } = string.Empty;
- public string PoLine { get; set; } = string.Empty;
- public string ItemCode { get; set; } = string.Empty;
- public string? SupplierCode { get; set; }
- public decimal? OrderQty { get; set; }
- public DateTime? OrderDate { get; set; }
- public DateTime? DueDate { get; set; }
- public string? Status { get; set; }
- public OrderContent? Content() => OrderQty.HasValue
- ? new(PoNo, PoLine, ItemCode, SupplierCode, OrderContent.QuantityOf(OrderQty.Value), OrderDate, DueDate, Status)
- : null;
- }
- }
|