Blame view

美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/UsAppLabelingAppService.cs 50.4 KB
536d25c4   李曜臣   打印预览,产品分类接口实现
1
2
3
4
5
6
  using System;
  using System.Collections.Generic;
  using System.Globalization;
  using System.Linq;
  using System.Text.Json;
  using System.Threading.Tasks;
43d16ca6   杨鑫   打印日志
7
  using FoodLabeling.Application.Contracts.Dtos.Common;
536d25c4   李曜臣   打印预览,产品分类接口实现
8
  using FoodLabeling.Application.Contracts.Dtos.Label;
43d16ca6   杨鑫   打印日志
9
  using FoodLabeling.Application.Contracts.Dtos.LabelTemplate;
07d5dea2   李曜臣   5-18代码优化
10
  using FoodLabeling.Application.Contracts.Dtos.Reports;
536d25c4   李曜臣   打印预览,产品分类接口实现
11
12
  using FoodLabeling.Application.Contracts.Dtos.UsAppLabeling;
  using FoodLabeling.Application.Contracts.IServices;
43d16ca6   杨鑫   打印日志
13
  using FoodLabeling.Application.Helpers;
536d25c4   李曜臣   打印预览,产品分类接口实现
14
  using FoodLabeling.Application.Services.DbModels;
43d16ca6   杨鑫   打印日志
15
  using FoodLabeling.Domain.Entities;
536d25c4   李曜臣   打印预览,产品分类接口实现
16
  using Microsoft.AspNetCore.Authorization;
43d16ca6   杨鑫   打印日志
17
  using Microsoft.AspNetCore.Mvc;
536d25c4   李曜臣   打印预览,产品分类接口实现
18
19
20
21
22
  using SqlSugar;
  using Volo.Abp;
  using Volo.Abp.Application.Services;
  using Volo.Abp.Guids;
  using Volo.Abp.Uow;
ca114eb9   李曜臣   打印日志接口实现
23
  using Yi.Framework.Rbac.Domain.Entities;
