Commit a407e0e3a2f693c4e8255f26d6ebdd5e307c58d7

Authored by 李曜臣
1 parent 0519811f

2026-10-19平台端打印日志到期时间优化

美国版/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 @@ -9,6 +9,10 @@ public class PrintLogDataItemDto
9 { 9 {
10 public string ElementId { get; set; } = string.Empty; 10 public string ElementId { get; set; } = string.Empty;
11 11
  12 + /// <summary>模板元素名(如 Duration Time (For Label))</summary>
  13 + public string? ElementName { get; set; }
  14 +
  15 + /// <summary>出纸文案(优先 <c>__previewFormatted</c>,如到期 12:00 / 10/20)</summary>
12 public string RenderValue { get; set; } = string.Empty; 16 public string RenderValue { get; set; } = string.Empty;
13 17
14 /// <summary> 18 /// <summary>
美国版/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 @@ -40,6 +40,9 @@ public class PrintLogItemDto
40 /// <summary>打印入参 JSON(直接来自 fl_label_print_task.PrintInputJson 列)</summary> 40 /// <summary>打印入参 JSON(直接来自 fl_label_print_task.PrintInputJson 列)</summary>
41 public string? PrintInputJson { get; set; } 41 public string? PrintInputJson { get; set; }
42 42
  43 + /// <summary>出纸明细(fl_label_print_data,含各格实际打印文案)</summary>
  44 + public List<PrintLogDataItemDto> PrintDataList { get; set; } = new();
  45 +
43 /// <summary>打印时间(PrintedAt ?? CreationTime)</summary> 46 /// <summary>打印时间(PrintedAt ?? CreationTime)</summary>
44 public DateTime PrintedAt { get; set; } 47 public DateTime PrintedAt { get; set; }
45 48
美国版/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 @@ -23,7 +23,7 @@ public interface IUsAppLabelingAppService : IApplicationService
23 Task<UsAppLabelPreviewDto> PreviewAsync(UsAppLabelPreviewInputVo input); 23 Task<UsAppLabelPreviewDto> PreviewAsync(UsAppLabelPreviewInputVo input);
24 24
25 /// <summary> 25 /// <summary>
26 - /// App 打印:创建打印任务并落库打印明细(fl_label_print_task / fl_label_print_data) 26 + /// App 打印:创建打印任务,并把出纸文案写入打印日志明细(fl_label_print_task / fl_label_print_data)
27 /// </summary> 27 /// </summary>
28 Task<UsAppLabelPrintOutputDto> PrintAsync(UsAppLabelPrintInputVo input); 28 Task<UsAppLabelPrintOutputDto> PrintAsync(UsAppLabelPrintInputVo input);
29 29
@@ -35,6 +35,7 @@ public interface IUsAppLabelingAppService : IApplicationService @@ -35,6 +35,7 @@ public interface IUsAppLabelingAppService : IApplicationService
35 /// <summary> 35 /// <summary>
36 /// App 打印日志:当前门店打印记录(分页)。已绑定该门店的账号可见门店内<b>全部用户</b>的打印任务。 36 /// App 打印日志:当前门店打印记录(分页)。已绑定该门店的账号可见门店内<b>全部用户</b>的打印任务。
37 /// 支持 <c>printDateDay</c> / <c>printDate</c> 按自然日筛选;出参 <c>labelId</c> 为门店当日打印序号(<c>yyyyMMdd-n</c>)。 37 /// 支持 <c>printDateDay</c> / <c>printDate</c> 按自然日筛选;出参 <c>labelId</c> 为门店当日打印序号(<c>yyyyMMdd-n</c>)。
  38 + /// 出参 <c>printDataList</c> 为出纸明细(各格实际打印文案)。
38 /// </summary> 39 /// </summary>
39 Task<PagedResultWithPageDto<PrintLogItemDto>> GetPrintLogListAsync(PrintLogGetListInputVo input); 40 Task<PagedResultWithPageDto<PrintLogItemDto>> GetPrintLogListAsync(PrintLogGetListInputVo input);
40 41
美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Helpers/ReportsPrintLogExpiryHelper.cs
1 using System.Globalization; 1 using System.Globalization;
2 using System.Text.Json; 2 using System.Text.Json;
  3 +using System.Text.Json.Nodes;
3 using System.Text.RegularExpressions; 4 using System.Text.RegularExpressions;
4 using FoodLabeling.Domain.Shared; 5 using FoodLabeling.Domain.Shared;
5 6
6 namespace FoodLabeling.Application.Helpers; 7 namespace FoodLabeling.Application.Helpers;
7 8
8 /// <summary> 9 /// <summary>
9 -/// Print Log「Expiration」列:从打印快照 <c>elements</c> 收集全部到期相关日期候选,取最早的一个再格式化展示(优先 <c>__previewFormatted</c>)。 10 +/// Print Log「Expiration」列:从打印快照 <c>elements</c> 解析到期日(优先 <c>__previewFormatted</c>)。
  11 +/// 泰鄂标签同时有「備料日期」与「到期日期」时,必须取到期日,不能取较早的制备日。
10 /// </summary> 12 /// </summary>
11 public static class ReportsPrintLogExpiryHelper 13 public static class ReportsPrintLogExpiryHelper
12 { 14 {
@@ -39,20 +41,36 @@ public static class ReportsPrintLogExpiryHelper @@ -39,20 +41,36 @@ public static class ReportsPrintLogExpiryHelper
39 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); 41 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
40 42
41 private static readonly Regex ExcludeNamePattern = new( 43 private static readonly Regex ExcludeNamePattern = new(
42 - @"(currentdate|currenttime|prepped|prepdate|prepon|pulled|labelname|durationdate2|duration_date_2|durationdate_2|duration\s*date\s*2)", 44 + @"(current\s*date|currentdate|current\s*time|currenttime|prepped|prepdate|prepon|pulled|labelname|備料|备料|durationdate2|duration_date_2|durationdate_2|duration\s*date\s*2)",
43 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); 45 RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
44 46
45 - /// <summary>解析全部到期候选并取最早时刻,格式化为 Print Log Expiration 列(含日期与时间)。</summary> 47 + /// <summary>打印明细一行(<c>fl_label_print_data</c>),出纸文案优先于偏移重算。</summary>
  48 + public readonly record struct PrintSnapshotLine(string? ElementName, string? RenderValue, string? RenderConfigJson);
  49 +
  50 + /// <summary>
  51 + /// 解析到期时刻。优先 <c>fl_label_print_data</c> 出纸快照(到期日期格 + 到期时间格,如 10/20 11:06),
  52 + /// 不要用 Printed at 的时分覆盖。
  53 + /// </summary>
46 public static string ExtractFormattedExpiryText( 54 public static string ExtractFormattedExpiryText(
47 string? printInputJson, 55 string? printInputJson,
48 string? renderTemplateJson = null, 56 string? renderTemplateJson = null,
49 DateTime? baseTime = null, 57 DateTime? baseTime = null,
50 - DateTime? printedAt = null) 58 + DateTime? printedAt = null,
  59 + IReadOnlyList<PrintSnapshotLine>? printSnapshotLines = null)
51 { 60 {
52 - var reference = NormalizeExpiryAnchor(baseTime ?? printedAt ?? DateTime.Now);  
53 - if (TryResolveExpiryDateTime(printInputJson, renderTemplateJson, reference, out var resolved)) 61 + var reference = PickExpiryAnchor(baseTime, printedAt);
  62 + var snapshotJson = BuildElementsJsonFromPrintData(printSnapshotLines);
  63 + // 合并模板 + PrintInputJson + 出纸快照后再算:Duration Date Days 0 必须叠 Duration Time Hours(甘蔗糖漿 366h → 11/03 22:31)
  64 + var merged = MergeExpiryElementsJson(printInputJson, snapshotJson, renderTemplateJson);
  65 + if (TryResolveExpiryDateTimeFromTemplateJson(merged, reference, out var resolved) &&
  66 + !IsPrintInstantFallback(resolved, reference))
  67 + {
  68 + return ReportsDateTimeDisplayHelper.FormatExpiryDateTime(resolved);
  69 + }
  70 +
  71 + if (TryResolveExpiryDateTimeFromTemplateJson(printInputJson, reference, out resolved) &&
  72 + !IsPrintInstantFallback(resolved, reference))
54 { 73 {
55 - // 模板最早到期日为纯日期时保留 00:00:00,不补打印墙钟(如 Ready 早于 Discard)  
56 return ReportsDateTimeDisplayHelper.FormatExpiryDateTime(resolved); 74 return ReportsDateTimeDisplayHelper.FormatExpiryDateTime(resolved);
57 } 75 }
58 76
@@ -73,24 +91,13 @@ public static class ReportsPrintLogExpiryHelper @@ -73,24 +91,13 @@ public static class ReportsPrintLogExpiryHelper
73 91
74 /// <summary>兼容旧调用:仅 PrintInputJson。</summary> 92 /// <summary>兼容旧调用:仅 PrintInputJson。</summary>
75 public static string ExtractFormattedExpiryText(string? printInputJson) => 93 public static string ExtractFormattedExpiryText(string? printInputJson) =>
76 - ExtractFormattedExpiryText(printInputJson, null, null, null); 94 + ExtractFormattedExpiryText(printInputJson, null, null, null, null);
77 95
78 - private static bool TryResolveExpiryDateTime(  
79 - string? printInputJson,  
80 - string? renderTemplateJson,  
81 - DateTime reference,  
82 - out DateTime expiry) 96 + /// <summary>解析结果仍是打印瞬间(0 天偏移未叠小时)时不能当到期日。</summary>
  97 + private static bool IsPrintInstantFallback(DateTime resolved, DateTime reference)
83 { 98 {
84 - expiry = default;  
85 - foreach (var json in new[] { printInputJson, renderTemplateJson })  
86 - {  
87 - if (TryResolveExpiryDateTimeFromTemplateJson(json, reference, out expiry))  
88 - {  
89 - return true;  
90 - }  
91 - }  
92 -  
93 - return false; 99 + var a = NormalizeExpiryAnchor(reference);
  100 + return resolved.Date == a.Date && Math.Abs((resolved - a).TotalSeconds) <= 1;
94 } 101 }
95 102
96 private static bool TryResolveExpiryDateTimeFromTemplateJson(string? json, DateTime reference, out DateTime expiry) 103 private static bool TryResolveExpiryDateTimeFromTemplateJson(string? json, DateTime reference, out DateTime expiry)
@@ -115,8 +122,20 @@ public static class ReportsPrintLogExpiryHelper @@ -115,8 +122,20 @@ public static class ReportsPrintLogExpiryHelper
115 return false; 122 return false;
116 } 123 }
117 124
118 - if (!TryCollectEarliestExpiryDateTime(elements, reference, out expiry)) 125 + if (TryResolveDurationDateAndTime(elements, reference, out expiry) &&
  126 + !IsPrintInstantFallback(expiry, reference))
  127 + {
  128 + return true;
  129 + }
  130 +
  131 + if (!TryCollectExpiryDateTime(elements, reference, out expiry))
  132 + {
  133 + return false;
  134 + }
  135 +
  136 + if (IsPrintInstantFallback(expiry, reference))
119 { 137 {
  138 + expiry = default;
120 return false; 139 return false;
121 } 140 }
122 141
@@ -128,14 +147,17 @@ public static class ReportsPrintLogExpiryHelper @@ -128,14 +147,17 @@ public static class ReportsPrintLogExpiryHelper
128 } 147 }
129 } 148 }
130 149
131 - /// <summary>遍历 elements 中全部到期日期候选,解析为 <see cref="DateTime"/> 后取最早(Min)。</summary>  
132 - private static bool TryCollectEarliestExpiryDateTime( 150 + /// <summary>
  151 + /// 收集到期日期候选。制备日(備料 / Prepped / 与打印时刻同一天且无正偏移)不能覆盖到期日。
  152 + /// 同时存在多条到期候选时取最晚(Use By / Discard / 到期日期)。
  153 + /// </summary>
  154 + private static bool TryCollectExpiryDateTime(
133 JsonElement elements, 155 JsonElement elements,
134 DateTime reference, 156 DateTime reference,
135 - out DateTime earliest) 157 + out DateTime expiry)
136 { 158 {
137 - earliest = default;  
138 - var candidates = new List<DateTime>(); 159 + expiry = default;
  160 + var candidates = new List<(int Score, DateTime Value, bool IsPrepLike)>();
139 161
140 foreach (var el in elements.EnumerateArray()) 162 foreach (var el in elements.EnumerateArray())
141 { 163 {
@@ -144,7 +166,8 @@ public static class ReportsPrintLogExpiryHelper @@ -144,7 +166,8 @@ public static class ReportsPrintLogExpiryHelper
144 continue; 166 continue;
145 } 167 }
146 168
147 - if (ScoreExpiryDateElement(el) <= 0) 169 + var score = ScoreExpiryDateElement(el);
  170 + if (score <= 0)
148 { 171 {
149 continue; 172 continue;
150 } 173 }
@@ -154,7 +177,12 @@ public static class ReportsPrintLogExpiryHelper @@ -154,7 +177,12 @@ public static class ReportsPrintLogExpiryHelper
154 continue; 177 continue;
155 } 178 }
156 179
157 - candidates.Add(resolved); 180 + if (IsPrintInstantFallback(resolved, reference))
  181 + {
  182 + continue;
  183 + }
  184 +
  185 + candidates.Add((score, resolved, IsPrepLikeExpiryElement(el, resolved, reference)));
