From a407e0e3a2f693c4e8255f26d6ebdd5e307c58d7 Mon Sep 17 00:00:00 2001 From: 李曜臣 Date: Mon, 19 Oct 2026 17:07:16 +0800 Subject: [PATCH] 2026-10-19平台端打印日志到期时间优化 --- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogDataItemDto.cs | 4 ++++ 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogItemDto.cs | 3 +++ 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs | 3 ++- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogExpiryHelper.cs | 859 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------------------------------------------------------------------------------------------------------- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/ReportsAppService.cs | 77 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------- 美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs | 247 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------------------------- 美国版/scripts/泰鄂测试版部署.ps1 | 78 ++++++++++++++++++++++++++++++++++++++++++------------------------------------ 7 files changed, 1032 insertions(+), 239 deletions(-) diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogDataItemDto.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogDataItemDto.cs index baec1ed..7d3a94d 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogDataItemDto.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogDataItemDto.cs @@ -9,6 +9,10 @@ public class PrintLogDataItemDto { public string ElementId { get; set; } = string.Empty; + /// 模板元素名(如 Duration Time (For Label)) + public string? ElementName { get; set; } + + /// 出纸文案(优先 __previewFormatted,如到期 12:00 / 10/20) public string RenderValue { get; set; } = string.Empty; /// diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogItemDto.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogItemDto.cs index a6bcefc..1514751 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogItemDto.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/Dtos/UsAppLabeling/PrintLogItemDto.cs @@ -40,6 +40,9 @@ public class PrintLogItemDto /// 打印入参 JSON(直接来自 fl_label_print_task.PrintInputJson 列) public string? PrintInputJson { get; set; } + /// 出纸明细(fl_label_print_data,含各格实际打印文案) + public List PrintDataList { get; set; } = new(); + /// 打印时间(PrintedAt ?? CreationTime) public DateTime PrintedAt { get; set; } diff --git a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs index a5a50f2..b6e6ea5 100644 --- a/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs +++ b/美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application.Contracts/IServices/IUsAppLabelingAppService.cs @@ -23,7 +23,7 @@ public interface IUsAppLabelingAppService : IApplicationService Task PreviewAsync(UsAppLabelPreviewInputVo input); /// - /// App 打印:创建打印任务并落库打印明细(fl_label_print_task / fl_label_print_data) + /// App 打印:创建打印任务,并把出纸文案写入打印日志明细(fl_label_print_task / fl_label_print_data) /// Task PrintAsync(UsAppLabelPrintInputVo input); @@ -35,6 +35,7 @@ public interface IUsAppLabelingAppService : IApplicationService /// /// App 打印日志:当前门店打印记录(分页)。已绑定该门店的账号可见门店内全部用户的打印任务。 /// 支持 printDateDay / printDate 按自然日筛选;出参 labelId 为门店当日打印序号(yyyyMMdd-n)。 + /// 出参 printDataList 为出纸明细(各格实际打印文案)。 /// Task> GetPrintLogListAsync(PrintLogGetListInputVo input); 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 df3b018..1e4b097 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 @@ -1,12 +1,14 @@ using System.Globalization; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.RegularExpressions; using FoodLabeling.Domain.Shared; namespace FoodLabeling.Application.Helpers; /// -/// Print Log「Expiration」列:从打印快照 elements 收集全部到期相关日期候选,取最早的一个再格式化展示(优先 __previewFormatted)。 +/// Print Log「Expiration」列:从打印快照 elements 解析到期日(优先 __previewFormatted)。 +/// 泰鄂标签同时有「備料日期」与「到期日期」时,必须取到期日,不能取较早的制备日。 /// public static class ReportsPrintLogExpiryHelper { @@ -39,20 +41,36 @@ public static class ReportsPrintLogExpiryHelper RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex ExcludeNamePattern = new( - @"(currentdate|currenttime|prepped|prepdate|prepon|pulled|labelname|durationdate2|duration_date_2|durationdate_2|duration\s*date\s*2)", + @"(current\s*date|currentdate|current\s*time|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 列(含日期与时间)。 + /// 打印明细一行(fl_label_print_data),出纸文案优先于偏移重算。 + public readonly record struct PrintSnapshotLine(string? ElementName, string? RenderValue, string? RenderConfigJson); + + /// + /// 解析到期时刻。优先 fl_label_print_data 出纸快照(到期日期格 + 到期时间格,如 10/20 11:06), + /// 不要用 Printed at 的时分覆盖。 + /// public static string ExtractFormattedExpiryText( string? printInputJson, string? renderTemplateJson = null, DateTime? baseTime = null, - DateTime? printedAt = null) + DateTime? printedAt = null, + IReadOnlyList? printSnapshotLines = null) { - var reference = NormalizeExpiryAnchor(baseTime ?? printedAt ?? DateTime.Now); - if (TryResolveExpiryDateTime(printInputJson, renderTemplateJson, reference, out var resolved)) + var reference = PickExpiryAnchor(baseTime, printedAt); + var snapshotJson = BuildElementsJsonFromPrintData(printSnapshotLines); + // 合并模板 + PrintInputJson + 出纸快照后再算:Duration Date Days 0 必须叠 Duration Time Hours(甘蔗糖漿 366h → 11/03 22:31) + var merged = MergeExpiryElementsJson(printInputJson, snapshotJson, renderTemplateJson); + if (TryResolveExpiryDateTimeFromTemplateJson(merged, reference, out var resolved) && + !IsPrintInstantFallback(resolved, reference)) + { + return ReportsDateTimeDisplayHelper.FormatExpiryDateTime(resolved); + } + + if (TryResolveExpiryDateTimeFromTemplateJson(printInputJson, reference, out resolved) && + !IsPrintInstantFallback(resolved, reference)) { - // 模板最早到期日为纯日期时保留 00:00:00,不补打印墙钟(如 Ready 早于 Discard) return ReportsDateTimeDisplayHelper.FormatExpiryDateTime(resolved); } @@ -73,24 +91,13 @@ public static class ReportsPrintLogExpiryHelper /// 兼容旧调用:仅 PrintInputJson。 public static string ExtractFormattedExpiryText(string? printInputJson) => - ExtractFormattedExpiryText(printInputJson, null, null, null); + ExtractFormattedExpiryText(printInputJson, null, null, null, null); - private static bool TryResolveExpiryDateTime( - string? printInputJson, - string? renderTemplateJson, - DateTime reference, - out DateTime expiry) + /// 解析结果仍是打印瞬间(0 天偏移未叠小时)时不能当到期日。 + private static bool IsPrintInstantFallback(DateTime resolved, DateTime reference) { - expiry = default; - foreach (var json in new[] { printInputJson, renderTemplateJson }) - { - if (TryResolveExpiryDateTimeFromTemplateJson(json, reference, out expiry)) - { - return true; - } - } - - return false; + var a = NormalizeExpiryAnchor(reference); + return resolved.Date == a.Date && Math.Abs((resolved - a).TotalSeconds) <= 1; } private static bool TryResolveExpiryDateTimeFromTemplateJson(string? json, DateTime reference, out DateTime expiry) @@ -115,8 +122,20 @@ public static class ReportsPrintLogExpiryHelper return false; } - if (!TryCollectEarliestExpiryDateTime(elements, reference, out expiry)) + if (TryResolveDurationDateAndTime(elements, reference, out expiry) && + !IsPrintInstantFallback(expiry, reference)) + { + return true; + } + + if (!TryCollectExpiryDateTime(elements, reference, out expiry)) + { + return false; + } + + if (IsPrintInstantFallback(expiry, reference)) { + expiry = default; return false; } @@ -128,14 +147,17 @@ public static class ReportsPrintLogExpiryHelper } } - /// 遍历 elements 中全部到期日期候选,解析为 后取最早(Min)。 - private static bool TryCollectEarliestExpiryDateTime( + /// + /// 收集到期日期候选。制备日(備料 / Prepped / 与打印时刻同一天且无正偏移)不能覆盖到期日。 + /// 同时存在多条到期候选时取最晚(Use By / Discard / 到期日期)。 + /// + private static bool TryCollectExpiryDateTime( JsonElement elements, DateTime reference, - out DateTime earliest) + out DateTime expiry) { - earliest = default; - var candidates = new List(); + expiry = default; + var candidates = new List<(int Score, DateTime Value, bool IsPrepLike)>(); foreach (var el in elements.EnumerateArray()) { @@ -144,7 +166,8 @@ public static class ReportsPrintLogExpiryHelper continue; } - if (ScoreExpiryDateElement(el) <= 0) + var score = ScoreExpiryDateElement(el); + if (score <= 0) { continue; } @@ -154,7 +177,12 @@ public static class ReportsPrintLogExpiryHelper continue; } - candidates.Add(resolved); + if (IsPrintInstantFallback(resolved, reference)) + { + continue; + } + + candidates.Add((score, resolved, IsPrepLikeExpiryElement(el, resolved, reference))); } if (candidates.Count == 0) @@ -162,11 +190,33 @@ public static class ReportsPrintLogExpiryHelper return false; } - earliest = candidates.Min(); + var useBy = candidates.Where(c => !c.IsPrepLike).ToList(); + var pool = useBy.Count > 0 ? useBy : candidates; + var bestScore = pool.Max(c => c.Score); + expiry = pool.Where(c => c.Score == bestScore).Max(c => c.Value); return true; } - /// 解析单个到期日期元素;无真实时分时尝试合并配对 durationtime(跳过 0 Days)。 + /// 備料/制备日:名称像 prep,或解析结果与打印锚点同一天且不晚于锚点。 + private static bool IsPrepLikeExpiryElement(JsonElement el, DateTime resolved, DateTime reference) + { + var nameHint = $"{GetStringProperty(el, "elementName", "ElementName")} {GetStringProperty(el, "inputKey", "InputKey")}" + .Trim(); + if (Regex.IsMatch( + nameHint, + @"備料|备料|prepped|prepdate|prepon|currentdate|pulled", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)) + { + return true; + } + + return resolved.Date <= reference.Date && resolved <= reference.AddMinutes(1); + } + + /// + /// 到期瞬间与 App 出纸一致:打印快照里的到期日期格 + 到期时间格(綠茶 10/20 11:06), + /// 不能用備料/打印时刻 15:06 覆盖时间格。 + /// private static bool TryResolveExpiryDateTimeForDateElement( JsonElement elements, JsonElement dateElement, @@ -174,35 +224,60 @@ public static class ReportsPrintLogExpiryHelper out DateTime resolved) { resolved = default; + var hasTime = TryFindPairedTimeElement(elements, dateElement, out var timeElement) || + TryFindDurationTimeElement(elements, out timeElement); + var hasDatePreview = TryGetElementPreviewDate(dateElement, reference, out var previewDate); + DateTime previewClock = default; + var hasTimePreview = hasTime && TryGetElementPreviewClock(timeElement, reference, out previewClock); + + if (hasDatePreview && hasTimePreview && HasMeaningfulTime(previewClock)) + { + resolved = CombineDateWithClock(previewDate, previewClock); + return true; + } + + var dateOff = TryReadElementOffset(dateElement); + var timeOff = hasTime ? TryReadElementOffset(timeElement) : null; + if (dateOff.HasValue || timeOff.HasValue) + { + resolved = CombineDurationExpiryDate(reference, dateOff, timeOff); + if (hasDatePreview) + { + resolved = CombineDateWithClock(previewDate, resolved); + } + + if (hasTimePreview && HasMeaningfulTime(previewClock)) + { + resolved = CombineDateWithClock(resolved, previewClock); + } + + return true; + } + if (!TryResolveElementDateTimeValue(dateElement, reference, out var datePart)) { return false; } resolved = datePart; - if (HasMeaningfulTime(datePart)) + if (hasTimePreview && HasMeaningfulTime(previewClock)) { + resolved = CombineDateWithClock(datePart, previewClock); return true; } - if (TryFindPairedTimeElement(elements, dateElement, out var timeElement) && + if (hasTime && TryResolveElementDateTimeValue(timeElement, reference, out var timePart) && HasMeaningfulTime(timePart) && - !IsZeroDayDurationTimeElement(timeElement)) + IsClockOffsetUnit(TryReadElementOffset(timeElement)?.unit)) { - resolved = new DateTime( - datePart.Year, - datePart.Month, - datePart.Day, - timePart.Hour, - timePart.Minute, - 0); + resolved = CombineDateWithClock(datePart, timePart); } return true; } - /// 为到期日期元素查找配对时间元素(durationdate↔durationtime 或同名 time 后缀)。 + /// 为到期日期元素查找配对时间元素(durationdate↔durationtime、同名 time 后缀,或 typeAdd Duration Time)。 private static bool TryFindPairedTimeElement( JsonElement elements, JsonElement dateElement, @@ -210,31 +285,8 @@ public static class ReportsPrintLogExpiryHelper { 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; - } + JsonElement? preferred = null; foreach (var el in elements.EnumerateArray()) { if (el.ValueKind != JsonValueKind.Object) @@ -243,24 +295,51 @@ public static class ReportsPrintLogExpiryHelper } var name = GetStringProperty(el, "elementName", "ElementName").Trim(); - if (string.IsNullOrWhiteSpace(name)) + if (!IsDurationTimeLike(el, name) || ExcludeNamePattern.IsMatch(name)) { continue; } - if (ScoreExpiryTimeElement(el) <= 0 && !ExpiryTimeNamePattern.IsMatch(name)) + if (!string.IsNullOrWhiteSpace(dateName) && + (name.Equals(dateName + "time", StringComparison.OrdinalIgnoreCase) || + (dateName.EndsWith("date", StringComparison.OrdinalIgnoreCase) && + name.Equals(dateName[..^4] + "time", StringComparison.OrdinalIgnoreCase)))) { - continue; + timeElement = el; + return true; } - if (name.Equals(dateName + "time", StringComparison.OrdinalIgnoreCase)) + if (dateName.Contains("duration date", StringComparison.OrdinalIgnoreCase) && + name.Contains("duration time", StringComparison.OrdinalIgnoreCase)) { timeElement = el; return true; } - if (dateName.EndsWith("date", StringComparison.OrdinalIgnoreCase) && - name.Equals(dateName[..^4] + "time", StringComparison.OrdinalIgnoreCase)) + preferred ??= el; + } + + if (preferred.HasValue) + { + timeElement = preferred.Value; + return true; + } + + return false; + } + + private static bool TryFindDurationTimeElement(JsonElement elements, out JsonElement timeElement) + { + timeElement = default; + foreach (var el in elements.EnumerateArray()) + { + if (el.ValueKind != JsonValueKind.Object) + { + continue; + } + + var name = GetStringProperty(el, "elementName", "ElementName").Trim(); + if (IsDurationTimeLike(el, name)) { timeElement = el; return true; @@ -270,6 +349,21 @@ public static class ReportsPrintLogExpiryHelper return false; } + private static bool IsDurationTimeLike(JsonElement el, string name) + { + if (ExpiryTimeNamePattern.IsMatch(name) || + ExpiryTimeNamePattern.IsMatch(GetStringProperty(el, "inputKey", "InputKey"))) + { + return true; + } + + var typeAdd = GetStringProperty(el, "typeAdd", "TypeAdd") + .Trim() + .ToLowerInvariant() + .Replace(" ", " ", StringComparison.Ordinal); + return typeAdd.Contains("duration time", StringComparison.Ordinal); + } + /// /// 从模板元素直接解析到期 ,避免 DATE 预设格式(如 MM/DD/YY)剥掉锚点时分。 /// 优先使用打印快照已渲染的 __previewFormatted / 字面量,避免用 UTC BaseTime 重算偏移导致小时偏差。 @@ -283,26 +377,21 @@ public static class ReportsPrintLogExpiryHelper } var previewFormatted = GetStringProperty(cfg, "__previewFormatted", "__PreviewFormatted").Trim(); - if (!string.IsNullOrWhiteSpace(previewFormatted) - && IsLikelyResolvedDateTimeLiteral(previewFormatted) - && ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(previewFormatted, reference, out result)) - { - return true; - } - var rawText = GetStringProperty(cfg, "text", "Text").Trim(); var formatText = GetStringProperty(cfg, "format", "Format").Trim(); var type = GetStringProperty(el, "type", "Type").Trim().ToUpperInvariant(); + var anchor = NormalizeExpiryAnchor(reference); - // 已展开的日期/时间字面量优先于偏移 JSON(打印快照与出纸一致) - if (!string.IsNullOrWhiteSpace(rawText) - && IsLikelyResolvedDateTimeLiteral(rawText) - && ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(rawText, reference, out result)) + if (TryResolveLiteralKeepingClock(previewFormatted, el, cfg, type, rawText, formatText, anchor, out result)) + { + return true; + } + + if (TryResolveLiteralKeepingClock(rawText, el, cfg, type, rawText, formatText, anchor, out result)) { return true; } - var anchor = NormalizeExpiryAnchor(reference); if (TryResolveOffsetToDateTime(anchor, rawText, out result) || TryResolveOffsetToDateTime(anchor, formatText, out result)) { @@ -328,6 +417,528 @@ public static class ReportsPrintLogExpiryHelper } /// + /// 已渲染字面量优先。纯日期(10/25)只锁定日历日,时分从 Duration 偏移或備料墙钟补上,避免变成 00:00:00。 + /// + private static bool TryResolveLiteralKeepingClock( + string literal, + JsonElement el, + JsonElement cfg, + string type, + string rawText, + string formatText, + DateTime anchor, + out DateTime result) + { + result = default; + if (string.IsNullOrWhiteSpace(literal) || !IsLikelyResolvedDateTimeLiteral(literal)) + { + return false; + } + + if (!ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(literal, anchor, out var parsed)) + { + return false; + } + + if ((HasRealTimeComponent(literal) || type == "TIME") && HasMeaningfulTime(parsed)) + { + result = parsed; + return true; + } + + result = parsed; + return true; + } + + private static bool TryResolveClockFromOffset( + JsonElement el, + JsonElement cfg, + string type, + string rawText, + string formatText, + DateTime anchor, + out DateTime clock) + { + if (TryResolveOffsetToDateTime(anchor, rawText, out clock) || + TryResolveOffsetToDateTime(anchor, formatText, out clock)) + { + return true; + } + + if (type is "DATE" or "TIME" or "DURATION") + { + var off = ReadOffsetFromElementConfig(el, cfg, type); + if (off.HasValue) + { + clock = ApplyOffsetToDate(anchor, off.Value.amount, off.Value.unit); + return true; + } + } + + clock = default; + return false; + } + + private static DateTime CombineDateWithClock(DateTime datePart, DateTime clock) => + new(datePart.Year, datePart.Month, datePart.Day, clock.Hour, clock.Minute, clock.Second, datePart.Kind); + + /// 与 App combineDurationExpiryDate 一致:Base + Duration Date + Duration Time。 + private static DateTime CombineDurationExpiryDate( + DateTime baseTime, + (int amount, string unit)? dateOff, + (int amount, string unit)? timeOff) + { + var d = baseTime; + if (dateOff.HasValue) + { + d = ApplyOffsetToDate(d, dateOff.Value.amount, dateOff.Value.unit); + if (IsClockOffsetUnit(dateOff.Value.unit) && dateOff.Value.amount != 0) + { + return d; + } + } + + if (timeOff.HasValue) + { + d = ApplyOffsetToDate(d, timeOff.Value.amount, timeOff.Value.unit); + } + + return d; + } + + private static bool IsClockOffsetUnit(string? unit) => + unit is "Seconds" or "Minutes" or "Hours"; + + private static (int amount, string unit)? TryReadElementOffset(JsonElement el) + { + if (!TryGetProperty(el, "config", out var cfg) && !TryGetProperty(el, "Config", out cfg)) + { + return null; + } + + foreach (var raw in EnumerateOffsetRaw(cfg)) + { + if (TryParseOffsetStored(raw, out var offset)) + { + var amount = NormalizeOffsetAmount(offset.value); + if (amount.HasValue) + { + return (amount.Value, offset.unit); + } + } + } + + var type = GetStringProperty(el, "type", "Type").Trim().ToUpperInvariant(); + return ReadOffsetFromElementConfig(el, cfg, type); + } + + private static IEnumerable EnumerateOffsetRaw(JsonElement cfg) + { + foreach (var key in new[] { "text", "Text", "format", "Format" }) + { + if (!TryGetProperty(cfg, key, out var v)) + { + continue; + } + + if (v.ValueKind == JsonValueKind.String) + { + var s = v.GetString(); + if (!string.IsNullOrWhiteSpace(s)) + { + yield return s; + } + } + else if (v.ValueKind == JsonValueKind.Object) + { + yield return v.GetRawText(); + } + } + } + + private static bool TryGetElementPreviewLiteral(JsonElement el, out string literal) + { + literal = string.Empty; + if (!TryGetProperty(el, "config", out var cfg) && !TryGetProperty(el, "Config", out cfg)) + { + return false; + } + + foreach (var raw in new[] + { + GetStringProperty(cfg, "__previewFormatted", "__PreviewFormatted"), + GetStringProperty(cfg, "text", "Text") + }) + { + if (!string.IsNullOrWhiteSpace(raw) && IsLikelyResolvedDateTimeLiteral(raw.Trim())) + { + literal = raw.Trim(); + return true; + } + } + + return false; + } + + private static bool TryGetElementPreviewDate(JsonElement el, DateTime reference, out DateTime date) + { + date = default; + return TryGetElementPreviewLiteral(el, out var literal) && + ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(literal, reference, out date); + } + + private static bool TryGetElementPreviewClock(JsonElement el, DateTime reference, out DateTime clock) + { + clock = default; + if (!TryGetElementPreviewLiteral(el, out var literal)) + { + return false; + } + + var trimmed = literal.Trim(); + var timeOnly = Regex.Match(trimmed, @"^(\d{1,2}):(\d{2})(?::(\d{2}))?$"); + if (timeOnly.Success && + int.TryParse(timeOnly.Groups[1].Value, out var h) && + int.TryParse(timeOnly.Groups[2].Value, out var m)) + { + var s = timeOnly.Groups[3].Success && int.TryParse(timeOnly.Groups[3].Value, out var sec) ? sec : 0; + clock = new DateTime(reference.Year, reference.Month, reference.Day, h, m, s, reference.Kind); + return HasMeaningfulTime(clock); + } + + if (!HasRealTimeComponent(trimmed)) + { + return false; + } + + return ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(trimmed, reference, out clock) && + HasMeaningfulTime(clock); + } + + private static string? BuildElementsJsonFromPrintData(IReadOnlyList? lines) + { + if (lines is null || lines.Count == 0) + { + return null; + } + + var root = new JsonObject(); + var arr = new JsonArray(); + foreach (var line in lines) + { + var name = (line.ElementName ?? string.Empty).Trim(); + var render = (line.RenderValue ?? string.Empty).Trim(); + if (render.Length == 0 || render.Equals("None", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + var inferredType = InferPrintDataElementType(name, line.RenderValue); + if (inferredType is null) + { + continue; + } + + var el = new JsonObject + { + ["elementName"] = name, + ["type"] = inferredType, + ["typeAdd"] = inferredType == "TIME" ? "duration time" : "duration date" + }; + + JsonObject cfg; + try + { + cfg = !string.IsNullOrWhiteSpace(line.RenderConfigJson) && + JsonNode.Parse(line.RenderConfigJson) is JsonObject parsed + ? parsed + : new JsonObject(); + } + catch + { + cfg = new JsonObject(); + } + + if (!cfg.ContainsKey("__previewFormatted") && + !cfg.ContainsKey("__PreviewFormatted") && + IsLikelyResolvedDateTimeLiteral(render)) + { + cfg["__previewFormatted"] = render; + } + + if (!cfg.ContainsKey("text") && !cfg.ContainsKey("Text") && render.Length > 0) + { + cfg["text"] = render; + } + + el["config"] = cfg; + arr.Add(el); + } + + root["elements"] = arr; + return root.ToJsonString(); + } + + /// + /// 模板提供 typeAdd,PrintInputJson 提供出纸预览与 Hours 偏移;空快照(RenderValue None)不得覆盖。 + /// + private static string? MergeExpiryElementsJson( + string? printInputJson, + string? snapshotJson, + string? renderTemplateJson) + { + var byKey = new Dictionary(StringComparer.OrdinalIgnoreCase); + var extras = new List(); + + void Ingest(string? json, bool requireUseful) + { + foreach (var el in ReadElementObjects(json)) + { + if (requireUseful && !HasUsefulExpiryPayload(el)) + { + continue; + } + + var key = ElementMergeKey(el); + if (key is null) + { + extras.Add(el); + continue; + } + + byKey[key] = el; + } + } + + Ingest(renderTemplateJson, false); + Ingest(printInputJson, false); + Ingest(snapshotJson, true); + + if (byKey.Count == 0 && extras.Count == 0) + { + return printInputJson ?? snapshotJson ?? renderTemplateJson; + } + + var arr = new JsonArray(); + foreach (var el in byKey.Values) + { + arr.Add(el.DeepClone()); + } + + foreach (var el in extras) + { + arr.Add(el.DeepClone()); + } + + return new JsonObject { ["elements"] = arr }.ToJsonString(); + } + + private static IEnumerable ReadElementObjects(string? json) + { + if (string.IsNullOrWhiteSpace(json)) + { + yield break; + } + + JsonNode? node; + try + { + node = JsonNode.Parse(json); + } + catch + { + yield break; + } + + if (node is not JsonObject root) + { + yield break; + } + + var arr = root["elements"] as JsonArray ?? root["Elements"] as JsonArray; + if (arr is null) + { + yield break; + } + + foreach (var item in arr) + { + if (item is JsonObject o) + { + yield return o; + } + } + } + + private static string? ElementMergeKey(JsonObject el) + { + var id = JsonNodeString(el["id"]) ?? JsonNodeString(el["Id"]); + if (!string.IsNullOrWhiteSpace(id)) + { + return "id:" + id.Trim(); + } + + var name = JsonNodeString(el["elementName"]) ?? JsonNodeString(el["ElementName"]); + return string.IsNullOrWhiteSpace(name) ? null : "name:" + name.Trim(); + } + + private static string? JsonNodeString(JsonNode? node) + { + if (node is JsonValue v && v.TryGetValue(out var s)) + { + return s; + } + + return null; + } + + private static bool HasUsefulExpiryPayload(JsonObject el) + { + var cfg = el["config"] as JsonObject ?? el["Config"] as JsonObject; + if (cfg is null) + { + return false; + } + + foreach (var key in new[] { "__previewFormatted", "__PreviewFormatted", "text", "Text" }) + { + if (cfg[key] is JsonValue jv && jv.TryGetValue(out var s) && + !string.IsNullOrWhiteSpace(s) && + (IsLikelyResolvedDateTimeLiteral(s) || s.TrimStart().StartsWith('{'))) + { + return true; + } + + if (cfg[key] is JsonObject) + { + return true; + } + } + + return false; + } + + /// 按 App 规则:Duration Date + Duration Time 预览/偏移合成到期瞬间。 + private static bool TryResolveDurationDateAndTime( + JsonElement elements, + DateTime reference, + out DateTime expiry) + { + expiry = default; + JsonElement? dateEl = null; + JsonElement? timeEl = null; + foreach (var el in elements.EnumerateArray()) + { + if (el.ValueKind != JsonValueKind.Object) + { + continue; + } + + var name = GetStringProperty(el, "elementName", "ElementName").Trim(); + if (ExcludeNamePattern.IsMatch(name)) + { + continue; + } + + if (dateEl is null && ScoreExpiryDateElement(el) > 0) + { + dateEl = el; + } + + if (timeEl is null && IsDurationTimeLike(el, name)) + { + timeEl = el; + } + } + + if (dateEl is null) + { + return false; + } + + if (!TryResolveExpiryDateTimeForDateElement(elements, dateEl.Value, reference, out expiry)) + { + return false; + } + + if (timeEl is { } te && + TryGetElementPreviewClock(te, reference, out var clock) && + HasMeaningfulTime(clock)) + { + expiry = CombineDateWithClock(expiry, clock); + } + + return !IsPrintInstantFallback(expiry, reference); + } + + private static string? InferPrintDataElementType(string elementName, string? renderValue) + { + var hint = elementName.Trim(); + if (ExcludeNamePattern.IsMatch(hint)) + { + return null; + } + + if (ExpiryTimeNamePattern.IsMatch(hint) || + hint.Contains("duration time", StringComparison.OrdinalIgnoreCase)) + { + return "TIME"; + } + + var raw = (renderValue ?? string.Empty).Trim(); + if (Regex.IsMatch(raw, @"^\d{1,2}:\d{2}(:\d{2})?$")) + { + return "TIME"; + } + + if (ExpiryNamePattern.IsMatch(hint) || + hint.Contains("duration date", StringComparison.OrdinalIgnoreCase)) + { + return "DATE"; + } + + return null; + } + + /// 00:00 / 00:00:00 是纯日期占位,不算标签上的到期时分。 + private static bool HasRealTimeComponent(string raw) + { + var m = Regex.Match(raw.Trim(), @"(\d{1,2}):(\d{2})(?::(\d{2}))?"); + if (!m.Success) + { + return false; + } + + var hour = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture); + var minute = int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture); + var second = m.Groups[3].Success + ? int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) + : 0; + return hour != 0 || minute != 0 || second != 0; + } + + /// 到期锚点:优先带真实时分的 BaseTime / Printed at(與標籤 13:46、14:00 對齊)。 + private static DateTime PickExpiryAnchor(DateTime? baseTime, DateTime? printedAt) + { + DateTime? NormalizeIfPresent(DateTime? value) => + value is { } dt && dt != DateTime.MinValue ? NormalizeExpiryAnchor(dt) : null; + + var fromBase = NormalizeIfPresent(baseTime); + var fromPrinted = NormalizeIfPresent(printedAt); + if (fromBase is { } bt && HasMeaningfulTime(bt)) + { + return bt; + } + + if (fromPrinted is { } pt && HasMeaningfulTime(pt)) + { + return pt; + } + + return fromBase ?? fromPrinted ?? DateTime.Now; + } + + /// /// BaseTime 若为 UTC(App 历史用 toISOString),按本地墙钟展示,与标签 Prepped On 对齐。 /// private static DateTime NormalizeExpiryAnchor(DateTime reference) @@ -608,7 +1219,8 @@ public static class ReportsPrintLogExpiryHelper return true; } - if (Regex.IsMatch(t, @"^\d{1,2}/\d{1,2}/\d{2,4}")) + // 标签画布常为 MM/DD 或 MM/DD HH:mm(无年份),必须当已渲染字面量,不能回退成 0 Days 制备日 + if (Regex.IsMatch(t, @"^\d{1,2}/\d{1,2}(/\d{2,4})?(\s+\d{1,2}:\d{2}(:\d{2})?)?$")) { return true; } @@ -625,46 +1237,6 @@ public static class ReportsPrintLogExpiryHelper ReportsDateTimeDisplayHelper.HasMeaningfulWallClockTime(dt); /// - /// Duration Time 配置为 0 Days 时不应把 BaseTime 的时分并进 Expiration(标签 Use By 常为纯日期)。 - /// - private static bool IsZeroDayDurationTimeElement(JsonElement el) - { - if (!TryGetProperty(el, "config", out var cfg) && !TryGetProperty(el, "Config", out cfg)) - { - return false; - } - - foreach (var raw in new[] - { - GetStringProperty(cfg, "__previewFormatted", "__PreviewFormatted"), - GetStringProperty(cfg, "text", "Text"), - GetStringProperty(cfg, "format", "Format") - }) - { - if (string.IsNullOrWhiteSpace(raw)) - { - continue; - } - - if (IsLikelyResolvedDateTimeLiteral(raw.Trim())) - { - return false; - } - - if (TryParseOffsetStored(raw, out var offset) && - string.Equals(offset.unit, "Days", StringComparison.OrdinalIgnoreCase) && - NormalizeOffsetAmount(offset.value) == 0) - { - return true; - } - } - - var type = GetStringProperty(el, "type", "Type").Trim().ToUpperInvariant(); - var off = ReadOffsetFromElementConfig(el, cfg, type); - return off is { amount: 0, unit: "Days" }; - } - - /// /// 解析保质期展示文本;无法解析时返回「无」。 /// public static string ExtractExpiryText(string? printInputJson, DateTime anchor) @@ -774,18 +1346,18 @@ public static class ReportsPrintLogExpiryHelper return false; } - /// 从 elements 收集全部到期候选,解析后取最早再格式化为展示文本(与 DateTime 主路径一致)。 + /// 从 elements 收集到期候选并格式化(与 DateTime 主路径一致,制备日让位于到期日)。 private static bool TryExtractEarliestFromElements(JsonElement elements, DateTime anchor, out string text) { text = FoodLabelingDisplayConsts.NotAvailable; - if (TryCollectEarliestExpiryDateTime(elements, anchor, out var earliest)) + if (TryCollectExpiryDateTime(elements, anchor, out var expiry)) { - text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(earliest); + text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(expiry); return true; } - DateTime? earliestParsed = null; - string? earliestRaw = null; + DateTime? latestParsed = null; + string? latestRaw = null; foreach (var el in elements.EnumerateArray()) { @@ -808,30 +1380,35 @@ public static class ReportsPrintLogExpiryHelper var trimmed = display.Trim(); if (ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(trimmed, anchor, out var parsed)) { - if (!earliestParsed.HasValue || parsed < earliestParsed.Value) + if (IsPrepLikeExpiryElement(el, parsed, anchor) && latestParsed.HasValue) + { + continue; + } + + if (!latestParsed.HasValue || parsed > latestParsed.Value) { - earliestParsed = parsed; - earliestRaw = trimmed; + latestParsed = parsed; + latestRaw = trimmed; } } - else if (!earliestParsed.HasValue && earliestRaw is null) + else if (latestRaw is null) { - earliestRaw = trimmed; + latestRaw = trimmed; } } - if (earliestParsed.HasValue) + if (latestParsed.HasValue) { - text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(earliestParsed.Value); + text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(latestParsed.Value); return true; } - if (string.IsNullOrWhiteSpace(earliestRaw)) + if (string.IsNullOrWhiteSpace(latestRaw)) { return false; } - text = earliestRaw; + text = latestRaw; return true; } 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 ace14ca..093680c 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 @@ -121,6 +121,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService x.LocationId, ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); + var printSnapshotMap = await LoadPrintSnapshotMapAsync(pageRows.Select(x => x.Id).ToList()); + var items = pageRows.Select(x => { var cat = !string.IsNullOrWhiteSpace(x.ProductCategoryName) @@ -151,11 +153,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService PrintedByName = ResolveUserName(userMap, x.CreatedBy), LocationText = locText, LocationId = x.LocationId?.Trim(), - ExpiryDateText = ReportsPrintLogExpiryHelper.ExtractFormattedExpiryText( - x.PrintInputJson, - x.RenderTemplateJson, - x.BaseTime, - printedAt) + ExpiryDateText = FormatPrintLogExpiry(x.PrintInputJson, x.RenderTemplateJson, x.BaseTime, printedAt, printSnapshotMap, x.Id) }; }).ToList(); @@ -239,6 +237,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService x.LocationId, ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); + var printSnapshotMap = await LoadPrintSnapshotMapAsync(rows.Select(x => x.Id).ToList()); + var fileName = $"print-log_{Clock.Now:yyyy-MM-dd_HH-mm-ss}.pdf"; var document = Document.Create(container => { @@ -296,11 +296,13 @@ public class ReportsAppService : ApplicationService, IReportsAppService table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3) .Text(FormatLocationText(x.LocName, x.LocCode)); table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3) - .Text(ReportsPrintLogExpiryHelper.ExtractFormattedExpiryText( + .Text(FormatPrintLogExpiry( x.PrintInputJson, x.RenderTemplateJson, x.BaseTime, - printedAt)); + printedAt, + printSnapshotMap, + x.Id)); } }); }); @@ -402,7 +404,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService x.LocationId, ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); - var items = pageRows.Select(x => MapPrintLogExportRowToListItem(x, userMap, dailyLabelIdMap)).ToList(); + var printSnapshotMap = await LoadPrintSnapshotMapAsync(pageRows.Select(x => x.Id).ToList()); + var items = pageRows.Select(x => MapPrintLogExportRowToListItem(x, userMap, dailyLabelIdMap, printSnapshotMap)).ToList(); var ms = ReportsPrintLogExcelHelper.BuildWorkbook(items); var fileName = $"print-log_{Clock.Now:yyyyMMdd-HHmmss}.xlsx"; @@ -973,7 +976,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService private static ReportsPrintLogListItemDto MapPrintLogExportRowToListItem( PrintLogExportRow x, Dictionary userMap, - IReadOnlyDictionary dailyLabelIdMap) + IReadOnlyDictionary dailyLabelIdMap, + IReadOnlyDictionary> printSnapshotMap) { var cat = !string.IsNullOrWhiteSpace(x.ProductCategoryName) ? x.ProductCategoryName!.Trim() @@ -1003,14 +1007,65 @@ public class ReportsAppService : ApplicationService, IReportsAppService PrintedByName = ResolveUserName(userMap, x.CreatedBy), LocationText = locText, LocationId = x.LocationId?.Trim(), - ExpiryDateText = ReportsPrintLogExpiryHelper.ExtractFormattedExpiryText( + ExpiryDateText = FormatPrintLogExpiry( x.PrintInputJson, x.RenderTemplateJson, x.BaseTime, - printedAt) + printedAt, + printSnapshotMap, + x.Id) }; } + private async Task>> LoadPrintSnapshotMapAsync( + IReadOnlyCollection taskIds) + { + var map = new Dictionary>(StringComparer.Ordinal); + var ids = taskIds.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList(); + if (ids.Count == 0) + { + return map; + } + + var rows = await _dbContext.SqlSugarClient.Queryable() + .Where(x => ids.Contains(x.PrintTaskId)) + .Select(x => new { x.PrintTaskId, x.ElementName, x.RenderValue, x.RenderConfigJson }) + .ToListAsync(); + + foreach (var row in rows) + { + if (!map.TryGetValue(row.PrintTaskId, out var list)) + { + list = new List(); + map[row.PrintTaskId] = list; + } + + list.Add(new ReportsPrintLogExpiryHelper.PrintSnapshotLine( + row.ElementName, + row.RenderValue, + row.RenderConfigJson)); + } + + return map; + } + + private static string FormatPrintLogExpiry( + string? printInputJson, + string? renderTemplateJson, + DateTime? baseTime, + DateTime printedAt, + IReadOnlyDictionary> printSnapshotMap, + string taskId) + { + printSnapshotMap.TryGetValue(taskId, out var lines); + return ReportsPrintLogExpiryHelper.ExtractFormattedExpiryText( + printInputJson, + renderTemplateJson, + baseTime, + printedAt, + lines); + } + /// /// 打印时刻:有真实时分的 PrintedAt → CreationTime → BaseTime;否则 coalesce 非空值(供排序/日序号)。 /// 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 ef83ae2..da7bbfb 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 @@ -656,22 +656,23 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ var currentUserId = CurrentUser?.Id?.ToString(); var batchId = _guidGenerator.Create().ToString(); var taskIds = new List(); + var printInputById = IndexPrintInputElements(input.PrintInputJson); for (var i = 1; i <= quantity; i++) { var taskId = _guidGenerator.Create().ToString(); taskIds.Add(taskId); - var renderTemplate = resolvedTemplate; + var renderTemplate = JsonSerializer.Deserialize( + JsonSerializer.Serialize(resolvedTemplate)) + ?? resolvedTemplate; if (reservedDailyLabelIds is { Count: > 0 }) { var dailyId = reservedDailyLabelIds[Math.Min(i - 1, reservedDailyLabelIds.Count - 1)]; - renderTemplate = JsonSerializer.Deserialize( - JsonSerializer.Serialize(resolvedTemplate)) - ?? resolvedTemplate; LabelTemplateLabelIdHelper.ApplyLabelIdToElements(renderTemplate.Elements, dailyId); } + ApplyLivePrintSnapshot(renderTemplate, printInputById); var renderTemplateJsonStr = JsonSerializer.Serialize(renderTemplate); var task = new FlLabelPrintTaskDbEntity @@ -701,29 +702,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ await _dbContext.SqlSugarClient.Insertable(task).ExecuteCommandAsync(); - var rows = renderTemplate.Elements.Select(e => - { - var cfgJson = e.ConfigJson is null ? null : JsonSerializer.Serialize(e.ConfigJson); - string? renderValue = null; - if (e.ConfigJson is JsonElement je && je.ValueKind == JsonValueKind.Object && je.TryGetProperty("text", out var tv)) - { - renderValue = tv.ValueKind == JsonValueKind.String ? tv.GetString() : tv.ToString(); - } - else if (e.ConfigJson is Dictionary dict && dict.TryGetValue("text", out var v)) - { - renderValue = v?.ToString(); - } - - return new FlLabelPrintDataDbEntity - { - Id = _guidGenerator.Create().ToString(), - PrintTaskId = taskId, - ElementId = e.Id?.Trim() ?? string.Empty, - ElementName = e.ElementName?.Trim(), - RenderValue = renderValue, - RenderConfigJson = cfgJson - }; - }).Where(x => !string.IsNullOrWhiteSpace(x.ElementId)).ToList(); + var rows = BuildPrintDataRows(taskId, renderTemplate); if (rows.Count > 0) { @@ -854,29 +833,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ await _dbContext.SqlSugarClient.Insertable(newTask).ExecuteCommandAsync(); - var rows = resolvedTemplate.Elements.Select(e => - { - var cfgJson = e.ConfigJson is null ? null : JsonSerializer.Serialize(e.ConfigJson); - string? renderValue = null; - if (e.ConfigJson is JsonElement je && je.ValueKind == JsonValueKind.Object && je.TryGetProperty("text", out var tv)) - { - renderValue = tv.ValueKind == JsonValueKind.String ? tv.GetString() : tv.ToString(); - } - else if (e.ConfigJson is Dictionary dict && dict.TryGetValue("text", out var v)) - { - renderValue = v?.ToString(); - } - - return new FlLabelPrintDataDbEntity - { - Id = _guidGenerator.Create().ToString(), - PrintTaskId = newTaskId, - ElementId = e.Id?.Trim() ?? string.Empty, - ElementName = e.ElementName?.Trim(), - RenderValue = renderValue, - RenderConfigJson = cfgJson - }; - }).Where(x => !string.IsNullOrWhiteSpace(x.ElementId)).ToList(); + var rows = BuildPrintDataRows(newTaskId, resolvedTemplate); if (rows.Count > 0) { @@ -957,6 +914,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ /// /// 可选按自然日筛选:printDateDay(yyyy-MM-dd,优先)或 printDate;均未传则返回该门店全部记录(分页)。 /// 出参 labelId 为门店当日打印序号(yyyyMMdd-n)。 + /// 出参 printDataList 为本次出纸各格文案(来自 fl_label_print_data)。 /// ```json /// { /// "locationId": "11111111-1111-1111-1111-111111111111", @@ -1072,6 +1030,8 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ pageRows.Select(x => new ReportsPrintLogDailyLabelIdHelper.PrintTaskScopeKey( x.Id, locationId, x.PrintedAt ?? x.CreationTime)).ToList()); + var printDataMap = await LoadPrintDataListMapAsync(pageTaskIds); + var items = pageRows.Select(x => new PrintLogItemDto { TaskId = x.Id, @@ -1085,6 +1045,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ TypeName = x.TypeName ?? string.Empty, LabelSizeText = FormatLabelSizeWithUnit(x.TemplateWidth, x.TemplateHeight, x.TemplateUnit), PrintInputJson = x.PrintInputJson, + PrintDataList = printDataMap.TryGetValue(x.Id, out var dataList) ? dataList : new List(), PrintedAt = x.PrintedAt ?? x.CreationTime, OperatorName = UsAppPrintLogScopeHelper.ResolveOperatorName( operatorMap, @@ -1955,6 +1916,192 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ public string TemplateUnit { get; set; } = "inch"; } + private List BuildPrintDataRows(string taskId, LabelTemplatePreviewDto renderTemplate) + { + return renderTemplate.Elements.Select(e => + { + var cfgJson = e.ConfigJson is null ? null : JsonSerializer.Serialize(e.ConfigJson); + return new FlLabelPrintDataDbEntity + { + Id = _guidGenerator.Create().ToString(), + PrintTaskId = taskId, + ElementId = e.Id?.Trim() ?? string.Empty, + ElementName = e.ElementName?.Trim(), + RenderValue = ExtractPrintRenderValue(e.ConfigJson), + RenderConfigJson = cfgJson + }; + }).Where(x => !string.IsNullOrWhiteSpace(x.ElementId)).ToList(); + } + + private static void ApplyLivePrintSnapshot( + LabelTemplatePreviewDto template, + IReadOnlyDictionary printInputById) + { + foreach (var el in template.Elements) + { + var liveCfg = ResolveLivePrintConfig(el, printInputById); + if (liveCfg is not null) + { + el.ConfigJson = liveCfg; + } + } + } + + private async Task>> LoadPrintDataListMapAsync( + IReadOnlyCollection taskIds) + { + var map = new Dictionary>(StringComparer.Ordinal); + if (taskIds.Count == 0) + { + return map; + } + + var rows = await _dbContext.SqlSugarClient.Queryable() + .Where(x => taskIds.Contains(x.PrintTaskId)) + .Select(x => new { x.PrintTaskId, x.ElementId, x.ElementName, x.RenderValue, x.RenderConfigJson }) + .ToListAsync(); + + foreach (var row in rows) + { + if (!map.TryGetValue(row.PrintTaskId, out var list)) + { + list = new List(); + map[row.PrintTaskId] = list; + } + + JsonElement? cfg = null; + if (!string.IsNullOrWhiteSpace(row.RenderConfigJson)) + { + try + { + cfg = JsonSerializer.Deserialize(row.RenderConfigJson); + } + catch + { + cfg = null; + } + } + + list.Add(new PrintLogDataItemDto + { + ElementId = row.ElementId ?? string.Empty, + ElementName = row.ElementName, + RenderValue = row.RenderValue ?? string.Empty, + RenderConfigJson = cfg + }); + } + + return map; + } + + /// 按元素 Id 索引 App 打印快照,便于把出纸 __previewFormatted 写入 fl_label_print_data。 + private static Dictionary IndexPrintInputElements(JsonElement? printInputJson) + { + var map = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (printInputJson is null) + { + return map; + } + + var root = printInputJson.Value; + if (root.ValueKind != JsonValueKind.Object) + { + return map; + } + + if (!root.TryGetProperty("elements", out var elements) && !root.TryGetProperty("Elements", out elements)) + { + return map; + } + + if (elements.ValueKind != JsonValueKind.Array) + { + return map; + } + + foreach (var el in elements.EnumerateArray()) + { + if (el.ValueKind != JsonValueKind.Object) + { + continue; + } + + var id = el.TryGetProperty("id", out var idEl) && idEl.ValueKind == JsonValueKind.String + ? idEl.GetString() + : el.TryGetProperty("Id", out idEl) && idEl.ValueKind == JsonValueKind.String + ? idEl.GetString() + : null; + if (!string.IsNullOrWhiteSpace(id)) + { + map[id.Trim()] = el; + } + } + + return map; + } + + private static object? ResolveLivePrintConfig( + LabelTemplateElementDto element, + IReadOnlyDictionary printInputById) + { + var id = element.Id?.Trim(); + if (!string.IsNullOrWhiteSpace(id) && + printInputById.TryGetValue(id, out var liveEl) && + (liveEl.TryGetProperty("config", out var cfg) || liveEl.TryGetProperty("Config", out cfg)) && + cfg.ValueKind == JsonValueKind.Object) + { + return cfg; + } + + return element.ConfigJson; + } + + /// 出纸展示文案:优先 __previewFormatted(如到期 12:00),再退回 text。 + private static string? ExtractPrintRenderValue(object? configJson) + { + if (configJson is JsonElement je && je.ValueKind == JsonValueKind.Object) + { + foreach (var key in new[] { "__previewFormatted", "__PreviewFormatted", "text", "Text" }) + { + if (!je.TryGetProperty(key, out var v) || v.ValueKind != JsonValueKind.String) + { + continue; + } + + var s = v.GetString()?.Trim(); + if (!string.IsNullOrWhiteSpace(s) && + !s.Equals("None", StringComparison.OrdinalIgnoreCase) && + !s.StartsWith('{')) + { + return s; + } + } + + return null; + } + + if (configJson is Dictionary dict) + { + foreach (var key in new[] { "__previewFormatted", "__PreviewFormatted", "text", "Text" }) + { + if (!dict.TryGetValue(key, out var v) || v is null) + { + continue; + } + + var s = v.ToString()?.Trim(); + if (!string.IsNullOrWhiteSpace(s) && + !s.Equals("None", StringComparison.OrdinalIgnoreCase) && + !s.StartsWith('{')) + { + return s; + } + } + } + + return null; + } + /// /// 将 App 入参中的 JsonElement(对象或 null)反序列化为 PreviewAsync 所需的扁平字典。 /// diff --git a/美国版/scripts/泰鄂测试版部署.ps1 b/美国版/scripts/泰鄂测试版部署.ps1 index dd38222..e46520d 100644 --- a/美国版/scripts/泰鄂测试版部署.ps1 +++ b/美国版/scripts/泰鄂测试版部署.ps1 @@ -1,9 +1,10 @@ -#Requires -Version 5.1 +#Requires -Version 5.1 <# .SYNOPSIS - 食品标签泰鄂测试版 API 一键部署 + Te test API deploy .DESCRIPTION - 发布泰鄂版 Yi.Abp.Web,上传到 47.253.11.59,重启 Kestrel 19002,健康检查 https://flusapi-tetest.3flabeling.com + Publish Thai Yi.Abp.Web to 47.253.11.59, restart Kestrel 19002. + https://flusapi-tetest.3flabeling.com #> param( [switch]$SkipBuild @@ -35,17 +36,17 @@ $PublishDir = Join-Path $RepoRoot "泰额版\Food Labeling Management Code\Yi.Ab Initialize-DeploySsh $SshOpts = $global:SshOpts -Write-Host "== 食品标签泰鄂测试版部署 ==" -ForegroundColor Cyan -Write-Host "目标: $HostName $RemoteDir" -Write-Host "域名: $HealthUrl" -Write-Host "数据库: $TestDbName @ $DbHost" +Write-Host "== Te test deploy ==" -ForegroundColor Cyan +Write-Host "target: $HostName $RemoteDir" +Write-Host "url: $HealthUrl" +Write-Host "db: $TestDbName @ $DbHost" if (-not $SkipBuild) { - if (-not (Test-Path $WebCsproj)) { throw "找不到工程: $WebCsproj" } - Write-Host "== 发布泰鄂版 Yi.Abp.Web ==" -ForegroundColor Cyan + if (-not (Test-Path $WebCsproj)) { throw "csproj not found: $WebCsproj" } + Write-Host "== dotnet publish ==" -ForegroundColor Cyan if (Test-Path $PublishDir) { Remove-Item $PublishDir -Recurse -Force } & dotnet publish $WebCsproj -c Release -o $PublishDir --nologo - if ($LASTEXITCODE -ne 0) { throw "dotnet publish 失败" } + if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed" } $appsettings = Join-Path $PublishDir "appsettings.json" if (Test-Path $appsettings) { @@ -69,36 +70,38 @@ if (-not $SkipBuild) { } if (-not (Test-Path (Join-Path $PublishDir "Yi.Abp.Web.dll"))) { - throw "发布目录缺少 Yi.Abp.Web.dll: $PublishDir" + throw "missing Yi.Abp.Web.dll: $PublishDir" } -Write-Host "== 停止远程进程 ==" -ForegroundColor Cyan -Invoke-Remote @' +Write-Host "== stop remote process ==" -ForegroundColor Cyan +$stopRemote = @" set -e -if [ -f "/var/tmp/net_project/食品标签泰鄂测试版.pid" ]; then - pid=$(cat "/var/tmp/net_project/食品标签泰鄂测试版.pid" || true) - if [ -n "$pid" ]; then kill "$pid" 2>/dev/null || true; fi +PIDFILE=/var/tmp/net_project/食品标签泰鄂测试版.pid +if test -f "`$PIDFILE"; then + pid=`$(cat "`$PIDFILE" || true) + if test -n "`$pid"; then kill `$pid 2>/dev/null || true; fi fi pkill -f "/www/wwwroot/FoodLabelingManagementTeTest/Yi.Abp.Web.dll" 2>/dev/null || true sleep 1 echo stopped -'@ +"@ +Invoke-Remote $stopRemote -Write-Host "== 上传发布包 ==" -ForegroundColor Cyan +Write-Host "== upload publish package ==" -ForegroundColor Cyan $tar = Join-Path $env:TEMP "flus-tetest-publish.tgz" if (Test-Path $tar) { Remove-Item $tar -Force } Push-Location $PublishDir try { & tar -czf $tar --exclude=logs --exclude=startup.log * - if ($LASTEXITCODE -ne 0) { throw "打包失败" } + if ($LASTEXITCODE -ne 0) { throw "tar failed" } } finally { Pop-Location } & scp @SshOpts $tar "${UserName}@${HostName}:/tmp/flus-tetest-publish.tgz" -if ($LASTEXITCODE -ne 0) { throw "scp 失败" } +if ($LASTEXITCODE -ne 0) { throw "scp failed" } -Invoke-Remote @" +$uploadRemote = @" set -e mkdir -p '$RemoteDir' cd '$RemoteDir' @@ -114,25 +117,27 @@ chmod -R a+rX '$RemoteDir' ls -l '$RemoteDir/Yi.Abp.Web.dll' echo uploaded_to=$RemoteDir "@ +Invoke-Remote $uploadRemote -Write-Host "== 登记宝塔 Net 项目 ==" -ForegroundColor Cyan +Write-Host "== register BT net project ==" -ForegroundColor Cyan $btPyLocal = Join-Path $ScriptDir "bt-register-net-project.py" & scp @SshOpts $btPyLocal "${UserName}@${HostName}:/tmp/bt-register-net-project.py" -if ($LASTEXITCODE -ne 0) { throw "上传宝塔登记脚本失败" } -Invoke-Remote @" +if ($LASTEXITCODE -ne 0) { throw "upload bt python failed" } +$btRemote = @" set -e sed -i 's/\r`$//' /tmp/bt-register-net-project.py python3 /tmp/bt-register-net-project.py name='$BtName' path='$RemoteDir' port='19002' ps='$BtName' domain='$BtDomain' cmd='$BtCmd' run_user='root' dotnet_version='8.0.100' "@ +Invoke-Remote $btRemote -Write-Host "== 启动 API ==" -ForegroundColor Cyan -Invoke-Remote -AllowFail @" +Write-Host "== start API ==" -ForegroundColor Cyan +$startRemote = @" mkdir -p /www/wwwlogs/net /var/tmp/net_project -if [ ! -f /swapfile ]; then - fallocate -l 2G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=2048 +test -f /swapfile || fallocate -l 2G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=2048 +if test -f /swapfile; then chmod 600 /swapfile - mkswap /swapfile - swapon /swapfile + mkswap /swapfile || true + swapon /swapfile || true grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab fi swapon -a || true @@ -144,24 +149,25 @@ ss -lntp | grep 19002 || true curl -s -o /dev/null -w 'local=%{http_code}\n' --max-time 15 http://127.0.0.1:19002/swagger/index.html || true tail -n 30 /www/wwwlogs/net/食品标签泰鄂测试版.log || true "@ +Invoke-Remote -AllowFail $startRemote -Write-Host "== 健康检查 ==" -ForegroundColor Cyan +Write-Host "== health check ==" -ForegroundColor Cyan $ok = $false for ($i = 1; $i -le 10; $i++) { try { $resp = Invoke-WebRequest -Uri $HealthUrl -UseBasicParsing -TimeoutSec 15 if ($resp.StatusCode -eq 200) { - Write-Host "访问成功: $HealthUrl HTTP $($resp.StatusCode)" -ForegroundColor Green + Write-Host "OK: $HealthUrl HTTP $($resp.StatusCode)" -ForegroundColor Green $ok = $true break } } catch { - Write-Host "等待服务就绪 ($i/10)..." + Write-Host "wait ($i/10)..." Start-Sleep -Seconds 3 } } -if (-not $ok) { throw "部署后健康检查失败: $HealthUrl" } -Write-Host "完成。API: https://flusapi-tetest.3flabeling.com" -ForegroundColor Green +if (-not $ok) { throw "health check failed: $HealthUrl" } +Write-Host "done. API: https://flusapi-tetest.3flabeling.com" -ForegroundColor Green Write-Host "Swagger: $HealthUrl" -Write-Host "登录: POST https://flusapi-tetest.3flabeling.com/api/app/th-web-auth/login" +Write-Host "login: POST https://flusapi-tetest.3flabeling.com/api/app/th-web-auth/login" -- libgit2 0.21.4