536d25c4   李曜臣   打印预览,产品分类接口实现
24
25
26
27
28
29
30
31
32
33
34
35
  using Yi.Framework.SqlSugarCore.Abstractions;
  
  namespace FoodLabeling.Application.Services;
  
  /// <summary>
  /// App Labeling:四级列表(标签分类  产品分类  产品  标签种类)
  /// </summary>
  public class UsAppLabelingAppService : ApplicationService, IUsAppLabelingAppService
  {
      private readonly ISqlSugarDbContext _dbContext;
      private readonly ILabelAppService _labelAppService;
      private readonly IGuidGenerator _guidGenerator;
ca114eb9   李曜臣   打印日志接口实现
36
      private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
536d25c4   李曜臣   打印预览,产品分类接口实现
37
  
ca114eb9   李曜臣   打印日志接口实现
38
39
40
41
42
      public UsAppLabelingAppService(
          ISqlSugarDbContext dbContext,
          ILabelAppService labelAppService,
          IGuidGenerator guidGenerator,
          ISqlSugarRepository<UserAggregateRoot, Guid> userRepository)
536d25c4   李曜臣   打印预览,产品分类接口实现
43
44
45
46
      {
          _dbContext = dbContext;
          _labelAppService = labelAppService;
          _guidGenerator = guidGenerator;
ca114eb9   李曜臣   打印日志接口实现
47
          _userRepository = userRepository;
536d25c4   李曜臣   打印预览,产品分类接口实现
48
49
50
51
52
53
      }
  
      /// <summary>
      /// 获取当前门店下四级嵌套数据
      /// </summary>
      /// <remarks>
8e0c49eb   李曜臣   产品标签类别优化;
54
55
      /// L1 标签分类 fl_label_category(含 buttonAppearanceCOLOR/IMAGE 展示值在 categoryPhotoUrl);仅对当前门店可用:ALL  SPECIFIED 且在 fl_label_category_location
      /// L2 产品分类 fl_product.CategoryId join fl_product_category(同上,展示值在 categoryPhotoUrl);
dc39baae   李曜臣   后台端:管理员查看日志优化,产品与...
56
      /// L3 产品卡片:按「产品 + 标签模板」拆分(同一 productId、不同 fl_label.TemplateId 为多张卡);L4 为该卡下与门店、标签分类、该产品、该模板关联的标签实例(fl_label + fl_label_type)。
07d5dea2   李曜臣   5-18代码优化
57
58
      /// L2 产品分类展示名来自 fl_product_category;产品范围已由 fl_location_product 限定当前门店,
      /// 不再因产品分类 SPECIFIED 未配 fl_product_category_location 而整行过滤(避免 App 全店空数据)。
8e0c49eb   李曜臣   产品标签类别优化;
59
      /// 未归类或分类行未关联到 fl_product_category 时仍归入「无」节点。
536d25c4   李曜臣   打印预览,产品分类接口实现
60
61
62
63
64
65
66
67
68
69
70
71
72
      /// </remarks>
      [Authorize]
      public virtual async Task<List<UsAppLabelCategoryTreeNodeDto>> GetLabelingTreeAsync(UsAppLabelingTreeInputVo input)
      {
          if (string.IsNullOrWhiteSpace(input.LocationId))
          {
              throw new UserFriendlyException("门店Id不能为空");
          }
  
          var locationId = input.LocationId.Trim();
          var keyword = input.Keyword?.Trim();
          var filterCategoryId = input.LabelCategoryId?.Trim();
  
07d5dea2   李曜臣   5-18代码优化
73
74
75
          await UsAppPrintLogScopeHelper.EnsureUserBoundToLocationAsync(
              CurrentUser, _dbContext.SqlSugarClient, locationId);
  
536d25c4   李曜臣   打印预览,产品分类接口实现
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
          var productIds = await _dbContext.SqlSugarClient.Queryable<FlLocationProductDbEntity>()
              .Where(x => x.LocationId == locationId)
              .Select(x => x.ProductId)
              .ToListAsync();
  
          if (productIds.Count == 0)
          {
              return new List<UsAppLabelCategoryTreeNodeDto>();
          }
  
          var query = BuildLabelingJoinQuery(locationId, productIds, filterCategoryId, keyword);
  
          var raw = await query
              .Select((lp, l, p, c, t, tpl, pc) => new LabelingTreeRow
              {
                  LabelCategoryId = c.Id,
                  LabelCategoryName = c.CategoryName,
                  LabelCategoryPhotoUrl = c.CategoryPhotoUrl,
8e0c49eb   李曜臣   产品标签类别优化;
94
                  LabelCategoryButtonAppearance = c.ButtonAppearance,
536d25c4   李曜臣   打印预览,产品分类接口实现
95
96
97
98
                  LabelCategoryOrderNum = c.OrderNum,
                  ProductCategoryId = p.CategoryId,
                  ProductCategoryName = pc.CategoryName,
                  ProductCategoryPhotoUrl = pc.CategoryPhotoUrl,
8e0c49eb   李曜臣   产品标签类别优化;
99
100
101
102
                  ProductCategoryDisplayText = pc.DisplayText,
                  ProductCategoryButtonAppearance = pc.ButtonAppearance,
                  ProductCategoryAvailabilityType = pc.AvailabilityType,
                  ProductCategoryOrderNum = pc.OrderNum,
536d25c4   李曜臣   打印预览,产品分类接口实现
103
104
105
106
107
108
109
                  ProductId = p.Id,
                  ProductName = p.ProductName,
                  ProductCode = p.ProductCode,
                  ProductImageUrl = p.ProductImageUrl,
                  LabelTypeId = t.Id,
                  TypeName = t.TypeName,
                  TypeOrderNum = t.OrderNum,
dc39baae   李曜臣   后台端:管理员查看日志优化,产品与...
110
111
                  LabelCode = l.LabelCode ?? string.Empty,
                  TemplateId = tpl.Id,
536d25c4   李曜臣   打印预览,产品分类接口实现
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
                  TemplateCode = tpl.TemplateCode,
                  TemplateWidth = tpl.Width,
                  TemplateHeight = tpl.Height,
                  TemplateUnit = tpl.Unit
              })
              .ToListAsync();
  
          if (raw.Count == 0)
          {
              return new List<UsAppLabelCategoryTreeNodeDto>();
          }
  
          var byL1 = raw.GroupBy(x => new
          {
              x.LabelCategoryId,
              x.LabelCategoryName,
              x.LabelCategoryPhotoUrl,
8e0c49eb   李曜臣   产品标签类别优化;
129
              x.LabelCategoryButtonAppearance,
536d25c4   李曜臣   打印预览,产品分类接口实现
130
131
132
133
134
135
              x.LabelCategoryOrderNum
          }).OrderBy(g => g.Key.LabelCategoryOrderNum).ThenBy(g => g.Key.LabelCategoryName);
  
          var result = new List<UsAppLabelCategoryTreeNodeDto>();
          foreach (var g1 in byL1)
          {
8e0c49eb   李曜臣   产品标签类别优化;
136
137
              var l1Appearance = string.IsNullOrWhiteSpace(g1.Key.LabelCategoryButtonAppearance)
                  ? "TEXT"
ecb291fd   李曜臣   门店支持优化;标签,产品组件优化
138
                  : g1.Key.LabelCategoryButtonAppearance.Trim();
536d25c4   李曜臣   打印预览,产品分类接口实现
139
140
141
142
143
              var l1 = new UsAppLabelCategoryTreeNodeDto
              {
                  Id = g1.Key.LabelCategoryId,
                  CategoryName = g1.Key.LabelCategoryName ?? string.Empty,
                  CategoryPhotoUrl = g1.Key.LabelCategoryPhotoUrl,
8e0c49eb   李曜臣   产品标签类别优化;
144
                  ButtonAppearance = l1Appearance,
536d25c4   李曜臣   打印预览,产品分类接口实现
145
146
147
148
149
150
151
152
153
154
155
156
157
                  OrderNum = g1.Key.LabelCategoryOrderNum,
                  ProductCategories = new List<UsAppProductCategoryNodeDto>()
              };
  
              var byL2 = g1.GroupBy(x =>
                  {
                      var categoryId = NormalizeNullableId(x.ProductCategoryId);
                      if (categoryId is null)
                      {
                          return new
                          {
                              CategoryId = (string?)null,
                              CategoryName = "无",
8e0c49eb   李曜臣   产品标签类别优化;
158
159
160
161
162
                              CategoryPhotoUrl = (string?)null,
                              DisplayText = (string?)null,
                              ButtonAppearance = (string?)null,
                              AvailabilityType = (string?)null,
                              CategoryOrderNum = int.MaxValue
536d25c4   李曜臣   打印预览,产品分类接口实现
163
164
165
166
167
168
169
170
171
                          };
                      }
  
                      var categoryName = NormalizeCategoryName(x.ProductCategoryName);
                      var categoryPhotoUrl = NormalizeNullableUrl(x.ProductCategoryPhotoUrl);
                      return new
                      {
                          CategoryId = (string?)categoryId,
                          CategoryName = categoryName,
8e0c49eb   李曜臣   产品标签类别优化;
172
173
174
175
176
                          CategoryPhotoUrl = categoryPhotoUrl,
                          DisplayText = NormalizeNullableUrl(x.ProductCategoryDisplayText),
                          ButtonAppearance = NormalizeNullableId(x.ProductCategoryButtonAppearance),
                          AvailabilityType = NormalizeNullableId(x.ProductCategoryAvailabilityType),
                          CategoryOrderNum = x.ProductCategoryOrderNum
536d25c4   李曜臣   打印预览,产品分类接口实现
177
178
                      };
                  })
8e0c49eb   李曜臣   产品标签类别优化;
179
180
                  .OrderBy(g => g.Key.CategoryOrderNum)
                  .ThenBy(g => g.Key.CategoryName);
536d25c4   李曜臣   打印预览,产品分类接口实现
181
182
183
  
              foreach (var g2 in byL2)
              {
dc39baae   李曜臣   后台端:管理员查看日志优化,产品与...
184
185
186
187
                  var productsGrouped = g2
                      .GroupBy(x => new { x.ProductId, x.TemplateId })
                      .OrderBy(pg => pg.First().ProductName)
                      .ThenBy(pg => pg.Key.TemplateId);
8e0c49eb   李曜臣   产品标签类别优化;
188
189
                  var appearance = string.IsNullOrWhiteSpace(g2.Key.ButtonAppearance)
                      ? "TEXT"
ecb291fd   李曜臣   门店支持优化;标签,产品组件优化
190
                      : g2.Key.ButtonAppearance.Trim();
8e0c49eb   李曜臣   产品标签类别优化;
191
192
193
                  var availability = string.IsNullOrWhiteSpace(g2.Key.AvailabilityType)
                      ? "ALL"
                      : g2.Key.AvailabilityType.Trim().ToUpperInvariant();
536d25c4   李曜臣   打印预览,产品分类接口实现
194
195
196
197
198
                  var l2 = new UsAppProductCategoryNodeDto
                  {
                      CategoryId = g2.Key.CategoryId,
                      CategoryPhotoUrl = g2.Key.CategoryPhotoUrl,
                      Name = g2.Key.CategoryName,
8e0c49eb   李曜臣   产品标签类别优化;
199
200
201
202
                      DisplayText = g2.Key.DisplayText,
                      ButtonAppearance = appearance,
                      AvailabilityType = availability,
                      OrderNum = g2.Key.CategoryOrderNum == int.MaxValue ? 0 : g2.Key.CategoryOrderNum,
536d25c4   李曜臣   打印预览,产品分类接口实现
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
                      ItemCount = productsGrouped.Count(),
                      Products = new List<UsAppLabelingProductNodeDto>()
                  };
  
                  foreach (var g3 in productsGrouped)
                  {
                      var first = g3.First();
                      var typeNodes = g3
                          .GroupBy(r => r.LabelCode)
                          .Select(gr => BuildLabelTypeNode(gr.First()))
                          .OrderBy(t => t.OrderNum)
                          .ThenBy(t => t.TypeName)
                          .ToList();
  
                      var subtitle = string.IsNullOrWhiteSpace(first.ProductCode?.Trim())
                          ? "无"
                          : first.ProductCode!.Trim();
dc39baae   李曜臣   后台端:管理员查看日志优化,产品与...
220
221
222
223
                      var templateLabelSizeText = FormatLabelSize(
                          first.TemplateWidth,
                          first.TemplateHeight,
                          first.TemplateUnit);
536d25c4   李曜臣   打印预览,产品分类接口实现
224
225
226
227
  
                      l2.Products.Add(new UsAppLabelingProductNodeDto
                      {
                          ProductId = first.ProductId,
dc39baae   李曜臣   后台端:管理员查看日志优化,产品与...
228
229
230
                          TemplateId = first.TemplateId,
                          TemplateCode = first.TemplateCode,
                          TemplateLabelSizeText = templateLabelSizeText,
536d25c4   李曜臣   打印预览,产品分类接口实现
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
                          ProductName = first.ProductName ?? string.Empty,
                          ProductCode = first.ProductCode ?? string.Empty,
                          ProductImageUrl = first.ProductImageUrl,
                          Subtitle = subtitle,
                          LabelTypeCount = typeNodes.Count,
                          LabelTypes = typeNodes
                      });
                  }
  
                  l1.ProductCategories.Add(l2);
              }
  
              result.Add(l1);
          }
  
          return result;
      }
  
      /// <summary>
      /// App 打印预览:按标签编码解析模板并返回顶部展示字段 + 预览模板结构
      /// </summary>
      /// <remarks>
      /// 示例请求:
      /// ```json
      /// {
      ///   "locationId": "LOC001",
      ///   "labelCode": "LBL0001",
      ///   "productId": "PROD001",
      ///   "baseTime": "2026-03-26T10:30:00",
      ///   "printInputJson": {
      ///     "price": "12.99"
      ///   }
      /// }
      /// ```
      /// </remarks>
      /// <param name="input">预览入参</param>
      /// <returns>顶部字段 + 预览模板结构</returns>
      /// <response code="200">成功</response>
      /// <response code="400">参数错误/数据不存在</response>
      /// <response code="500">服务器错误</response>
      [Authorize]
      public virtual async Task<UsAppLabelPreviewDto> PreviewAsync(UsAppLabelPreviewInputVo input)
      {
          if (input is null)
          {
              throw new UserFriendlyException("入参不能为空");
          }
  
          var locationId = input.LocationId?.Trim();
          if (string.IsNullOrWhiteSpace(locationId))
          {
              throw new UserFriendlyException("门店Id不能为空");
          }
  
          var labelCode = input.LabelCode?.Trim();
          if (string.IsNullOrWhiteSpace(labelCode))
          {
              throw new UserFriendlyException("labelCode不能为空");
          }
  
          var labelRow = await _dbContext.SqlSugarClient
              .Queryable<FlLabelDbEntity, FlLabelCategoryDbEntity, FlLabelTypeDbEntity, FlLabelTemplateDbEntity>(
                  (l, c, t, tpl) => l.LabelCategoryId == c.Id && l.LabelTypeId == t.Id && l.TemplateId == tpl.Id)
              .Where((l, c, t, tpl) => !l.IsDeleted && l.State)
              .Where((l, c, t, tpl) => !c.IsDeleted && c.State)
              .Where((l, c, t, tpl) => !t.IsDeleted && t.State)
              .Where((l, c, t, tpl) => !tpl.IsDeleted)
              .Where((l, c, t, tpl) => l.LabelCode == labelCode)
              .Select((l, c, t, tpl) => new
              {
a4baaa73   李曜臣   模板与产品关联实现
301
                  l.Id,
536d25c4   李曜臣   打印预览,产品分类接口实现
302
303
                  l.LabelCode,
                  l.LocationId,
a4baaa73   李曜臣   模板与产品关联实现
304
305
306
307
                  l.LabelTypeId,
                  l.TemplateId,
                  l.LastModificationTime,
                  l.CreationTime,
536d25c4   李曜臣   打印预览,产品分类接口实现
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
                  LabelCategoryName = c.CategoryName,
                  TypeName = t.TypeName,
                  TemplateCode = tpl.TemplateCode,
                  TemplateWidth = tpl.Width,
                  TemplateHeight = tpl.Height,
                  TemplateUnit = tpl.Unit
              })
              .FirstAsync();
  
          if (labelRow is null)
          {
              throw new UserFriendlyException("标签不存在或不可用");
          }
  
          if (!string.Equals(labelRow.LocationId?.Trim(), locationId, StringComparison.OrdinalIgnoreCase))
          {
              throw new UserFriendlyException("该标签不属于当前门店");
          }
  
a4baaa73   李曜臣   模板与产品关联实现
327
328
          var previewProductId = await ResolvePreviewProductIdAsync(labelRow.Id, input.ProductId);
  
536d25c4   李曜臣   打印预览,产品分类接口实现
329
330
331
          var template = await _labelAppService.PreviewAsync(new LabelPreviewResolveInputVo
          {
              LabelCode = labelCode,
a4baaa73   李曜臣   模板与产品关联实现
332
              ProductId = previewProductId,
536d25c4   李曜臣   打印预览,产品分类接口实现
333
334
335
336
              BaseTime = input.BaseTime,
              PrintInputJson = input.PrintInputJson?.ToDictionary(x => x.Key, x => (object?)x.Value)
          });
  
a4baaa73   李曜臣   模板与产品关联实现
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
          Dictionary<string, object?>? templateProductDefaultValues = null;
          if (!string.IsNullOrWhiteSpace(previewProductId))
          {
              var productDefault = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateProductDefaultDbEntity>()
                  .Where(x => x.TemplateId == labelRow.TemplateId)
                  .Where(x => x.ProductId == previewProductId)
                  .Where(x => x.LabelTypeId == labelRow.LabelTypeId)
                  .OrderBy(x => x.OrderNum)
                  .FirstAsync();
  
              if (!string.IsNullOrWhiteSpace(productDefault?.DefaultValuesJson))
              {
                  try
                  {
                      templateProductDefaultValues =
                          JsonSerializer.Deserialize<Dictionary<string, object?>>(productDefault.DefaultValuesJson!);
                  }
                  catch
                  {
                      templateProductDefaultValues = null;
                  }
              }
          }
  
536d25c4   李曜臣   打印预览,产品分类接口实现
361
362
          var productName = string.Empty;
          var productCategoryName = "无";
a4baaa73   李曜臣   模板与产品关联实现
363
          if (!string.IsNullOrWhiteSpace(previewProductId))
536d25c4   李曜臣   打印预览,产品分类接口实现
364
          {
536d25c4   李曜臣   打印预览,产品分类接口实现
365
              var p = await _dbContext.SqlSugarClient.Queryable<FlProductDbEntity>()
a4baaa73   李曜臣   模板与产品关联实现
366
                  .FirstAsync(x => !x.IsDeleted && x.State && x.Id == previewProductId);
536d25c4   李曜臣   打印预览,产品分类接口实现
367
368
369
370
371
372
373
374
375
376
377
378
379
380
              if (p is not null)
              {
                  productName = p.ProductName ?? string.Empty;
                  if (!string.IsNullOrWhiteSpace(p.CategoryId))
                  {
                      var pc = await _dbContext.SqlSugarClient.Queryable<FlProductCategoryDbEntity>()
                          .FirstAsync(x => !x.IsDeleted && x.State && x.Id == p.CategoryId);
                      productCategoryName = NormalizeCategoryName(pc?.CategoryName);
                  }
              }
          }
  
          return new UsAppLabelPreviewDto
          {
a4baaa73   李曜臣   模板与产品关联实现
381
              LabelId = labelRow.Id,
536d25c4   李曜臣   打印预览,产品分类接口实现
382
383
384
385
386
387
388
389
              LocationId = locationId,
              LabelCode = labelCode,
              TemplateCode = labelRow.TemplateCode,
              LabelSizeText = FormatLabelSize(labelRow.TemplateWidth, labelRow.TemplateHeight, labelRow.TemplateUnit),
              TypeName = labelRow.TypeName,
              ProductName = string.IsNullOrWhiteSpace(productName) ? null : productName,
              ProductCategoryName = productCategoryName,
              LabelCategoryName = labelRow.LabelCategoryName,
a4baaa73   李曜臣   模板与产品关联实现
390
              LabelLastEdited = labelRow.LastModificationTime ?? labelRow.CreationTime,
536d25c4   李曜臣   打印预览,产品分类接口实现
391
              PreviewImageBase64Png = null,
a4baaa73   李曜臣   模板与产品关联实现
392
393
              Template = template,
              TemplateProductDefaultValues = templateProductDefaultValues
536d25c4   李曜臣   打印预览,产品分类接口实现
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
          };
      }
  
      /// <summary>
      /// App 打印:创建打印任务并落库打印明细(fl_label_print_task / fl_label_print_data
      /// </summary>
      /// <param name="input">打印入参</param>
      /// <returns>任务Id</returns>
      [Authorize]
      [UnitOfWork]
      public virtual async Task<UsAppLabelPrintOutputDto> PrintAsync(UsAppLabelPrintInputVo input)
      {
          if (input is null)
          {
              throw new UserFriendlyException("入参不能为空");
          }
  
          var locationId = input.LocationId?.Trim();
          if (string.IsNullOrWhiteSpace(locationId))
          {
              throw new UserFriendlyException("门店Id不能为空");
          }
  
          var labelCode = input.LabelCode?.Trim();
          if (string.IsNullOrWhiteSpace(labelCode))
          {
              throw new UserFriendlyException("labelCode不能为空");
          }
  
          var quantity = input.PrintQuantity <= 0 ? 1 : input.PrintQuantity;
c304e27c   李曜臣   打印日志优化
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
          var clientRequestId = input.ClientRequestId?.Trim();
          if (!string.IsNullOrWhiteSpace(clientRequestId))
          {
              // 幂等:同一个 clientRequestId 重复调用,直接返回首次创建的任务集合
              var existed = await _dbContext.SqlSugarClient.Queryable<FlLabelPrintTaskDbEntity>()
                  .Where(x => x.ClientRequestId == clientRequestId)
                  .OrderBy(x => x.CopyIndex)
                  .ToListAsync();
  
              if (existed is not null && existed.Count > 0)
              {
                  var existedBatchId = existed.First().BatchId;
                  var existedTaskIds = existed.Select(x => x.Id).ToList();
                  return new UsAppLabelPrintOutputDto
                  {
                      TaskId = existedTaskIds.FirstOrDefault() ?? string.Empty,
                      PrintQuantity = existedTaskIds.Count,
                      BatchId = existedBatchId,
                      TaskIds = existedTaskIds
                  };
              }
          }
536d25c4   李曜臣   打印预览,产品分类接口实现
446
447
448
449
450
451
452
453
454
455
456
  
          // 校验 label + location,并补齐一些顶部字段用于任务表落库
          var labelRow = await _dbContext.SqlSugarClient
              .Queryable<FlLabelDbEntity, FlLabelTypeDbEntity, FlLabelTemplateDbEntity>(
                  (l, t, tpl) => l.LabelTypeId == t.Id && l.TemplateId == tpl.Id)
              .Where((l, t, tpl) => !l.IsDeleted && l.State)
              .Where((l, t, tpl) => !t.IsDeleted && t.State)
              .Where((l, t, tpl) => !tpl.IsDeleted)
              .Where((l, t, tpl) => l.LabelCode == labelCode)
              .Select((l, t, tpl) => new
              {
c304e27c   李曜臣   打印日志优化
457
                  l.Id,
536d25c4   李曜臣   打印预览,产品分类接口实现
458
459
                  l.LocationId,
                  l.LabelTypeId,
c304e27c   李曜臣   打印日志优化
460
                  l.TemplateId
536d25c4   李曜臣   打印预览,产品分类接口实现
461
462
463
464
465
466
467
468
469
470
471
472
473
              })
              .FirstAsync();
  
          if (labelRow is null)
          {
              throw new UserFriendlyException("标签不存在或不可用");
          }
  
          if (!string.Equals(labelRow.LocationId?.Trim(), locationId, StringComparison.OrdinalIgnoreCase))
          {
              throw new UserFriendlyException("该标签不属于当前门店");
          }
  
c304e27c   李曜臣   打印日志优化
474
          var previewProductId = await ResolvePreviewProductIdAsync(labelRow.Id, input.ProductId);
8e0c49eb   李曜臣   产品标签类别优化;
475
          var normalizedPrintInput = ParsePrintInputJsonToDictionary(input.PrintInputJson);
43d16ca6   杨鑫   打印日志
476
  
c304e27c   李曜臣   打印日志优化
477
478
          // 解析模板 elements(与预览一致的渲染数据)
          var resolvedTemplate = await _labelAppService.PreviewAsync(new LabelPreviewResolveInputVo
a001da6d   杨鑫   APP 预览打印
479
          {
c304e27c   李曜臣   打印日志优化
480
481
482
483
484
              LabelCode = labelCode,
              ProductId = previewProductId,
              BaseTime = input.BaseTime,
              PrintInputJson = normalizedPrintInput
          });
43d16ca6   杨鑫   打印日志
485
  
c304e27c   李曜臣   打印日志优化
486
487
488
489
          var templateProductDefaultValuesJson = await ResolveTemplateProductDefaultValuesJsonAsync(
              labelRow.TemplateId,
              previewProductId,
              labelRow.LabelTypeId);
a001da6d   杨鑫   APP 预览打印
490
  
536d25c4   李曜臣   打印预览,产品分类接口实现
491
492
493
          var printInputJsonStr = input.PrintInputJson is null
              ? null
              : JsonSerializer.Serialize(input.PrintInputJson);
c304e27c   李曜臣   打印日志优化
494
          var renderTemplateJsonStr = JsonSerializer.Serialize(resolvedTemplate);
536d25c4   李曜臣   打印预览,产品分类接口实现
495
496
497
  
          var now = DateTime.Now;
          var currentUserId = CurrentUser?.Id?.ToString();
c304e27c   李曜臣   打印日志优化
498
499
          var batchId = _guidGenerator.Create().ToString();
          var taskIds = new List<string>();
536d25c4   李曜臣   打印预览,产品分类接口实现
500
  
c304e27c   李曜臣   打印日志优化
501
          for (var i = 1; i <= quantity; i++)
536d25c4   李曜臣   打印预览,产品分类接口实现
502
          {
c304e27c   李曜臣   打印日志优化
503
504
              var taskId = _guidGenerator.Create().ToString();
              taskIds.Add(taskId);
536d25c4   李曜臣   打印预览,产品分类接口实现
505
  
c304e27c   李曜臣   打印日志优化
506
              var task = new FlLabelPrintTaskDbEntity
a001da6d   杨鑫   APP 预览打印
507
              {
c304e27c   李曜臣   打印日志优化
508
509
510
511
512
513
514
515
516
                  Id = taskId,
                  BatchId = batchId,
                  CopyIndex = i,
                  ClientRequestId = string.IsNullOrWhiteSpace(clientRequestId) ? null : clientRequestId,
                  LabelId = labelRow.Id,
                  TemplateId = labelRow.TemplateId,
                  LabelTypeId = labelRow.LabelTypeId,
                  ProductId = previewProductId,
                  LocationId = locationId,
a001da6d   杨鑫   APP 预览打印
517
                  BaseTime = input.BaseTime,
c304e27c   李曜臣   打印日志优化
518
519
520
521
522
523
524
525
526
527
528
529
                  PrintInputJson = printInputJsonStr,
                  TemplateProductDefaultValuesJson = templateProductDefaultValuesJson,
                  RenderTemplateJson = renderTemplateJsonStr,
                  PrinterId = input.PrinterId?.Trim(),
                  PrinterMac = input.PrinterMac?.Trim(),
                  PrinterAddress = input.PrinterAddress?.Trim(),
                  Status = "CREATED",
                  PrintedAt = null,
                  ErrorMessage = null,
                  CreatedBy = currentUserId,
                  CreationTime = now
              };
536d25c4   李曜臣   打印预览,产品分类接口实现
530
  
c304e27c   李曜臣   打印日志优化
531
              await _dbContext.SqlSugarClient.Insertable(task).ExecuteCommandAsync();
536d25c4   李曜臣   打印预览,产品分类接口实现
532
  
c304e27c   李曜臣   打印日志优化
533
534
535
536
537
538
539
540
541
542
543
544
              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<string, object?> dict && dict.TryGetValue("text", out var v))
                  {
                      renderValue = v?.ToString();
                  }
536d25c4   李曜臣   打印预览,产品分类接口实现
545
  
c304e27c   李曜臣   打印日志优化
546
547
548
549
550
551
552
553
554
555
                  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();
536d25c4   李曜臣   打印预览,产品分类接口实现
556
  
c304e27c   李曜臣   打印日志优化
557
558
559
560
561
              if (rows.Count > 0)
              {
                  await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync();
              }
          }
536d25c4   李曜臣   打印预览,产品分类接口实现
562
563
564
  
          return new UsAppLabelPrintOutputDto
          {
c304e27c   李曜臣   打印日志优化
565
              TaskId = taskIds.FirstOrDefault() ?? string.Empty,
43d16ca6   杨鑫   打印日志
566
              PrintQuantity = quantity,
c304e27c   李曜臣   打印日志优化
567
568
              BatchId = batchId,
              TaskIds = taskIds
43d16ca6   杨鑫   打印日志
569
570
571
572
          };
      }
  
      /// <summary>
