| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151 |
- using System.Globalization;
- using System.Text.Json;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- public static class PurchaseBatchProcessor
- {
- private static readonly PurchaseOrderSchemaRegistry Schemas = new();
- public static PurchaseBatchProcessingResult Process(PreparedIngestBatch prepared, string leaseToken)
- {
- var batch = prepared.Batch;
- var identity = batch.Identity;
- var configured = batch.Versions.FieldMapJson is string json
- ? new PurchaseVersionConfiguration(identity.DatasetKey, batch.Versions.SourceSchema.Version, json) : null;
- ISchemaRegistry registry = (ISchemaRegistry?)configured ?? Schemas;
- var reverse = configured?.Names.ToDictionary(p => p.Value,p => p.Key,StringComparer.Ordinal);
- var contract = registry.Find(identity.DatasetKey, batch.Versions.SourceSchema.Version);
- if (contract?.Snapshot() != batch.Versions)
- throw new InvalidDataException("FROZEN_PURCHASE_CONTRACT_UNAVAILABLE");
- if (batch.AcceptedRowCount != prepared.Events.Count || prepared.Events.Count is < 1 or > 100
- || PurchaseOrderSchemaRegistry.ComputeSha256(batch.Payload.Span) != batch.PayloadSha256)
- throw new InvalidDataException("RAW_BATCH_INTEGRITY_ERROR");
- var items = new List<PurchaseHandoffLine>();
- var quarantines = new List<PurchaseQuarantine>();
- var businessKeys = new HashSet<string>(StringComparer.Ordinal);
- var events = new HashSet<Guid>();
- for (var ordinal = 0; ordinal < prepared.Events.Count; ordinal++)
- {
- var rawEvent = prepared.Events[ordinal];
- if (rawEvent.BatchId != batch.BatchId || rawEvent.RecordOrdinal != ordinal || !events.Add(rawEvent.RawEventId)
- || rawEvent.PayloadLength <= 0 || rawEvent.PayloadOffset < 0
- || rawEvent.PayloadOffset > batch.Payload.Length - rawEvent.PayloadLength)
- throw new InvalidDataException("RAW_EVENT_INTEGRITY_ERROR");
- var slice = batch.Payload.Slice(rawEvent.PayloadOffset, rawEvent.PayloadLength);
- var (line, quarantine) = ConvertLine(rawEvent, slice, reverse);
- if (quarantine is not null)
- quarantines.Add(quarantine);
- else if (businessKeys.Add(line!.BusinessKey))
- items.Add(line);
- else
- quarantines.Add(new PurchaseQuarantine(rawEvent.RawEventId, "PoNo#PoLine", "DUPLICATE_ORDER_LINE"));
- }
- var package = new PurchaseHandoffPackage(batch.BatchId, leaseToken, identity.TenantId, identity.FactoryId,
- identity.SourceId, identity.DatasetId, identity.DatasetKey, identity.SourceCode, PurchaseHandoffPackage.Version,
- batch.Versions.SourceSchema.Version, batch.Versions.MappingVersion, items);
- return new PurchaseBatchProcessingResult(package, quarantines);
- }
- public static (PurchaseHandoffLine? Line, PurchaseQuarantine? Quarantine) ConvertLine(
- RawIngestEvent rawEvent, ReadOnlyMemory<byte> rowPayload, IReadOnlyDictionary<string,string>? reverse = null)
- {
- if (rawEvent.RawEventId == Guid.Empty || rawEvent.ObjectCode != "PURCHASE_ORDER"
- || rowPayload.Length != rawEvent.PayloadLength
- || PurchaseOrderSchemaRegistry.ComputeSha256(rowPayload.Span) != rawEvent.PayloadSha256)
- throw new InvalidDataException("RAW_EVENT_INTEGRITY_ERROR");
- using var row = JsonDocument.Parse(rowPayload, new JsonDocumentOptions { MaxDepth = 16 });
- var fields = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
- foreach (var property in row.RootElement.EnumerateObject())
- {
- var name = reverse == null ? property.Name : reverse.GetValueOrDefault(property.Name);
- if (name != null && PurchaseVersionConfiguration.Fields.Contains(name) && !fields.TryAdd(name, property.Value))
- return Reject(name, "DUPLICATE_FIELD");
- }
- if (!TryText(fields, "PoNo", 100, required: true, out var poNo) || poNo!.Contains('#'))
- return Reject("PoNo", "INVALID_ORDER_KEY");
- if (!TryText(fields, "PoLine", 50, required: true, out var poLine) || poLine!.Contains('#'))
- return Reject("PoLine", "INVALID_ORDER_KEY");
- if (!TryText(fields, "ItemCode", 100, required: true, out var itemCode))
- return Reject("ItemCode", fields.ContainsKey("ItemCode") ? "INVALID_ITEM_CODE" : "REQUIRED");
- if (!fields.TryGetValue("OrderQty", out var number) || number.ValueKind != JsonValueKind.Number
- || !number.TryGetDecimal(out var quantity) || quantity <= 0 || quantity >= 1_000_000_000_000m
- || !FitsQuantityPrecision(number.GetRawText()))
- return Reject("OrderQty", "INVALID_QUANTITY");
- if (!TryText(fields, "SupplierCode", 100, required: false, out var supplier))
- return Reject("SupplierCode", "INVALID_TEXT");
- if (!TryText(fields, "Status", 50, required: false, out var status))
- return Reject("Status", "INVALID_TEXT");
- if (!TryDate(fields, "OrderDate", out var orderDate))
- return Reject("OrderDate", "INVALID_BUSINESS_DATE");
- if (!TryDate(fields, "DueDate", out var dueDate) || dueDate < orderDate)
- return Reject("DueDate", "INVALID_BUSINESS_DATE");
- if (rawEvent.SourceUpdatedAt is not { Length: >= 6 } updatedAt
- || !(updatedAt.EndsWith('Z') || updatedAt[^6] is '+' or '-')
- || !fields.TryGetValue("sourceUpdatedAt", out var sourceTime) || sourceTime.ValueKind != JsonValueKind.String
- || sourceTime.GetString() != updatedAt || !sourceTime.TryGetDateTimeOffset(out _))
- return Reject("sourceUpdatedAt", "INVALID_SOURCE_TIME");
- if ($"{poNo}#{poLine}" != rawEvent.SourceBusinessKey)
- throw new InvalidDataException("RAW_BUSINESS_KEY_MISMATCH");
- return (new PurchaseHandoffLine(rawEvent.RawEventId, poNo!, poLine!, itemCode!, quantity, supplier, orderDate,
- dueDate, status, updatedAt), null);
- (PurchaseHandoffLine?, PurchaseQuarantine) Reject(string field, string reason) =>
- (null, new PurchaseQuarantine(rawEvent.RawEventId, field, reason));
- }
- private static bool TryText(Dictionary<string, JsonElement> fields, string field, int maxLength, bool required, out string? value)
- {
- value = null;
- if (!fields.TryGetValue(field, out var element) || element.ValueKind == JsonValueKind.Null)
- return !required;
- if (element.ValueKind != JsonValueKind.String)
- return false;
- value = element.GetString()!;
- return value.Length <= maxLength && (!required || !string.IsNullOrWhiteSpace(value));
- }
- private static bool TryDate(Dictionary<string, JsonElement> fields, string field, out DateTime? value)
- {
- value = null;
- if (!TryText(fields, field, 19, required: false, out var text))
- return false;
- if (text is null)
- return true;
- if (!DateTime.TryParseExact(text, "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)
- || date.Year < 1000)
- return false;
- value = date;
- return true;
- }
- private static bool FitsQuantityPrecision(ReadOnlySpan<char> number)
- {
- var exponentIndex = number.IndexOfAny('e', 'E');
- var mantissa = exponentIndex < 0 ? number : number[..exponentIndex];
- var exponent = 0;
- if (exponentIndex >= 0 && !int.TryParse(number[(exponentIndex + 1)..], NumberStyles.AllowLeadingSign,
- CultureInfo.InvariantCulture, out exponent))
- return false;
- var decimalPoint = mantissa.IndexOf('.');
- var fractionalDigits = decimalPoint < 0 ? 0 : mantissa.Length - decimalPoint - 1;
- var trailingZeroes = 0;
- for (var index = mantissa.Length - 1; index >= 0; index--)
- {
- if (mantissa[index] == '.')
- continue;
- if (mantissa[index] != '0')
- break;
- trailingZeroes++;
- }
- return (long)fractionalDigits - exponent - trailingZeroes <= 6;
- }
- }
|