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);
/// 在调用方持有范围行锁的事务中,用同一份业务对照处理两个入口。
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 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 = Hash(content);
var deleted = await db.Ado.GetIntAsync("""
SELECT COUNT(*) FROM mdp_std_purchase_order_version
WHERE tenant_id=@TenantId AND factory_id=@FactoryId AND po_no=@PoNo AND po_line=@PoLine AND is_deleted=1
""", new { scope.TenantId, scope.FactoryId, line.PoNo, line.PoLine }) > 0;
var existing = await db.Ado.SqlQuerySingleAsync(
"""
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 = deleted || (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 ObserveAsync(db, scope, writer, line, batchId, traceId, digest, result);
return result;
}
internal static async Task TakeVersionedCustodyAsync(ISqlSugarClient db, PurchaseMigrationScope scope,
PurchaseHandoffLine line, long standardId, string previousKey, string nextKey, long? pinnedStageId,
long? previousSourceId, long? previousDatasetId)
{
var args = new { scope.Id, scope.TenantId, scope.FactoryId, scope.LegacySourceCode, scope.NewSourceCode,
line.PoNo, line.PoLine, StandardId = standardId, PreviousKey = previousKey, NextKey = nextKey };
var previous = await db.Ado.SqlQuerySingleAsync("""
SELECT s.id AS Id,s.source_system AS SourceCode,s.sync_batch_id AS BatchId
FROM mdp_stg_purchase_order s JOIN mdp_std_purchase_order p
ON p.tenant_id=s.tenant_id AND p.factory_id=s.factory_id AND p.source_system=s.source_system
AND p.source_biz_key=s.source_biz_key AND p.id=@StandardId
WHERE s.tenant_id=@TenantId AND s.factory_id=@FactoryId AND s.source_system=@LegacySourceCode
AND s.source_table='S3_PURCHASE_ORDER' AND s.source_biz_key=@PreviousKey
FOR UPDATE
""", args);
if (previous is null || (pinnedStageId.HasValue && previous.Id != pinnedStageId.Value))
return null;
var inherited = await db.Ado.GetIntAsync("""
SELECT COUNT(*) FROM mdp_purchase_migration_line WHERE scope_id=@Id
AND po_no=@PoNo AND po_line=@PoLine AND stage_id=@StageId AND standard_id=@StandardId
""", new { scope.Id, line.PoNo, line.PoLine, StageId = previous.Id, StandardId = standardId }) == 1;
if (!inherited && previousSourceId.HasValue && previousDatasetId.HasValue)
{
inherited = await db.Ado.GetIntAsync("""
SELECT COUNT(*) FROM mdp_std_purchase_order_version v JOIN mdp_ingest_handoff_receipt r
ON r.batch_id=v.batch_id AND r.tenant_id=v.tenant_id AND r.factory_id=v.factory_id
AND r.dataset_id=v.dataset_id AND r.source_id=v.source_id
WHERE v.tenant_id=@TenantId AND v.factory_id=@FactoryId AND v.po_no=@PoNo AND v.po_line=@PoLine
AND v.stage_id=@StageId AND v.standard_id=@StandardId AND v.source_system=@LegacySourceCode
AND v.source_id=@SourceId AND v.dataset_id=@DatasetId
""", new { scope.TenantId, scope.FactoryId, line.PoNo, line.PoLine, StageId = previous.Id,
StandardId = standardId, scope.LegacySourceCode, SourceId = previousSourceId, DatasetId = previousDatasetId }) == 1;
}
if (!inherited && !await HasCustodyEvidenceAsync(db, scope, previous, legacy: true, MdpPurchaseMigrationStore.Unified))
return null;
var occupied = await db.Ado.GetIntAsync("""
SELECT COUNT(*) FROM mdp_stg_purchase_order WHERE tenant_id=@TenantId AND factory_id=@FactoryId
AND source_system=@NewSourceCode AND source_table='S3_PURCHASE_ORDER' AND source_biz_key=@NextKey
""", args);
if (occupied != 0)
return null;
await db.Ado.ExecuteCommandAsync("""
UPDATE mdp_stg_purchase_order SET source_system=@NewSourceCode,source_biz_key=@NextKey
WHERE id=@StageId AND tenant_id=@TenantId AND factory_id=@FactoryId
""", new { scope.NewSourceCode, NextKey = nextKey, StageId = previous.Id, scope.TenantId, scope.FactoryId });
await db.Ado.ExecuteCommandAsync("""
UPDATE mdp_std_purchase_order SET source_system=@NewSourceCode,source_biz_key=@NextKey
WHERE id=@StandardId AND tenant_id=@TenantId AND factory_id=@FactoryId
""", args);
return previous.Id;
}
internal static async Task RecordVersionedAsync(ISqlSugarClient db, PurchaseMigrationScope scope, PurchaseHandoffLine line,
string batchId, PurchaseMigrationLineResult result, string? traceId = null)
{
var digest = Hash(OrderContent.From(line));
if (result.Status == "WRITTEN" && result.StageId is long stageId && result.StandardId is long standardId)
{
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))
ON DUPLICATE KEY UPDATE content_sha256=VALUES(content_sha256),stage_id=VALUES(stage_id),standard_id=VALUES(standard_id)
""", new { ScopeId = scope.Id, line.PoNo, line.PoLine, Digest = digest, StageId = stageId, StandardId = standardId });
}
await ObserveAsync(db, scope, MdpPurchaseMigrationStore.Unified, line, batchId, traceId ?? line.RawEventId.ToString("D"),
digest, result);
}
private static string Hash(OrderContent content) =>
Convert.ToHexString(SHA256.HashData(JsonSerializer.SerializeToUtf8Bytes(content))).ToLowerInvariant();
private static Task ObserveAsync(ISqlSugarClient db, PurchaseMigrationScope scope, string writer,
PurchaseHandoffLine line, string batchId, string traceId, string digest, PurchaseMigrationLineResult result) =>
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 { ScopeId = scope.Id, Writer = writer, TraceId = traceId, BatchId = batchId, line.PoNo, line.PoLine,
Digest = digest, result.Status, result.StageId, result.StandardId });
private static async Task 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(
"""
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(
"""
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 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;
}
}