ca114eb9   李曜臣   打印日志接口实现
573
      /// App 重新打印:根据历史任务Id重打(创建新任务与明细)
43d16ca6   杨鑫   打印日志
574
575
      /// </summary>
      [Authorize]
ca114eb9   李曜臣   打印日志接口实现
576
577
      [UnitOfWork]
      public virtual async Task<UsAppLabelPrintOutputDto> ReprintAsync(UsAppLabelReprintInputVo input)
43d16ca6   杨鑫   打印日志
578
      {
ca114eb9   李曜臣   打印日志接口实现
579
          if (input is null)
43d16ca6   杨鑫   打印日志
580
581
582
583
584
585
586
587
588
589
          {
              throw new UserFriendlyException("入参不能为空");
          }
  
          var locationId = input.LocationId?.Trim();
          if (string.IsNullOrWhiteSpace(locationId))
          {
              throw new UserFriendlyException("门店Id不能为空");
          }
  
ca114eb9   李曜臣   打印日志接口实现
590
591
          var taskId = input.TaskId?.Trim();
          if (string.IsNullOrWhiteSpace(taskId))
43d16ca6   杨鑫   打印日志
592
          {
ca114eb9   李曜臣   打印日志接口实现
593
              throw new UserFriendlyException("taskId不能为空");
43d16ca6   杨鑫   打印日志
594
595
          }
  
ca114eb9   李曜臣   打印日志接口实现
596
597
598
          var quantity = input.PrintQuantity <= 0 ? 1 : input.PrintQuantity;
          var clientRequestId = input.ClientRequestId?.Trim();
          if (!string.IsNullOrWhiteSpace(clientRequestId))
43d16ca6   杨鑫   打印日志
599
          {
ca114eb9   李曜臣   打印日志接口实现
600
601
602
              var existed = await _dbContext.SqlSugarClient.Queryable<FlLabelPrintTaskDbEntity>()
                  .Where(x => x.ClientRequestId == clientRequestId)
                  .OrderBy(x => x.CopyIndex)
43d16ca6   杨鑫   打印日志
603
                  .ToListAsync();
43d16ca6   杨鑫   打印日志
604
  
ca114eb9   李曜臣   打印日志接口实现
605
              if (existed is not null && existed.Count > 0)
43d16ca6   杨鑫   打印日志
606
              {
ca114eb9   李曜臣   打印日志接口实现
607
608
609
                  var existedBatchId = existed.First().BatchId;
                  var existedTaskIds = existed.Select(x => x.Id).ToList();
                  return new UsAppLabelPrintOutputDto
43d16ca6   杨鑫   打印日志
610
                  {
ca114eb9   李曜臣   打印日志接口实现
611
612
613
614
615
                      TaskId = existedTaskIds.FirstOrDefault() ?? string.Empty,
                      PrintQuantity = existedTaskIds.Count,
                      BatchId = existedBatchId,
                      TaskIds = existedTaskIds
                  };
43d16ca6   杨鑫   打印日志
616
              }
ca114eb9   李曜臣   打印日志接口实现
617
          }
43d16ca6   杨鑫   打印日志
618
  
ca114eb9   李曜臣   打印日志接口实现
619
620
          var currentUserId = CurrentUser?.Id?.ToString();
          if (string.IsNullOrWhiteSpace(currentUserId))
43d16ca6   杨鑫   打印日志
621
          {
ca114eb9   李曜臣   打印日志接口实现
622
623
              throw new UserFriendlyException("未登录");
          }
43d16ca6   杨鑫   打印日志
624
  
ca114eb9   李曜臣   打印日志接口实现
625
626
627
          var old = await _dbContext.SqlSugarClient.Queryable<FlLabelPrintTaskDbEntity>()
              .FirstAsync(x => x.Id == taskId);
          if (old is null)
43d16ca6   杨鑫   打印日志
628
          {
ca114eb9   李曜臣   打印日志接口实现
629
              throw new UserFriendlyException("打印任务不存在");
43d16ca6   杨鑫   打印日志
630
631
          }
  
07d5dea2   李曜臣   5-18代码优化
632
633
634
635
          // 管理员 / Partner 角色:可重打当前门店任意用户任务;其它角色仅本人
          var canViewAll = await UsAppPrintLogScopeHelper.CanViewAllPrintsAtLocationAsync(
              CurrentUser, _dbContext.SqlSugarClient);
          if (!canViewAll && !string.Equals(old.CreatedBy?.Trim(), currentUserId, StringComparison.OrdinalIgnoreCase))
43d16ca6   杨鑫   打印日志
636
          {
ca114eb9   李曜臣   打印日志接口实现
637
              throw new UserFriendlyException("无权限重打该任务");
43d16ca6   杨鑫   打印日志
638
          }
ca114eb9   李曜臣   打印日志接口实现
639
          if (!string.Equals(old.LocationId?.Trim(), locationId, StringComparison.OrdinalIgnoreCase))
43d16ca6   杨鑫   打印日志
640
          {
ca114eb9   李曜臣   打印日志接口实现
641
              throw new UserFriendlyException("该任务不属于当前门店");
43d16ca6   杨鑫   打印日志
642
643
          }
  
ca114eb9   李曜臣   打印日志接口实现
644
          LabelTemplatePreviewDto? resolvedTemplate = null;
43d16ca6   杨鑫   打印日志
645
646
          try
          {
ca114eb9   李曜臣   打印日志接口实现
647
              resolvedTemplate = JsonSerializer.Deserialize<LabelTemplatePreviewDto>(old.RenderTemplateJson);
43d16ca6   杨鑫   打印日志
648
649
650
          }
          catch
          {
ca114eb9   李曜臣   打印日志接口实现
651
              resolvedTemplate = null;
43d16ca6   杨鑫   打印日志
652
653
          }
  
ca114eb9   李曜臣   打印日志接口实现
654
655
656
657
          if (resolvedTemplate is null)
          {
              throw new UserFriendlyException("历史任务渲染快照解析失败,无法重打");
          }
43d16ca6   杨鑫   打印日志
658
  
ca114eb9   李曜臣   打印日志接口实现
659
660
661
662
663
          var now = DateTime.Now;
          var batchId = _guidGenerator.Create().ToString();
          var taskIds = new List<string>();
  
          for (var i = 1; i <= quantity; i++)
43d16ca6   杨鑫   打印日志
664
          {
ca114eb9   李曜臣   打印日志接口实现
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
              var newTaskId = _guidGenerator.Create().ToString();
              taskIds.Add(newTaskId);
  
              var newTask = new FlLabelPrintTaskDbEntity
              {
                  Id = newTaskId,
                  BatchId = batchId,
                  CopyIndex = i,
                  ClientRequestId = string.IsNullOrWhiteSpace(clientRequestId) ? null : clientRequestId,
                  LabelId = old.LabelId,
                  TemplateId = old.TemplateId,
                  LabelTypeId = old.LabelTypeId,
                  ProductId = old.ProductId,
                  LocationId = old.LocationId,
                  BaseTime = old.BaseTime,
                  PrintInputJson = old.PrintInputJson,
                  TemplateProductDefaultValuesJson = old.TemplateProductDefaultValuesJson,
                  RenderTemplateJson = old.RenderTemplateJson,
                  PrinterId = string.IsNullOrWhiteSpace(input.PrinterId) ? old.PrinterId : input.PrinterId.Trim(),
                  PrinterMac = string.IsNullOrWhiteSpace(input.PrinterMac) ? old.PrinterMac : input.PrinterMac.Trim(),
                  PrinterAddress = string.IsNullOrWhiteSpace(input.PrinterAddress) ? old.PrinterAddress : input.PrinterAddress.Trim(),
                  Status = "CREATED",
                  PrintedAt = null,
                  ErrorMessage = null,
                  CreatedBy = currentUserId,
                  CreationTime = now
              };
  
              await _dbContext.SqlSugarClient.Insertable(newTask).ExecuteCommandAsync();
  
              var rows = resolvedTemplate.Elements.Select(e =>
43d16ca6   杨鑫   打印日志
696
              {
ca114eb9   李曜臣   打印日志接口实现
697
698
699
                  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))
43d16ca6   杨鑫   打印日志
700
                  {
ca114eb9   李曜臣   打印日志接口实现
701
702
703
704
705
                      renderValue = tv.ValueKind == JsonValueKind.String ? tv.GetString() : tv.ToString();
                  }
                  else if (e.ConfigJson is Dictionary<string, object?> dict && dict.TryGetValue("text", out var v))
                  {
                      renderValue = v?.ToString();
43d16ca6   杨鑫   打印日志
706
                  }
ca114eb9   李曜臣   打印日志接口实现
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
  
                  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();
  
              if (rows.Count > 0)
              {
                  await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync();
43d16ca6   杨鑫   打印日志
722
723
              }
          }
43d16ca6   杨鑫   打印日志
724
  
ca114eb9   李曜臣   打印日志接口实现
725
726
727
728
729
730
731
          return new UsAppLabelPrintOutputDto
          {
              TaskId = taskIds.FirstOrDefault() ?? string.Empty,
              PrintQuantity = quantity,
              BatchId = batchId,
              TaskIds = taskIds
          };
43d16ca6   杨鑫   打印日志
732
733
734
      }
  
      /// <summary>
