PurchaseBatchProcessor.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. using System.Globalization;
  2. using System.Text.Json;
  3. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  4. public static class PurchaseBatchProcessor
  5. {
  6. private static readonly PurchaseOrderSchemaRegistry Schemas = new();
  7. public static PurchaseBatchProcessingResult Process(PreparedIngestBatch prepared, string leaseToken)
  8. {
  9. var batch = prepared.Batch;
  10. var identity = batch.Identity;
  11. var configured = batch.Versions.FieldMapJson is string json
  12. ? new PurchaseVersionConfiguration(identity.DatasetKey, batch.Versions.SourceSchema.Version, json) : null;
  13. ISchemaRegistry registry = (ISchemaRegistry?)configured ?? Schemas;
  14. var reverse = configured?.Names.ToDictionary(p => p.Value,p => p.Key,StringComparer.Ordinal);
  15. var contract = registry.Find(identity.DatasetKey, batch.Versions.SourceSchema.Version);
  16. if (contract?.Snapshot() != batch.Versions)
  17. throw new InvalidDataException("FROZEN_PURCHASE_CONTRACT_UNAVAILABLE");
  18. if (batch.AcceptedRowCount != prepared.Events.Count || prepared.Events.Count is < 1 or > 100
  19. || PurchaseOrderSchemaRegistry.ComputeSha256(batch.Payload.Span) != batch.PayloadSha256)
  20. throw new InvalidDataException("RAW_BATCH_INTEGRITY_ERROR");
  21. var items = new List<PurchaseHandoffLine>();
  22. var quarantines = new List<PurchaseQuarantine>();
  23. var businessKeys = new HashSet<(string Key, long? Version)>();
  24. var events = new HashSet<Guid>();
  25. var verifiedRelational = batch.SourceWindow?.Watermark == IngestSourceWindow.VerifiedRelationalSnapshot;
  26. var generation = verifiedRelational ? batch.SourceWindow?.SourceGeneration : null;
  27. for (var ordinal = 0; ordinal < prepared.Events.Count; ordinal++)
  28. {
  29. var rawEvent = prepared.Events[ordinal];
  30. if (rawEvent.BatchId != batch.BatchId || rawEvent.RecordOrdinal != ordinal || !events.Add(rawEvent.RawEventId)
  31. || rawEvent.PayloadLength <= 0 || rawEvent.PayloadOffset < 0
  32. || rawEvent.PayloadOffset > batch.Payload.Length - rawEvent.PayloadLength)
  33. throw new InvalidDataException("RAW_EVENT_INTEGRITY_ERROR");
  34. var slice = batch.Payload.Slice(rawEvent.PayloadOffset, rawEvent.PayloadLength);
  35. var (line, quarantine) = ConvertLine(rawEvent, slice, reverse, verifiedRelational, generation);
  36. if (quarantine is not null)
  37. quarantines.Add(quarantine);
  38. else if (businessKeys.Add((line!.BusinessKey, line.SourceChange?.Version)))
  39. items.Add(line);
  40. else
  41. quarantines.Add(new PurchaseQuarantine(rawEvent.RawEventId, "PoNo#PoLine", "DUPLICATE_ORDER_LINE"));
  42. }
  43. var package = new PurchaseHandoffPackage(batch.BatchId, leaseToken, identity.TenantId, identity.FactoryId,
  44. identity.SourceId, identity.DatasetId, identity.DatasetKey, identity.SourceCode,
  45. generation.HasValue ? PurchaseHandoffPackage.RelationalChangeVersion : PurchaseHandoffPackage.Version,
  46. batch.Versions.SourceSchema.Version, batch.Versions.MappingVersion, items);
  47. return new PurchaseBatchProcessingResult(package, quarantines);
  48. }
  49. public static (PurchaseHandoffLine? Line, PurchaseQuarantine? Quarantine) ConvertLine(
  50. RawIngestEvent rawEvent, ReadOnlyMemory<byte> rowPayload, IReadOnlyDictionary<string,string>? reverse = null,
  51. bool verifiedRelational = false, long? sourceGeneration = null)
  52. {
  53. if (rawEvent.RawEventId == Guid.Empty || rawEvent.ObjectCode != "PURCHASE_ORDER"
  54. || rowPayload.Length != rawEvent.PayloadLength
  55. || PurchaseOrderSchemaRegistry.ComputeSha256(rowPayload.Span) != rawEvent.PayloadSha256)
  56. throw new InvalidDataException("RAW_EVENT_INTEGRITY_ERROR");
  57. using var row = JsonDocument.Parse(rowPayload, new JsonDocumentOptions { MaxDepth = 16 });
  58. if (verifiedRelational && row.RootElement.TryGetProperty("_mdpConversionError", out var failed)
  59. && failed.ValueKind == JsonValueKind.Array && failed.GetArrayLength() > 0)
  60. return Reject("sourceType", "RELATIONAL_CONVERSION_FAILED");
  61. var fields = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
  62. foreach (var property in row.RootElement.EnumerateObject())
  63. {
  64. var name = reverse == null ? property.Name : reverse.GetValueOrDefault(property.Name);
  65. if (name != null && PurchaseVersionConfiguration.Fields.Contains(name) && !fields.TryAdd(name, property.Value))
  66. return Reject(name, "DUPLICATE_FIELD");
  67. }
  68. if (!TryText(fields, "PoNo", 100, required: true, out var poNo) || poNo!.Contains('#'))
  69. return Reject("PoNo", "INVALID_ORDER_KEY");
  70. if (!TryText(fields, "PoLine", 50, required: true, out var poLine) || poLine!.Contains('#'))
  71. return Reject("PoLine", "INVALID_ORDER_KEY");
  72. PurchaseSourceChange? change = null;
  73. if (verifiedRelational && sourceGeneration is { } generation)
  74. {
  75. if (generation <= 0 || !row.RootElement.TryGetProperty("_mdpChangeVersion", out var revision)
  76. || revision.ValueKind != JsonValueKind.Number || !revision.TryGetInt64(out var version) || version <= 0
  77. || !row.RootElement.TryGetProperty("_mdpDeleted", out var deleted)
  78. || deleted.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
  79. return Reject("sourceVersion", "RELATIONAL_CHANGE_METADATA_INVALID");
  80. change = new(generation, version, deleted.GetBoolean());
  81. if (change.Deleted)
  82. return (new PurchaseHandoffLine(rawEvent.RawEventId, poNo!, poLine!, "", 0m, null, null,
  83. null, null, rawEvent.SourceUpdatedAt ?? "") { SourceChange = change }, null);
  84. }
  85. if (!TryText(fields, "ItemCode", 100, required: true, out var itemCode))
  86. return Reject("ItemCode", fields.ContainsKey("ItemCode") ? "INVALID_ITEM_CODE" : "REQUIRED");
  87. if (!fields.TryGetValue("OrderQty", out var number) || number.ValueKind != JsonValueKind.Number
  88. || !number.TryGetDecimal(out var quantity) || quantity <= 0 || quantity >= 1_000_000_000_000m
  89. || !FitsQuantityPrecision(number.GetRawText()))
  90. return Reject("OrderQty", "INVALID_QUANTITY");
  91. if (!TryText(fields, "SupplierCode", 100, required: false, out var supplier))
  92. return Reject("SupplierCode", "INVALID_TEXT");
  93. if (!TryText(fields, "Status", 50, required: false, out var status))
  94. return Reject("Status", "INVALID_TEXT");
  95. if (!TryDate(fields, "OrderDate", out var orderDate))
  96. return Reject("OrderDate", "INVALID_BUSINESS_DATE");
  97. if (!TryDate(fields, "DueDate", out var dueDate) || dueDate < orderDate)
  98. return Reject("DueDate", "INVALID_BUSINESS_DATE");
  99. if (rawEvent.SourceUpdatedAt is not { Length: >= 6 } updatedAt
  100. || !(updatedAt.EndsWith('Z') || updatedAt[^6] is '+' or '-')
  101. || !fields.TryGetValue("sourceUpdatedAt", out var sourceTime) || sourceTime.ValueKind != JsonValueKind.String
  102. || sourceTime.GetString() != updatedAt || !sourceTime.TryGetDateTimeOffset(out _))
  103. return Reject("sourceUpdatedAt", "INVALID_SOURCE_TIME");
  104. if ($"{poNo}#{poLine}" != rawEvent.SourceBusinessKey)
  105. throw new InvalidDataException("RAW_BUSINESS_KEY_MISMATCH");
  106. return (new PurchaseHandoffLine(rawEvent.RawEventId, poNo!, poLine!, itemCode!, quantity, supplier, orderDate,
  107. dueDate, status, updatedAt) { SourceChange = change }, null);
  108. (PurchaseHandoffLine?, PurchaseQuarantine) Reject(string field, string reason) =>
  109. (null, new PurchaseQuarantine(rawEvent.RawEventId, field, reason));
  110. }
  111. private static bool TryText(Dictionary<string, JsonElement> fields, string field, int maxLength, bool required, out string? value)
  112. {
  113. value = null;
  114. if (!fields.TryGetValue(field, out var element) || element.ValueKind == JsonValueKind.Null)
  115. return !required;
  116. if (element.ValueKind != JsonValueKind.String)
  117. return false;
  118. value = element.GetString()!;
  119. return value.Length <= maxLength && (!required || !string.IsNullOrWhiteSpace(value));
  120. }
  121. private static bool TryDate(Dictionary<string, JsonElement> fields, string field, out DateTime? value)
  122. {
  123. value = null;
  124. if (!TryText(fields, field, 19, required: false, out var text))
  125. return false;
  126. if (text is null)
  127. return true;
  128. if (!DateTime.TryParseExact(text, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
  129. || date.Year < 1000)
  130. return false;
  131. value = date;
  132. return true;
  133. }
  134. private static bool FitsQuantityPrecision(ReadOnlySpan<char> number)
  135. {
  136. var exponentIndex = number.IndexOfAny('e', 'E');
  137. var mantissa = exponentIndex < 0 ? number : number[..exponentIndex];
  138. var exponent = 0;
  139. if (exponentIndex >= 0 && !int.TryParse(number[(exponentIndex + 1)..], NumberStyles.AllowLeadingSign,
  140. CultureInfo.InvariantCulture, out exponent))
  141. return false;
  142. var decimalPoint = mantissa.IndexOf('.');
  143. var fractionalDigits = decimalPoint < 0 ? 0 : mantissa.Length - decimalPoint - 1;
  144. var trailingZeroes = 0;
  145. for (var index = mantissa.Length - 1; index >= 0; index--)
  146. {
  147. if (mantissa[index] == '.')
  148. continue;
  149. if (mantissa[index] != '0')
  150. break;
  151. trailingZeroes++;
  152. }
  153. return (long)fractionalDigits - exponent - trailingZeroes <= 6;
  154. }
  155. }