158 } 186 }
159 187
160 if (candidates.Count == 0) 188 if (candidates.Count == 0)
@@ -162,11 +190,33 @@ public static class ReportsPrintLogExpiryHelper @@ -162,11 +190,33 @@ public static class ReportsPrintLogExpiryHelper
162 return false; 190 return false;
163 } 191 }
164 192
165 - earliest = candidates.Min(); 193 + var useBy = candidates.Where(c => !c.IsPrepLike).ToList();
  194 + var pool = useBy.Count > 0 ? useBy : candidates;
  195 + var bestScore = pool.Max(c => c.Score);
  196 + expiry = pool.Where(c => c.Score == bestScore).Max(c => c.Value);
166 return true; 197 return true;
167 } 198 }
168 199
169 - /// <summary>解析单个到期日期元素;无真实时分时尝试合并配对 durationtime(跳过 0 Days)。</summary> 200 + /// <summary>備料/制备日:名称像 prep,或解析结果与打印锚点同一天且不晚于锚点。</summary>
  201 + private static bool IsPrepLikeExpiryElement(JsonElement el, DateTime resolved, DateTime reference)
  202 + {
  203 + var nameHint = $"{GetStringProperty(el, "elementName", "ElementName")} {GetStringProperty(el, "inputKey", "InputKey")}"
  204 + .Trim();
  205 + if (Regex.IsMatch(
  206 + nameHint,
  207 + @"備料|备料|prepped|prepdate|prepon|currentdate|pulled",
  208 + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
  209 + {
  210 + return true;
  211 + }
  212 +
  213 + return resolved.Date <= reference.Date && resolved <= reference.AddMinutes(1);
  214 + }
  215 +
  216 + /// <summary>
  217 + /// 到期瞬间与 App 出纸一致:打印快照里的到期日期格 + 到期时间格(綠茶 10/20 11:06),
  218 + /// 不能用備料/打印时刻 15:06 覆盖时间格。
  219 + /// </summary>
170 private static bool TryResolveExpiryDateTimeForDateElement( 220 private static bool TryResolveExpiryDateTimeForDateElement(
171 JsonElement elements, 221 JsonElement elements,
172 JsonElement dateElement, 222 JsonElement dateElement,
@@ -174,35 +224,60 @@ public static class ReportsPrintLogExpiryHelper @@ -174,35 +224,60 @@ public static class ReportsPrintLogExpiryHelper
174 out DateTime resolved) 224 out DateTime resolved)
175 { 225 {
176 resolved = default; 226 resolved = default;
  227 + var hasTime = TryFindPairedTimeElement(elements, dateElement, out var timeElement) ||
  228 + TryFindDurationTimeElement(elements, out timeElement);
  229 + var hasDatePreview = TryGetElementPreviewDate(dateElement, reference, out var previewDate);
  230 + DateTime previewClock = default;
  231 + var hasTimePreview = hasTime && TryGetElementPreviewClock(timeElement, reference, out previewClock);
  232 +
  233 + if (hasDatePreview && hasTimePreview && HasMeaningfulTime(previewClock))
  234 + {
  235 + resolved = CombineDateWithClock(previewDate, previewClock);
  236 + return true;
  237 + }
  238 +
  239 + var dateOff = TryReadElementOffset(dateElement);
  240 + var timeOff = hasTime ? TryReadElementOffset(timeElement) : null;
  241 + if (dateOff.HasValue || timeOff.HasValue)
  242 + {
  243 + resolved = CombineDurationExpiryDate(reference, dateOff, timeOff);
  244 + if (hasDatePreview)
  245 + {
  246 + resolved = CombineDateWithClock(previewDate, resolved);
  247 + }
  248 +
  249 + if (hasTimePreview && HasMeaningfulTime(previewClock))
  250 + {
  251 + resolved = CombineDateWithClock(resolved, previewClock);
  252 + }
  253 +
  254 + return true;
  255 + }
  256 +
177 if (!TryResolveElementDateTimeValue(dateElement, reference, out var datePart)) 257 if (!TryResolveElementDateTimeValue(dateElement, reference, out var datePart))
178 { 258 {
179 return false; 259 return false;
180 } 260 }
181 261
182 resolved = datePart; 262 resolved = datePart;
183 - if (HasMeaningfulTime(datePart)) 263 + if (hasTimePreview && HasMeaningfulTime(previewClock))
184 { 264 {
  265 + resolved = CombineDateWithClock(datePart, previewClock);
185 return true; 266 return true;
186 } 267 }
187 268
188 - if (TryFindPairedTimeElement(elements, dateElement, out var timeElement) && 269 + if (hasTime &&
189 TryResolveElementDateTimeValue(timeElement, reference, out var timePart) && 270 TryResolveElementDateTimeValue(timeElement, reference, out var timePart) &&
190 HasMeaningfulTime(timePart) && 271 HasMeaningfulTime(timePart) &&
191 - !IsZeroDayDurationTimeElement(timeElement)) 272 + IsClockOffsetUnit(TryReadElementOffset(timeElement)?.unit))
192 { 273 {
193 - resolved = new DateTime(  
194 - datePart.Year,  
195 - datePart.Month,  
196 - datePart.Day,  
197 - timePart.Hour,  
198 - timePart.Minute,  
199 - 0); 274 + resolved = CombineDateWithClock(datePart, timePart);
200 } 275 }
201 276
202 return true; 277 return true;
203 } 278 }
204 279
205 - /// <summary>为到期日期元素查找配对时间元素(durationdate↔durationtime 或同名 time 后缀)。</summary> 280 + /// <summary>为到期日期元素查找配对时间元素(durationdate↔durationtime、同名 time 后缀,或 typeAdd Duration Time)。</summary>
206 private static bool TryFindPairedTimeElement( 281 private static bool TryFindPairedTimeElement(
207 JsonElement elements, 282 JsonElement elements,
208 JsonElement dateElement, 283 JsonElement dateElement,
@@ -210,31 +285,8 @@ public static class ReportsPrintLogExpiryHelper @@ -210,31 +285,8 @@ public static class ReportsPrintLogExpiryHelper
210 { 285 {
211 timeElement = default; 286 timeElement = default;
212 var dateName = GetStringProperty(dateElement, "elementName", "ElementName").Trim(); 287 var dateName = GetStringProperty(dateElement, "elementName", "ElementName").Trim();
213 - if (string.IsNullOrWhiteSpace(dateName))  
214 - {  
215 - return false;  
216 - }  
217 -  
218 - if (dateName.Equals("durationdate", StringComparison.OrdinalIgnoreCase))  
219 - {  
220 - foreach (var el in elements.EnumerateArray())  
221 - {  
222 - if (el.ValueKind != JsonValueKind.Object)  
223 - {  
224 - continue;  
225 - }  
226 -  
227 - var name = GetStringProperty(el, "elementName", "ElementName").Trim();  
228 - if (name.Equals("durationtime", StringComparison.OrdinalIgnoreCase))  
229 - {  
230 - timeElement = el;  
231 - return true;  
232 - }  
233 - }  
234 -  
235 - return false;  
236 - }  
237 288
  289 + JsonElement? preferred = null;
238 foreach (var el in elements.EnumerateArray()) 290 foreach (var el in elements.EnumerateArray())
239 { 291 {
240 if (el.ValueKind != JsonValueKind.Object) 292 if (el.ValueKind != JsonValueKind.Object)
@@ -243,24 +295,51 @@ public static class ReportsPrintLogExpiryHelper @@ -243,24 +295,51 @@ public static class ReportsPrintLogExpiryHelper
243 } 295 }
244 296
245 var name = GetStringProperty(el, "elementName", "ElementName").Trim(); 297 var name = GetStringProperty(el, "elementName", "ElementName").Trim();
246 - if (string.IsNullOrWhiteSpace(name)) 298 + if (!IsDurationTimeLike(el, name) || ExcludeNamePattern.IsMatch(name))
247 { 299 {
248 continue; 300 continue;
249 } 301 }
250 302
251 - if (ScoreExpiryTimeElement(el) <= 0 && !ExpiryTimeNamePattern.IsMatch(name)) 303 + if (!string.IsNullOrWhiteSpace(dateName) &&
  304 + (name.Equals(dateName + "time", StringComparison.OrdinalIgnoreCase) ||
  305 + (dateName.EndsWith("date", StringComparison.OrdinalIgnoreCase) &&
  306 + name.Equals(dateName[..^4] + "time", StringComparison.OrdinalIgnoreCase))))
252 { 307 {
253 - continue; 308 + timeElement = el;
  309 + return true;
254 } 310 }
255 311
256 - if (name.Equals(dateName + "time", StringComparison.OrdinalIgnoreCase)) 312 + if (dateName.Contains("duration date", StringComparison.OrdinalIgnoreCase) &&
  313 + name.Contains("duration time", StringComparison.OrdinalIgnoreCase))
257 { 314 {
258 timeElement = el; 315 timeElement = el;
259 return true; 316 return true;
260 } 317 }
261 318
262 - if (dateName.EndsWith("date", StringComparison.OrdinalIgnoreCase) &&  
263 - name.Equals(dateName[..^4] + "time", StringComparison.OrdinalIgnoreCase)) 319 + preferred ??= el;
  320 + }
  321 +
  322 + if (preferred.HasValue)
  323 + {
  324 + timeElement = preferred.Value;
  325 + return true;
  326 + }
  327 +
  328 + return false;
  329 + }
  330 +
  331 + private static bool TryFindDurationTimeElement(JsonElement elements, out JsonElement timeElement)
  332 + {
  333 + timeElement = default;
  334 + foreach (var el in elements.EnumerateArray())
  335 + {
  336 + if (el.ValueKind != JsonValueKind.Object)
  337 + {
  338 + continue;
  339 + }
  340 +
  341 + var name = GetStringProperty(el, "elementName", "ElementName").Trim();
  342 + if (IsDurationTimeLike(el, name))
264 { 343 {
265 timeElement = el; 344 timeElement = el;
266 return true; 345 return true;
@@ -270,6 +349,21 @@ public static class ReportsPrintLogExpiryHelper @@ -270,6 +349,21 @@ public static class ReportsPrintLogExpiryHelper
270 return false; 349 return false;
271 } 350 }
272 351
  352 + private static bool IsDurationTimeLike(JsonElement el, string name)
  353 + {
  354 + if (ExpiryTimeNamePattern.IsMatch(name) ||
  355 + ExpiryTimeNamePattern.IsMatch(GetStringProperty(el, "inputKey", "InputKey")))
  356 + {
  357 + return true;
  358 + }
  359 +
  360 + var typeAdd = GetStringProperty(el, "typeAdd", "TypeAdd")
  361 + .Trim()
  362 + .ToLowerInvariant()
  363 + .Replace(" ", " ", StringComparison.Ordinal);
  364 + return typeAdd.Contains("duration time", StringComparison.Ordinal);
  365 + }
  366 +
273 /// <summary> 367 /// <summary>
274 /// 从模板元素直接解析到期 <see cref="DateTime"/>,避免 DATE 预设格式(如 MM/DD/YY)剥掉锚点时分。 368 /// 从模板元素直接解析到期 <see cref="DateTime"/>,避免 DATE 预设格式(如 MM/DD/YY)剥掉锚点时分。
275 /// 优先使用打印快照已渲染的 <c>__previewFormatted</c> / 字面量,避免用 UTC BaseTime 重算偏移导致小时偏差。 369 /// 优先使用打印快照已渲染的 <c>__previewFormatted</c> / 字面量,避免用 UTC BaseTime 重算偏移导致小时偏差。
@@ -283,26 +377,21 @@ public static class ReportsPrintLogExpiryHelper @@ -283,26 +377,21 @@ public static class ReportsPrintLogExpiryHelper
283 } 377 }
284 378
285 var previewFormatted = GetStringProperty(cfg, "__previewFormatted", "__PreviewFormatted").Trim(); 379 var previewFormatted = GetStringProperty(cfg, "__previewFormatted", "__PreviewFormatted").Trim();
286 - if (!string.IsNullOrWhiteSpace(previewFormatted)  
287 - && IsLikelyResolvedDateTimeLiteral(previewFormatted)  
288 - && ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(previewFormatted, reference, out result))  
289 - {  
290 - return true;  
291 - }  
292 -  
293 var rawText = GetStringProperty(cfg, "text", "Text").Trim(); 380 var rawText = GetStringProperty(cfg, "text", "Text").Trim();
294 var formatText = GetStringProperty(cfg, "format", "Format").Trim(); 381 var formatText = GetStringProperty(cfg, "format", "Format").Trim();
295 var type = GetStringProperty(el, "type", "Type").Trim().ToUpperInvariant(); 382 var type = GetStringProperty(el, "type", "Type").Trim().ToUpperInvariant();
  383 + var anchor = NormalizeExpiryAnchor(reference);
296 384
297 - // 已展开的日期/时间字面量优先于偏移 JSON(打印快照与出纸一致)  
298 - if (!string.IsNullOrWhiteSpace(rawText)  
299 - && IsLikelyResolvedDateTimeLiteral(rawText)  
300 - && ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(rawText, reference, out result)) 385 + if (TryResolveLiteralKeepingClock(previewFormatted, el, cfg, type, rawText, formatText, anchor, out result))
  386 + {
  387 + return true;
  388 + }
  389 +
  390 + if (TryResolveLiteralKeepingClock(rawText, el, cfg, type, rawText, formatText, anchor, out result))
301 { 391 {
302 return true; 392 return true;
303 } 393 }
304 394
305 - var anchor = NormalizeExpiryAnchor(reference);  
306 if (TryResolveOffsetToDateTime(anchor, rawText, out result) || 395 if (TryResolveOffsetToDateTime(anchor, rawText, out result) ||
307 TryResolveOffsetToDateTime(anchor, formatText, out result)) 396 TryResolveOffsetToDateTime(anchor, formatText, out result))
308 { 397 {
@@ -328,6 +417,528 @@ public static class ReportsPrintLogExpiryHelper @@ -328,6 +417,528 @@ public static class ReportsPrintLogExpiryHelper
328 } 417 }
329 418
330 /// <summary> 419 /// <summary>
  420 + /// 已渲染字面量优先。纯日期(<c>10/25</c>)只锁定日历日,时分从 Duration 偏移或備料墙钟补上,避免变成 00:00:00。
  421 + /// </summary>
  422 + private static bool TryResolveLiteralKeepingClock(
  423 + string literal,
  424 + JsonElement el,
  425 + JsonElement cfg,
  426 + string type,
  427 + string rawText,
  428 + string formatText,
  429 + DateTime anchor,
  430 + out DateTime result)
  431 + {
  432 + result = default;
  433 + if (string.IsNullOrWhiteSpace(literal) || !IsLikelyResolvedDateTimeLiteral(literal))
  434 + {
  435 + return false;
  436 + }
  437 +
  438 + if (!ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(literal, anchor, out var parsed))
  439 + {
  440 + return false;
  441 + }
  442 +
  443 + if ((HasRealTimeComponent(literal) || type == "TIME") && HasMeaningfulTime(parsed))
  444 + {
  445 + result = parsed;
  446 + return true;
  447 + }
  448 +
  449 + result = parsed;
  450 + return true;
  451 + }
  452 +
  453 + private static bool TryResolveClockFromOffset(
  454 + JsonElement el,
  455 + JsonElement cfg,
  456 + string type,
  457 + string rawText,
  458 + string formatText,
  459 + DateTime anchor,
  460 + out DateTime clock)
  461 + {
  462 + if (TryResolveOffsetToDateTime(anchor, rawText, out clock) ||
  463 + TryResolveOffsetToDateTime(anchor, formatText, out clock))
  464 + {
  465 + return true;
  466 + }
  467 +
  468 + if (type is "DATE" or "TIME" or "DURATION")
  469 + {
  470 + var off = ReadOffsetFromElementConfig(el, cfg, type);
  471 + if (off.HasValue)
  472 + {
  473 + clock = ApplyOffsetToDate(anchor, off.Value.amount, off.Value.unit);
  474 + return true;
  475 + }
  476 + }
  477 +
  478 + clock = default;
  479 + return false;
  480 + }
  481 +
  482 + private static DateTime CombineDateWithClock(DateTime datePart, DateTime clock) =>
  483 + new(datePart.Year, datePart.Month, datePart.Day, clock.Hour, clock.Minute, clock.Second, datePart.Kind);
  484 +
  485 + /// <summary>与 App <c>combineDurationExpiryDate</c> 一致:Base + Duration Date + Duration Time。</summary>
  486 + private static DateTime CombineDurationExpiryDate(
  487 + DateTime baseTime,
  488 + (int amount, string unit)? dateOff,
  489 + (int amount, string unit)? timeOff)
  490 + {
  491 + var d = baseTime;
  492 + if (dateOff.HasValue)
  493 + {
  494 + d = ApplyOffsetToDate(d, dateOff.Value.amount, dateOff.Value.unit);
  495 + if (IsClockOffsetUnit(dateOff.Value.unit) && dateOff.Value.amount != 0)
  496 + {
  497 + return d;
  498 + }
  499 + }
  500 +
  501 + if (timeOff.HasValue)
  502 + {
  503 + d = ApplyOffsetToDate(d, timeOff.Value.amount, timeOff.Value.unit);
  504 + }
  505 +
  506 + return d;
  507 + }
  508 +
  509 + private static bool IsClockOffsetUnit(string? unit) =>
  510 + unit is "Seconds" or "Minutes" or "Hours";
  511 +
  512 + private static (int amount, string unit)? TryReadElementOffset(JsonElement el)
  513 + {
  514 + if (!TryGetProperty(el, "config", out var cfg) && !TryGetProperty(el, "Config", out cfg))
  515 + {
  516 + return null;
  517 + }
  518 +
  519 + foreach (var raw in EnumerateOffsetRaw(cfg))
  520 + {
  521 + if (TryParseOffsetStored(raw, out var offset))
  522 + {
  523 + var amount = NormalizeOffsetAmount(offset.value);
  524 + if (amount.HasValue)
  525 + {
  526 + return (amount.Value, offset.unit);
  527 + }
  528 + }
  529 + }
  530 +
  531 + var type = GetStringProperty(el, "type", "Type").Trim().ToUpperInvariant();
  532 + return ReadOffsetFromElementConfig(el, cfg, type);
  533 + }
  534 +
  535 + private static IEnumerable<string> EnumerateOffsetRaw(JsonElement cfg)
  536 + {
  537 + foreach (var key in new[] { "text", "Text", "format", "Format" })
  538 + {
  539 + if (!TryGetProperty(cfg, key, out var v))
  540 + {
  541 + continue;
  542 + }
  543 +
  544 + if (v.ValueKind == JsonValueKind.String)
  545 + {
  546 + var s = v.GetString();
  547 + if (!string.IsNullOrWhiteSpace(s))
  548 + {
  549 + yield return s;
  550 + }
  551 + }
  552 + else if (v.ValueKind == JsonValueKind.Object)
  553 + {
  554 + yield return v.GetRawText();
  555 + }
  556 + }
  557 + }
  558 +
  559 + private static bool TryGetElementPreviewLiteral(JsonElement el, out string literal)
  560 + {
  561 + literal = string.Empty;
  562 + if (!TryGetProperty(el, "config", out var cfg) && !TryGetProperty(el, "Config", out cfg))
  563 + {
  564 + return false;
  565 + }
  566 +
  567 + foreach (var raw in new[]
  568 + {
  569 + GetStringProperty(cfg, "__previewFormatted", "__PreviewFormatted"),
  570 + GetStringProperty(cfg, "text", "Text")
  571 + })
  572 + {
  573 + if (!string.IsNullOrWhiteSpace(raw) && IsLikelyResolvedDateTimeLiteral(raw.Trim()))
  574 + {
  575 + literal = raw.Trim();
  576 + return true;
  577 + }
  578 + }
  579 +
  580 + return false;
  581 + }
  582 +
  583 + private static bool TryGetElementPreviewDate(JsonElement el, DateTime reference, out DateTime date)
  584 + {
  585 + date = default;
  586 + return TryGetElementPreviewLiteral(el, out var literal) &&
  587 + ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(literal, reference, out date);
  588 + }
  589 +
  590 + private static bool TryGetElementPreviewClock(JsonElement el, DateTime reference, out DateTime clock)
  591 + {
  592 + clock = default;
  593 + if (!TryGetElementPreviewLiteral(el, out var literal))
  594 + {
  595 + return false;
  596 + }
  597 +
  598 + var trimmed = literal.Trim();
  599 + var timeOnly = Regex.Match(trimmed, @"^(\d{1,2}):(\d{2})(?::(\d{2}))?$");
  600 + if (timeOnly.Success &&
  601 + int.TryParse(timeOnly.Groups[1].Value, out var h) &&
  602 + int.TryParse(timeOnly.Groups[2].Value, out var m))
  603 + {
  604 + var s = timeOnly.Groups[3].Success && int.TryParse(timeOnly.Groups[3].Value, out var sec) ? sec : 0;
  605 + clock = new DateTime(reference.Year, reference.Month, reference.Day, h, m, s, reference.Kind);
  606 + return HasMeaningfulTime(clock);
  607 + }
  608 +
  609 + if (!HasRealTimeComponent(trimmed))
  610 + {
  611 + return false;
  612 + }
  613 +
  614 + return ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(trimmed, reference, out clock) &&
  615 + HasMeaningfulTime(clock);
  616 + }
  617 +
  618 + private static string? BuildElementsJsonFromPrintData(IReadOnlyList<PrintSnapshotLine>? lines)
  619 + {
  620 + if (lines is null || lines.Count == 0)
  621 + {
  622 + return null;
  623 + }
  624 +
  625 + var root = new JsonObject();
  626 + var arr = new JsonArray();
  627 + foreach (var line in lines)
  628 + {
  629 + var name = (line.ElementName ?? string.Empty).Trim();
  630 + var render = (line.RenderValue ?? string.Empty).Trim();
  631 + if (render.Length == 0 || render.Equals("None", StringComparison.OrdinalIgnoreCase))
  632 + {
  633 + continue;
  634 + }
  635 +
  636 + var inferredType = InferPrintDataElementType(name, line.RenderValue);
  637 + if (inferredType is null)
  638 + {
  639 + continue;
  640 + }
  641 +
  642 + var el = new JsonObject
  643 + {
  644 + ["elementName"] = name,
  645 + ["type"] = inferredType,
  646 + ["typeAdd"] = inferredType == "TIME" ? "duration time" : "duration date"
  647 + };
  648 +
  649 + JsonObject cfg;
  650 + try
  651 + {
  652 + cfg = !string.IsNullOrWhiteSpace(line.RenderConfigJson) &&
  653 + JsonNode.Parse(line.RenderConfigJson) is JsonObject parsed
  654 + ? parsed
  655 + : new JsonObject();
  656 + }
  657 + catch
  658 + {
  659 + cfg = new JsonObject();
  660 + }
  661 +
  662 + if (!cfg.ContainsKey("__previewFormatted") &&
  663 + !cfg.ContainsKey("__PreviewFormatted") &&
  664 + IsLikelyResolvedDateTimeLiteral(render))
  665 + {
  666 + cfg["__previewFormatted"] = render;
  667 + }
  668 +
  669 + if (!cfg.ContainsKey("text") && !cfg.ContainsKey("Text") && render.Length > 0)
  670 + {
  671 + cfg["text"] = render;
  672 + }
  673 +
  674 + el["config"] = cfg;
  675 + arr.Add(el);
  676 + }
  677 +
  678 + root["elements"] = arr;
  679 + return root.ToJsonString();
  680 + }
  681 +
  682 + /// <summary>
  683 + /// 模板提供 typeAdd,PrintInputJson 提供出纸预览与 Hours 偏移;空快照(RenderValue None)不得覆盖。
  684 + /// </summary>
  685 + private static string? MergeExpiryElementsJson(
  686 + string? printInputJson,
  687 + string? snapshotJson,
  688 + string? renderTemplateJson)
  689 + {
  690 + var byKey = new Dictionary<string, JsonObject>(StringComparer.OrdinalIgnoreCase);
  691 + var extras = new List<JsonObject>();
  692 +
  693 + void Ingest(string? json, bool requireUseful)
  694 + {
  695 + foreach (var el in ReadElementObjects(json))
  696 + {
  697 + if (requireUseful && !HasUsefulExpiryPayload(el))
  698 + {
  699 + continue;
  700 + }
  701 +
  702 + var key = ElementMergeKey(el);
  703 + if (key is null)
  704 + {
  705 + extras.Add(el);
  706 + continue;
  707 + }
  708 +
  709 + byKey[key] = el;
  710 + }
  711 + }
  712 +
  713 + Ingest(renderTemplateJson, false);
  714 + Ingest(printInputJson, false);
  715 + Ingest(snapshotJson, true);
  716 +
  717 + if (byKey.Count == 0 && extras.Count == 0)
  718 + {
  719 + return printInputJson ?? snapshotJson ?? renderTemplateJson;
  720 + }
  721 +
  722 + var arr = new JsonArray();
  723 + foreach (var el in byKey.Values)
  724 + {
  725 + arr.Add(el.DeepClone());
  726 + }
  727 +
  728 + foreach (var el in extras)
  729 + {
  730 + arr.Add(el.DeepClone());
  731 + }
  732 +
  733 + return new JsonObject { ["elements"] = arr }.ToJsonString();
  734 + }
  735 +
  736 + private static IEnumerable<JsonObject> ReadElementObjects(string? json)
  737 + {
  738 + if (string.IsNullOrWhiteSpace(json))
  739 + {
  740 + yield break;
  741 + }
  742 +
  743 + JsonNode? node;
  744 + try
  745 + {
  746 + node = JsonNode.Parse(json);
  747 + }
  748 + catch
  749 + {
  750 + yield break;
  751 + }
  752 +
  753 + if (node is not JsonObject root)
  754 + {
  755 + yield break;
  756 + }
  757 +
  758 + var arr = root["elements"] as JsonArray ?? root["Elements"] as JsonArray;
  759 + if (arr is null)
  760 + {
  761 + yield break;
  762 + }
  763 +
  764 + foreach (var item in arr)
  765 + {
  766 + if (item is JsonObject o)
  767 + {
  768 + yield return o;
  769 + }
  770 + }
  771 + }
  772 +
  773 + private static string? ElementMergeKey(JsonObject el)
  774 + {
  775 + var id = JsonNodeString(el["id"]) ?? JsonNodeString(el["Id"]);
  776 + if (!string.IsNullOrWhiteSpace(id))
  777 + {
  778 + return "id:" + id.Trim();
  779 + }
  780 +
  781 + var name = JsonNodeString(el["elementName"]) ?? JsonNodeString(el["ElementName"]);
  782 + return string.IsNullOrWhiteSpace(name) ? null : "name:" + name.Trim();
  783 + }
  784 +
  785 + private static string? JsonNodeString(JsonNode? node)
  786 + {
  787 + if (node is JsonValue v && v.TryGetValue<string>(out var s))
  788 + {
  789 + return s;
  790 + }
  791 +
  792 + return null;
  793 + }
  794 +
  795 + private static bool HasUsefulExpiryPayload(JsonObject el)
  796 + {
  797 + var cfg = el["config"] as JsonObject ?? el["Config"] as JsonObject;
  798 + if (cfg is null)
  799 + {
  800 + return false;
  801 + }
  802 +
  803 + foreach (var key in new[] { "__previewFormatted", "__PreviewFormatted", "text", "Text" })
  804 + {
  805 + if (cfg[key] is JsonValue jv && jv.TryGetValue<string>(out var s) &&
  806 + !string.IsNullOrWhiteSpace(s) &&
  807 + (IsLikelyResolvedDateTimeLiteral(s) || s.TrimStart().StartsWith('{')))
  808 + {
  809 + return true;
  810 + }
  811 +
  812 + if (cfg[key] is JsonObject)
  813 + {
  814 + return true;
  815 + }
  816 + }
  817 +
  818 + return false;
  819 + }
  820 +
  821 + /// <summary>按 App 规则:Duration Date + Duration Time 预览/偏移合成到期瞬间。</summary>
  822 + private static bool TryResolveDurationDateAndTime(
  823 + JsonElement elements,
  824 + DateTime reference,
  825 + out DateTime expiry)
  826 + {
  827 + expiry = default;
  828 + JsonElement? dateEl = null;
  829 + JsonElement? timeEl = null;
  830 + foreach (var el in elements.EnumerateArray())
  831 + {
  832 + if (el.ValueKind != JsonValueKind.Object)
  833 + {
  834 + continue;
  835 + }
  836 +
  837 + var name = GetStringProperty(el, "elementName", "ElementName").Trim();
  838 + if (ExcludeNamePattern.IsMatch(name))
  839 + {
  840 + continue;
  841 + }
  842 +
  843 + if (dateEl is null && ScoreExpiryDateElement(el) > 0)
  844 + {
  845 + dateEl = el;
  846 + }
  847 +
  848 + if (timeEl is null && IsDurationTimeLike(el, name))
  849 + {
  850 + timeEl = el;
  851 + }
  852 + }
  853 +
  854 + if (dateEl is null)
  855 + {
  856 + return false;
  857 + }
  858 +
  859 + if (!TryResolveExpiryDateTimeForDateElement(elements, dateEl.Value, reference, out expiry))
  860 + {
  861 + return false;
  862 + }
  863 +
  864 + if (timeEl is { } te &&
  865 + TryGetElementPreviewClock(te, reference, out var clock) &&
  866 + HasMeaningfulTime(clock))
  867 + {
  868 + expiry = CombineDateWithClock(expiry, clock);
  869 + }
  870 +
  871 + return !IsPrintInstantFallback(expiry, reference);
  872 + }
  873 +
  874 + private static string? InferPrintDataElementType(string elementName, string? renderValue)
  875 + {
  876 + var hint = elementName.Trim();
  877 + if (ExcludeNamePattern.IsMatch(hint))
  878 + {
  879 + return null;
  880 + }
  881 +
  882 + if (ExpiryTimeNamePattern.IsMatch(hint) ||
  883 + hint.Contains("duration time", StringComparison.OrdinalIgnoreCase))
  884 + {
  885 + return "TIME";
  886 + }
  887 +
  888 + var raw = (renderValue ?? string.Empty).Trim();
  889 + if (Regex.IsMatch(raw, @"^\d{1,2}:\d{2}(:\d{2})?$"))
  890 + {
  891 + return "TIME";
  892 + }
  893 +
  894 + if (ExpiryNamePattern.IsMatch(hint) ||
  895 + hint.Contains("duration date", StringComparison.OrdinalIgnoreCase))
  896 + {
  897 + return "DATE";
  898 + }
  899 +
  900 + return null;
  901 + }
  902 +
  903 + /// <summary><c>00:00</c> / <c>00:00:00</c> 是纯日期占位,不算标签上的到期时分。</summary>
  904 + private static bool HasRealTimeComponent(string raw)
  905 + {
  906 + var m = Regex.Match(raw.Trim(), @"(\d{1,2}):(\d{2})(?::(\d{2}))?");
  907 + if (!m.Success)
  908 + {
  909 + return false;
  910 + }
  911 +
  912 + var hour = int.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
  913 + var minute = int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
  914 + var second = m.Groups[3].Success
  915 + ? int.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture)
  916 + : 0;
  917 + return hour != 0 || minute != 0 || second != 0;
  918 + }
  919 +
  920 + /// <summary>到期锚点:优先带真实时分的 BaseTime / Printed at(與標籤 13:46、14:00 對齊)。</summary>
  921 + private static DateTime PickExpiryAnchor(DateTime? baseTime, DateTime? printedAt)
  922 + {
  923 + DateTime? NormalizeIfPresent(DateTime? value) =>
  924 + value is { } dt && dt != DateTime.MinValue ? NormalizeExpiryAnchor(dt) : null;
  925 +
  926 + var fromBase = NormalizeIfPresent(baseTime);
  927 + var fromPrinted = NormalizeIfPresent(printedAt);
  928 + if (fromBase is { } bt && HasMeaningfulTime(bt))
  929 + {
  930 + return bt;
  931 + }
  932 +
  933 + if (fromPrinted is { } pt && HasMeaningfulTime(pt))
  934 + {
  935 + return pt;
  936 + }
  937 +
  938 + return fromBase ?? fromPrinted ?? DateTime.Now;
  939 + }
  940 +
  941 + /// <summary>
331 /// BaseTime 若为 UTC(App 历史用 toISOString),按本地墙钟展示,与标签 Prepped On 对齐。 942 /// BaseTime 若为 UTC(App 历史用 toISOString),按本地墙钟展示,与标签 Prepped On 对齐。
332 /// </summary> 943 /// </summary>
333 private static DateTime NormalizeExpiryAnchor(DateTime reference) 944 private static DateTime NormalizeExpiryAnchor(DateTime reference)
@@ -608,7 +1219,8 @@ public static class ReportsPrintLogExpiryHelper @@ -608,7 +1219,8 @@ public static class ReportsPrintLogExpiryHelper
608 return true; 1219 return true;
609 } 1220 }
610 1221
611 - if (Regex.IsMatch(t, @"^\d{1,2}/\d{1,2}/\d{2,4}")) 1222 + // 标签画布常为 MM/DD 或 MM/DD HH:mm(无年份),必须当已渲染字面量,不能回退成 0 Days 制备日
  1223 + if (Regex.IsMatch(t, @"^\d{1,2}/\d{1,2}(/\d{2,4})?(\s+\d{1,2}:\d{2}(:\d{2})?)?$"))
612 { 1224 {
613 return true; 1225 return true;
614 } 1226 }
@@ -625,46 +1237,6 @@ public static class ReportsPrintLogExpiryHelper @@ -625,46 +1237,6 @@ public static class ReportsPrintLogExpiryHelper
625 ReportsDateTimeDisplayHelper.HasMeaningfulWallClockTime(dt); 1237 ReportsDateTimeDisplayHelper.HasMeaningfulWallClockTime(dt);
626 1238
627 /// <summary> 1239 /// <summary>
628 - /// Duration Time 配置为 0 Days 时不应把 BaseTime 的时分并进 Expiration(标签 Use By 常为纯日期)。  
629 - /// </summary>  
630 - private static bool IsZeroDayDurationTimeElement(JsonElement el)  
631 - {  
632 - if (!TryGetProperty(el, "config", out var cfg) && !TryGetProperty(el, "Config", out cfg))  
633 - {  
634 - return false;  
635 - }  
636 -  
637 - foreach (var raw in new[]  
638 - {  
639 - GetStringProperty(cfg, "__previewFormatted", "__PreviewFormatted"),  
640 - GetStringProperty(cfg, "text", "Text"),  
641 - GetStringProperty(cfg, "format", "Format")  
642 - })  
643 - {  
644 - if (string.IsNullOrWhiteSpace(raw))  
645 - {  
646 - continue;  
647 - }  
648 -  
649 - if (IsLikelyResolvedDateTimeLiteral(raw.Trim()))  
650 - {  
651 - return false;  
652 - }  
653 -  
654 - if (TryParseOffsetStored(raw, out var offset) &&  
655 - string.Equals(offset.unit, "Days", StringComparison.OrdinalIgnoreCase) &&  
656 - NormalizeOffsetAmount(offset.value) == 0)  
657 - {  
658 - return true;  
659 - }  
660 - }  
661 -  
662 - var type = GetStringProperty(el, "type", "Type").Trim().ToUpperInvariant();  
663 - var off = ReadOffsetFromElementConfig(el, cfg, type);  
664 - return off is { amount: 0, unit: "Days" };  
665 - }  
666 -  
667 - /// <summary>  
668 /// 解析保质期展示文本;无法解析时返回「无」。 1240 /// 解析保质期展示文本;无法解析时返回「无」。
669 /// </summary> 1241 /// </summary>
670 public static string ExtractExpiryText(string? printInputJson, DateTime anchor) 1242 public static string ExtractExpiryText(string? printInputJson, DateTime anchor)
@@ -774,18 +1346,18 @@ public static class ReportsPrintLogExpiryHelper @@ -774,18 +1346,18 @@ public static class ReportsPrintLogExpiryHelper
774 return false; 1346 return false;
775 } 1347 }
776 1348
777 - /// <summary>从 elements 收集全部到期候选,解析后取最早再格式化为展示文本(与 DateTime 主路径一致)。</summary> 1349 + /// <summary>从 elements 收集到期候选并格式化(与 DateTime 主路径一致,制备日让位于到期日)。</summary>
778 private static bool TryExtractEarliestFromElements(JsonElement elements, DateTime anchor, out string text) 1350 private static bool TryExtractEarliestFromElements(JsonElement elements, DateTime anchor, out string text)
779 { 1351 {
780 text = FoodLabelingDisplayConsts.NotAvailable; 1352 text = FoodLabelingDisplayConsts.NotAvailable;
781 - if (TryCollectEarliestExpiryDateTime(elements, anchor, out var earliest)) 1353 + if (TryCollectExpiryDateTime(elements, anchor, out var expiry))
782 { 1354 {
783 - text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(earliest); 1355 + text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(expiry);
784 return true; 1356 return true;
785 } 1357 }
786 1358
787 - DateTime? earliestParsed = null;  
788 - string? earliestRaw = null; 1359 + DateTime? latestParsed = null;
  1360 + string? latestRaw = null;
789 1361
790 foreach (var el in elements.EnumerateArray()) 1362 foreach (var el in elements.EnumerateArray())
791 { 1363 {
@@ -808,30 +1380,35 @@ public static class ReportsPrintLogExpiryHelper @@ -808,30 +1380,35 @@ public static class ReportsPrintLogExpiryHelper
808 var trimmed = display.Trim(); 1380 var trimmed = display.Trim();
809 if (ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(trimmed, anchor, out var parsed)) 1381 if (ReportsDateTimeDisplayHelper.TryParseExpiryDateTime(trimmed, anchor, out var parsed))
810 { 1382 {
811 - if (!earliestParsed.HasValue || parsed < earliestParsed.Value) 1383 + if (IsPrepLikeExpiryElement(el, parsed, anchor) && latestParsed.HasValue)
  1384 + {
  1385 + continue;
  1386 + }
  1387 +
  1388 + if (!latestParsed.HasValue || parsed > latestParsed.Value)
812 { 1389 {
813 - earliestParsed = parsed;  
814 - earliestRaw = trimmed; 1390 + latestParsed = parsed;
  1391 + latestRaw = trimmed;
815 } 1392 }
816 } 1393 }
817 - else if (!earliestParsed.HasValue && earliestRaw is null) 1394 + else if (latestRaw is null)
818 { 1395 {
819 - earliestRaw = trimmed; 1396 + latestRaw = trimmed;
820 } 1397 }
821 } 1398 }
822 1399
823 - if (earliestParsed.HasValue) 1400 + if (latestParsed.HasValue)
824 { 1401 {
825 - text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(earliestParsed.Value); 1402 + text = ReportsDateTimeDisplayHelper.FormatExpiryDateTime(latestParsed.Value);
826 return true; 1403 return true;
827 } 1404 }
828 1405
829 - if (string.IsNullOrWhiteSpace(earliestRaw)) 1406 + if (string.IsNullOrWhiteSpace(latestRaw))
830 { 1407 {
831 return false; 1408 return false;
832 } 1409 }
833 1410
834 - text = earliestRaw; 1411 + text = latestRaw;
835 return true; 1412 return true;
836 } 1413 }
837 1414
美国版/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 @@ -121,6 +121,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService
121 x.LocationId, 121 x.LocationId,
122 ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); 122 ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList());
123 123
  124 + var printSnapshotMap = await LoadPrintSnapshotMapAsync(pageRows.Select(x => x.Id).ToList());
  125 +