07d5dea2   李曜臣   5-18代码优化
735
      /// App 打印日志:当前门店打印记录(分页,时间倒序)
43d16ca6   杨鑫   打印日志
736
      /// </summary>
ca114eb9   李曜臣   打印日志接口实现
737
      /// <remarks>
07d5dea2   李曜臣   5-18代码优化
738
739
740
741
742
      /// 数据范围(须已绑定 <c>input.locationId</c>):
      /// <list type="bullet">
      /// <item><b>管理员</b><see cref="ReportsRoleHelper.IsAdminRole"/>)或角色码/名含 <c>partner</c>:该门店 <b>全部</b> 打印任务;</item>
      /// <item>其它角色:仅 <c>CreatedBy == CurrentUser.Id</c></item>
      /// </list>
ca114eb9   李曜臣   打印日志接口实现
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
      ///
      /// 示例请求:
      /// ```json
      /// {
      ///   "locationId": "11111111-1111-1111-1111-111111111111",
      ///   "skipCount": 1,
      ///   "maxResultCount": 20
      /// }
      /// ```
      ///
      /// 参数说明:
      /// - locationId: 当前门店 Id(必填)
      /// - skipCount: 页码(从 1 开始,遵循本项目约定)
      /// - maxResultCount: 每页条数
      /// </remarks>
      /// <param name="input">分页查询入参</param>
      /// <returns>分页打印日志</returns>
      /// <response code="200">成功</response>
      /// <response code="400">参数错误/未登录</response>
      /// <response code="500">服务器错误</response>
