PurchaseBatchProcessor.cs 10 KB

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