PurchaseBatchProcessor.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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.ConfigPackageJson ?? 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, configured?.Package);
  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. GovernancePackage? governance = null)
  55. {
  56. if (rawEvent.RawEventId == Guid.Empty || rawEvent.ObjectCode != "PURCHASE_ORDER"
  57. || rowPayload.Length != rawEvent.PayloadLength
  58. || PurchaseOrderSchemaRegistry.ComputeSha256(rowPayload.Span) != rawEvent.PayloadSha256)
  59. throw new InvalidDataException("RAW_EVENT_INTEGRITY_ERROR");
  60. using var row = JsonDocument.Parse(rowPayload, new JsonDocumentOptions { MaxDepth = 16 });
  61. if (verifiedRelational && row.RootElement.TryGetProperty("_mdpConversionError", out var failed)
  62. && failed.ValueKind == JsonValueKind.Array && failed.GetArrayLength() > 0)
  63. return Reject("sourceType", "RELATIONAL_CONVERSION_FAILED");
  64. var fields = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
  65. if (governance != null)
  66. {
  67. var keysOnly = verifiedRelational && row.RootElement.TryGetProperty("_mdpDeleted", out var flag)
  68. && flag.ValueKind == JsonValueKind.True;
  69. if (governance.Apply(row.RootElement, fields, keysOnly) is { } issue)
  70. return Reject(issue.Field, issue.Reason);
  71. }
  72. else
  73. foreach (var property in row.RootElement.EnumerateObject())
  74. {
  75. var name = reverse == null ? property.Name : reverse.GetValueOrDefault(property.Name);
  76. if (name != null && PurchaseVersionConfiguration.Fields.Contains(name) && !fields.TryAdd(name, property.Value))
  77. return Reject(name, "DUPLICATE_FIELD");
  78. }
  79. if (!TryText(fields, "PoNo", 100, required: true, out var poNo) || poNo!.Contains('#'))
  80. return Reject("PoNo", "INVALID_ORDER_KEY");
  81. if (!TryText(fields, "PoLine", 50, required: true, out var poLine) || poLine!.Contains('#'))
  82. return Reject("PoLine", "INVALID_ORDER_KEY");
  83. PurchaseSourceChange? change = null;
  84. if (verifiedRelational && sourceGeneration is { } generation)
  85. {
  86. if (generation <= 0 || !row.RootElement.TryGetProperty("_mdpChangeVersion", out var revision)
  87. || revision.ValueKind != JsonValueKind.Number || !revision.TryGetInt64(out var version) || version <= 0
  88. || !row.RootElement.TryGetProperty("_mdpDeleted", out var deleted)
  89. || deleted.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
  90. return Reject("sourceVersion", "RELATIONAL_CHANGE_METADATA_INVALID");
  91. change = new(generation, version, deleted.GetBoolean());
  92. if (change.Deleted)
  93. return (new PurchaseHandoffLine(rawEvent.RawEventId, poNo!, poLine!, "", 0m, null, null,
  94. null, null, rawEvent.SourceUpdatedAt ?? "") { SourceChange = change }, null);
  95. }
  96. if (!TryText(fields, "ItemCode", 100, required: true, out var itemCode))
  97. return Reject("ItemCode", fields.ContainsKey("ItemCode") ? "INVALID_ITEM_CODE" : "REQUIRED");
  98. if (!fields.TryGetValue("OrderQty", out var number) || number.ValueKind != JsonValueKind.Number
  99. || !number.TryGetDecimal(out var quantity) || quantity <= 0 || quantity >= 1_000_000_000_000m
  100. || !FitsQuantityPrecision(number.GetRawText()))
  101. return Reject("OrderQty", "INVALID_QUANTITY");
  102. if (!TryText(fields, "SupplierCode", 100, required: false, out var supplier))
  103. return Reject("SupplierCode", "INVALID_TEXT");
  104. if (!TryText(fields, "Status", 50, required: false, out var status))
  105. return Reject("Status", "INVALID_TEXT");
  106. if (!TryDate(fields, "OrderDate", out var orderDate))
  107. return Reject("OrderDate", "INVALID_BUSINESS_DATE");
  108. if (!TryDate(fields, "DueDate", out var dueDate) || dueDate < orderDate)
  109. return Reject("DueDate", "INVALID_BUSINESS_DATE");
  110. if (rawEvent.SourceUpdatedAt is not { Length: >= 6 } updatedAt
  111. || !(updatedAt.EndsWith('Z') || updatedAt[^6] is '+' or '-')
  112. || !fields.TryGetValue("sourceUpdatedAt", out var sourceTime) || sourceTime.ValueKind != JsonValueKind.String
  113. || sourceTime.GetString() != updatedAt || !sourceTime.TryGetDateTimeOffset(out var sourceInstant))
  114. return Reject("sourceUpdatedAt", "INVALID_SOURCE_TIME");
  115. if (versionedApi)
  116. {
  117. if (sourceInstant.UtcTicks <= 0)
  118. return Reject("sourceUpdatedAt", "INVALID_SOURCE_TIME");
  119. change = new PurchaseSourceChange(0, sourceInstant.UtcTicks, false);
  120. }
  121. if ($"{poNo}#{poLine}" != rawEvent.SourceBusinessKey)
  122. throw new InvalidDataException("RAW_BUSINESS_KEY_MISMATCH");
  123. return (new PurchaseHandoffLine(rawEvent.RawEventId, poNo!, poLine!, itemCode!, quantity, supplier, orderDate,
  124. dueDate, status, updatedAt) { SourceChange = change }, null);
  125. (PurchaseHandoffLine?, PurchaseQuarantine) Reject(string field, string reason) =>
  126. (null, new PurchaseQuarantine(rawEvent.RawEventId, field, reason));
  127. }
  128. private static bool TryText(Dictionary<string, JsonElement> fields, string field, int maxLength, bool required, out string? value)
  129. {
  130. value = null;
  131. if (!fields.TryGetValue(field, out var element) || element.ValueKind == JsonValueKind.Null)
  132. return !required;
  133. if (element.ValueKind != JsonValueKind.String)
  134. return false;
  135. value = element.GetString()!;
  136. return value.Length <= maxLength && (!required || !string.IsNullOrWhiteSpace(value));
  137. }
  138. private static bool TryDate(Dictionary<string, JsonElement> fields, string field, out DateTime? value)
  139. {
  140. value = null;
  141. if (!TryText(fields, field, 19, required: false, out var text))
  142. return false;
  143. if (text is null)
  144. return true;
  145. if (!DateTime.TryParseExact(text, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
  146. || date.Year < 1000)
  147. return false;
  148. value = date;
  149. return true;
  150. }
  151. private static bool FitsQuantityPrecision(ReadOnlySpan<char> number)
  152. {
  153. var exponentIndex = number.IndexOfAny('e', 'E');
  154. var mantissa = exponentIndex < 0 ? number : number[..exponentIndex];
  155. var exponent = 0;
  156. if (exponentIndex >= 0 && !int.TryParse(number[(exponentIndex + 1)..], NumberStyles.AllowLeadingSign,
  157. CultureInfo.InvariantCulture, out exponent))
  158. return false;
  159. var decimalPoint = mantissa.IndexOf('.');
  160. var fractionalDigits = decimalPoint < 0 ? 0 : mantissa.Length - decimalPoint - 1;
  161. var trailingZeroes = 0;
  162. for (var index = mantissa.Length - 1; index >= 0; index--)
  163. {
  164. if (mantissa[index] == '.')
  165. continue;
  166. if (mantissa[index] != '0')
  167. break;
  168. trailingZeroes++;
  169. }
  170. return (long)fractionalDigits - exponent - trailingZeroes <= 6;
  171. }
  172. }