43d16ca6   杨鑫   打印日志
763
      [Authorize]
43d16ca6   杨鑫   打印日志
764
      [HttpPost]
ca114eb9   李曜臣   打印日志接口实现
765
      public virtual async Task<PagedResultWithPageDto<PrintLogItemDto>> GetPrintLogListAsync(PrintLogGetListInputVo input)
43d16ca6   杨鑫   打印日志
766
      {
ca114eb9   李曜臣   打印日志接口实现
767
          if (input is null)
43d16ca6   杨鑫   打印日志
768
769
770
771
          {
              throw new UserFriendlyException("入参不能为空");
          }
  
ca114eb9   李曜臣   打印日志接口实现
772
773
774
775
776
          if (!CurrentUser.Id.HasValue)
          {
              throw new UserFriendlyException("用户未登录");
          }
  
43d16ca6   杨鑫   打印日志
777
778
779
780
781
782
          var locationId = input.LocationId?.Trim();
          if (string.IsNullOrWhiteSpace(locationId))
          {
              throw new UserFriendlyException("门店Id不能为空");
          }
  
ca114eb9   李曜臣   打印日志接口实现
783
          var currentUserIdStr = CurrentUser.Id.Value.ToString();
07d5dea2   李曜臣   5-18代码优化
784
785
          await UsAppPrintLogScopeHelper.EnsureUserBoundToLocationAsync(
              CurrentUser, _dbContext.SqlSugarClient, locationId);
43d16ca6   杨鑫   打印日志
786
  
07d5dea2   李曜臣   5-18代码优化
787
788
789
          var canViewAll = await UsAppPrintLogScopeHelper.CanViewAllPrintsAtLocationAsync(
              CurrentUser, _dbContext.SqlSugarClient);
          var restrictToCreator = !canViewAll;
43d16ca6   杨鑫   打印日志
790
  
ca114eb9   李曜臣   打印日志接口实现
791
792
          var locationName = "无";
          if (Guid.TryParse(locationId, out var locationGuid))
43d16ca6   杨鑫   打印日志
793
          {
ca114eb9   李曜臣   打印日志接口实现
794
795
796
797
798
799
800
801
802
803
804
805
              var loc = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
                  .Where(x => !x.IsDeleted && x.Id == locationGuid)
                  .Select(x => new { x.LocationCode, x.LocationName })
                  .FirstAsync();
              if (loc is not null)
              {
                  var name = loc.LocationName?.Trim();
                  if (!string.IsNullOrWhiteSpace(name))
                  {
                      locationName = name;
                  }
              }
43d16ca6   杨鑫   打印日志
806
807
          }
  
ca114eb9   李曜臣   打印日志接口实现
808
          RefAsync<int> total = 0;
43d16ca6   杨鑫   打印日志
809
  
07d5dea2   李曜臣   5-18代码优化
810
811
          var query = UsAppPrintLogScopeHelper.BuildLocationPrintTaskQuery(
                  _dbContext.SqlSugarClient, locationId, restrictToCreator, currentUserIdStr)
ca114eb9   李曜臣   打印日志接口实现
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
              .OrderBy((t, l, p, lt, tpl) => SqlFunc.IsNull(t.PrintedAt, t.CreationTime), OrderByType.Desc)
              .OrderBy((t, l, p, lt, tpl) => t.CreationTime, OrderByType.Desc)
              .Select((t, l, p, lt, tpl) => new
              {
                  t.Id,
                  t.BatchId,
                  t.CopyIndex,
                  t.LabelId,
                  LabelCode = l.LabelCode,
                  t.ProductId,
                  ProductName = p.ProductName,
                  TypeName = lt.TypeName,
                  TemplateWidth = tpl.Width,
                  TemplateHeight = tpl.Height,
                  TemplateUnit = tpl.Unit,
90dc7e2f   李曜臣   重新打印优化
827
                  t.PrintInputJson,
ca114eb9   李曜臣   打印日志接口实现
828
                  t.PrintedAt,
07d5dea2   李曜臣   5-18代码优化
829
830
                  t.CreationTime,
                  t.CreatedBy
ca114eb9   李曜臣   打印日志接口实现
831
              });
43d16ca6   杨鑫   打印日志
832
  
ca114eb9   李曜臣   打印日志接口实现
833
          var pageRows = await query.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
43d16ca6   杨鑫   打印日志
834
  
07d5dea2   李曜臣   5-18代码优化
835
836
837
838
          var operatorMap = await UsAppPrintLogScopeHelper.LoadOperatorNameMapAsync(
              _dbContext.SqlSugarClient,
              pageRows.Select(x => x.CreatedBy));
  
ca114eb9   李曜臣   打印日志接口实现
839
840
841
842
843
844
845
846
847
848
849
          var items = pageRows.Select(x => new PrintLogItemDto
          {
              TaskId = x.Id,
              BatchId = x.BatchId,
              CopyIndex = x.CopyIndex,
              LabelId = x.LabelId,
              LabelCode = x.LabelCode ?? string.Empty,
              ProductId = x.ProductId,
              ProductName = string.IsNullOrWhiteSpace(x.ProductName) ? "无" : x.ProductName.Trim(),
              TypeName = x.TypeName ?? string.Empty,
              LabelSizeText = FormatLabelSizeWithUnit(x.TemplateWidth, x.TemplateHeight, x.TemplateUnit),
90dc7e2f   李曜臣   重新打印优化
850
              PrintInputJson = x.PrintInputJson,
ca114eb9   李曜臣   打印日志接口实现
851
              PrintedAt = x.PrintedAt ?? x.CreationTime,
07d5dea2   李曜臣   5-18代码优化
852
              OperatorName = UsAppPrintLogScopeHelper.ResolveOperatorName(operatorMap, x.CreatedBy),
ca114eb9   李曜臣   打印日志接口实现
853
              LocationName = locationName
43d16ca6   杨鑫   打印日志
854
855
          }).ToList();
  
ca114eb9   李曜臣   打印日志接口实现
856
857
858
859
          var pageSize = input.MaxResultCount <= 0 ? items.Count : input.MaxResultCount;
          var pageIndex = pageSize <= 0 ? 1 : PagedQueryConvention.PageIndexFromSkipCount(input.SkipCount);
          var totalCount = (long)total;
          var totalPages = pageSize <= 0 ? 0 : (int)Math.Ceiling(totalCount / (double)pageSize);
43d16ca6   杨鑫   打印日志
860
  
ca114eb9   李曜臣   打印日志接口实现
861
          return new PagedResultWithPageDto<PrintLogItemDto>
43d16ca6   杨鑫   打印日志
862
          {
ca114eb9   李曜臣   打印日志接口实现
863
864
865
866
867
              PageIndex = pageIndex,
              PageSize = pageSize,
              TotalCount = totalCount,
              TotalPages = totalPages,
              Items = items
536d25c4   李曜臣   打印预览,产品分类接口实现
868
869
870
          };
      }
  
