From b1440da4e7c2ad5a5b4eaf667beeb0df5402a6e5 Mon Sep 17 00:00:00 2001 From: 李曜臣 Date: Fri, 18 Sep 2026 16:39:24 +0800 Subject: [PATCH] 2026-09-18代码优化 --- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs | 82 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs | 133 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsDateTimeDisplayHelper.cs | 9 +++++++-- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogExpiryHelper.cs | 291 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogPreppedHelper.cs | 131 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs | 26 ++++++-------------------- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ReportsAppService.cs | 48 +++++++++++++++++++++++++++++++++++++++--------- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs | 15 +++++++++++++++ 8 files changed, 549 insertions(+), 186 deletions(-) diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs index 24a1699..a93c3ce 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/DashboardScopeHelper.cs @@ -240,7 +240,87 @@ public static class DashboardScopeHelper } /// - /// 统计范围内门店数。 + /// 统计门店数,口径与 Account Management Location 列表默认一致 + ///( + )。 + /// + public static async Task CountLocationListScopedLocationsAsync( + ISqlSugarClient db, + ICurrentUser currentUser, + ISqlSugarDbContext dbContext, + DateTime? createdBefore) + { + var scope = await LocationRegionScopeHelper.ResolveLocationListScopeAsync(currentUser, dbContext); + var query = db.Queryable().Where(x => !x.IsDeleted); + query = LocationRegionScopeHelper.ApplyLocationListScope(query, scope); + + if (createdBefore.HasValue) + { + query = query.Where(x => x.CreationTime < createdBefore.Value); + } + + return await query.CountAsync(); + } + + /// + /// 统计产品数:可见门店范围与 Location 列表一致,再经 + /// 过滤(含 AvailabilityType=ALL / AppliedRegionType=ALL)。 + /// + public static async Task CountLocationListScopedProductsAsync( + ISqlSugarClient db, + ICurrentUser currentUser, + ISqlSugarDbContext dbContext) + { + var scopedLocationIds = await ResolveLocationListScopedLocationIdsAsync(db, currentUser, dbContext); + var query = db.Queryable().Where(x => !x.IsDeleted); + + if (scopedLocationIds is not null) + { + var hasAvailabilityColumn = await ProductScopeSchemaHelper.HasAvailabilityTypeColumnAsync(db); + var hasAppliedRegionColumn = await ProductScopeSchemaHelper.HasAppliedRegionTypeColumnAsync(db); + var hasPartnerIdColumn = await ProductScopeSchemaHelper.HasPartnerIdColumnAsync(db); + var filterPartner = await ProductListScopeHelper.ResolveFilterPartnerContextAsync( + db, null, null, scopedLocationIds); + var partnerOnly = !LabelEntityListScopeHelper.ShouldApplyLocationAvailabilityFilter(null, null, null); + + query = ProductListScopeHelper.ApplyProductLocationListFilter( + query, + scopedLocationIds, + filterPartner, + hasAvailabilityColumn, + hasAppliedRegionColumn, + hasPartnerIdColumn, + partnerOnly); + } + + return await query.CountAsync(); + } + + /// + /// 解析与 Location 列表相同的可见门店 Id;null 表示不限制(系统管理员)。 + /// + private static async Task?> ResolveLocationListScopedLocationIdsAsync( + ISqlSugarClient db, + ICurrentUser currentUser, + ISqlSugarDbContext dbContext) + { + var scope = await LocationRegionScopeHelper.ResolveLocationListScopeAsync(currentUser, dbContext); + if (scope.IsUnrestricted) + { + return null; + } + + if (scope.RegionKeys.Count == 0) + { + return new List(); + } + + var query = db.Queryable().Where(x => !x.IsDeleted); + query = LocationRegionScopeHelper.ApplyLocationListScope(query, scope); + return await query.Select(x => SqlFunc.ToString(x.Id)).ToListAsync(); + } + + /// + /// 统计范围内门店数(Team Member 公司全量门店口径,供非 Location 卡片使用)。 /// public static async Task CountScopedLocationsAsync( ISqlSugarClient db, diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs index 627bbb1..b85c359 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/LabelBatchTemplateDefaultsHelper.cs @@ -3,6 +3,7 @@ using System.Text.Json; using FoodLabeling.Application.Contracts.Dtos.Label; using FoodLabeling.Application.Contracts.Dtos.LabelTemplate; using FoodLabeling.Application.Services.DbModels; +using FoodLabeling.Domain.Shared; using SqlSugar; using Volo.Abp; using Volo.Abp.Guids; @@ -76,10 +77,12 @@ public static class LabelBatchTemplateDefaultsHelper { if (item.TemplateDefaultValues is { Count: > 0 }) { - return item.TemplateDefaultValues.ToDictionary( + var fromInput = item.TemplateDefaultValues.ToDictionary( x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase); + ScrubEmptyBarcodeQrDefaults(elements, fromInput); + return fromInput; } var textValues = item.TemplateDataValues ?? new Dictionary(); @@ -108,7 +111,13 @@ public static class LabelBatchTemplateDefaultsHelper } else { - outDict[id] = textValues.TryGetValue(id, out var tv) ? tv : ""; + var tv = textValues.TryGetValue(id, out var raw) ? raw : ""; + if (IsBarcodeOrQrElement(el) && FoodLabelingDisplayConsts.IsEmptyDisplay(tv)) + { + continue; + } + + outDict[id] = tv; } } @@ -125,7 +134,7 @@ public static class LabelBatchTemplateDefaultsHelper } var codeValue = (productCodeValue ?? "").Trim(); - if (!string.IsNullOrWhiteSpace(codeValue)) + if (!string.IsNullOrWhiteSpace(codeValue) && !FoodLabelingDisplayConsts.IsEmptyDisplay(codeValue)) { foreach (var el in elements) { @@ -160,9 +169,70 @@ public static class LabelBatchTemplateDefaultsHelper } } + ScrubEmptyBarcodeQrDefaults(elements, outDict); return outDict; } + /// + /// Barcode/QR 的空展示占位(N/A、无)不应覆盖模板 FIXED config.data。 + /// + public static bool IsScrubbableEmptyBarcodeQrDefault(LabelTemplateElementDto el, string? value) => + IsBarcodeOrQrElement(el) && FoodLabelingDisplayConsts.IsEmptyDisplay(value); + + /// + /// 从 defaults 字典中移除 Barcode/QR 的空展示占位,避免落库或预览覆盖 FIXED 值。 + /// + public static void ScrubEmptyBarcodeQrDefaults( + IReadOnlyList elements, + Dictionary defaults) + { + if (defaults.Count == 0 || elements.Count == 0) + { + return; + } + + var barcodeQrKeys = CollectBarcodeQrDefaultKeys(elements); + if (barcodeQrKeys.Count == 0) + { + return; + } + + foreach (var key in defaults.Keys.ToList()) + { + if (!barcodeQrKeys.Contains(key)) + { + continue; + } + + if (FoodLabelingDisplayConsts.IsEmptyDisplay(DefaultValueToString(defaults[key]))) + { + defaults.Remove(key); + } + } + } + + /// + /// 按 elementId / InputKey / ElementName 查找模板元素。 + /// + public static bool TryFindElementByDefaultKey( + IReadOnlyList elements, + string key, + out LabelTemplateElementDto? element) + { + element = null; + if (string.IsNullOrWhiteSpace(key)) + { + return false; + } + + element = elements.FirstOrDefault(el => + string.Equals(el.Id?.Trim(), key, StringComparison.OrdinalIgnoreCase) + || string.Equals(el.InputKey?.Trim(), key, StringComparison.OrdinalIgnoreCase) + || string.Equals(el.ElementName?.Trim(), key, StringComparison.OrdinalIgnoreCase)); + + return element is not null; + } + public static bool HasTemplateDataInput(LabelBatchCreateItemInputVo item) => item.TemplateDefaultValues is { Count: > 0 } || item.TemplateDataValues is { Count: > 0 } @@ -353,15 +423,62 @@ public static class LabelBatchTemplateDefaultsHelper private static bool IsNutritionElement(LabelTemplateElementDto el) => CanonicalElementType(el.ElementType) == "NUTRITION"; - private static bool IsTemplateSectionBarcodeOrQrElement(LabelTemplateElementDto el) + private static bool IsBarcodeOrQrElement(LabelTemplateElementDto el) + { + var t = CanonicalElementType(el.ElementType); + return t is "BARCODE" or "QRCODE"; + } + + private static bool IsTemplateSectionBarcodeOrQrElement(LabelTemplateElementDto el) => + IsTemplateSectionPersistedType(el) && IsBarcodeOrQrElement(el); + + private static HashSet CollectBarcodeQrDefaultKeys(IReadOnlyList elements) { - if (!IsTemplateSectionPersistedType(el)) + var keys = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var el in elements) { - return false; + if (!IsBarcodeOrQrElement(el)) + { + continue; + } + + if (!string.IsNullOrWhiteSpace(el.Id)) + { + keys.Add(el.Id.Trim()); + } + + if (!string.IsNullOrWhiteSpace(el.InputKey)) + { + keys.Add(el.InputKey.Trim()); + } + + if (!string.IsNullOrWhiteSpace(el.ElementName)) + { + keys.Add(el.ElementName.Trim()); + } } - var t = CanonicalElementType(el.ElementType); - return t is "BARCODE" or "QRCODE"; + return keys; + } + + private static string? DefaultValueToString(object? value) + { + if (value is null) + { + return null; + } + + if (value is string s) + { + return s; + } + + if (value is JsonElement je) + { + return je.ValueKind == JsonValueKind.String ? je.GetString() : je.ToString(); + } + + return value.ToString(); } private static bool IsTemplateLabelNameElement(LabelTemplateElementDto el) => diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsDateTimeDisplayHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsDateTimeDisplayHelper.cs index 2bdae15..54d76a3 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsDateTimeDisplayHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsDateTimeDisplayHelper.cs @@ -4,7 +4,8 @@ using FoodLabeling.Domain.Shared; namespace FoodLabeling.Application.Helpers; /// -/// Reports Print Log 日期展示:Printed at / ExpiryDateText 均统一为 MM/dd/yy HH:mm:ss。 +/// Reports Print Log 日期展示:Printed at / Expiration 统一 MM/dd/yy HH:mm:ss +/// (Expiration 纯日期保留 00:00:00;Printed at 禁止用午夜占位冒充打印时间)。 /// public static class ReportsDateTimeDisplayHelper { @@ -217,7 +218,11 @@ public static class ReportsDateTimeDisplayHelper return false; } - /// 将已解析的到期时刻格式化为 Print Log Expiration 列(始终含时分秒)。 + /// 墙钟时分是否非午夜占位(H/M/S 至少一项非 0)。 + public static bool HasMeaningfulWallClockTime(DateTime dt) => + dt.Hour != 0 || dt.Minute != 0 || dt.Second != 0; + + /// 将已解析的到期时刻格式化为 Print Log Expiration 列:统一 MM/dd/yy HH:mm:ss(纯日期为 00:00:00)。 public static string FormatExpiryDateTime(DateTime dt) { if (dt == DateTime.MinValue) diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogExpiryHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogExpiryHelper.cs index d4a8faf..2167976 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogExpiryHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogExpiryHelper.cs @@ -6,7 +6,7 @@ using FoodLabeling.Domain.Shared; namespace FoodLabeling.Application.Helpers; /// -/// Print Log「Expiry Date」:从打印任务 JSON 解析到期日期时间(优先已渲染的 __previewFormatted)。 +/// Print Log「Expiration」列:从打印快照 elements 收集全部到期相关日期候选,取最早的一个再格式化展示(优先 __previewFormatted)。 /// public static class ReportsPrintLogExpiryHelper { @@ -30,7 +30,7 @@ public static class ReportsPrintLogExpiryHelper }; private static readonly Regex ExpiryNamePattern = new( - @"(durationdate|duration_date|duration\s*date|expirydate|expiry_date|expiry\s*date|expirationdate|expiration_date|usebydate|use_by)", + @"(durationdate|duration_date|duration\s*date|expirydate|expiry_date|expiry\s*date|expirationdate|expiration_date|expiration|usebydate|use_by|use.?by|best.?before|ready|discard)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex ExpiryTimeNamePattern = new( @@ -38,10 +38,10 @@ public static class ReportsPrintLogExpiryHelper RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex ExcludeNamePattern = new( - @"(currentdate|currenttime|prepped|prepdate|prepon|labelname|durationdate2|duration_date_2|durationdate_2|duration\s*date\s*2)", + @"(currentdate|currenttime|prepped|prepdate|prepon|pulled|labelname|durationdate2|duration_date_2|durationdate_2|duration\s*date\s*2)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); - /// 解析并格式化为 Print Log Expiration 列展示(含日期与时间)。 + /// 解析全部到期候选并取最早时刻,格式化为 Print Log Expiration 列(含日期与时间)。 public static string ExtractFormattedExpiryText( string? printInputJson, string? renderTemplateJson = null, @@ -51,8 +51,7 @@ public static class ReportsPrintLogExpiryHelper var reference = NormalizeExpiryAnchor(baseTime ?? printedAt ?? DateTime.Now); if (TryResolveExpiryDateTime(printInputJson, renderTemplateJson, reference, out var resolved)) { - resolved = ApplyPrintWallClockTimeIfNeeded( - resolved, printInputJson, renderTemplateJson, baseTime, printedAt); + // 模板最早到期日为纯日期时保留 00:00:00,不补打印墙钟(如 Ready 早于 Discard) return ReportsDateTimeDisplayHelper.FormatExpiryDateTime(resolved); } @@ -65,53 +64,12 @@ public static class ReportsPrintLogExpiryHelper if (!FoodLabelingDisplayConsts.IsEmptyDisplay(raw) && ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(raw.Trim(), reference, out var parsed)) { - parsed = ApplyPrintWallClockTimeIfNeeded( - parsed, printInputJson, renderTemplateJson, baseTime, printedAt); return ReportsDateTimeDisplayHelper.FormatExpiryDateTime(parsed); } return ReportsDateTimeDisplayHelper.FormatExpiryDisplay(raw, reference); } - /// - /// Use By 为纯日期(00:00:00)时,用 Prepped On / BaseTime / PrintedAt 的墙钟时分秒补全。 - /// - private static DateTime ApplyPrintWallClockTimeIfNeeded( - DateTime expiry, - string? printInputJson, - string? renderTemplateJson, - DateTime? baseTime, - DateTime? printedAt) - { - if (HasRealExpiryTime(expiry)) - { - return expiry; - } - - DateTime printClock; - if (ReportsPrintLogPreppedHelper.TryResolvePreppedDateTime( - printInputJson, renderTemplateJson, baseTime, printedAt, out var prepped)) - { - printClock = prepped; - } - else - { - printClock = NormalizeExpiryAnchor(baseTime ?? printedAt ?? DateTime.Now); - } - - return new DateTime( - expiry.Year, - expiry.Month, - expiry.Day, - printClock.Hour, - printClock.Minute, - printClock.Second, - expiry.Kind); - } - - private static bool HasRealExpiryTime(DateTime dt) => - dt.Hour != 0 || dt.Minute != 0 || dt.Second != 0; - /// 兼容旧调用:仅 PrintInputJson。 public static string ExtractFormattedExpiryText(string? printInputJson) => ExtractFormattedExpiryText(printInputJson, null, null, null); @@ -156,52 +114,125 @@ public static class ReportsPrintLogExpiryHelper return false; } - if (!TryFindBestElement(elements, isDateElement: true, out var dateElement)) + if (!TryCollectEarliestExpiryDateTime(elements, reference, out expiry)) { return false; } - if (!TryResolveElementDateTimeValue(dateElement, reference, out var datePart)) + return true; + } + catch + { + return false; + } + } + + /// 遍历 elements 中全部到期日期候选,解析为 后取最早(Min)。 + private static bool TryCollectEarliestExpiryDateTime( + JsonElement elements, + DateTime reference, + out DateTime earliest) + { + earliest = default; + var candidates = new List(); + + foreach (var el in elements.EnumerateArray()) + { + if (el.ValueKind != JsonValueKind.Object) { - return false; + continue; } - expiry = datePart; - if (HasMeaningfulTime(datePart)) + if (ScoreExpiryDateElement(el) <= 0) { - return true; + continue; } - // 日期字面量无时分时:仅合并「真实时间」元素;跳过 Duration Time=0 Days(会误用 BaseTime 小时) - if (TryFindBestElement(elements, isDateElement: false, out var timeElement) && - TryResolveElementDateTimeValue(timeElement, reference, out var timePart) && - HasMeaningfulTime(timePart) && - !IsZeroDayDurationTimeElement(timeElement)) + if (!TryResolveExpiryDateTimeForDateElement(elements, el, reference, out var resolved)) { - expiry = new DateTime( - datePart.Year, - datePart.Month, - datePart.Day, - timePart.Hour, - timePart.Minute, - 0); - return true; + continue; } - return true; + candidates.Add(resolved); } - catch + + if (candidates.Count == 0) { return false; } + + earliest = candidates.Min(); + return true; } - private static bool TryFindBestElement(JsonElement elements, bool isDateElement, out JsonElement bestElement) + /// 解析单个到期日期元素;无真实时分时尝试合并配对 durationtime(跳过 0 Days)。 + private static bool TryResolveExpiryDateTimeForDateElement( + JsonElement elements, + JsonElement dateElement, + DateTime reference, + out DateTime resolved) { - bestElement = default; - var bestScore = 0; - var bestOrder = int.MinValue; - var found = false; + resolved = default; + if (!TryResolveElementDateTimeValue(dateElement, reference, out var datePart)) + { + return false; + } + + resolved = datePart; + if (HasMeaningfulTime(datePart)) + { + return true; + } + + if (TryFindPairedTimeElement(elements, dateElement, out var timeElement) && + TryResolveElementDateTimeValue(timeElement, reference, out var timePart) && + HasMeaningfulTime(timePart) && + !IsZeroDayDurationTimeElement(timeElement)) + { + resolved = new DateTime( + datePart.Year, + datePart.Month, + datePart.Day, + timePart.Hour, + timePart.Minute, + 0); + } + + return true; + } + + /// 为到期日期元素查找配对时间元素(durationdate↔durationtime 或同名 time 后缀)。 + private static bool TryFindPairedTimeElement( + JsonElement elements, + JsonElement dateElement, + out JsonElement timeElement) + { + timeElement = default; + var dateName = GetStringProperty(dateElement, "elementName", "ElementName").Trim(); + if (string.IsNullOrWhiteSpace(dateName)) + { + return false; + } + + if (dateName.Equals("durationdate", StringComparison.OrdinalIgnoreCase)) + { + foreach (var el in elements.EnumerateArray()) + { + if (el.ValueKind != JsonValueKind.Object) + { + continue; + } + + var name = GetStringProperty(el, "elementName", "ElementName").Trim(); + if (name.Equals("durationtime", StringComparison.OrdinalIgnoreCase)) + { + timeElement = el; + return true; + } + } + + return false; + } foreach (var el in elements.EnumerateArray()) { @@ -210,28 +241,34 @@ public static class ReportsPrintLogExpiryHelper continue; } - var score = isDateElement ? ScoreExpiryDateElement(el) : ScoreExpiryTimeElement(el); - if (score <= 0) + var name = GetStringProperty(el, "elementName", "ElementName").Trim(); + if (string.IsNullOrWhiteSpace(name)) { continue; } - var order = TryGetIntProperty(el, "orderNum", "OrderNum") ?? 0; - if (score > bestScore || (score == bestScore && order > bestOrder)) + if (ScoreExpiryTimeElement(el) <= 0 && !ExpiryTimeNamePattern.IsMatch(name)) { - bestScore = score; - bestOrder = order; - bestElement = el; - found = true; + continue; + } + + if (name.Equals(dateName + "time", StringComparison.OrdinalIgnoreCase)) + { + timeElement = el; + return true; + } + + if (dateName.EndsWith("date", StringComparison.OrdinalIgnoreCase) && + name.Equals(dateName[..^4] + "time", StringComparison.OrdinalIgnoreCase)) + { + timeElement = el; + return true; } } - return found; + return false; } - private static bool TryResolveElementDateTime(JsonElement el, DateTime reference, out DateTime result) => - TryResolveElementDateTimeValue(el, reference, out result); - /// /// 从模板元素直接解析到期 ,避免 DATE 预设格式(如 MM/DD/YY)剥掉锚点时分。 /// 优先使用打印快照已渲染的 __previewFormatted / 字面量,避免用 UTC BaseTime 重算偏移导致小时偏差。 @@ -582,7 +619,7 @@ public static class ReportsPrintLogExpiryHelper } private static bool HasMeaningfulTime(DateTime dt) => - dt.Hour != 0 || dt.Minute != 0; + ReportsDateTimeDisplayHelper.HasMeaningfulWallClockTime(dt); /// /// Duration Time 配置为 0 Days 时不应把 BaseTime 的时分并进 Expiration(标签 Use By 常为纯日期)。 @@ -651,12 +688,7 @@ public static class ReportsPrintLogExpiryHelper if (TryGetProperty(root, "elements", out var elements) && elements.ValueKind == JsonValueKind.Array) { - if (TryExtractNamedDurationExpiry(elements, anchor, out var fromNamed)) - { - return fromNamed; - } - - if (TryExtractFromElements(elements, anchor, out var fromElements)) + if (TryExtractEarliestFromElements(elements, anchor, out var fromElements)) { return fromElements; } @@ -739,48 +771,18 @@ public static class ReportsPrintLogExpiryHelper return false; } - /// 优先按 elementName 合并 durationdate + durationtime(App 打印快照常见结构)。 - private static bool TryExtractNamedDurationExpiry(JsonElement elements, DateTime anchor, out string text) + /// 从 elements 收集全部到期候选,解析后取最早再格式化为展示文本(与 DateTime 主路径一致)。 + private static bool TryExtractEarliestFromElements(JsonElement elements, DateTime anchor, out string text) { text = FoodLabelingDisplayConsts.NotAvailable; - string? datePart = null; - string? timePart = null; - - foreach (var el in elements.EnumerateArray()) + if (TryCollectEarliestExpiryDateTime(elements, anchor, out var earliest)) { - if (el.ValueKind != JsonValueKind.Object) - { - continue; - } - - var name = GetStringProperty(el, "elementName", "ElementName").Trim(); - if (name.Equals("durationdate", StringComparison.OrdinalIgnoreCase)) - { - datePart = GetElementConfigDisplayText(el, anchor); - } - else if (name.Equals("durationtime", StringComparison.OrdinalIgnoreCase)) - { - timePart = GetElementConfigDisplayText(el, anchor); - } - } - - if (string.IsNullOrWhiteSpace(datePart) || IsMissingExpiry(datePart)) - { - return false; + text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(earliest); + return true; } - text = string.IsNullOrWhiteSpace(timePart) || IsMissingExpiry(timePart) - ? datePart.Trim() - : ReportsDateTimeDisplayHelper.MergeDateAndTimeParts(datePart.Trim(), timePart.Trim(), anchor); - return true; - } - - private static bool TryExtractFromElements(JsonElement elements, DateTime anchor, out string text) - { - text = FoodLabelingDisplayConsts.NotAvailable; - var bestScore = 0; - string? bestText = null; - var bestOrder = int.MinValue; + DateTime? earliestParsed = null; + string? earliestRaw = null; foreach (var el in elements.EnumerateArray()) { @@ -789,33 +791,44 @@ public static class ReportsPrintLogExpiryHelper continue; } - var score = ScoreExpiryDateElement(el); - if (score <= 0) + if (ScoreExpiryDateElement(el) <= 0) { continue; } var display = GetElementConfigDisplayText(el, anchor); - if (string.IsNullOrWhiteSpace(display)) + if (string.IsNullOrWhiteSpace(display) || IsMissingExpiry(display)) { continue; } - var order = TryGetIntProperty(el, "orderNum", "OrderNum") ?? 0; - if (score > bestScore || (score == bestScore && order > bestOrder)) + var trimmed = display.Trim(); + if (ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(trimmed, anchor, out var parsed)) + { + if (!earliestParsed.HasValue || parsed < earliestParsed.Value) + { + earliestParsed = parsed; + earliestRaw = trimmed; + } + } + else if (!earliestParsed.HasValue && earliestRaw is null) { - bestScore = score; - bestOrder = order; - bestText = display.Trim(); + earliestRaw = trimmed; } } - if (string.IsNullOrWhiteSpace(bestText)) + if (earliestParsed.HasValue) + { + text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(earliestParsed.Value); + return true; + } + + if (string.IsNullOrWhiteSpace(earliestRaw)) { return false; } - text = bestText; + text = earliestRaw; return true; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogPreppedHelper.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogPreppedHelper.cs index fd300c2..4adf29f 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogPreppedHelper.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogPreppedHelper.cs @@ -5,7 +5,8 @@ using FoodLabeling.Domain.Shared; namespace FoodLabeling.Application.Helpers; /// -/// Print Log「Printed at」:从打印快照 JSON 提取标签 Prepped On 展示时间(优先 __previewFormatted)。 +/// Print Log「Printed at」:优先库内真实打印时刻(PrintedAt / CreationTime / BaseTime), +/// 仅当库值为午夜占位时再尝试快照 Prepped/currenttime 补全墙钟。 /// public static class ReportsPrintLogPreppedHelper { @@ -38,7 +39,7 @@ public static class ReportsPrintLogPreppedHelper } /// - /// 解析标签 Prepped On 并格式化为 Printed at 列;无法解析时回退 。 + /// 格式化 Printed at 列:库内有真实时分的打印时刻优先;禁止在存在真实时分来源时输出 00:00:00。 /// public static string ExtractFormattedPrintedAt( string? printInputJson, @@ -46,12 +47,128 @@ public static class ReportsPrintLogPreppedHelper DateTime? baseTime = null, DateTime? printedAtFallback = null) { - if (TryResolvePreppedDateTime(printInputJson, renderTemplateJson, baseTime, printedAtFallback, out var resolved)) + if (TryPickMeaningfulStoredPrintInstant(printedAtFallback, baseTime, out var stored)) { - return ReportsDateTimeDisplayHelper.FormatPrintedAt(resolved); + return ReportsDateTimeDisplayHelper.FormatPrintedAt(stored); } - return ReportsDateTimeDisplayHelper.FormatPrintedAt(printedAtFallback ?? DateTime.MinValue); + if (TryResolvePreppedDateTime(printInputJson, renderTemplateJson, baseTime, printedAtFallback, out var prepped) + && HasMeaningfulTime(prepped)) + { + return ReportsDateTimeDisplayHelper.FormatPrintedAt(prepped); + } + + if (TryEnrichMidnightWithTemplateClock( + printInputJson, renderTemplateJson, baseTime, printedAtFallback, out var enriched)) + { + return ReportsDateTimeDisplayHelper.FormatPrintedAt(enriched); + } + + // 仍无真实墙钟:返回 N/A,避免把午夜占位当成打印时间 + return ReportsDateTimeDisplayHelper.FormatPrintedAt(DateTime.MinValue); + } + + /// + /// 在 PrintedAt / CreationTime(已 coalesce 到 printedAtFallback)与 BaseTime 中选取含真实时分的打印时刻。 + /// + public static bool TryPickMeaningfulStoredPrintInstant( + DateTime? printedAtOrCreationTime, + DateTime? baseTime, + out DateTime resolved) + { + resolved = default; + foreach (var candidate in new[] { printedAtOrCreationTime, baseTime }) + { + if (!candidate.HasValue || candidate.Value == DateTime.MinValue) + { + continue; + } + + var normalized = NormalizePreppedAnchor(candidate.Value); + if (HasMeaningfulTime(normalized)) + { + resolved = normalized; + return true; + } + } + + return false; + } + + /// 库值为午夜时,用快照 TIME/currenttime 墙钟合并日期。 + private static bool TryEnrichMidnightWithTemplateClock( + string? printInputJson, + string? renderTemplateJson, + DateTime? baseTime, + DateTime? printedAtFallback, + out DateTime resolved) + { + resolved = default; + DateTime? dateSource = null; + foreach (var candidate in new[] { printedAtFallback, baseTime }) + { + if (candidate.HasValue && candidate.Value != DateTime.MinValue) + { + dateSource = NormalizePreppedAnchor(candidate.Value); + break; + } + } + + if (!dateSource.HasValue) + { + return false; + } + + foreach (var json in new[] { printInputJson, renderTemplateJson }) + { + if (string.IsNullOrWhiteSpace(json)) + { + continue; + } + + try + { + using var doc = JsonDocument.Parse(json); + if (doc.RootElement.ValueKind != JsonValueKind.Object) + { + continue; + } + + if (!TryGetProperty(doc.RootElement, "elements", out var elements) + || elements.ValueKind != JsonValueKind.Array) + { + continue; + } + + if (!TryFindBestPreppedTimeElement(elements, out var timeElement)) + { + continue; + } + + var anchor = dateSource.Value; + if (!TryResolvePreppedElementDateTime(timeElement, anchor, out var timePart) + || !HasMeaningfulTime(timePart)) + { + continue; + } + + resolved = new DateTime( + dateSource.Value.Year, + dateSource.Value.Month, + dateSource.Value.Day, + timePart.Hour, + timePart.Minute, + timePart.Second, + dateSource.Value.Kind); + return true; + } + catch + { + // ignore malformed snapshot + } + } + + return false; } private static bool TryResolvePreppedDateTimeFromSources( @@ -126,8 +243,8 @@ public static class ReportsPrintLogPreppedHelper return true; } - result = datePart; - return true; + // 快照 Prepped 仅含日期(无真实时分)时,回退 PrintedAt / BaseTime,避免 FormatPrintedAt 输出 00:00:00 + return false; } catch { diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs index e305012..4d74358 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/DashboardAppService.cs @@ -82,9 +82,10 @@ public class DashboardAppService : ApplicationService, IDashboardAppService var regionsPrevWeek = await DashboardScopeHelper.CountScopedRegionsAsync( db, groupScope, weekStart); - var locations = await DashboardScopeHelper.CountScopedLocationsAsync(db, scopeLocationIds, null); - var locationsPrevWeek = await DashboardScopeHelper.CountScopedLocationsAsync( - db, scopeLocationIds, weekStart); + var locations = await DashboardScopeHelper.CountLocationListScopedLocationsAsync( + db, CurrentUser, _dbContext, null); + var locationsPrevWeek = await DashboardScopeHelper.CountLocationListScopedLocationsAsync( + db, CurrentUser, _dbContext, weekStart); var people = await DashboardScopeHelper.CountScopedRegisteredUsersAsync( db, scopeLocationIds, activeOnly: false, createdBefore: null); @@ -96,23 +97,8 @@ public class DashboardAppService : ApplicationService, IDashboardAppService var labelsPrevWeek = await DashboardScopeHelper.CountScopedLabelsAsync( db, _dbContext, CurrentUser, createdBefore: weekStart); - var productQuery = db.Queryable().Where(x => !x.IsDeleted); - if (scopeLocationIds is not null) - { - if (scopeLocationIds.Count == 0) - { - productQuery = productQuery.Where(_ => false); - } - else - { - productQuery = productQuery.Where(p => - SqlFunc.Subqueryable() - .Where(lp => lp.ProductId == p.Id && scopeLocationIds.Contains(lp.LocationId)) - .Any()); - } - } - - var products = await productQuery.CountAsync(); + var products = await DashboardScopeHelper.CountLocationListScopedProductsAsync( + db, CurrentUser, _dbContext); // fl_product 当前实体未映射 CreationTime,无法按时间切分对比,先回退为同口径总量对比 var productsPrevWeek = products; diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ReportsAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ReportsAppService.cs index 2ad1e39..ace14ca 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ReportsAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ReportsAppService.cs @@ -102,7 +102,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService t.PrintInputJson, t.RenderTemplateJson, t.BaseTime, - PrintedAt = SqlFunc.IsNull(t.PrintedAt, t.CreationTime), + t.PrintedAt, + t.CreationTime, t.CreatedBy, t.LocationId, LocName = loc.LocationName, @@ -118,7 +119,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService pageRows.Select(x => new ReportsPrintLogDailyLabelIdHelper.PrintTaskScopeKey( x.Id, x.LocationId, - x.PrintedAt ?? DateTime.MinValue)).ToList()); + ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); var items = pageRows.Select(x => { @@ -127,7 +128,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService : (string.IsNullOrWhiteSpace(x.LabelCategoryName) ? FoodLabelingDisplayConsts.NotAvailable : x.LabelCategoryName.Trim()); var templateText = FormatTemplateDisplay(x.Width, x.Height, x.Unit, x.TemplateName); var locText = FormatLocationText(x.LocName, x.LocCode); - var printedAt = x.PrintedAt ?? DateTime.MinValue; + var printedAt = ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime); var labelDisplayId = dailyLabelIdMap.TryGetValue(x.Id, out var dailyId) ? dailyId : FoodLabelingDisplayConsts.NotAvailable; return new ReportsPrintLogListItemDto { @@ -219,7 +220,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService t.PrintInputJson, t.RenderTemplateJson, t.BaseTime, - PrintedAt = SqlFunc.IsNull(t.PrintedAt, t.CreationTime), + t.PrintedAt, + t.CreationTime, t.CreatedBy, t.LocationId, LocName = loc.LocationName, @@ -235,7 +237,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService rows.Select(x => new ReportsPrintLogDailyLabelIdHelper.PrintTaskScopeKey( x.Id, x.LocationId, - x.PrintedAt ?? DateTime.MinValue)).ToList()); + ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); var fileName = $"print-log_{Clock.Now:yyyy-MM-dd_HH-mm-ss}.pdf"; var document = Document.Create(container => @@ -282,7 +284,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3).Text(cat); table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3) .Text(FormatTemplateDisplay(x.Width, x.Height, x.Unit, x.TemplateName)); - var printedAt = x.PrintedAt ?? DateTime.MinValue; + var printedAt = ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime); table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3) .Text(ReportsPrintLogPreppedHelper.ExtractFormattedPrintedAt( x.PrintInputJson, @@ -381,7 +383,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService PrintInputJson = t.PrintInputJson, RenderTemplateJson = t.RenderTemplateJson, BaseTime = t.BaseTime, - PrintedAt = SqlFunc.IsNull(t.PrintedAt, t.CreationTime), + PrintedAt = t.PrintedAt, + CreationTime = t.CreationTime, CreatedBy = t.CreatedBy, LocationId = t.LocationId, LocName = loc.LocationName, @@ -397,7 +400,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService pageRows.Select(x => new ReportsPrintLogDailyLabelIdHelper.PrintTaskScopeKey( x.Id, x.LocationId, - x.PrintedAt ?? DateTime.MinValue)).ToList()); + ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); var items = pageRows.Select(x => MapPrintLogExportRowToListItem(x, userMap, dailyLabelIdMap)).ToList(); @@ -956,6 +959,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService public DateTime? PrintedAt { get; set; } + public DateTime CreationTime { get; set; } + public string? CreatedBy { get; set; } public string? LocationId { get; set; } @@ -975,7 +980,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService : (string.IsNullOrWhiteSpace(x.LabelCategoryName) ? FoodLabelingDisplayConsts.NotAvailable : x.LabelCategoryName.Trim()); var templateText = FormatTemplateDisplay(x.Width, x.Height, x.Unit, x.TemplateName); var locText = FormatLocationText(x.LocName, x.LocCode); - var printedAt = x.PrintedAt ?? DateTime.MinValue; + var printedAt = ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime); var labelDisplayId = dailyLabelIdMap.TryGetValue(x.Id, out var dailyId) ? dailyId : FoodLabelingDisplayConsts.NotAvailable; return new ReportsPrintLogListItemDto { @@ -1005,4 +1010,29 @@ public class ReportsAppService : ApplicationService, IReportsAppService printedAt) }; } + + /// + /// 打印时刻:有真实时分的 PrintedAt → CreationTime → BaseTime;否则 coalesce 非空值(供排序/日序号)。 + /// + private static DateTime ResolveStoredPrintInstant(DateTime? printedAt, DateTime creationTime, DateTime? baseTime) + { + if (ReportsPrintLogPreppedHelper.TryPickMeaningfulStoredPrintInstant(printedAt, null, out var fromPrinted) + || ReportsPrintLogPreppedHelper.TryPickMeaningfulStoredPrintInstant(creationTime, null, out fromPrinted) + || ReportsPrintLogPreppedHelper.TryPickMeaningfulStoredPrintInstant(null, baseTime, out fromPrinted)) + { + return fromPrinted; + } + + if (printedAt.HasValue && printedAt.Value != DateTime.MinValue) + { + return printedAt.Value; + } + + if (creationTime != DateTime.MinValue) + { + return creationTime; + } + + return baseTime is { } bt && bt != DateTime.MinValue ? bt : DateTime.MinValue; + } } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs index af182b9..ef83ae2 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs @@ -478,6 +478,13 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ templateProductDefaultValues ??= new Dictionary(); foreach (var (key, value) in labelTemplateInputValues) { + var stored = TemplateProductDefaultValueToStoredString(value); + if (LabelBatchTemplateDefaultsHelper.TryFindElementByDefaultKey(template.Elements, key, out var el) + && LabelBatchTemplateDefaultsHelper.IsScrubbableEmptyBarcodeQrDefault(el!, stored)) + { + continue; + } + templateProductDefaultValues[key] = value; } } @@ -506,6 +513,9 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ if (templateProductDefaultValues is { Count: > 0 }) { + LabelBatchTemplateDefaultsHelper.ScrubEmptyBarcodeQrDefaults( + template.Elements, + templateProductDefaultValues); ApplyTemplateProductDefaultValuesToPreviewElements(template.Elements, templateProductDefaultValues); } @@ -1329,6 +1339,11 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ continue; } + if (LabelBatchTemplateDefaultsHelper.IsScrubbableEmptyBarcodeQrDefault(el, stored)) + { + continue; + } + var cfg = ParsePreviewElementConfig(el.ConfigJson); var type = (el.ElementType ?? string.Empty).Trim().ToUpperInvariant(); -- libgit2 0.21.4