PurchaseBatchProcessor.cs 8.1 KB

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