07d5dea2   李曜臣   5-18代码优化
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
      /// <summary>
      /// App Label Report:当前门店打印统计(权限与 <see cref="GetPrintLogListAsync"/> 一致)
      /// </summary>
      /// <remarks>
      /// 示例:<c>POST /api/app/us-app-labeling/get-label-report</c>
      /// ```json
      /// { "locationId": "3a21220f-db37-3e32-7390-d55f64cd62a8", "startDate": "2026-04-07", "endDate": "2026-05-18" }
      /// ```
      /// </remarks>
      [Authorize]
      [HttpPost]
      public virtual async Task<ReportsLabelReportOutputDto> GetLabelReportAsync(UsAppLabelReportQueryInputVo input)
      {
          if (input is null)
          {
              throw new UserFriendlyException("入参不能为空");
          }
  
          if (!CurrentUser.Id.HasValue)
          {
              throw new UserFriendlyException("用户未登录");
          }
  
          var locationId = input.LocationId?.Trim();
          if (string.IsNullOrWhiteSpace(locationId))
          {
              throw new UserFriendlyException("门店Id不能为空");
          }
  
          await UsAppPrintLogScopeHelper.EnsureUserBoundToLocationAsync(
              CurrentUser, _dbContext.SqlSugarClient, locationId);
  
          var canViewAll = await UsAppPrintLogScopeHelper.CanViewAllPrintsAtLocationAsync(
              CurrentUser, _dbContext.SqlSugarClient);
          var restrictToCreator = !canViewAll;
          var currentUserIdStr = CurrentUser.Id.Value.ToString();
          var keyword = input.Keyword?.Trim();
  
          var (curStart, curEndExcl) = ResolveAppDateRange(input.StartDate, input.EndDate);
          var span = curEndExcl - curStart;
          if (span.TotalDays < 1)
          {
              span = TimeSpan.FromDays(1);
          }
  
          var prevEndExcl = curStart;
          var prevStart = curStart - span;
          var db = _dbContext.SqlSugarClient;
  
          ISugarQueryable<FlLabelPrintTaskDbEntity, FlLabelDbEntity, FlProductDbEntity, FlLabelCategoryDbEntity,
              FlProductCategoryDbEntity, FlLabelTypeDbEntity, FlLabelTemplateDbEntity> Core() =>
              UsAppPrintLogScopeHelper.BuildLocationPrintTaskReportQuery(
                  db, locationId, restrictToCreator, currentUserIdStr, keyword);
  
          var totalCur = await Core()
              .Where((t, l, p, lc, pc, lt, tpl) =>
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) >= curStart &&
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) < curEndExcl)
              .CountAsync();
  
          var totalPrev = await Core()
              .Where((t, l, p, lc, pc, lt, tpl) =>
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) >= prevStart &&
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) < prevEndExcl)
              .CountAsync();
  
          var dayCount = Math.Max(1, (int)Math.Ceiling((curEndExcl - curStart).TotalDays));
          var prevDayCount = Math.Max(1, (int)Math.Ceiling((prevEndExcl - prevStart).TotalDays));
          var avgDaily = Math.Round((decimal)totalCur / dayCount, 2);
          var avgDailyPrev = Math.Round((decimal)totalPrev / prevDayCount, 2);
  
          var categoryRows = await Core()
              .Where((t, l, p, lc, pc, lt, tpl) =>
                  l.LabelCategoryId != null &&
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) >= curStart &&
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) < curEndExcl)
              .GroupBy((t, l, p, lc, pc, lt, tpl) => new { lc.Id, lc.CategoryName })
              .Select((t, l, p, lc, pc, lt, tpl) => new { lc.Id, lc.CategoryName, Cnt = SqlFunc.AggregateCount(t.Id) })
              .ToListAsync();
  
          var topCat = categoryRows.OrderByDescending(x => x.Cnt).FirstOrDefault();
  
          var productRows = await Core()
              .Where((t, l, p, lc, pc, lt, tpl) =>
                  !string.IsNullOrEmpty(p.Id) &&
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) >= curStart &&
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) < curEndExcl)
              .GroupBy((t, l, p, lc, pc, lt, tpl) => new { p.Id, p.ProductName, Cat = pc.CategoryName })
              .Select((t, l, p, lc, pc, lt, tpl) => new
              {
                  p.Id,
                  p.ProductName,
                  CategoryName = pc.CategoryName,
                  Cnt = SqlFunc.AggregateCount(t.Id)
              })
              .ToListAsync();
  
          var topProd = productRows.OrderByDescending(x => x.Cnt).FirstOrDefault();
          var topList = productRows.OrderByDescending(x => x.Cnt).Take(20).ToList();
  
          var trendEndDay = curEndExcl.Date.AddDays(-1);
          var trendStartDay = trendEndDay.AddDays(-6);
          if (trendStartDay < curStart.Date)
          {
              trendStartDay = curStart.Date;
          }
  
          var trendEndExcl = trendEndDay.AddDays(1);
  
          var trendRaw = await Core()
              .Where((t, l, p, lc, pc, lt, tpl) =>
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) >= trendStartDay &&
                  SqlFunc.IsNull(t.PrintedAt, t.CreationTime) < trendEndExcl)
              .Select((t, l, p, lc, pc, lt, tpl) => SqlFunc.IsNull(t.PrintedAt, t.CreationTime))
              .ToListAsync();
  
          var trendDict = trendRaw
              .Where(x => x.HasValue)
              .GroupBy(x => x!.Value.Date)
              .ToDictionary(g => g.Key, g => g.Count());
  
          var trend = new List<ReportsDailyCountDto>();
          for (var d = trendStartDay; d <= trendEndDay; d = d.AddDays(1))
          {
              trend.Add(new ReportsDailyCountDto
              {
                  Date = d.ToString("yyyy-MM-dd"),
                  Count = trendDict.TryGetValue(d, out var c) ? c : 0
              });
          }
  
          var byCategory = categoryRows
              .OrderByDescending(x => x.Cnt)
              .Select(x => new ReportsCategoryCountDto
              {
                  CategoryId = string.IsNullOrWhiteSpace(x.Id) ? null : x.Id.Trim(),
                  CategoryName = string.IsNullOrWhiteSpace(x.CategoryName) ? null : x.CategoryName.Trim(),
                  Count = x.Cnt
              })
              .ToList();
  
          var mostUsed = topList.Select(x =>
          {
              var pct = totalCur <= 0 ? 0m : Math.Round(x.Cnt * 100m / totalCur, 2);
              return new ReportsTopProductRowDto
              {
                  ProductId = string.IsNullOrWhiteSpace(x.Id) ? null : x.Id.Trim(),
                  ProductName = string.IsNullOrWhiteSpace(x.ProductName) ? null : x.ProductName.Trim(),
                  CategoryName = string.IsNullOrWhiteSpace(x.CategoryName) ? null : x.CategoryName!.Trim(),
                  TotalPrinted = x.Cnt,
                  UsagePercent = pct
              };
          }).ToList();
  
          return new ReportsLabelReportOutputDto
          {
              Summary = new ReportsLabelReportSummaryDto
              {
                  TotalLabelsPrinted = totalCur,
                  TotalLabelsPrintedPrevPeriod = totalPrev,
                  TotalLabelsPrintedChangeRate = CalcAppChangeRate(totalCur, totalPrev),
                  MostPrintedCategoryName = string.IsNullOrWhiteSpace(topCat?.CategoryName) ? null : topCat.CategoryName.Trim(),
                  MostPrintedCategoryCount = topCat?.Cnt ?? 0,
                  TopProductName = string.IsNullOrWhiteSpace(topProd?.ProductName) ? null : topProd.ProductName.Trim(),
                  TopProductCount = topProd?.Cnt ?? 0,
                  AvgDailyPrints = avgDaily,
                  AvgDailyPrintsPrevPeriod = avgDailyPrev,
                  AvgDailyPrintsChangeRate = CalcAppChangeRate(avgDaily, avgDailyPrev)
              },
              LabelsByCategory = byCategory,
              PrintVolumeTrend = trend,
              MostUsedProducts = mostUsed
          };
      }
  
      private static (DateTime rangeStart, DateTime rangeEndExcl) ResolveAppDateRange(DateTime? startDate, DateTime? endDate)
      {
          var endDay = (endDate ?? DateTime.Today).Date;
          var endExcl = endDay.AddDays(1);
          var start = (startDate ?? endDay.AddDays(-29)).Date;
          if (start >= endExcl)
          {
              start = endExcl.AddDays(-1);
          }
  
          return (start, endExcl);
      }
  
      private static decimal CalcAppChangeRate(decimal current, decimal previous)
      {
          if (previous == 0)
          {
              return current > 0 ? 100m : 0m;
          }
  
          return Math.Round((current - previous) * 100m / previous, 2);
      }
  