124 var items = pageRows.Select(x => 126 var items = pageRows.Select(x =>
125 { 127 {
126 var cat = !string.IsNullOrWhiteSpace(x.ProductCategoryName) 128 var cat = !string.IsNullOrWhiteSpace(x.ProductCategoryName)
@@ -151,11 +153,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService @@ -151,11 +153,7 @@ public class ReportsAppService : ApplicationService, IReportsAppService
151 PrintedByName = ResolveUserName(userMap, x.CreatedBy), 153 PrintedByName = ResolveUserName(userMap, x.CreatedBy),
152 LocationText = locText, 154 LocationText = locText,
153 LocationId = x.LocationId?.Trim(), 155 LocationId = x.LocationId?.Trim(),
154 - ExpiryDateText = ReportsPrintLogExpiryHelper.ExtractFormattedExpiryText(  
155 - x.PrintInputJson,  
156 - x.RenderTemplateJson,  
157 - x.BaseTime,  
158 - printedAt) 156 + ExpiryDateText = FormatPrintLogExpiry(x.PrintInputJson, x.RenderTemplateJson, x.BaseTime, printedAt, printSnapshotMap, x.Id)
159 }; 157 };
160 }).ToList(); 158 }).ToList();
161 159
@@ -239,6 +237,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService @@ -239,6 +237,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService
239 x.LocationId, 237 x.LocationId,
240 ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); 238 ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList());
241 239
  240 + var printSnapshotMap = await LoadPrintSnapshotMapAsync(rows.Select(x => x.Id).ToList());
  241 +
