using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Xml; namespace Jingyao.AIEmployee { // 沿用原站付款请求原文、审核版本及核销 XML 校验。 internal static class FinancePaymentJournalRequest { private static string Text(Dictionary values, string key, int maximum) { object raw; if (!values.TryGetValue(key, out raw) || !(raw is string)) throw new ArgumentException(key + "必须为明确文本。"); string value = (string)raw; if (String.IsNullOrWhiteSpace(value) || value.Length > maximum || value != value.Trim()) throw new ArgumentException(key + "缺失、超长或含首尾空格。"); for (int i = 0; i < value.Length; i++) { char c = value[i]; if (Char.IsControl(c) || c == '\uFFFE' || c == '\uFFFF') throw new ArgumentException(key + "含非法字符。"); if (Char.IsHighSurrogate(c)) { if (i + 1 >= value.Length || !Char.IsLowSurrogate(value[++i])) throw new ArgumentException(key + "含非法Unicode字符。"); } else if (Char.IsLowSurrogate(c)) throw new ArgumentException(key + "含非法Unicode字符。"); } return value; } private static long Id(string value, long maximum) { long id; if (!Int64.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id) || id <= 0 || id > maximum || id.ToString(CultureInfo.InvariantCulture) != value) throw new ArgumentException("必须提供实际主键范围内的正整数文本。"); return id; } private static void Fields(Dictionary values, params string[] allowed) { var set = new HashSet(allowed, StringComparer.Ordinal); foreach (string key in values.Keys) if (!set.Contains(key)) throw new ArgumentException("存在非本动作字段。"); } private static string Version(Dictionary values) { string value = Text(values, "expectedVersion", 16); FinancePaymentJournalPolicy.RequireVersion(value); return value; } private static byte[] VersionBytes(string value) { byte[] bytes = new byte[8]; for (int i = 0; i < 8; i++) bytes[i] = Byte.Parse(value.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture); return bytes; } private static string AllocationXml(Dictionary values) { object raw; if (!values.TryGetValue("allocations", out raw) || !(raw is IList)) throw new ArgumentException("缺少核销明细数组。"); IList array = (IList)raw; if (array.Count < 1 || array.Count > FinancePaymentJournalPolicy.MaxAllocationLines) throw new ArgumentException("核销明细条数须为1至200。"); var sorted = new SortedDictionary(); foreach (object item in array) { var line = item as Dictionary; if (line == null) throw new ArgumentException("核销行必须是明确对象。"); Fields(line, "payableId", "amount", "expectedVersion"); int id = (int)Id(Text(line, "payableId", 10), Int32.MaxValue); decimal amount = FinancePaymentRegistrationPolicy.ReadAmount(Text(line, "amount", 19), false); string version = Version(line); if (sorted.ContainsKey(id)) throw new ArgumentException("同一次核销不得重复应付主键。"); sorted.Add(id, new string[] { amount.ToString("F2", CultureInfo.InvariantCulture), version }); } var result = new StringBuilder(); using (XmlWriter xml = XmlWriter.Create(result, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false, NewLineHandling = NewLineHandling.None })) { xml.WriteStartElement("allocations"); foreach (var row in sorted) { xml.WriteStartElement("line"); xml.WriteAttributeString("payableId", row.Key.ToString(CultureInfo.InvariantCulture)); xml.WriteAttributeString("amount", row.Value[0]); xml.WriteAttributeString("expectedVersion", row.Value[1]); xml.WriteEndElement(); } xml.WriteEndElement(); } return result.ToString(); } private static void Add(SqlCommand command, string name, SqlDbType type, object value) { SqlParameter parameter = command.Parameters.Add(name, type); if (type == SqlDbType.VarChar || type == SqlDbType.NVarChar || type == SqlDbType.VarBinary) parameter.Size = -1; if (type == SqlDbType.Decimal) { parameter.Precision = 18; parameter.Scale = 2; } parameter.Value = value; } public static void BindResolution(SqlCommand command, Dictionary values, string trustedPerson) { if (command == null || values == null || command.Parameters.Count != 0) throw new ArgumentException("须使用空命令与明确原请求。"); Fields(values, "action", "mode", "original", "closeReason", "checked"); string action = Text(values, "action", 8), mode = Text(values, "mode", 17); if (mode != "INSPECT" && mode != "CLOSE_UNCOMMITTED") throw new ArgumentException("只能核对或关闭尚未办理的原请求,不能冲正。"); object raw, check; if (!values.TryGetValue("original", out raw) || !(raw is Dictionary) || !values.TryGetValue("checked", out check) || !(check is bool) || !(bool)check) throw new ArgumentException("须提供完整原请求并明确核对本次请求处理。"); object reason = DBNull.Value; if (mode == "CLOSE_UNCOMMITTED") reason = Text(values, "closeReason", 1000); else if (values.ContainsKey("closeReason")) throw new ArgumentException("只读核对不能附带关闭说明。"); // Validate the original business request unchanged, using the current // trusted actor. A failing nested request leaves the real command empty. using (SqlCommand original = new SqlCommand()) { Bind(original, action, (Dictionary)raw, trustedPerson); foreach (SqlParameter parameter in original.Parameters) command.Parameters.Add((SqlParameter)((ICloneable)parameter).Clone()); } Add(command, "@请求处理", SqlDbType.VarChar, mode); Add(command, "@关闭说明", SqlDbType.NVarChar, reason); } public static void Bind(SqlCommand command, string action, Dictionary values, string trustedPerson) { if (command == null || values == null || command.Parameters.Count != 0) throw new ArgumentException("须使用空参数命令与完整付款请求。"); Id(trustedPerson, Int32.MaxValue); if (action == "REGISTER") Fields(values, "supplierId", "currency", "amount", "paymentDate", "voucherReference", "accountReference", "reason", "idempotencyKey", "checked"); else if (action == "REVIEW") Fields(values, "paymentId", "expectedVersion", "decision", "reason", "idempotencyKey", "checked"); else if (action == "ALLOCATE") Fields(values, "paymentId", "expectedVersion", "allocations", "reason", "idempotencyKey", "checked"); else throw new ArgumentException("付款动作未开放;冲正规则等待9007确认。"); object check; if (!values.TryGetValue("checked", out check) || !(check is bool) || !(bool)check) throw new ArgumentException("须明确核对本次操作,不能自动勾选。"); string reason = Text(values, "reason", 1000), key = Text(values, "idempotencyKey", 100); int supplier = 0; long payment = 0; decimal amount = 0; DateTime date = DateTime.MinValue; string currency = null, voucher = null, account = null, version = null, decision = null, allocations = null; if (action == "REGISTER") { supplier = (int)Id(Text(values, "supplierId", 10), Int32.MaxValue); currency = Text(values, "currency", 3); FinancePaymentJournalPolicy.RequireCurrency(currency); amount = FinancePaymentRegistrationPolicy.ReadAmount(Text(values, "amount", 19), false); string dateText = Text(values, "paymentDate", 10); if (!DateTime.TryParseExact(dateText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date) || date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) != dateText) throw new ArgumentException("付款日期须明确填写有效yyyy-MM-dd,不使用当前日期默认值。"); voucher = Text(values, "voucherReference", 200); account = Text(values, "accountReference", 200); } else { payment = Id(Text(values, "paymentId", 19), Int64.MaxValue); version = Version(values); if (action == "REVIEW") { decision = Text(values, "decision", 7); if (decision != "CONFIRM" && decision != "REJECT") throw new ArgumentException("付款审批结论无效。"); } else allocations = AllocationXml(values); } // Only now bind: invalid requests leave the caller's command untouched. Add(command, "@动作", SqlDbType.VarChar, action); Add(command, "@操作人", SqlDbType.NVarChar, trustedPerson); Add(command, "@幂等键", SqlDbType.NVarChar, key); Add(command, "@办理说明", SqlDbType.NVarChar, reason); Add(command, "@策略版本", SqlDbType.VarChar, FinancePaymentJournalPolicy.Version); Add(command, "@已核对", SqlDbType.Bit, true); if (action == "REGISTER") { Add(command, "@供应商流水号", SqlDbType.Int, supplier); Add(command, "@币种", SqlDbType.VarChar, currency); // Preserve explicit two-place text into SQL, so the procedure can // reject excess precision before a DECIMAL parameter rounds it. Add(command, "@付款金额", SqlDbType.NVarChar, amount.ToString("F2", CultureInfo.InvariantCulture)); Add(command, "@付款日期", SqlDbType.Date, date); Add(command, "@付款凭证引用", SqlDbType.NVarChar, voucher); Add(command, "@付款账户引用", SqlDbType.NVarChar, account); } else { Add(command, "@付款流水号", SqlDbType.BigInt, payment); Add(command, "@预期版本", SqlDbType.VarBinary, VersionBytes(version)); if (action == "REVIEW") Add(command, "@审批结论", SqlDbType.VarChar, decision); else Add(command, "@核销明细", SqlDbType.Xml, allocations); } } } internal static class FinancePaymentInboxRequest { public const string Version = "FINANCE_PAYMENT_INBOX_20261104_V1"; private static void Fields(Dictionary values, params string[] names) { if (values == null) throw new ArgumentException("请求箱参数缺失。"); var set = new HashSet(names, StringComparer.Ordinal); foreach (string key in values.Keys) if (!set.Contains(key)) throw new ArgumentException("请求箱包含非本动作字段。"); } private static string Text(Dictionary values, string name, int maximum) { object raw; if (!values.TryGetValue(name, out raw) || !(raw is string)) throw new ArgumentException("请求箱文本字段缺失。"); string value = (string)raw; if (String.IsNullOrWhiteSpace(value) || value.Length > maximum || value != value.Trim()) throw new ArgumentException("请求箱文本格式无效。"); foreach (char c in value) if (Char.IsControl(c)) throw new ArgumentException("请求箱包含控制字符。"); return value; } private static long Id(string value) { long id; if (!Int64.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out id) || id <= 0 || id.ToString(CultureInfo.InvariantCulture) != value) throw new ArgumentException("请求箱主键或代次必须为完整正整数文本。"); return id; } private static void Empty(SqlCommand command, string actor) { if (command == null || command.Parameters.Count != 0 || Id(actor) > Int32.MaxValue) throw new ArgumentException("请求箱命令或可信人员无效。"); } private static void Add(SqlCommand command, string name, SqlDbType type, object value) { SqlParameter p = command.Parameters.Add(name, type); if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar) p.Size = -1; p.Value = value; } private static void Copy(SqlCommand from, SqlCommand to) { foreach (SqlParameter parameter in from.Parameters) to.Parameters.Add((SqlParameter)((ICloneable)parameter).Clone()); } public static void BindWrite(SqlCommand command, string action, Dictionary values, string actor) { Empty(command, actor); if (values == null) throw new ArgumentException("付款原请求缺失。"); string mode = Text(values, "requestMode", 7); if (mode != "PREPARE" && mode != "EXECUTE") throw new ArgumentException("付款请求处理模式无效。"); if (Text(values, "inboxVersion", 60) != Version) throw new ArgumentException("付款页面协议已变化,请恢复原请求。"); long generation = Id(Text(values, "generation", 19)); var business = new Dictionary(values, StringComparer.Ordinal); business.Remove("requestMode"); business.Remove("generation"); business.Remove("inboxVersion"); using (SqlCommand original = new SqlCommand()) { FinancePaymentJournalRequest.Bind(original, action, business, actor); Copy(original, command); } Add(command, "@请求处理", SqlDbType.VarChar, mode); Add(command, "@请求代次", SqlDbType.BigInt, generation); } public static void BindResolution(SqlCommand command, Dictionary values, string actor) { Empty(command, actor); if (values == null || Text(values, "inboxVersion", 60) != Version) throw new ArgumentException("付款请求处理协议不符。"); long generation = Id(Text(values, "generation", 19)); var original = new Dictionary(values, StringComparer.Ordinal); original.Remove("generation"); original.Remove("inboxVersion"); using (SqlCommand nested = new SqlCommand()) { FinancePaymentJournalRequest.BindResolution(nested, original, actor); Copy(nested, command); } Add(command, "@请求代次", SqlDbType.BigInt, generation); } public static void BindRecovery(SqlCommand command, Dictionary values, string actor, bool acknowledge) { Empty(command, actor); object key = DBNull.Value, generation = DBNull.Value, terminal = DBNull.Value, terminalId = DBNull.Value; if (!acknowledge) { Fields(values, "mode"); if (Text(values, "mode", 5) != "INBOX") throw new ArgumentException("只允许读取本人原请求。"); } else { Fields(values, "mode", "inboxVersion", "idempotencyKey", "generation", "terminal", "terminalId", "checked"); object check; if (Text(values, "mode", 3) != "ACK" || Text(values, "inboxVersion", 60) != Version || !values.TryGetValue("checked", out check) || !(check is bool) || !(bool)check) throw new ArgumentException("须明确核对原请求终态后收讫。"); key = Text(values, "idempotencyKey", 100); generation = Id(Text(values, "generation", 19)); string state = Text(values, "terminal", 9); if (state != "COMMITTED" && state != "CLOSED") throw new ArgumentException("未知请求不能收讫。"); terminal = state; terminalId = Id(Text(values, "terminalId", 19)); } Add(command, "@模式", SqlDbType.VarChar, acknowledge ? "ACK" : "LOOKUP"); Add(command, "@操作人", SqlDbType.NVarChar, actor); Add(command, "@幂等键", SqlDbType.NVarChar, key); Add(command, "@请求代次", SqlDbType.BigInt, generation); Add(command, "@终态", SqlDbType.VarChar, terminal); Add(command, "@终态流水号", SqlDbType.BigInt, terminalId); Add(command, "@已核对", SqlDbType.Bit, acknowledge); } private static string Cell(DataRow row, string name) { if (row[name] == DBNull.Value || !(row[name] is string)) throw new InvalidOperationException("请求箱文本回执不完整。"); return (string)row[name]; } private static string OptionalId(DataRow row, string name) { if (row[name] == DBNull.Value) return null; string value = Cell(row, name); Id(value); return value; } private static void Columns(DataTable table, params string[] expected) { if (table.Columns.Count != expected.Length) throw new InvalidOperationException("请求箱回执字段不符。"); foreach (string name in expected) if (!table.Columns.Contains(name)) throw new InvalidOperationException("请求箱回执字段缺失。"); } private static XmlElement Xml(string source, string root) { if (source == null || source.Length > 262144) throw new InvalidOperationException("请求箱原文长度无效。"); var doc = new XmlDocument(); doc.XmlResolver = null; doc.PreserveWhitespace = true; var settings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit, XmlResolver = null, MaxCharactersInDocument = 262144 }; using (var reader = XmlReader.Create(new StringReader(source), settings)) doc.Load(reader); if (doc.ChildNodes.Count != 1 || doc.DocumentElement == null || doc.DocumentElement.Name != root || doc.DocumentElement.NamespaceURI != "" || doc.DocumentElement.Attributes.Count != 0) throw new InvalidOperationException("请求箱原文根节点无效。"); return doc.DocumentElement; } private static Dictionary Elements(XmlElement parent, params string[] names) { var allowed = new HashSet(names, StringComparer.Ordinal); var result = new Dictionary(StringComparer.Ordinal); foreach (XmlNode node in parent.ChildNodes) { XmlElement element = node as XmlElement; if (element == null || element.NamespaceURI != "" || element.Attributes.Count != 0 || !allowed.Contains(element.Name) || result.ContainsKey(element.Name)) throw new InvalidOperationException("请求箱原文含未知或重复节点。"); result.Add(element.Name, element); } if (result.Count != names.Length) throw new InvalidOperationException("请求箱原文节点缺失。"); return result; } private static string Value(Dictionary elements, string key) { XmlElement e = elements[key]; if (e.ChildNodes.Count != 1 || e.FirstChild.NodeType != XmlNodeType.Text) throw new InvalidOperationException("请求箱标量不完整。"); return e.InnerText; } private static List> Lines(XmlElement root, bool context) { var result = new List>(); var ids = new HashSet(StringComparer.Ordinal); string[] names = context ? new[] { "payableId", "paidAmount", "remaining", "expectedVersion" } : new[] { "payableId", "amount", "expectedVersion" }; foreach (XmlNode node in root.ChildNodes) { XmlElement e = node as XmlElement; if (e == null || e.Name != "line" || e.NamespaceURI != "" || e.HasChildNodes || e.Attributes.Count != names.Length) throw new InvalidOperationException("请求箱核销行无效。"); var line = new Dictionary(StringComparer.Ordinal); foreach (string name in names) { if (!e.HasAttribute(name)) throw new InvalidOperationException("请求箱核销行字段缺失。"); line.Add(name, e.GetAttribute(name)); } string id = (string)line["payableId"]; if (Id(id) > Int32.MaxValue || !ids.Add(id)) throw new InvalidOperationException("请求箱核销行主键重复或越界。"); FinancePaymentJournalPolicy.RequireVersion((string)line["expectedVersion"]); if (context) { FinancePaymentRegistrationPolicy.ReadAmount((string)line["paidAmount"], true); FinancePaymentRegistrationPolicy.ReadAmount((string)line["remaining"], true); } else FinancePaymentRegistrationPolicy.ReadAmount((string)line["amount"], false); result.Add(line); } if (result.Count > FinancePaymentJournalPolicy.MaxAllocationLines) throw new InvalidOperationException("请求箱核销行超限。"); return result; } private static void Hash(string source, string digest) { using (SHA256 sha = SHA256.Create()) { string actual = BitConverter.ToString(sha.ComputeHash(Encoding.Unicode.GetBytes(source))).Replace("-", ""); if (actual != digest) throw new InvalidOperationException("请求箱原文摘要不符。"); } } private static bool Same(object left, object right) { byte[] a = left as byte[], b = right as byte[]; if (a != null && b != null) { if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) if (a[i] != b[i]) return false; return true; } return Object.Equals(left, right); } public static Dictionary Read(DataSet data, string actor, SqlCommand expected) { if (data == null || data.Tables.Count != 2 || data.Tables[0].Rows.Count != 1 || data.Tables[1].Rows.Count > 1) throw new InvalidOperationException("请求箱回执不完整,不能另建付款。"); Columns(data.Tables[0], "协议版本", "操作人", "下一代次", "待核对流水号"); Columns(data.Tables[1], "请求流水号", "幂等键", "操作人", "代次", "动作", "原请求", "请求摘要", "核对快照", "快照摘要", "登记时间", "请求版本", "请求状态", "终态流水号", "已收讫"); DataRow h = data.Tables[0].Rows[0]; if (Cell(h, "协议版本") != Version || Cell(h, "操作人") != actor) throw new InvalidOperationException("请求箱人员或协议不符。"); string next = Cell(h, "下一代次"), active = OptionalId(h, "待核对流水号"); Id(next); var summary = new Dictionary { { "protocol", Version }, { "actor", actor }, { "nextGeneration", next }, { "activeRequestId", active } }; bool lookup = expected.Parameters.Contains("@模式") && (string)expected.Parameters["@模式"].Value == "LOOKUP"; if (data.Tables[1].Rows.Count == 0) { if (!lookup || active != null) throw new InvalidOperationException("请求箱原记录缺失。"); return new Dictionary { { "summary", summary }, { "request", null } }; } DataRow row = data.Tables[1].Rows[0]; string id = Cell(row, "请求流水号"), key = Cell(row, "幂等键"), generation = Cell(row, "代次"), action = Cell(row, "动作"), state = Cell(row, "请求状态"); Id(id); Id(generation); FinancePaymentJournalPolicy.RequireVersion(Cell(row, "请求版本")); if (Cell(row, "操作人") != actor || !(row["已收讫"] is bool) || !(row["登记时间"] is DateTime) || (lookup && id != active)) throw new InvalidOperationException("请求箱原记录身份或范围不符。"); bool acknowledged = (bool)row["已收讫"]; string terminalId = OptionalId(row, "终态流水号"); if ((!acknowledged && active != id) || (acknowledged && active == id) || Id(next) <= Id(generation)) throw new InvalidOperationException("请求箱当前通道或后续代次不符。"); if ((state != "PENDING" && state != "COMMITTED" && state != "CLOSED") || (state == "PENDING" ? terminalId != null || acknowledged : terminalId == null)) throw new InvalidOperationException("请求箱终态凭据不完整。"); if (!lookup && (key != (string)expected.Parameters["@幂等键"].Value || generation != Convert.ToString(expected.Parameters["@请求代次"].Value, CultureInfo.InvariantCulture))) throw new InvalidOperationException("请求箱原键或代次不符。"); if (expected.Parameters.Contains("@模式") && (string)expected.Parameters["@模式"].Value == "ACK" && (!acknowledged || state != (string)expected.Parameters["@终态"].Value || terminalId != Convert.ToString(expected.Parameters["@终态流水号"].Value, CultureInfo.InvariantCulture))) throw new InvalidOperationException("请求收讫未核实。"); string original = Cell(row, "原请求"), snapshot = Cell(row, "核对快照"); Hash(original, Cell(row, "请求摘要")); Hash(snapshot, Cell(row, "快照摘要")); XmlElement xml = Xml(original, "request"), ctx = Xml(snapshot, "context"); string[] names = action == "REGISTER" ? new[] { "action", "actor", "supplier", "currency", "amount", "paymentDate", "voucherReference", "accountReference", "reason", "policy" } : action == "REVIEW" ? new[] { "action", "actor", "paymentId", "expectedVersion", "decision", "reason", "policy" } : new[] { "action", "actor", "paymentId", "expectedVersion", "allocations", "reason", "policy" }; var elements = Elements(xml, names); if (Value(elements, "action") != action || Value(elements, "actor") != actor || Value(elements, "policy") != FinancePaymentJournalPolicy.Version) throw new InvalidOperationException("请求箱规范原文不匹配。"); var payload = new Dictionary { { "idempotencyKey", key }, { "reason", Value(elements, "reason") }, { "checked", true } }; object context = null; if (action == "REGISTER") { Elements(ctx); payload.Add("supplierId", Value(elements, "supplier")); foreach (string name in new[] { "currency", "amount", "paymentDate", "voucherReference", "accountReference" }) payload.Add(name, Value(elements, name)); } else { payload.Add("paymentId", Value(elements, "paymentId")); payload.Add("expectedVersion", Value(elements, "expectedVersion")); var contextElements = Elements(ctx, "supplierId", "currency", "amount", "appliedAmount", "creatorId", "sources"); var contextData = new Dictionary(); foreach (string name in new[] { "supplierId", "currency", "amount", "appliedAmount", "creatorId" }) contextData.Add(name, Value(contextElements, name)); if (Id((string)contextData["supplierId"]) > Int32.MaxValue || Id((string)contextData["creatorId"]) > Int32.MaxValue) throw new InvalidOperationException("快照主键无效。"); FinancePaymentJournalPolicy.RequireCurrency((string)contextData["currency"]); decimal amount = FinancePaymentRegistrationPolicy.ReadAmount((string)contextData["amount"], false), applied = FinancePaymentRegistrationPolicy.ReadAmount((string)contextData["appliedAmount"], true); if (applied > amount) throw new InvalidOperationException("快照金额不守恒。"); var sources = Lines(contextElements["sources"], true); contextData.Add("sources", sources); context = contextData; if (action == "REVIEW") { if (sources.Count != 0) throw new InvalidOperationException("审批快照不能含核销来源。"); payload.Add("decision", Value(elements, "decision")); } else { var nested = Elements(elements["allocations"], "allocations"); var lines = Lines(nested["allocations"], false); if (lines.Count == 0 || lines.Count != sources.Count) throw new InvalidOperationException("核销原文与快照行数不符。"); for (int i = 0; i < lines.Count; i++) if ((string)lines[i]["payableId"] != (string)sources[i]["payableId"] || (string)lines[i]["expectedVersion"] != (string)sources[i]["expectedVersion"]) throw new InvalidOperationException("核销快照版本或主键不符。"); payload.Add("allocations", lines); } } using (SqlCommand normalized = new SqlCommand()) { FinancePaymentJournalRequest.Bind(normalized, action, payload, actor); if (expected.Parameters.Contains("@动作")) foreach (SqlParameter p in normalized.Parameters) { if (p.ParameterName == "@操作人") { if (!Same(p.Value, actor) || !expected.Parameters.Contains("@人员编号") || Convert.ToString(expected.Parameters["@人员编号"].Value, CultureInfo.InvariantCulture) != actor) throw new InvalidOperationException("留存原请求与受信员工不同。"); } else if (!expected.Parameters.Contains(p.ParameterName) || !Same(p.Value, expected.Parameters[p.ParameterName].Value)) throw new InvalidOperationException("留存原请求与本次准备内容不同。"); } } var request = new Dictionary { { "requestId", id }, { "actor", actor }, { "generation", generation }, { "action", action }, { "payload", payload }, { "context", context }, { "requestHash", Cell(row, "请求摘要") }, { "contextHash", Cell(row, "快照摘要") }, { "requestVersion", Cell(row, "请求版本") }, { "state", state }, { "terminalId", terminalId }, { "acknowledged", acknowledged } }; return new Dictionary { { "summary", summary }, { "request", request } }; } } internal static class FinancePaymentRegistrationPolicy { public const decimal MaxAmount = 9999999999999999.99m; // Matches the existing DECIMAL(18,2) storage envelope, not a new currency, // exchange-rate, rounding, tolerance or accounting-period policy. public static decimal ReadAmount(string value, bool allowZero) { decimal amount; if (value == null || value.Length > 19 || !Regex.IsMatch(value, @"\A(?:0|[1-9][0-9]{0,15})(?:\.[0-9]{1,2})?\z") || !Decimal.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out amount) || amount > MaxAmount || amount < 0 || (!allowZero && amount == 0)) throw new ArgumentException("付款/核销金额必须明确填写,使用最多两位小数的非负金额;本次付款及核销须大于零,不自动舍入。"); return amount; } } internal static class FinancePaymentJournalPolicy { public const string Version = "FINANCE_PAYMENT_JOURNAL_20261103_V1"; public const int MaxAllocationLines = 200; public static void RequireCurrency(string currency) { if (currency != "USD" && currency != "CNY") throw new ArgumentException("付款仅支持已明确两位金额精度的USD或CNY,不默认币种、不自动换汇。"); } public static void RequireVersion(string version) { if (version == null || !Regex.IsMatch(version, @"\A[0-9A-F]{16}\z")) throw new ArgumentException("付款及应付均须完整八字节大写十六进制版本。"); } } }