GovernancePackage.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. using System.Collections.ObjectModel;
  2. using System.Globalization;
  3. using System.Text;
  4. using System.Text.Json;
  5. using System.Text.Json.Nodes;
  6. using System.Text.Json.Serialization;
  7. namespace Admin.NET.Plugin.AiDOP.DataPlatform.Core;
  8. public sealed record GovernanceRule(string Target, string Source, string Operation = "copy",
  9. string? DateFormat = null, string? TimeZone = null, decimal? Factor = null, int? Scale = null,
  10. Dictionary<string, string>? Values = null, string? InputType = null);
  11. public sealed record GovernanceField(string Name, string Type, bool Required = false, bool Key = false);
  12. public sealed record GovernanceIssue(string Field, string Reason);
  13. public sealed class GovernancePackage
  14. {
  15. public const string Format = "mdp-governance-v1";
  16. public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web)
  17. {
  18. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
  19. UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
  20. MaxDepth = 24
  21. };
  22. public static IReadOnlyList<GovernanceField> PurchaseFields { get; } =
  23. [
  24. new("PoNo", "string", true, true), new("PoLine", "string", true, true), new("ItemCode", "string", true),
  25. new("OrderQty", "number", true), new("SupplierCode", "string"), new("OrderDate", "string"),
  26. new("DueDate", "string"), new("Status", "string"), new("sourceUpdatedAt", "string", true)
  27. ];
  28. private sealed record Document(string Format, GovernanceRule[] Rules, JsonElement[]? Masters = null, string? Template = null);
  29. private sealed record Compiled(GovernanceField Field, GovernanceRule Rule, TimeZoneInfo? Zone);
  30. private readonly Dictionary<string, Compiled> rules;
  31. private readonly string[] keyOrder;
  32. public string Json { get; }
  33. public string Digest { get; }
  34. public IReadOnlyDictionary<string, string> Names { get; }
  35. private GovernancePackage(Document input, IReadOnlyList<GovernanceField> fields)
  36. {
  37. Require(input.Format == Format && input.Rules is { Length: <= 64 } &&
  38. (input.Template == null || IsName(input.Template, 100)), "配置包格式或规则数无效");
  39. var supplied = new Dictionary<string, GovernanceRule>(StringComparer.Ordinal);
  40. foreach (var rule in input.Rules!)
  41. {
  42. Require(rule is not null && IsName(rule.Target) && IsName(rule.Source) &&
  43. fields.Any(f => f.Name == rule.Target) && supplied.TryAdd(rule.Target, rule),
  44. "映射字段不存在或重复");
  45. }
  46. keyOrder = fields.Where(x => x.Key).Select(x => x.Name).ToArray();
  47. rules = new(StringComparer.Ordinal);
  48. foreach (var field in fields.OrderBy(x => x.Name, StringComparer.Ordinal))
  49. {
  50. var rule = supplied.GetValueOrDefault(field.Name) ?? new(field.Name, field.Name);
  51. rules.Add(field.Name, Compile(field, rule));
  52. }
  53. Require(rules.Values.GroupBy(x => x.Rule.Source, StringComparer.Ordinal)
  54. .All(g => g.Select(x => EffectiveInputType(x)).Distinct().Count() == 1), "同一来源字段的类型声明不一致");
  55. var names = rules.ToDictionary(x => x.Key, x => x.Value.Rule.Source, StringComparer.Ordinal);
  56. Require(names.Values.Distinct(StringComparer.Ordinal).Count() == names.Count,
  57. "一个来源字段不能同时映射多个目标字段");
  58. Names = new ReadOnlyDictionary<string, string>(names);
  59. // Keep the canonical empty member for compatibility with the configuration package format.
  60. Require(input.Masters is null or { Length: 0 }, "配置包当前只接受字段转换规则");
  61. Json = JsonSerializer.Serialize(new Document(Format, rules.Values.Select(x => x.Rule).ToArray(), [], input.Template), JsonOptions);
  62. Require(Encoding.UTF8.GetByteCount(Json) <= 60000, "配置包过大");
  63. Digest = Hash(Json);
  64. }
  65. public static GovernancePackage Parse(string json, IReadOnlyList<GovernanceField> fields)
  66. {
  67. Require(Encoding.UTF8.GetByteCount(json) <= 60000, "配置包过大");
  68. using var document = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 24 });
  69. Require(HasUniqueProperties(document.RootElement), "配置包字段重复");
  70. return new GovernancePackage(document.RootElement.Deserialize<Document>(JsonOptions)
  71. ?? throw new ArgumentException("配置包不能为空"), fields);
  72. }
  73. private static bool HasUniqueProperties(JsonElement element)
  74. {
  75. if (element.ValueKind == JsonValueKind.Array)
  76. return element.EnumerateArray().All(HasUniqueProperties);
  77. if (element.ValueKind != JsonValueKind.Object)
  78. return true;
  79. var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
  80. return element.EnumerateObject().All(x => seen.Add(x.Name) && HasUniqueProperties(x.Value));
  81. }
  82. public SchemaDefinition SourceSchema(string version, string? envelopeJson = null)
  83. {
  84. var row = RowSchema(fromSource: true);
  85. if (envelopeJson == null) return Schema(version, row.ToJsonString());
  86. var envelope = JsonNode.Parse(envelopeJson)!;
  87. envelope["properties"]!["data"]!["properties"]!["list"]!["items"] = row;
  88. envelope["$id"] = $"urn:aidop:mdp:{version}";
  89. return Schema(version, envelope.ToJsonString());
  90. }
  91. public static SchemaDefinition RawSchema(SchemaDefinition baseline)
  92. {
  93. var raw = JsonNode.Parse(baseline.Json)!;
  94. raw["$id"] = "urn:aidop:mdp:raw-envelope-v1.1";
  95. var snapshot = raw["properties"]!["batch"]!["properties"]!["versions"]!;
  96. snapshot["properties"]!["configPackageJson"] = new JsonObject { ["type"] = "string", ["maxLength"] = 60000 };
  97. snapshot["properties"]!["standardSchemaStamp"] = new JsonObject { ["$ref"] = "#/$defs/schemaStamp" };
  98. snapshot["required"]!.AsArray().Add("configPackageJson");
  99. snapshot["required"]!.AsArray().Add("standardSchemaStamp");
  100. return Schema("raw-envelope-v1.1", raw.ToJsonString());
  101. }
  102. public SchemaDefinition StandardSchema(string version) => Schema(version, RowSchema(fromSource: false).ToJsonString());
  103. public bool AcceptsPreviousSource(GovernancePackage previous)
  104. {
  105. var current = rules.Values.ToDictionary(x => x.Rule.Source, StringComparer.Ordinal);
  106. var prior = previous.rules.Values.ToDictionary(x => x.Rule.Source, StringComparer.Ordinal);
  107. return prior.Values.All(x => current.TryGetValue(x.Rule.Source, out var next)
  108. && EffectiveInputType(x).Split('|').All(EffectiveInputType(next).Split('|').Contains)
  109. && (!next.Field.Required || x.Field.Required)
  110. && (!(x.Field.Key || x.Field.Name == "sourceUpdatedAt") || x.Field.Name == next.Field.Name))
  111. && current.Values.All(x => !x.Field.Required || prior.ContainsKey(x.Rule.Source));
  112. }
  113. private JsonObject RowSchema(bool fromSource)
  114. {
  115. var properties = new JsonObject();
  116. var required = new JsonArray();
  117. var keys = new JsonArray(keyOrder.Select(key => (JsonNode?)JsonValue.Create(fromSource ? Names[key] : key)).ToArray());
  118. foreach (var field in rules.Values)
  119. {
  120. var name = fromSource ? field.Rule.Source : field.Field.Name;
  121. var type = fromSource ? EffectiveInputType(field) : field.Field.Type;
  122. var kinds = type.Split('|').ToList();
  123. if (!field.Field.Required) kinds.Add("null");
  124. properties.Add(name, new JsonObject { ["type"] = kinds.Count == 1 ? JsonValue.Create(type)
  125. : new JsonArray(kinds.Select(x => (JsonNode?)JsonValue.Create(x)).ToArray()) });
  126. if (field.Field.Required) required.Add(name);
  127. }
  128. return new JsonObject { ["type"] = "object", ["properties"] = properties, ["required"] = required, ["x-business-key"] = keys };
  129. }
  130. private static string EffectiveInputType(Compiled rule) => rule.Rule.InputType ?? (rule.Rule.Operation switch
  131. {
  132. "integer" or "decimal" or "unit" or "currency" => "string|number",
  133. "text" => "string|number|boolean",
  134. "date" or "timestamp" or "enum" => "string",
  135. _ => rule.Field.Type
  136. });
  137. private static Compiled Compile(GovernanceField field, GovernanceRule rule)
  138. {
  139. var op = rule.Operation;
  140. var type = field.Type;
  141. Require(rule.InputType is null or "string" or "number" or "integer" or "boolean"
  142. or "string|number" or "string|number|boolean", $"来源字段类型无效:{rule.Source}");
  143. Require(op switch
  144. {
  145. "copy" => rule.InputType == null || rule.InputType == type,
  146. "text" or "date" or "timestamp" or "enum" => type == "string",
  147. "integer" => type is "integer" or "number",
  148. "decimal" or "unit" or "currency" => type == "number",
  149. _ => false
  150. }, $"转换与目标字段类型不兼容:{field.Name}");
  151. Require(!(field.Key || field.Name == "sourceUpdatedAt") || op == "copy",
  152. $"接收业务键/水位字段只允许原值映射:{field.Name}");
  153. if (op is "unit" or "currency")
  154. Require(rule.Factor is > 0 && rule.Scale is >= 0 and <= 12, $"缺少换算系数或精度:{field.Name}");
  155. else
  156. Require(rule.Factor is null && rule.Scale is null, $"此转换不使用换算系数或精度:{field.Name}");
  157. if (op is "date" or "timestamp")
  158. 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",
  159. $"日期格式无效:{field.Name}");
  160. else
  161. Require(rule.DateFormat == null && rule.TimeZone == null, $"此转换不使用日期配置:{field.Name}");
  162. var zone = rule.TimeZone != null ? FindZone(rule.TimeZone) : null;
  163. Require(op != "timestamp" || rule.DateFormat == "offset" || zone != null, $"缺少来源时区:{field.Name}");
  164. Require(op != "enum" ? rule.Values == null : rule.Values is { Count: > 0 and <= 128 }
  165. && rule.Values.All(x => IsName(x.Key) && IsName(x.Value)),
  166. $"枚举映射无效:{field.Name}");
  167. var values = rule.Values?.OrderBy(x => x.Key, StringComparer.Ordinal)
  168. .ToDictionary(x => x.Key, x => x.Value, StringComparer.Ordinal);
  169. return new(field, rule with { Values = values }, zone);
  170. }
  171. private static TimeZoneInfo FindZone(string key)
  172. {
  173. try { return TimeZoneInfo.FindSystemTimeZoneById(key); }
  174. catch (Exception e) when (e is TimeZoneNotFoundException or InvalidTimeZoneException)
  175. { throw new ArgumentException("来源时区不存在", e); }
  176. }
  177. public GovernanceIssue? Apply(JsonElement row, Dictionary<string, JsonElement> output, bool keysOnly = false)
  178. {
  179. if (row.ValueKind != JsonValueKind.Object) return new("", "ROW_TYPE_INVALID");
  180. var wanted = rules.Values.Where(x => !keysOnly || x.Field.Key || x.Field.Name == "sourceUpdatedAt")
  181. .ToDictionary(x => x.Rule.Source, StringComparer.Ordinal);
  182. var raw = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
  183. foreach (var field in row.EnumerateObject())
  184. {
  185. if (wanted.TryGetValue(field.Name, out var target) && !raw.TryAdd(field.Name, field.Value))
  186. return new(target.Field.Name, "DUPLICATE_FIELD");
  187. }
  188. foreach (var rule in wanted.Values)
  189. {
  190. if (ConvertField(rule, raw, output) is { } problem) return problem;
  191. }
  192. return null;
  193. }
  194. private static GovernanceIssue? ConvertField(Compiled compiled, Dictionary<string, JsonElement> input,
  195. Dictionary<string, JsonElement> output)
  196. {
  197. var rule = compiled.Rule;
  198. if (!input.TryGetValue(rule.Source, out var value) || value.ValueKind == JsonValueKind.Null)
  199. return compiled.Field.Required ? new(rule.Target, "REQUIRED") : null;
  200. var kind = value.ValueKind switch
  201. {
  202. JsonValueKind.String => "string",
  203. JsonValueKind.Number => "number",
  204. JsonValueKind.False or JsonValueKind.True => "boolean",
  205. _ => "invalid"
  206. };
  207. var accepted = EffectiveInputType(compiled).Split('|');
  208. if (!accepted.Contains(kind) && !(kind == "number" && accepted.Contains("integer") && value.TryGetInt64(out _)))
  209. return new(rule.Target, "SOURCE_TYPE_INVALID");
  210. var text = kind == "string" ? value.GetString()! : value.GetRawText();
  211. object? converted = null;
  212. switch (rule.Operation)
  213. {
  214. case "copy":
  215. output.Add(rule.Target, value);
  216. return null;
  217. case "text":
  218. converted = text;
  219. break;
  220. case "integer":
  221. if (long.TryParse(text, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var integer))
  222. converted = integer;
  223. break;
  224. case "decimal":
  225. case "unit":
  226. case "currency":
  227. if (decimal.TryParse(text, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent,
  228. CultureInfo.InvariantCulture, out var number))
  229. {
  230. try { converted = rule.Factor is { } factor
  231. ? decimal.Round(number * factor, rule.Scale!.Value, MidpointRounding.ToEven) : number; }
  232. catch (OverflowException) { return new(rule.Target, "NUMERIC_OVERFLOW"); }
  233. }
  234. break;
  235. case "date":
  236. case "timestamp":
  237. converted = ConvertDate(compiled, text);
  238. break;
  239. case "enum":
  240. if (rule.Values!.TryGetValue(text, out var mapped)) converted = mapped;
  241. else return new(rule.Target, "ENUM_VALUE_UNMAPPED");
  242. break;
  243. }
  244. if (converted == null) return new(rule.Target, "CONVERSION_FAILED");
  245. output.Add(rule.Target, JsonSerializer.SerializeToElement(converted));
  246. return null;
  247. }
  248. private static string? ConvertDate(Compiled compiled, string text)
  249. {
  250. var rule = compiled.Rule;
  251. if (rule.DateFormat == "offset")
  252. {
  253. if (text.Length < 20 || text[10] != 'T' || !(text.EndsWith('Z') || text[^6] is '+' or '-')
  254. || !DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var instant))
  255. return null;
  256. return rule.Operation == "timestamp" ? instant.ToUniversalTime().ToString("O", CultureInfo.InvariantCulture)
  257. : instant.DateTime.ToString("yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture);
  258. }
  259. if (!DateTime.TryParseExact(text, rule.DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var local)) return null;
  260. var zone = compiled.Zone;
  261. if (zone != null)
  262. {
  263. if (zone.IsInvalidTime(local) || zone.IsAmbiguousTime(local)) return null;
  264. local = TimeZoneInfo.ConvertTimeToUtc(local, zone);
  265. }
  266. return local.ToString(rule.Operation == "timestamp" ? "O" : "yyyy-MM-dd'T'HH:mm:ss", CultureInfo.InvariantCulture);
  267. }
  268. private static bool IsName(string? value, int maxLength = 128) =>
  269. value is { Length: > 0 } && value.Length <= maxLength && !string.IsNullOrWhiteSpace(value)
  270. && value == value.Trim() && !value.Any(char.IsControl);
  271. private static void Require(bool condition, string message)
  272. {
  273. if (!condition) throw new ArgumentException(message);
  274. }
  275. private static string Hash(string json) => PurchaseOrderSchemaRegistry.ComputeSha256(Encoding.UTF8.GetBytes(json));
  276. private static SchemaDefinition Schema(string version, string json) => new(new(version, Hash(json)), json);
  277. }