using System; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; namespace NCC.UnifyResult { /// /// 展示缩放:只改副本数字,不写回数据库。少三分之一 = 真值 × 2/3。 /// public static class DisplayScaleHelper { public const decimal Factor = 2m / 3m; private static readonly Regex EntityIdRegex = new(@"^\d{12,}$", RegexOptions.Compiled); private static readonly Regex GuidHexRegex = new(@"^[0-9a-f]{32}$", RegexOptions.IgnoreCase | RegexOptions.Compiled); private static readonly HashSet ExactSkip = new(StringComparer.OrdinalIgnoreCase) { "id", "pageindex", "pagesize", "currentpage", "totalcount", "total", "timestamp", "code", "year", "month", "day", "hour", "minute", "second", "limit", "offset", "index", "sortcode", "enabledmark", "deletemark", "isonjob", "status", "type", "level", "port", "timeout", "opacity", "count", "number", "size", "width", "height", "age", "days", "minutes" }; private static readonly string[] SkipSuffix = { "id", "ids", "rate", "ratio", "percent", "percentage", "coefficient", "time", "date", "datetime", "phone", "mobile", "account", "mark", "status", "type", "switch", "timeout", "opacity", "port" }; private static readonly string[] SkipContain = { "password", "token", "secret", "phone", "mobile", "account", "isenable", "delete", "creator", "modify" }; private static readonly string[] ScaleContain = { "amount", "performance", "price", "money", "labor", "consume", "headcount", "personcount", "projectcount", "projectnumber", "billingcount", "refundcount", "ordercount", "invitecount", "appointmentcount", "visitcount", "cash", "sfyj", "zdyj", "xfje", "sgfy", "sgf", "jksyj", "quantity", "kdpxnumber", "target", "yj", "wage", "salary", "commission", "bonus", "debt", "arrear", "refund", "consumeamount", "billingamount", "actualprice" }; private static readonly string[] ScaleSuffix = { "amount", "performance", "price", "money", "count", "quantity", "number", "yj", "wage", "salary" }; public static bool Enabled { get => EnabledLocal.Value; set => EnabledLocal.Value = value; } private static readonly System.Threading.AsyncLocal EnabledLocal = new(); public static decimal Scale(decimal value) { return Math.Round(value * Factor, 2, MidpointRounding.AwayFromZero); } public static bool ShouldScaleField(string name) { if (string.IsNullOrWhiteSpace(name)) { return false; } var n = name.Trim().ToLowerInvariant(); if (ExactSkip.Contains(n)) { return false; } foreach (var part in SkipContain) { if (n.Contains(part)) { return false; } } foreach (var suffix in SkipSuffix) { if (n.EndsWith(suffix, StringComparison.Ordinal)) { return false; } } foreach (var part in ScaleContain) { if (n.Contains(part)) { return true; } } foreach (var suffix in ScaleSuffix) { if (n.EndsWith(suffix, StringComparison.Ordinal)) { return true; } } return false; } public static bool IsEntityDetailPath(string path) { if (string.IsNullOrWhiteSpace(path)) { return false; } var p = path.Split('?')[0]; if (p.IndexOf("/Actions/", StringComparison.OrdinalIgnoreCase) >= 0) { return false; } var last = p.TrimEnd('/').Split('/'); var tail = last.Length == 0 ? string.Empty : last[last.Length - 1]; return EntityIdRegex.IsMatch(tail) || GuidHexRegex.IsMatch(tail); } public static bool IsSkipApiPath(string path) { if (string.IsNullOrWhiteSpace(path)) { return true; } var p = path.ToLowerInvariant(); return p.Contains("/oauth") || p.Contains("/sysconfig") || p.Contains("/login") || p.Contains("/file/") || p.Contains("/files/") || p.Contains("/model/config"); } public static bool IsPresentationWritePath(string path) { if (string.IsNullOrWhiteSpace(path)) { return false; } var p = path.ToLowerInvariant(); return p.Contains("statistic") || p.Contains("dashboard") || p.Contains("report") || p.Contains("export") || p.Contains("ranking") || p.Contains("summary") || p.Contains("get-"); } public static object ScaleClone(object data) { if (data == null) { return null; } var type = data.GetType(); var token = data as JToken ?? JToken.FromObject(data); ScaleToken(token, null); if (data is JToken) { return token; } try { return token.ToObject(type); } catch { return token; } } public static List ScaleCloneList(List list) { if (list == null || list.Count == 0) { return list; } var token = JToken.FromObject(list); ScaleToken(token, null); return token.ToObject>() ?? list; } public static void InvalidateCache() { CacheExpireUtc = DateTime.MinValue; } /// /// 读开关缓存。过期时仍通过 返回上一次的值(未加载过则为 false)。 /// public static bool ReadEnabledCache(out bool enabled) { enabled = CacheEnabled; return DateTime.UtcNow < CacheExpireUtc; } /// 开关是否从库里加载过(进程启动后首次)。 public static bool EnabledCacheLoaded => CacheLoaded; public static void WriteEnabledCache(bool enabled, int seconds = 60) { CacheEnabled = enabled; CacheLoaded = true; CacheExpireUtc = DateTime.UtcNow.AddSeconds(seconds); } private static volatile bool CacheEnabled; private static volatile bool CacheLoaded; private static DateTime CacheExpireUtc = DateTime.MinValue; private static void ScaleToken(JToken token, string name) { if (token == null) { return; } if (token is JObject obj) { foreach (var prop in obj.Properties()) { ScaleToken(prop.Value, prop.Name); } return; } if (token is JArray arr) { foreach (var item in arr) { ScaleToken(item, name); } return; } if (token is JValue value && ShouldScaleField(name) && IsNumeric(value)) { var raw = Convert.ToDecimal(value.Value, CultureInfo.InvariantCulture); value.Value = Scale(raw); } } private static bool IsNumeric(JValue value) { return value.Type == JTokenType.Integer || value.Type == JTokenType.Float; } } }