c304e27c   李曜臣   打印日志优化
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
      private async Task<string?> ResolveTemplateProductDefaultValuesJsonAsync(
          string templateId,
          string? productId,
          string labelTypeId)
      {
          if (string.IsNullOrWhiteSpace(templateId) || string.IsNullOrWhiteSpace(productId) || string.IsNullOrWhiteSpace(labelTypeId))
          {
              return null;
          }
  
          var productDefault = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateProductDefaultDbEntity>()
              .Where(x => x.TemplateId == templateId)
              .Where(x => x.ProductId == productId)
              .Where(x => x.LabelTypeId == labelTypeId)
              .OrderBy(x => x.OrderNum)
              .FirstAsync();
  
          return string.IsNullOrWhiteSpace(productDefault?.DefaultValuesJson) ? null : productDefault!.DefaultValuesJson;
      }
  
536d25c4   李曜臣   打印预览,产品分类接口实现
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
      private ISugarQueryable<FlLabelProductDbEntity, FlLabelDbEntity, FlProductDbEntity, FlLabelCategoryDbEntity, FlLabelTypeDbEntity, FlLabelTemplateDbEntity, FlProductCategoryDbEntity> BuildLabelingJoinQuery(
          string locationId,
          List<string> productIds,
          string? filterCategoryId,
          string? keyword)
      {
          var q = _dbContext.SqlSugarClient
              .Queryable<FlLabelProductDbEntity>()
              .InnerJoin<FlLabelDbEntity>((lp, l) => lp.LabelId == l.Id)
              .InnerJoin<FlProductDbEntity>((lp, l, p) => lp.ProductId == p.Id)
              .InnerJoin<FlLabelCategoryDbEntity>((lp, l, p, c) => l.LabelCategoryId == c.Id)
              .InnerJoin<FlLabelTypeDbEntity>((lp, l, p, c, t) => l.LabelTypeId == t.Id)
              .InnerJoin<FlLabelTemplateDbEntity>((lp, l, p, c, t, tpl) => l.TemplateId == tpl.Id)
              .LeftJoin<FlProductCategoryDbEntity>((lp, l, p, c, t, tpl, pc) => p.CategoryId == pc.Id)
              .Where((lp, l, p, c, t, tpl, pc) => productIds.Contains(p.Id))
              .Where((lp, l, p, c, t, tpl, pc) => l.LocationId == locationId)
              .Where((lp, l, p, c, t, tpl, pc) => !l.IsDeleted && l.State)
              .Where((lp, l, p, c, t, tpl, pc) => !p.IsDeleted && p.State)
07d5dea2   李曜臣   5-18代码优化
1107
              .Where((lp, l, p, c, t, tpl, pc) => !c.IsDeleted && c.State)
536d25c4   李曜臣   打印预览,产品分类接口实现
1108
1109
              .Where((lp, l, p, c, t, tpl, pc) => !t.IsDeleted && t.State)
              .Where((lp, l, p, c, t, tpl, pc) => !tpl.IsDeleted)
8e0c49eb   李曜臣   产品标签类别优化;
1110
              .Where((lp, l, p, c, t, tpl, pc) =>
07d5dea2   李曜臣   5-18代码优化
1111
                  pc.Id == null || (!pc.IsDeleted && pc.State))
536d25c4   李曜臣   打印预览,产品分类接口实现
1112
1113
1114
1115
1116
              .WhereIF(!string.IsNullOrWhiteSpace(filterCategoryId), (lp, l, p, c, t, tpl, pc) => l.LabelCategoryId == filterCategoryId)
              .WhereIF(!string.IsNullOrWhiteSpace(keyword), (lp, l, p, c, t, tpl, pc) =>
                  (l.LabelName != null && l.LabelName.Contains(keyword!)) ||
                  (p.ProductName != null && p.ProductName.Contains(keyword!)) ||
                  (pc.CategoryName != null && pc.CategoryName.Contains(keyword!)) ||
8e0c49eb   李曜臣   产品标签类别优化;
1117
                  (pc.DisplayText != null && pc.DisplayText.Contains(keyword!)) ||
536d25c4   李曜臣   打印预览,产品分类接口实现
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
                  (c.CategoryName != null && c.CategoryName.Contains(keyword!)) ||
                  (t.TypeName != null && t.TypeName.Contains(keyword!)) ||
                  (l.LabelCode != null && l.LabelCode.Contains(keyword!)));
  
          return q;
      }
  
      private sealed class LabelingTreeRow
      {
          public string LabelCategoryId { get; set; } = string.Empty;
  
          public string? LabelCategoryName { get; set; }
  
          public string? LabelCategoryPhotoUrl { get; set; }
  
8e0c49eb   李曜臣   产品标签类别优化;
1133
1134
          public string? LabelCategoryButtonAppearance { get; set; }
  
536d25c4   李曜臣   打印预览,产品分类接口实现
1135
1136
1137
1138
1139
1140
1141
1142
          public int LabelCategoryOrderNum { get; set; }
  
          public string? ProductCategoryId { get; set; }
  
          public string? ProductCategoryName { get; set; }
  
          public string? ProductCategoryPhotoUrl { get; set; }
  
8e0c49eb   李曜臣   产品标签类别优化;
1143
1144
1145
1146
1147
1148
1149
1150
          public string? ProductCategoryDisplayText { get; set; }
  
          public string? ProductCategoryButtonAppearance { get; set; }
  
          public string? ProductCategoryAvailabilityType { get; set; }
  
          public int ProductCategoryOrderNum { get; set; }
  
536d25c4   李曜臣   打印预览,产品分类接口实现
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
          public string ProductId { get; set; } = string.Empty;
  
          public string? ProductName { get; set; }
  
          public string? ProductCode { get; set; }
  
          public string? ProductImageUrl { get; set; }
  
          public string LabelTypeId { get; set; } = string.Empty;
  
          public string? TypeName { get; set; }
  
          public int TypeOrderNum { get; set; }
  
          public string LabelCode { get; set; } = string.Empty;
  
dc39baae   李曜臣   后台端:管理员查看日志优化,产品与...
1167
1168
          public string TemplateId { get; set; } = string.Empty;
  
536d25c4   李曜臣   打印预览,产品分类接口实现
1169
1170
1171
1172
1173
1174
1175
1176
1177
          public string? TemplateCode { get; set; }
  
          public decimal TemplateWidth { get; set; }
  
          public decimal TemplateHeight { get; set; }
  
          public string TemplateUnit { get; set; } = "inch";
      }
  