242 var fileName = $"print-log_{Clock.Now:yyyy-MM-dd_HH-mm-ss}.pdf"; 242 var fileName = $"print-log_{Clock.Now:yyyy-MM-dd_HH-mm-ss}.pdf";
243 var document = Document.Create(container => 243 var document = Document.Create(container =>
244 { 244 {
@@ -296,11 +296,13 @@ public class ReportsAppService : ApplicationService, IReportsAppService @@ -296,11 +296,13 @@ public class ReportsAppService : ApplicationService, IReportsAppService
296 table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3) 296 table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
297 .Text(FormatLocationText(x.LocName, x.LocCode)); 297 .Text(FormatLocationText(x.LocName, x.LocCode));
298 table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3) 298 table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
299 - .Text(ReportsPrintLogExpiryHelper.ExtractFormattedExpiryText( 299 + .Text(FormatPrintLogExpiry(
300 x.PrintInputJson, 300 x.PrintInputJson,
301 x.RenderTemplateJson, 301 x.RenderTemplateJson,
302 x.BaseTime, 302 x.BaseTime,
303 - printedAt)); 303 + printedAt,
  304 + printSnapshotMap,
  305 + x.Id));
304 } 306 }
305 }); 307 });
306 }); 308 });
@@ -402,7 +404,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService @@ -402,7 +404,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService
402 x.LocationId, 404 x.LocationId,
403 ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList()); 405 ResolveStoredPrintInstant(x.PrintedAt, x.CreationTime, x.BaseTime))).ToList());
404 406
405 - var items = pageRows.Select(x => MapPrintLogExportRowToListItem(x, userMap, dailyLabelIdMap)).ToList(); 407 + var printSnapshotMap = await LoadPrintSnapshotMapAsync(pageRows.Select(x => x.Id).ToList());
  408 + var items = pageRows.Select(x => MapPrintLogExportRowToListItem(x, userMap, dailyLabelIdMap, printSnapshotMap)).ToList();
