using System.Collections.ObjectModel; using System.Globalization; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core; public sealed record GovernanceRule(string Target, string Source, string Operation = "copy", string? DateFormat = null, string? TimeZone = null, decimal? Factor = null, int? Scale = null, Dictionary? Values = null, string? InputType = null); public sealed record GovernanceField(string Name, string Type, bool Required = false, bool Key = false); public sealed record GovernanceIssue(string Field, string Reason); public sealed class GovernancePackage { public const string Format = "mdp-governance-v1"; public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, MaxDepth = 24 }; public static IReadOnlyList PurchaseFields { get; } = [ new("PoNo", "string", true, true), new("PoLine", "string", true, true), new("ItemCode", "string", true), new("OrderQty", "number", true), new("SupplierCode", "string"), new("OrderDate", "string"), new("DueDate", "string"), new("Status", "string"), new("sourceUpdatedAt", "string", true) ]; private sealed record Document(string Format, GovernanceRule[] Rules, JsonElement[]? Masters = null, string? Template = null); private sealed record Compiled(GovernanceField Field, GovernanceRule Rule, TimeZoneInfo? Zone); private readonly Dictionary rules; private readonly string[] keyOrder; public string Json { get; } public string Digest { get; } public IReadOnlyDictionary Names { get; } private GovernancePackage(Document input, IReadOnlyList fields) { Require(input.Format == Format && input.Rules is { Length: <= 64 } && (input.Template == null || IsName(input.Template, 100)), "配置包格式或规则数无效"); var supplied = new Dictionary(StringComparer.Ordinal); foreach (var rule in input.Rules!) { Require(rule is not null && IsName(rule.Target) && IsName(rule.Source) && fields.Any(f => f.Name == rule.Target) && supplied.TryAdd(rule.Target, rule), "映射字段不存在或重复"); } keyOrder = fields.Where(x => x.Key).Select(x => x.Name).ToArray(); rules = new(StringComparer.Ordinal); foreach (var field in fields.OrderBy(x => x.Name, StringComparer.Ordinal)) { var rule = supplied.GetValueOrDefault(field.Name) ?? new(field.Name, field.Name); rules.Add(field.Name, Compile(field, rule)); } Require(rules.Values.GroupBy(x => x.Rule.Source, StringComparer.Ordinal) .All(g => g.Select(x => EffectiveInputType(x)).Distinct().Count() == 1), "同一来源字段的类型声明不一致"); var names = rules.ToDictionary(x => x.Key, x => x.Value.Rule.Source, StringComparer.Ordinal); Require(names.Values.Distinct(StringComparer.Ordinal).Count() == names.Count, "一个来源字段不能同时映射多个目标字段"); Names = new ReadOnlyDictionary(names); // Keep the canonical empty member for compatibility with the configuration package format. Require(input.Masters is null or { Length: 0 }, "配置包当前只接受字段转换规则"); Json = JsonSerializer.Serialize(new Document(Format, rules.Values.Select(x => x.Rule).ToArray(), [], input.Template), JsonOptions); Require(Encoding.UTF8.GetByteCount(Json) <= 60000, "配置包过大"); Digest = Hash(Json); } public static GovernancePackage Parse(string json, IReadOnlyList fields) { Require(Encoding.UTF8.GetByteCount(json) <= 60000, "配置包过大"); using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 24 }); Require(HasUniqueProperties(document.RootElement), "配置包字段重复"); return new GovernancePackage(document.RootElement.Deserialize(JsonOptions) ?? throw new ArgumentException("配置包不能为空"), fields); } private static bool HasUniqueProperties(JsonElement element) { if (element.ValueKind == JsonValueKind.Array) return element.EnumerateArray().All(HasUniqueProperties); if (element.ValueKind != JsonValueKind.Object) return true; var seen = new HashSet(StringComparer.OrdinalIgnoreCase); return element.EnumerateObject().All(x => seen.Add(x.Name) && HasUniqueProperties(x.Value)); } public SchemaDefinition SourceSchema(string version, string? envelopeJson = null) { var row = RowSchema(fromSource: true); if (envelopeJson == null) return Schema(version, row.ToJsonString()); var envelope = JsonNode.Parse(envelopeJson)!; envelope["properties"]!["data"]!["properties"]!["list"]!["items"] = row; envelope["$id"] = $"urn:aidop:mdp:{version}"; return Schema(version, envelope.ToJsonString()); } public static SchemaDefinition RawSchema(SchemaDefinition baseline) { var raw = JsonNode.Parse(baseline.Json)!; raw["$id"] = "urn:aidop:mdp:raw-envelope-v1.1"; var snapshot = raw["properties"]!["batch"]!["properties"]!["versions"]!; snapshot["properties"]!["configPackageJson"] = new JsonObject { ["type"] = "string", ["maxLength"] = 60000 }; snapshot["properties"]!["standardSchemaStamp"] = new JsonObject { ["$ref"] = "#/$defs/schemaStamp" }; snapshot["required"]!.AsArray().Add("configPackageJson"); snapshot["required"]!.AsArray().Add("standardSchemaStamp"); return Schema("raw-envelope-v1.1", raw.ToJsonString()); } public SchemaDefinition StandardSchema(string version) => Schema(version, RowSchema(fromSource: false).ToJsonString()); public bool AcceptsPreviousSource(GovernancePackage previous) { var current = rules.Values.ToDictionary(x => x.Rule.Source, StringComparer.Ordinal); var prior = previous.rules.Values.ToDictionary(x => x.Rule.Source, StringComparer.Ordinal); return prior.Values.All(x => current.TryGetValue(x.Rule.Source, out var next) && EffectiveInputType(x).Split('|').All(EffectiveInputType(next).Split('|').Contains) && (!next.Field.Required || x.Field.Required) && (!(x.Field.Key || x.Field.Name == "sourceUpdatedAt") || x.Field.Name == next.Field.Name)) && current.Values.All(x => !x.Field.Required || prior.ContainsKey(x.Rule.Source)); } private JsonObject RowSchema(bool fromSource) { var properties = new JsonObject(); var required = new JsonArray(); var keys = new JsonArray(keyOrder.Select(key => (JsonNode?)JsonValue.Create(fromSource ? Names[key] : key)).ToArray()); foreach (var field in rules.Values) { var name = fromSource ? field.Rule.Source : field.Field.Name; var type = fromSource ? EffectiveInputType(field) : field.Field.Type; var kinds = type.Split('|').ToList(); if (!field.Field.Required) kinds.Add("null"); properties.Add(name, new JsonObject { ["type"] = kinds.Count == 1 ? JsonValue.Create(type) : new JsonArray(kinds.Select(x => (JsonNode?)JsonValue.Create(x)).ToArray()) }); if (field.Field.Required) required.Add(name); } return new JsonObject { ["type"] = "object", ["properties"] = properties, ["required"] = required, ["x-business-key"] = keys }; } private static string EffectiveInputType(Compiled rule) => rule.Rule.InputType ?? (rule.Rule.Operation switch { "integer" or "decimal" or "unit" or "currency" => "string|number", "text" => "string|number|boolean", "date" or "timestamp" or "enum" => "string", _ => rule.Field.Type }); private static Compiled Compile(GovernanceField field, GovernanceRule rule) { var op = rule.Operation; var type = field.Type; Require(rule.InputType is null or "string" or "number" or "integer" or "boolean" or "string|number" or "string|number|boolean", $"来源字段类型无效:{rule.Source}"); Require(op switch { "copy" => rule.InputType == null || rule.InputType == type, "text" or "date" or "timestamp" or "enum" => type == "string", "integer" => type is "integer" or "number", "decimal" or "unit" or "currency" => type == "number", _ => false }, $"转换与目标字段类型不兼容:{field.Name}"); Require(!(field.Key || field.Name == "sourceUpdatedAt") || op == "copy", $"接收业务键/水位字段只允许原值映射:{field.Name}"); if (op is "unit" or "currency") Require(rule.Factor is > 0 && rule.Scale is >= 0 and <= 12, $"缺少换算系数或精度:{field.Name}"); else Require(rule.Factor is null && rule.Scale is null, $"此转换不使用换算系数或精度:{field.Name}"); if (op is "date" or "timestamp") Require(rule.DateFormat is "yyyyMMdd" or "yyyy-MM-dd" or "yyyy-MM-dd HH:mm:ss" or "yyyy-MM-dd'T'HH:mm:ss" or "offset", $"日期格式无效:{field.Name}"); else Require(rule.DateFormat == null && rule.TimeZone == null, $"此转换不使用日期配置:{field.Name}"); var zone = rule.TimeZone != null ? FindZone(rule.TimeZone) : null; Require(op != "timestamp" || rule.DateFormat == "offset" || zone != null, $"缺少来源时区:{field.Name}"); Require(op != "enum" ? rule.Values == null : rule.Values is { Count: > 0 and <= 128 } && rule.Values.All(x => IsName(x.Key) && IsName(x.Value)), $"枚举映射无效:{field.Name}"); var values = rule.Values?.OrderBy(x => x.Key, StringComparer.Ordinal) .ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal); return new(field, rule with { Values = values }, zone); } private static TimeZoneInfo FindZone(string key) { try { return TimeZoneInfo.FindSystemTimeZoneById(key); } catch (Exception e) when (e is TimeZoneNotFoundException or InvalidTimeZoneException) { throw new ArgumentException("来源时区不存在", e); } } public GovernanceIssue? Apply(JsonElement row, Dictionary output, bool keysOnly = false) { if (row.ValueKind != JsonValueKind.Object) return new("", "ROW_TYPE_INVALID"); var wanted = rules.Values.Where(x => !keysOnly || x.Field.Key || x.Field.Name == "sourceUpdatedAt") .ToDictionary(x => x.Rule.Source, StringComparer.Ordinal); var raw = new Dictionary(StringComparer.Ordinal); foreach (var field in row.EnumerateObject()) { if (wanted.TryGetValue(field.Name, out var target) && !raw.TryAdd(field.Name, field.Value)) return new(target.Field.Name, "DUPLICATE_FIELD"); } foreach (var rule in wanted.Values) { if (ConvertField(rule, raw, output) is { } problem) return problem; } return null; } private static GovernanceIssue? ConvertField(Compiled compiled, Dictionary input, Dictionary output) { var rule = compiled.Rule; if (!input.TryGetValue(rule.Source, out var value) || value.ValueKind == JsonValueKind.Null) return compiled.Field.Required ? new(rule.Target, "REQUIRED") : null; var kind = value.ValueKind switch { JsonValueKind.String => "string", JsonValueKind.Number => "number", JsonValueKind.False or JsonValueKind.True => "boolean", _ => "invalid" }; var accepted = EffectiveInputType(compiled).Split('|'); if (!accepted.Contains(kind) && !(kind == "number" && accepted.Contains("integer") && value.TryGetInt64(out _))) return new(rule.Target, "SOURCE_TYPE_INVALID"); var text = kind == "string" ? value.GetString()! : value.GetRawText(); object? converted = null; switch (rule.Operation) { case "copy": output.Add(rule.Target, value); return null; case "text": converted = text; break; case "integer": if (long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var integer)) converted = integer; break; case "decimal": case "unit": case "currency": if (decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var number)) { try { converted = rule.Factor is { } factor ? decimal.Round(number * factor, rule.Scale!.Value, MidpointRounding.ToEven) : number; } catch (OverflowException) { return new(rule.Target, "NUMERIC_OVERFLOW"); } } break; case "date": case "timestamp": converted = ConvertDate(compiled, text); break; case "enum": if (rule.Values!.TryGetValue(text, out var mapped)) converted = mapped; else return new(rule.Target, "ENUM_VALUE_UNMAPPED"); break; } if (converted == null) return new(rule.Target, "CONVERSION_FAILED"); output.Add(rule.Target, JsonSerializer.SerializeToElement(converted)); return null; } private static string? ConvertDate(Compiled compiled, string text) { var rule = compiled.Rule; if (rule.DateFormat == "offset") { if (text.Length < 20 || text[10] != 'T' || !(text.EndsWith('Z') || text[^6] is '+' or '-') || !DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var instant)) return null; return rule.Operation == "timestamp" ? instant.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture) : instant.DateTime.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture); } if (!DateTime.TryParseExact(text, rule.DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var local)) return null; var zone = compiled.Zone; if (zone != null) { if (zone.IsInvalidTime(local) || zone.IsAmbiguousTime(local)) return null; local = TimeZoneInfo.ConvertTimeToUtc(local, zone); } return local.ToString(rule.Operation == "timestamp" ? "O" : "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture); } private static bool IsName(string? value, int maxLength = 128) => value is { Length: > 0 } && value.Length <= maxLength && !string.IsNullOrWhiteSpace(value) && value == value.Trim() && !value.Any(char.IsControl); private static void Require(bool condition, string message) { if (!condition) throw new ArgumentException(message); } private static string Hash(string json) => PurchaseOrderSchemaRegistry.ComputeSha256(Encoding.UTF8.GetBytes(json)); private static SchemaDefinition Schema(string version, string json) => new(new(version, Hash(json)), json); }