8e0c49eb   李曜臣   产品标签类别优化;
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
      /// <summary>
      ///  App 入参中的 JsonElement(对象或 null)反序列化为 PreviewAsync 所需的扁平字典。
      /// </summary>
      private static Dictionary<string, object?>? ParsePrintInputJsonToDictionary(JsonElement? printInputJson)
      {
          if (printInputJson is null)
          {
              return null;
          }
  
          var je = printInputJson.Value;
          if (je.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined)
          {
              return null;
          }
  
          try
          {
              return JsonSerializer.Deserialize<Dictionary<string, object?>>(je.GetRawText());
          }
          catch
          {
              return null;
          }
      }
  
536d25c4   李曜臣   打印预览,产品分类接口实现
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
      private static string NormalizeCategoryName(string? categoryName)
      {
          var s = categoryName?.Trim();
          return string.IsNullOrWhiteSpace(s) ? "无" : s;
      }
  
      private static string? NormalizeNullableId(string? id)
      {
          var s = id?.Trim();
          return string.IsNullOrWhiteSpace(s) ? null : s;
      }
  
      private static string? NormalizeNullableUrl(string? url)
      {
          var s = url?.Trim();
          return string.IsNullOrWhiteSpace(s) ? null : s;
      }
  
a4baaa73   李曜臣   模板与产品关联实现
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
      private async Task<string?> ResolvePreviewProductIdAsync(string labelId, string? productId)
      {
          var resolvedProductId = productId?.Trim();
          if (!string.IsNullOrWhiteSpace(resolvedProductId))
          {
              return resolvedProductId;
          }
  
          return await _dbContext.SqlSugarClient.Queryable<FlLabelProductDbEntity>()
              .Where(x => x.LabelId == labelId)
              .Select(x => x.ProductId)
              .FirstAsync();
      }
  
536d25c4   李曜臣   打印预览,产品分类接口实现
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
      private static UsAppLabelTypeNodeDto BuildLabelTypeNode(LabelingTreeRow r)
      {
          return new UsAppLabelTypeNodeDto
          {
              LabelTypeId = r.LabelTypeId,
              TypeName = r.TypeName ?? string.Empty,
              OrderNum = r.TypeOrderNum,
              LabelCode = r.LabelCode ?? string.Empty,
              TemplateCode = r.TemplateCode,
              LabelSizeText = FormatLabelSize(r.TemplateWidth, r.TemplateHeight, r.TemplateUnit)
          };
      }
  
      private static string? FormatLabelSize(decimal w, decimal h, string unit)
      {
          var u = (unit ?? "inch").Trim().ToLowerInvariant();
          var ws = w.ToString(CultureInfo.InvariantCulture);
          var hs = h.ToString(CultureInfo.InvariantCulture);
          return u is "inch" or "in"
              ? $"{ws}\"x{hs}\""
              : $"{ws}x{hs}{u}";
      }
ca114eb9   李曜臣   打印日志接口实现
1258
1259
1260
1261
1262
1263
1264
1265
1266
  
      private static string? FormatLabelSizeWithUnit(decimal w, decimal h, string unit)
      {
          var u = (unit ?? "inch").Trim().ToLowerInvariant();
          var ws = w.ToString(CultureInfo.InvariantCulture);
          var hs = h.ToString(CultureInfo.InvariantCulture);
          var normalizedUnit = u is "in" ? "inch" : u;
          return $"{ws}x{hs}{normalizedUnit}";
      }
536d25c4   李曜臣   打印预览,产品分类接口实现
1267
  }