406 409
407 var ms = ReportsPrintLogExcelHelper.BuildWorkbook(items); 410 var ms = ReportsPrintLogExcelHelper.BuildWorkbook(items);
408 var fileName = $"print-log_{Clock.Now:yyyyMMdd-HHmmss}.xlsx"; 411 var fileName = $"print-log_{Clock.Now:yyyyMMdd-HHmmss}.xlsx";
@@ -973,7 +976,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService @@ -973,7 +976,8 @@ public class ReportsAppService : ApplicationService, IReportsAppService
973 private static ReportsPrintLogListItemDto MapPrintLogExportRowToListItem( 976 private static ReportsPrintLogListItemDto MapPrintLogExportRowToListItem(
974 PrintLogExportRow x, 977 PrintLogExportRow x,
975 Dictionary<string, string> userMap, 978 Dictionary<string, string> userMap,
976 - IReadOnlyDictionary<string, string> dailyLabelIdMap) 979 + IReadOnlyDictionary<string, string> dailyLabelIdMap,
  980 + IReadOnlyDictionary<string, List<ReportsPrintLogExpiryHelper.PrintSnapshotLine>> printSnapshotMap)
977 { 981 {
978 var cat = !string.IsNullOrWhiteSpace(x.ProductCategoryName) 982 var cat = !string.IsNullOrWhiteSpace(x.ProductCategoryName)
979 ? x.ProductCategoryName!.Trim() 983 ? x.ProductCategoryName!.Trim()
@@ -1003,14 +1007,65 @@ public class ReportsAppService : ApplicationService, IReportsAppService @@ -1003,14 +1007,65 @@ public class ReportsAppService : ApplicationService, IReportsAppService
1003 PrintedByName = ResolveUserName(userMap, x.CreatedBy), 1007 PrintedByName = ResolveUserName(userMap, x.CreatedBy),
1004 LocationText = locText, 1008 LocationText = locText,
1005 LocationId = x.LocationId?.Trim(), 1009 LocationId = x.LocationId?.Trim(),
1006 - ExpiryDateText = ReportsPrintLogExpiryHelper.ExtractFormattedExpiryText( 1010 + ExpiryDateText = FormatPrintLogExpiry(
1007 x.PrintInputJson, 1011 x.PrintInputJson,
1008 x.RenderTemplateJson, 1012 x.RenderTemplateJson,
1009 x.BaseTime, 1013 x.BaseTime,
1010 - printedAt) 1014 + printedAt,
  1015 + printSnapshotMap,
  1016 + x.Id)
1011 }; 1017 };
1012 } 1018 }
1013 1019
  1020 + private async Task<Dictionary<string, List<ReportsPrintLogExpiryHelper.PrintSnapshotLine>>> LoadPrintSnapshotMapAsync(
  1021 + IReadOnlyCollection<string> taskIds)
  1022 + {
  1023 + var map = new Dictionary<string, List<ReportsPrintLogExpiryHelper.PrintSnapshotLine>>(StringComparer.Ordinal);
  1024 + var ids = taskIds.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList();
  1025 + if (ids.Count == 0)
  1026 + {
  1027 + return map;
  1028 + }
  1029 +
  1030 + var rows = await _dbContext.SqlSugarClient.Queryable<FlLabelPrintDataDbEntity>()
  1031 + .Where(x => ids.Contains(x.PrintTaskId))
  1032 + .Select(x => new { x.PrintTaskId, x.ElementName, x.RenderValue, x.RenderConfigJson })
  1033 + .ToListAsync();
  1034 +
  1035 + foreach (var row in rows)
  1036 + {
  1037 + if (!map.TryGetValue(row.PrintTaskId, out var list))
  1038 + {
  1039 + list = new List<ReportsPrintLogExpiryHelper.PrintSnapshotLine>();
  1040 + map[row.PrintTaskId] = list;
  1041 + }
  1042 +
  1043 + list.Add(new ReportsPrintLogExpiryHelper.PrintSnapshotLine(
  1044 + row.ElementName,
  1045 + row.RenderValue,
  1046 + row.RenderConfigJson));
  1047 + }
  1048 +
  1049 + return map;
  1050 + }
  1051 +
  1052 + private static string FormatPrintLogExpiry(
  1053 + string? printInputJson,
  1054 + string? renderTemplateJson,
  1055 + DateTime? baseTime,
  1056 + DateTime printedAt,
  1057 + IReadOnlyDictionary<string, List<ReportsPrintLogExpiryHelper.PrintSnapshotLine>> printSnapshotMap,
  1058 + string taskId)
  1059 + {
  1060 + printSnapshotMap.TryGetValue(taskId, out var lines);
  1061 + return ReportsPrintLogExpiryHelper.ExtractFormattedExpiryText(
  1062 + printInputJson,
  1063 + renderTemplateJson,
  1064 + baseTime,
  1065 + printedAt,
  1066 + lines);
  1067 + }
  1068 +
