| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- using System.Security.Cryptography;
- using System.Text;
- using System.Text.Json;
- using System.Text.RegularExpressions;
- namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core;
- /// <summary>冻结采购字段到来源字段的映射。结构、转换规则及二级包由版本化的采购模板提供。</summary>
- public sealed class PurchaseVersionConfiguration : ISchemaRegistry
- {
- internal static IReadOnlyList<string> Fields { get; } =
- ["PoNo", "PoLine", "ItemCode", "OrderQty", "SupplierCode", "OrderDate", "DueDate", "Status", "sourceUpdatedAt"];
- private static readonly IngestContract Baseline = new PurchaseOrderSchemaRegistry().Find(PurchaseOrderSchemaRegistry.DatasetKey, PurchaseOrderSchemaRegistry.SourceVersion)!;
- private readonly IngestContract contract;
- public string MappingJson { get; }
- public IReadOnlyDictionary<string, string> Names { get; }
- public PurchaseVersionConfiguration(string dataset, string version, string mappingJson)
- {
- if (string.IsNullOrWhiteSpace(version) || string.IsNullOrWhiteSpace(mappingJson) || !Regex.IsMatch(version, @"\A[A-Za-z0-9][A-Za-z0-9._-]{0,63}\z") || mappingJson.Length > 8192)
- throw new ArgumentException("版本或映射格式无效");
- using var parsed = JsonDocument.Parse(mappingJson);
- if (parsed.RootElement.ValueKind != JsonValueKind.Object) throw new ArgumentException("映射应为字段对象");
- var names = new SortedDictionary<string, string>(StringComparer.Ordinal);
- foreach (var pair in parsed.RootElement.EnumerateObject())
- {
- if (!Fields.Contains(pair.Name) || pair.Value.ValueKind != JsonValueKind.String
- || pair.Value.GetString() is not { Length: > 0 and <= 128 } value || value.Any(char.IsControl)
- || !names.TryAdd(pair.Name, value))
- throw new ArgumentException("采购字段映射无效或重复");
- }
- foreach (var field in Fields) names.TryAdd(field, field);
- if (names.Values.Distinct(StringComparer.Ordinal).Count() != names.Count)
- throw new ArgumentException("一个来源字段不能同时映射多个采购字段");
- Names = names;
- MappingJson = JsonSerializer.Serialize(names);
- if (version == PurchaseOrderSchemaRegistry.SourceVersion && dataset == PurchaseOrderSchemaRegistry.DatasetKey)
- {
- if (names.Any(p => p.Key != p.Value)) throw new ArgumentException("内置采购 v1 已冻结,请另建版本");
- contract = Baseline;
- return;
- }
- var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(MappingJson))).ToLowerInvariant();
- contract = Baseline with
- {
- DatasetKey = dataset,
- SourceSchema = Baseline.SourceSchema with { Stamp = new SchemaStamp(version, Baseline.SourceSchema.Stamp.Sha256) },
- MappingVersion = hash,
- ConfigVersion = version,
- FieldMapJson = MappingJson
- };
- }
- public IngestContract? Find(string datasetKey, string sourceSchemaVersion) =>
- datasetKey == contract.DatasetKey && sourceSchemaVersion == contract.SourceSchema.Stamp.Version ? contract : null;
- }
|