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(); var quarantines = new List(); var businessKeys = new HashSet(StringComparer.Ordinal); var events = new HashSet(); 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 rowPayload, IReadOnlyDictionary? 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(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 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 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 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; } }