1014 /// <summary> 1069 /// <summary>
1015 /// 打印时刻:有真实时分的 PrintedAt → CreationTime → BaseTime;否则 coalesce 非空值(供排序/日序号)。 1070 /// 打印时刻:有真实时分的 PrintedAt → CreationTime → BaseTime;否则 coalesce 非空值(供排序/日序号)。
1016 /// </summary> 1071 /// </summary>
美国版/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 @@ -656,22 +656,23 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
656 var currentUserId = CurrentUser?.Id?.ToString(); 656 var currentUserId = CurrentUser?.Id?.ToString();
657 var batchId = _guidGenerator.Create().ToString(); 657 var batchId = _guidGenerator.Create().ToString();
658 var taskIds = new List<string>(); 658 var taskIds = new List<string>();
  659 + var printInputById = IndexPrintInputElements(input.PrintInputJson);
659 660
660 for (var i = 1; i <= quantity; i++) 661 for (var i = 1; i <= quantity; i++)
661 { 662 {
662 var taskId = _guidGenerator.Create().ToString(); 663 var taskId = _guidGenerator.Create().ToString();
663 taskIds.Add(taskId); 664 taskIds.Add(taskId);
664 665
665 - var renderTemplate = resolvedTemplate; 666 + var renderTemplate = JsonSerializer.Deserialize<LabelTemplatePreviewDto>(
  667 + JsonSerializer.Serialize(resolvedTemplate))
  668 + ?? resolvedTemplate;
666 if (reservedDailyLabelIds is { Count: > 0 }) 669 if (reservedDailyLabelIds is { Count: > 0 })
667 { 670 {
668 var dailyId = reservedDailyLabelIds[Math.Min(i - 1, reservedDailyLabelIds.Count - 1)]; 671 var dailyId = reservedDailyLabelIds[Math.Min(i - 1, reservedDailyLabelIds.Count - 1)];
669 - renderTemplate = JsonSerializer.Deserialize<LabelTemplatePreviewDto>(  
670 - JsonSerializer.Serialize(resolvedTemplate))  
671 - ?? resolvedTemplate;  
672 LabelTemplateLabelIdHelper.ApplyLabelIdToElements(renderTemplate.Elements, dailyId); 672 LabelTemplateLabelIdHelper.ApplyLabelIdToElements(renderTemplate.Elements, dailyId);
673 } 673 }
674 674
  675 + ApplyLivePrintSnapshot(renderTemplate, printInputById);
675 var renderTemplateJsonStr = JsonSerializer.Serialize(renderTemplate); 676 var renderTemplateJsonStr = JsonSerializer.Serialize(renderTemplate);
676 677
677 var task = new FlLabelPrintTaskDbEntity 678 var task = new FlLabelPrintTaskDbEntity
@@ -701,29 +702,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ @@ -701,29 +702,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
701 702
702 await _dbContext.SqlSugarClient.Insertable(task).ExecuteCommandAsync(); 703 await _dbContext.SqlSugarClient.Insertable(task).ExecuteCommandAsync();
703 704
704 - var rows = renderTemplate.Elements.Select(e =>  
705 - {  
706 - var cfgJson = e.ConfigJson is null ? null : JsonSerializer.Serialize(e.ConfigJson);  
707 - string? renderValue = null;  
708 - if (e.ConfigJson is JsonElement je && je.ValueKind == JsonValueKind.Object && je.TryGetProperty("text", out var tv))  
709 - {  
710 - renderValue = tv.ValueKind == JsonValueKind.String ? tv.GetString() : tv.ToString();  
711 - }  
712 - else if (e.ConfigJson is Dictionary<string, object?> dict && dict.TryGetValue("text", out var v))  
713 - {  
714 - renderValue = v?.ToString();  
715 - }  
716 -  
717 - return new FlLabelPrintDataDbEntity  
718 - {  
719 - Id = _guidGenerator.Create().ToString(),  
720 - PrintTaskId = taskId,  
721 - ElementId = e.Id?.Trim() ?? string.Empty,  
722 - ElementName = e.ElementName?.Trim(),  
723 - RenderValue = renderValue,  
724 - RenderConfigJson = cfgJson  
725 - };  
726 - }).Where(x => !string.IsNullOrWhiteSpace(x.ElementId)).ToList(); 705 + var rows = BuildPrintDataRows(taskId, renderTemplate);
727 706
728 if (rows.Count > 0) 707 if (rows.Count > 0)
729 { 708 {
@@ -854,29 +833,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ @@ -854,29 +833,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
854 833
855 await _dbContext.SqlSugarClient.Insertable(newTask).ExecuteCommandAsync(); 834 await _dbContext.SqlSugarClient.Insertable(newTask).ExecuteCommandAsync();
856 835
857 - var rows = resolvedTemplate.Elements.Select(e =>  
858 - {  
859 - var cfgJson = e.ConfigJson is null ? null : JsonSerializer.Serialize(e.ConfigJson);  
860 - string? renderValue = null;  
861 - if (e.ConfigJson is JsonElement je && je.ValueKind == JsonValueKind.Object && je.TryGetProperty("text", out var tv))  
862 - {  
863 - renderValue = tv.ValueKind == JsonValueKind.String ? tv.GetString() : tv.ToString();  
864 - }  
865 - else if (e.ConfigJson is Dictionary<string, object?> dict && dict.TryGetValue("text", out var v))  
866 - {  
867 - renderValue = v?.ToString();  
868 - }  
869 -  
870 - return new FlLabelPrintDataDbEntity  
871 - {  
872 - Id = _guidGenerator.Create().ToString(),  
873 - PrintTaskId = newTaskId,  
874 - ElementId = e.Id?.Trim() ?? string.Empty,  
875 - ElementName = e.ElementName?.Trim(),  
876 - RenderValue = renderValue,  
877 - RenderConfigJson = cfgJson  
878 - };  
879 - }).Where(x => !string.IsNullOrWhiteSpace(x.ElementId)).ToList(); 836 + var rows = BuildPrintDataRows(newTaskId, resolvedTemplate);
880 837
881 if (rows.Count > 0) 838 if (rows.Count > 0)
882 { 839 {
@@ -957,6 +914,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ @@ -957,6 +914,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
957 /// 914 ///
958 /// 可选按自然日筛选:<c>printDateDay</c>(<c>yyyy-MM-dd</c>,优先)或 <c>printDate</c>;均未传则返回该门店全部记录(分页)。 915 /// 可选按自然日筛选:<c>printDateDay</c>(<c>yyyy-MM-dd</c>,优先)或 <c>printDate</c>;均未传则返回该门店全部记录(分页)。
959 /// 出参 <c>labelId</c> 为门店当日打印序号(<c>yyyyMMdd-n</c>)。 916 /// 出参 <c>labelId</c> 为门店当日打印序号(<c>yyyyMMdd-n</c>)。
  917 + /// 出参 <c>printDataList</c> 为本次出纸各格文案(来自 fl_label_print_data)。
960 /// ```json 918 /// ```json
961 /// { 919 /// {
962 /// "locationId": "11111111-1111-1111-1111-111111111111", 920 /// "locationId": "11111111-1111-1111-1111-111111111111",
@@ -1072,6 +1030,8 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ @@ -1072,6 +1030,8 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
1072 pageRows.Select(x => new ReportsPrintLogDailyLabelIdHelper.PrintTaskScopeKey( 1030 pageRows.Select(x => new ReportsPrintLogDailyLabelIdHelper.PrintTaskScopeKey(
1073 x.Id, locationId, x.PrintedAt ?? x.CreationTime)).ToList()); 1031 x.Id, locationId, x.PrintedAt ?? x.CreationTime)).ToList());
1074 1032
  1033 + var printDataMap = await LoadPrintDataListMapAsync(pageTaskIds);
  1034 +
1075 var items = pageRows.Select(x => new PrintLogItemDto 1035 var items = pageRows.Select(x => new PrintLogItemDto
1076 { 1036 {
1077 TaskId = x.Id, 1037 TaskId = x.Id,
@@ -1085,6 +1045,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ @@ -1085,6 +1045,7 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
1085 TypeName = x.TypeName ?? string.Empty, 1045 TypeName = x.TypeName ?? string.Empty,
1086 LabelSizeText = FormatLabelSizeWithUnit(x.TemplateWidth, x.TemplateHeight, x.TemplateUnit), 1046 LabelSizeText = FormatLabelSizeWithUnit(x.TemplateWidth, x.TemplateHeight, x.TemplateUnit),
1087 PrintInputJson = x.PrintInputJson, 1047 PrintInputJson = x.PrintInputJson,
  1048 + PrintDataList = printDataMap.TryGetValue(x.Id, out var dataList) ? dataList : new List<PrintLogDataItemDto>(),
1088 PrintedAt = x.PrintedAt ?? x.CreationTime, 1049 PrintedAt = x.PrintedAt ?? x.CreationTime,
1089 OperatorName = UsAppPrintLogScopeHelper.ResolveOperatorName( 1050 OperatorName = UsAppPrintLogScopeHelper.ResolveOperatorName(
1090 operatorMap, 1051 operatorMap,
@@ -1955,6 +1916,192 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ @@ -1955,6 +1916,192 @@ public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppServ
1955 public string TemplateUnit { get; set; } = "inch"; 1916 public string TemplateUnit { get; set; } = "inch";
1956 } 1917 }
1957 1918
  1919 + private List<FlLabelPrintDataDbEntity> BuildPrintDataRows(string taskId, LabelTemplatePreviewDto renderTemplate)
  1920 + {
  1921 + return renderTemplate.Elements.Select(e =>
  1922 + {
  1923 + var cfgJson = e.ConfigJson is null ? null : JsonSerializer.Serialize(e.ConfigJson);
  1924 + return new FlLabelPrintDataDbEntity
  1925 + {
  1926 + Id = _guidGenerator.Create().ToString(),
  1927 + PrintTaskId = taskId,
  1928 + ElementId = e.Id?.Trim() ?? string.Empty,
  1929 + ElementName = e.ElementName?.Trim(),
  1930 + RenderValue = ExtractPrintRenderValue(e.ConfigJson),
  1931 + RenderConfigJson = cfgJson
  1932 + };
  1933 + }).Where(x => !string.IsNullOrWhiteSpace(x.ElementId)).ToList();
  1934 + }
  1935 +
  1936 + private static void ApplyLivePrintSnapshot(
  1937 + LabelTemplatePreviewDto template,
  1938 + IReadOnlyDictionary<string, JsonElement> printInputById)
  1939 + {
  1940 + foreach (var el in template.Elements)
  1941 + {
  1942 + var liveCfg = ResolveLivePrintConfig(el, printInputById);
  1943 + if (liveCfg is not null)
  1944 + {
  1945 + el.ConfigJson = liveCfg;
  1946 + }
  1947 + }
  1948 + }
  1949 +
  1950 + private async Task<Dictionary<string, List<PrintLogDataItemDto>>> LoadPrintDataListMapAsync(
  1951 + IReadOnlyCollection<string> taskIds)
  1952 + {
  1953 + var map = new Dictionary<string, List<PrintLogDataItemDto>>(StringComparer.Ordinal);
  1954 + if (taskIds.Count == 0)
  1955 + {
  1956 + return map;
  1957 + }
  1958 +
  1959 + var rows = await _dbContext.SqlSugarClient.Queryable<FlLabelPrintDataDbEntity>()
  1960 + .Where(x => taskIds.Contains(x.PrintTaskId))
  1961 + .Select(x => new { x.PrintTaskId, x.ElementId, x.ElementName, x.RenderValue, x.RenderConfigJson })
  1962 + .ToListAsync();
  1963 +
  1964 + foreach (var row in rows)
  1965 + {
  1966 + if (!map.TryGetValue(row.PrintTaskId, out var list))
  1967 + {
  1968 + list = new List<PrintLogDataItemDto>();
  1969 + map[row.PrintTaskId] = list;
  1970 + }
  1971 +
  1972 + JsonElement? cfg = null;
  1973 + if (!string.IsNullOrWhiteSpace(row.RenderConfigJson))
  1974 + {
  1975 + try
  1976 + {
  1977 + cfg = JsonSerializer.Deserialize<JsonElement>(row.RenderConfigJson);
  1978 + }
  1979 + catch
  1980 + {
  1981 + cfg = null;
  1982 + }
  1983 + }
  1984 +
  1985 + list.Add(new PrintLogDataItemDto
  1986 + {
  1987 + ElementId = row.ElementId ?? string.Empty,
  1988 + ElementName = row.ElementName,
  1989 + RenderValue = row.RenderValue ?? string.Empty,
  1990 + RenderConfigJson = cfg
  1991 + });
  1992 + }
  1993 +
  1994 + return map;
  1995 + }
  1996 +
  1997 + /// <summary>按元素 Id 索引 App 打印快照,便于把出纸 <c>__previewFormatted</c> 写入 fl_label_print_data。</summary>
  1998 + private static Dictionary<string, JsonElement> IndexPrintInputElements(JsonElement? printInputJson)
  1999 + {
  2000 + var map = new Dictionary<string, JsonElement>(StringComparer.OrdinalIgnoreCase);
  2001 + if (printInputJson is null)
  2002 + {
  2003 + return map;
  2004 + }
  2005 +
  2006 + var root = printInputJson.Value;
  2007 + if (root.ValueKind != JsonValueKind.Object)
  2008 + {
  2009 + return map;
  2010 + }
  2011 +
  2012 + if (!root.TryGetProperty("elements", out var elements) && !root.TryGetProperty("Elements", out elements))
  2013 + {
  2014 + return map;
  2015 + }
  2016 +
  2017 + if (elements.ValueKind != JsonValueKind.Array)
  2018 + {
  2019 + return map;
  2020 + }
  2021 +
  2022 + foreach (var el in elements.EnumerateArray())
  2023 + {
  2024 + if (el.ValueKind != JsonValueKind.Object)
  2025 + {
  2026 + continue;
  2027 + }
  2028 +
  2029 + var id = el.TryGetProperty("id", out var idEl) && idEl.ValueKind == JsonValueKind.String
  2030 + ? idEl.GetString()
  2031 + : el.TryGetProperty("Id", out idEl) && idEl.ValueKind == JsonValueKind.String
  2032 + ? idEl.GetString()
  2033 + : null;
  2034 + if (!string.IsNullOrWhiteSpace(id))
  2035 + {
  2036 + map[id.Trim()] = el;
  2037 + }
  2038 + }
  2039 +
  2040 + return map;
  2041 + }
  2042 +
  2043 + private static object? ResolveLivePrintConfig(
  2044 + LabelTemplateElementDto element,
  2045 + IReadOnlyDictionary<string, JsonElement> printInputById)
  2046 + {
  2047 + var id = element.Id?.Trim();
  2048 + if (!string.IsNullOrWhiteSpace(id) &&
  2049 + printInputById.TryGetValue(id, out var liveEl) &&
  2050 + (liveEl.TryGetProperty("config", out var cfg) || liveEl.TryGetProperty("Config", out cfg)) &&
  2051 + cfg.ValueKind == JsonValueKind.Object)
  2052 + {
  2053 + return cfg;
  2054 + }
  2055 +
  2056 + return element.ConfigJson;
  2057 + }
  2058 +
  2059 + /// <summary>出纸展示文案:优先 <c>__previewFormatted</c>(如到期 12:00),再退回 text。</summary>
  2060 + private static string? ExtractPrintRenderValue(object? configJson)
  2061 + {
  2062 + if (configJson is JsonElement je && je.ValueKind == JsonValueKind.Object)
  2063 + {
  2064 + foreach (var key in new[] { "__previewFormatted", "__PreviewFormatted", "text", "Text" })
  2065 + {
  2066 + if (!je.TryGetProperty(key, out var v) || v.ValueKind != JsonValueKind.String)
  2067 + {
  2068 + continue;
  2069 + }
  2070 +
  2071 + var s = v.GetString()?.Trim();
  2072 + if (!string.IsNullOrWhiteSpace(s) &&
  2073 + !s.Equals("None", StringComparison.OrdinalIgnoreCase) &&
  2074 + !s.StartsWith('{'))
  2075 + {
  2076 + return s;
  2077 + }
  2078 + }
  2079 +
  2080 + return null;
  2081 + }
  2082 +
  2083 + if (configJson is Dictionary<string, object?> dict)
  2084 + {
  2085 + foreach (var key in new[] { "__previewFormatted", "__PreviewFormatted", "text", "Text" })
  2086 + {
  2087 + if (!dict.TryGetValue(key, out var v) || v is null)
  2088 + {
  2089 + continue;
  2090 + }
  2091 +
  2092 + var s = v.ToString()?.Trim();
  2093 + if (!string.IsNullOrWhiteSpace(s) &&
  2094 + !s.Equals("None", StringComparison.OrdinalIgnoreCase) &&
  2095 + !s.StartsWith('{'))
  2096 + {
  2097 + return s;
  2098 + }
  2099 + }
  2100 + }
  2101 +
  2102 + return null;
  2103 + }
  2104 +
1958 /// <summary> 2105 /// <summary>
1959 /// 将 App 入参中的 JsonElement(对象或 null)反序列化为 PreviewAsync 所需的扁平字典。 2106 /// 将 App 入参中的 JsonElement(对象或 null)反序列化为 PreviewAsync 所需的扁平字典。
1960 /// </summary> 2107 /// </summary>
美国版/scripts/泰鄂测试版部署.ps1
1 -#Requires -Version 5.1 1 +#Requires -Version 5.1
2 <# 2 <#
3 .SYNOPSIS 3 .SYNOPSIS
4 - 食品标签泰鄂测试版 API 一键部署 4 + Te test API deploy
5 .DESCRIPTION 5 .DESCRIPTION
6 - 发布泰鄂版 Yi.Abp.Web,上传到 47.253.11.59,重启 Kestrel 19002,健康检查 https://flusapi-tetest.3flabeling.com 6 + Publish Thai Yi.Abp.Web to 47.253.11.59, restart Kestrel 19002.
  7 + https://flusapi-tetest.3flabeling.com
7 #> 8 #>
8 param( 9 param(
9 [switch]$SkipBuild 10 [switch]$SkipBuild
@@ -35,17 +36,17 @@ $PublishDir = Join-Path $RepoRoot &quot;泰额版\Food Labeling Management Code\Yi.Ab @@ -35,17 +36,17 @@ $PublishDir = Join-Path $RepoRoot &quot;泰额版\Food Labeling Management Code\Yi.Ab
35 Initialize-DeploySsh 36 Initialize-DeploySsh
36 $SshOpts = $global:SshOpts 37 $SshOpts = $global:SshOpts
37 38
38 -Write-Host "== 食品标签泰鄂测试版部署 ==" -ForegroundColor Cyan  
39 -Write-Host "目标: $HostName $RemoteDir"  
40 -Write-Host "域名: $HealthUrl"  
41 -Write-Host "数据库: $TestDbName @ $DbHost" 39 +Write-Host "== Te test deploy ==" -ForegroundColor Cyan
  40 +Write-Host "target: $HostName $RemoteDir"
  41 +Write-Host "url: $HealthUrl"
  42 +Write-Host "db: $TestDbName @ $DbHost"
42 43
43 if (-not $SkipBuild) { 44 if (-not $SkipBuild) {
44 - if (-not (Test-Path $WebCsproj)) { throw "找不到工程: $WebCsproj" }  
45 - Write-Host "== 发布泰鄂版 Yi.Abp.Web ==" -ForegroundColor Cyan 45 + if (-not (Test-Path $WebCsproj)) { throw "csproj not found: $WebCsproj" }
  46 + Write-Host "== dotnet publish ==" -ForegroundColor Cyan
46 if (Test-Path $PublishDir) { Remove-Item $PublishDir -Recurse -Force } 47 if (Test-Path $PublishDir) { Remove-Item $PublishDir -Recurse -Force }
47 & dotnet publish $WebCsproj -c Release -o $PublishDir --nologo 48 & dotnet publish $WebCsproj -c Release -o $PublishDir --nologo
48 - if ($LASTEXITCODE -ne 0) { throw "dotnet publish 失败" } 49 + if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed" }
49 50
50 $appsettings = Join-Path $PublishDir "appsettings.json" 51 $appsettings = Join-Path $PublishDir "appsettings.json"
51 if (Test-Path $appsettings) { 52 if (Test-Path $appsettings) {
@@ -69,36 +70,38 @@ if (-not $SkipBuild) { @@ -69,36 +70,38 @@ if (-not $SkipBuild) {
69 } 70 }
70 71
71 if (-not (Test-Path (Join-Path $PublishDir "Yi.Abp.Web.dll"))) { 72 if (-not (Test-Path (Join-Path $PublishDir "Yi.Abp.Web.dll"))) {
72 - throw "发布目录缺少 Yi.Abp.Web.dll: $PublishDir" 73 + throw "missing Yi.Abp.Web.dll: $PublishDir"
73 } 74 }
74 75
75 -Write-Host "== 停止远程进程 ==" -ForegroundColor Cyan  
76 -Invoke-Remote @' 76 +Write-Host "== stop remote process ==" -ForegroundColor Cyan
  77 +$stopRemote = @"
77 set -e 78 set -e
78 -if [ -f "/var/tmp/net_project/食品标签泰鄂测试版.pid" ]; then  
79 - pid=$(cat "/var/tmp/net_project/食品标签泰鄂测试版.pid" || true)  
80 - if [ -n "$pid" ]; then kill "$pid" 2>/dev/null || true; fi 79 +PIDFILE=/var/tmp/net_project/食品标签泰鄂测试版.pid
  80 +if test -f "`$PIDFILE"; then
  81 + pid=`$(cat "`$PIDFILE" || true)
  82 + if test -n "`$pid"; then kill `$pid 2>/dev/null || true; fi
81 fi 83 fi
82 pkill -f "/www/wwwroot/FoodLabelingManagementTeTest/Yi.Abp.Web.dll" 2>/dev/null || true 84 pkill -f "/www/wwwroot/FoodLabelingManagementTeTest/Yi.Abp.Web.dll" 2>/dev/null || true
83 sleep 1 85 sleep 1
84 echo stopped 86 echo stopped
85 -'@ 87 +"@
  88 +Invoke-Remote $stopRemote
86 89
87 -Write-Host "== 上传发布包 ==" -ForegroundColor Cyan 90 +Write-Host "== upload publish package ==" -ForegroundColor Cyan
88 $tar = Join-Path $env:TEMP "flus-tetest-publish.tgz" 91 $tar = Join-Path $env:TEMP "flus-tetest-publish.tgz"
89 if (Test-Path $tar) { Remove-Item $tar -Force } 92 if (Test-Path $tar) { Remove-Item $tar -Force }
90 Push-Location $PublishDir 93 Push-Location $PublishDir
91 try { 94 try {
92 & tar -czf $tar --exclude=logs --exclude=startup.log * 95 & tar -czf $tar --exclude=logs --exclude=startup.log *
93 - if ($LASTEXITCODE -ne 0) { throw "打包失败" } 96 + if ($LASTEXITCODE -ne 0) { throw "tar failed" }
94 } finally { 97 } finally {
95 Pop-Location 98 Pop-Location
96 } 99 }
97 100
98 & scp @SshOpts $tar "${UserName}@${HostName}:/tmp/flus-tetest-publish.tgz" 101 & scp @SshOpts $tar "${UserName}@${HostName}:/tmp/flus-tetest-publish.tgz"
99 -if ($LASTEXITCODE -ne 0) { throw "scp 失败" } 102 +if ($LASTEXITCODE -ne 0) { throw "scp failed" }
100 103
101 -Invoke-Remote @" 104 +$uploadRemote = @"
102 set -e 105 set -e
103 mkdir -p '$RemoteDir' 106 mkdir -p '$RemoteDir'
104 cd '$RemoteDir' 107 cd '$RemoteDir'
@@ -114,25 +117,27 @@ chmod -R a+rX &#39;$RemoteDir&#39; @@ -114,25 +117,27 @@ chmod -R a+rX &#39;$RemoteDir&#39;
114 ls -l '$RemoteDir/Yi.Abp.Web.dll' 117 ls -l '$RemoteDir/Yi.Abp.Web.dll'
115 echo uploaded_to=$RemoteDir 118 echo uploaded_to=$RemoteDir
116 "@ 119 "@
  120 +Invoke-Remote $uploadRemote
117 121
118 -Write-Host "== 登记宝塔 Net 项目 ==" -ForegroundColor Cyan 122 +Write-Host "== register BT net project ==" -ForegroundColor Cyan
119 $btPyLocal = Join-Path $ScriptDir "bt-register-net-project.py" 123 $btPyLocal = Join-Path $ScriptDir "bt-register-net-project.py"
120 & scp @SshOpts $btPyLocal "${UserName}@${HostName}:/tmp/bt-register-net-project.py" 124 & scp @SshOpts $btPyLocal "${UserName}@${HostName}:/tmp/bt-register-net-project.py"
121 -if ($LASTEXITCODE -ne 0) { throw "上传宝塔登记脚本失败" }  
122 -Invoke-Remote @" 125 +if ($LASTEXITCODE -ne 0) { throw "upload bt python failed" }
  126 +$btRemote = @"
123 set -e 127 set -e
124 sed -i 's/\r`$//' /tmp/bt-register-net-project.py 128 sed -i 's/\r`$//' /tmp/bt-register-net-project.py
125 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' 129 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'
126 "@ 130 "@
  131 +Invoke-Remote $btRemote
127 132
128 -Write-Host "== 启动 API ==" -ForegroundColor Cyan  
129 -Invoke-Remote -AllowFail @" 133 +Write-Host "== start API ==" -ForegroundColor Cyan
  134 +$startRemote = @"
130 mkdir -p /www/wwwlogs/net /var/tmp/net_project 135 mkdir -p /www/wwwlogs/net /var/tmp/net_project
131 -if [ ! -f /swapfile ]; then  
132 - fallocate -l 2G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=2048 136 +test -f /swapfile || fallocate -l 2G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=2048
  137 +if test -f /swapfile; then
133 chmod 600 /swapfile 138 chmod 600 /swapfile
134 - mkswap /swapfile  
135 - swapon /swapfile 139 + mkswap /swapfile || true
  140 + swapon /swapfile || true
136 grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab 141 grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
137 fi 142 fi
138 swapon -a || true 143 swapon -a || true
@@ -144,24 +149,25 @@ ss -lntp | grep 19002 || true @@ -144,24 +149,25 @@ ss -lntp | grep 19002 || true
144 curl -s -o /dev/null -w 'local=%{http_code}\n' --max-time 15 http://127.0.0.1:19002/swagger/index.html || true 149 curl -s -o /dev/null -w 'local=%{http_code}\n' --max-time 15 http://127.0.0.1:19002/swagger/index.html || true
145 tail -n 30 /www/wwwlogs/net/食品标签泰鄂测试版.log || true 150 tail -n 30 /www/wwwlogs/net/食品标签泰鄂测试版.log || true
146 "@ 151 "@
  152 +Invoke-Remote -AllowFail $startRemote
147 153
148 -Write-Host "== 健康检查 ==" -ForegroundColor Cyan 154 +Write-Host "== health check ==" -ForegroundColor Cyan
149 $ok = $false 155 $ok = $false
150 for ($i = 1; $i -le 10; $i++) { 156 for ($i = 1; $i -le 10; $i++) {
151 try { 157 try {
152 $resp = Invoke-WebRequest -Uri $HealthUrl -UseBasicParsing -TimeoutSec 15 158 $resp = Invoke-WebRequest -Uri $HealthUrl -UseBasicParsing -TimeoutSec 15
153 if ($resp.StatusCode -eq 200) { 159 if ($resp.StatusCode -eq 200) {
154 - Write-Host "访问成功: $HealthUrl HTTP $($resp.StatusCode)" -ForegroundColor Green 160 + Write-Host "OK: $HealthUrl HTTP $($resp.StatusCode)" -ForegroundColor Green
155 $ok = $true 161 $ok = $true
156 break 162 break
157 } 163 }
158 } catch { 164 } catch {
159 - Write-Host "等待服务就绪 ($i/10)..." 165 + Write-Host "wait ($i/10)..."
160 Start-Sleep -Seconds 3 166 Start-Sleep -Seconds 3
161 } 167 }
162 } 168 }
163 169
164 -if (-not $ok) { throw "部署后健康检查失败: $HealthUrl" }  
165 -Write-Host "完成。API: https://flusapi-tetest.3flabeling.com" -ForegroundColor Green 170 +if (-not $ok) { throw "health check failed: $HealthUrl" }
  171 +Write-Host "done. API: https://flusapi-tetest.3flabeling.com" -ForegroundColor Green
166 Write-Host "Swagger: $HealthUrl" 172 Write-Host "Swagger: $HealthUrl"
167 -Write-Host "登录: POST https://flusapi-tetest.3flabeling.com/api/app/th-web-auth/login" 173 +Write-Host "login: POST https://flusapi-tetest.3flabeling.com/api/app/th-web-auth/login"