Blame view

美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/LabelTemplateAppService.cs 25.8 KB
919c1b6a   李曜臣   1
1
  using System.Text.Json;
143afd59   杨鑫   打印,标签
2
  using FoodLabeling.Application.Helpers;
919c1b6a   李曜臣   1
3
4
5
6
  using FoodLabeling.Application.Contracts.Dtos.Common;
  using FoodLabeling.Application.Contracts.Dtos.LabelTemplate;
  using FoodLabeling.Application.Contracts.IServices;
  using FoodLabeling.Application.Services.DbModels;
919c1b6a   李曜臣   1
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  using SqlSugar;
  using Volo.Abp;
  using Volo.Abp.Application.Services;
  using Volo.Abp.Guids;
  using Volo.Abp.Uow;
  using Yi.Framework.SqlSugarCore.Abstractions;
  
  namespace FoodLabeling.Application.Services;
  
  /// <summary>
  /// 标签模板管理(Label Templates
  /// </summary>
  public class LabelTemplateAppService : ApplicationService, ILabelTemplateAppService
  {
      private readonly ISqlSugarDbContext _dbContext;
      private readonly IGuidGenerator _guidGenerator;
  
      public LabelTemplateAppService(ISqlSugarDbContext dbContext, IGuidGenerator guidGenerator)
      {
          _dbContext = dbContext;
          _guidGenerator = guidGenerator;
      }
  
      public async Task<PagedResultWithPageDto<LabelTemplateGetListOutputDto>> GetListAsync(LabelTemplateGetListInputVo input)
      {
14afbc16   李曜臣   2026-6-22
32
          input ??= new LabelTemplateGetListInputVo();
919c1b6a   李曜臣   1
33
34
          RefAsync<int> total = 0;
          var keyword = input.Keyword?.Trim();
14afbc16   李曜臣   2026-6-22
35
36
          var scopedLocationIds = await LocationScopeBindingHelper.ResolveFilteredLocationIdsForListAsync(
              _dbContext.SqlSugarClient, input.PartnerId, input.GroupId, input.LocationId);
919c1b6a   李曜臣   1
37
38
39
40
41
42
43
44
  
          var query = _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
              .Where(x => !x.IsDeleted)
              .WhereIF(!string.IsNullOrWhiteSpace(keyword), x =>
                  x.TemplateName.Contains(keyword!) || x.TemplateCode.Contains(keyword!))
              .WhereIF(!string.IsNullOrWhiteSpace(input.LabelType), x => x.LabelType == input.LabelType)
              .WhereIF(input.State != null, x => x.State == input.State);
  
49755ef0   李曜臣   6-12代码优化
45
46
          query = await LabelTemplateScopeHelper.ApplyTemplateScopeFilterAsync(
              _dbContext.SqlSugarClient, query, scopedLocationIds);
919c1b6a   李曜臣   1
47
  
14afbc16   李曜臣   2026-6-22
48
49
          query = ApplyLabelTemplateListSorting(query, input.Sorting);
          query = LabelTemplateQueryHelper.ProjectListColumns(query);
919c1b6a   李曜臣   1
50
  
14afbc16   李曜臣   2026-6-22
51
52
          var pageSize = input.MaxResultCount <= 0 ? 10 : input.MaxResultCount;
          var pageEntities = await query.ToPageListAsync(input.SkipCount, pageSize, total);
919c1b6a   李曜臣   1
53
54
          var templateIds = pageEntities.Select(x => x.Id).ToList();
  
14afbc16   李曜臣   2026-6-22
55
56
57
58
59
60
61
62
63
64
          var elementCountMap = new Dictionary<string, int>(StringComparer.Ordinal);
          if (templateIds.Count > 0)
          {
              var elementCounts = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateElementDbEntity>()
                  .Where(x => templateIds.Contains(x.TemplateId))
                  .GroupBy(x => x.TemplateId)
                  .Select(x => new { TemplateId = x.TemplateId, Count = SqlFunc.AggregateCount(x.Id) })
                  .ToListAsync();
              elementCountMap = elementCounts.ToDictionary(x => x.TemplateId, x => (int)x.Count);
          }
919c1b6a   李曜臣   1
65
  
49755ef0   李曜臣   6-12代码优化
66
67
          var scopeMap = await LabelTemplateScopeHelper.BuildScopeDisplayMapAsync(
              _dbContext.SqlSugarClient, pageEntities);
14afbc16   李曜臣   2026-6-22
68
69
70
71
          var itemsMap = templateIds.Count > 0
              ? await LabelTemplateListItemsHelper.ResolveTemplateItemsMapAsync(
                  _dbContext.SqlSugarClient, templateIds)
              : new Dictionary<string, LabelTemplateListItemsHelper.TemplateItemsDisplay>(StringComparer.Ordinal);
919c1b6a   李曜臣   1
72
73
74
  
          var items = pageEntities.Select(x =>
          {
49755ef0   李曜臣   6-12代码优化
75
76
              scopeMap.TryGetValue(x.Id, out var scope);
              itemsMap.TryGetValue(x.Id, out var itemsDisplay);
919c1b6a   李曜臣   1
77
78
              var lastEdited = x.LastModificationTime ?? x.CreationTime;
              var contentsCount = elementCountMap.TryGetValue(x.Id, out var c) ? c : 0;
49755ef0   李曜臣   6-12代码优化
79
              var locationDisplay = scope?.Location ?? EmptyDisplay;
919c1b6a   李曜臣   1
80
81
82
83
84
85
86
87
              var sizeText = $"{x.Width}x{x.Height}{x.Unit}";
  
              return new LabelTemplateGetListOutputDto
              {
                  Id = x.TemplateCode, // front-end uses templateCode as identifier
                  TemplateCode = x.TemplateCode,
                  TemplateName = x.TemplateName,
                  LabelType = x.LabelType,
49755ef0   李曜臣   6-12代码优化
88
89
90
91
92
93
94
95
96
                  LocationText = locationDisplay,
                  Company = scope?.Company ?? string.Empty,
                  Region = scope?.Region ?? string.Empty,
                  Location = locationDisplay,
                  PartnerIds = scope?.PartnerIds ?? new List<string>(),
                  CompanyIds = scope?.PartnerIds ?? new List<string>(),
                  RegionIds = scope?.RegionIds ?? new List<string>(),
                  GroupIds = scope?.RegionIds ?? new List<string>(),
                  LocationIds = scope?.LocationIds ?? new List<string>(),
919c1b6a   李曜臣   1
97
                  ContentsCount = contentsCount,
49755ef0   李曜臣   6-12代码优化
98
99
                  Items = itemsDisplay?.Items ?? "无",
                  ItemNames = itemsDisplay?.ItemNames ?? new List<string>(),
919c1b6a   李曜臣   1
100
101
102
103
104
105
                  SizeText = sizeText,
                  VersionNo = x.VersionNo,
                  LastEdited = lastEdited
              };
          }).ToList();
  
14afbc16   李曜臣   2026-6-22
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
          return BuildPagedResult(input.SkipCount, pageSize, total, items);
      }
  
      /// <summary>
      /// 列表排序:白名单字段 + IFNULL(LastModificationTime, CreationTime),避免 <c>??</c> 与原始 Sorting 拼接导致 SQL 异常。
      /// </summary>
      private static ISugarQueryable<FlLabelTemplateDbEntity> ApplyLabelTemplateListSorting(
          ISugarQueryable<FlLabelTemplateDbEntity> query,
          string? sorting)
      {
          if (!string.IsNullOrWhiteSpace(sorting))
          {
              var s = sorting.Trim();
              if (s.Equals("TemplateName asc", StringComparison.OrdinalIgnoreCase))
              {
                  return query.OrderBy(x => x.TemplateName);
              }
  
              if (s.Equals("TemplateName desc", StringComparison.OrdinalIgnoreCase))
              {
                  return query.OrderByDescending(x => x.TemplateName);
              }
  
              if (s.Equals("TemplateCode asc", StringComparison.OrdinalIgnoreCase))
              {
                  return query.OrderBy(x => x.TemplateCode);
              }
  
              if (s.Equals("TemplateCode desc", StringComparison.OrdinalIgnoreCase))
              {
                  return query.OrderByDescending(x => x.TemplateCode);
              }
  
              if (s.Equals("CreationTime asc", StringComparison.OrdinalIgnoreCase))
              {
                  return query.OrderBy(x => x.CreationTime);
              }
  
              if (s.Equals("CreationTime desc", StringComparison.OrdinalIgnoreCase))
              {
                  return query.OrderByDescending(x => x.CreationTime);
              }
  
              if (s.Equals("LastModificationTime asc", StringComparison.OrdinalIgnoreCase))
              {
                  return query.OrderBy(x => x.LastModificationTime);
              }
  
              if (s.Equals("LastModificationTime desc", StringComparison.OrdinalIgnoreCase))
              {
                  return query.OrderByDescending(x => x.LastModificationTime);
              }
          }
  
          return query
              .OrderBy(x => SqlFunc.IsNull(x.LastModificationTime, x.CreationTime), OrderByType.Desc)
              .OrderBy(x => x.TemplateCode, OrderByType.Asc);
919c1b6a   李曜臣   1
163
164
165
166
      }
  
      public async Task<LabelTemplateGetOutputDto> GetAsync(string id)
      {
14afbc16   李曜臣   2026-6-22
167
168
          var template = await LabelTemplateQueryHelper.ProjectListColumns(
                  _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>())
919c1b6a   李曜臣   1
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
              .FirstAsync(x => !x.IsDeleted && x.TemplateCode == id);
          if (template is null)
          {
              throw new UserFriendlyException("模板不存在");
          }
  
          var elements = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateElementDbEntity>()
              .Where(x => x.TemplateId == template.Id)
              .OrderBy(x => x.OrderNum)
              .ToListAsync();
  
          List<LabelTemplateElementDto> MapElements()
          {
              return elements.Select(e =>
              {
                  object? cfg = null;
                  if (!string.IsNullOrWhiteSpace(e.ConfigJson))
                  {
                      cfg = JsonSerializer.Deserialize<object>(e.ConfigJson);
                  }
  
                  return new LabelTemplateElementDto
                  {
                      Id = e.ElementKey,
                      ElementType = e.ElementType,
58d2e61c   杨鑫   最新代码
194
                      TypeAdd = e.TypeAdd,
a4baaa73   李曜臣   模板与产品关联实现
195
                      ElementName = e.ElementName,
919c1b6a   李曜臣   1
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
                      PosX = e.PosX,
                      PosY = e.PosY,
                      Width = e.Width,
                      Height = e.Height,
                      Rotation = e.Rotation,
                      BorderType = e.BorderType,
                      ZIndex = e.ZIndex,
                      OrderNum = e.OrderNum,
                      ValueSourceType = e.ValueSourceType,
                      BindingExpr = e.BindingExpr,
                      AutoQueryKey = e.AutoQueryKey,
                      InputKey = e.InputKey,
                      IsRequiredInput = e.IsRequiredInput,
                      ConfigJson = cfg
                  };
              }).ToList();
          }
  
a4baaa73   李曜臣   模板与产品关联实现
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
          var defaultRows = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateProductDefaultDbEntity>()
              .Where(x => x.TemplateId == template.Id)
              .OrderBy(x => x.OrderNum)
              .ToListAsync();
  
          var productDefaults = defaultRows.Select(x =>
          {
              object? defaults = null;
              if (!string.IsNullOrWhiteSpace(x.DefaultValuesJson))
              {
                  defaults = JsonSerializer.Deserialize<object>(x.DefaultValuesJson);
              }
  
              return new LabelTemplateProductDefaultDto
              {
                  ProductId = x.ProductId,
                  LabelTypeId = x.LabelTypeId,
                  DefaultValues = defaults,
                  OrderNum = x.OrderNum
              };
          }).ToList();
  
49755ef0   李曜臣   6-12代码优化
236
          var dto = new LabelTemplateGetOutputDto
919c1b6a   李曜臣   1
237
238
239
240
241
242
243
244
245
          {
              Id = template.TemplateCode,
              TemplateCode = template.TemplateCode,
              TemplateName = template.TemplateName,
              LabelType = template.LabelType,
              Unit = template.Unit,
              Width = template.Width,
              Height = template.Height,
              AppliedLocationType = template.AppliedLocationType,
14afbc16   李曜臣   2026-6-22
246
247
              AppliedPartnerType = LabelTemplateScopeHelper.ScopeAll,
              AppliedRegionType = LabelTemplateScopeHelper.ScopeAll,
919c1b6a   李曜臣   1
248
249
              ShowRuler = template.ShowRuler,
              ShowGrid = template.ShowGrid,
540ac0e3   杨鑫   前端修改bug
250
              BorderType = NormalizeTemplateBorderType(template.BorderType),
4cb354d4   杨鑫   提交
251
              PrintOrientationType = NormalizePrintOrientationType(template.PrintOrientationType),
919c1b6a   李曜臣   1
252
253
254
              VersionNo = template.VersionNo,
              State = template.State,
              Elements = MapElements(),
a4baaa73   李曜臣   模板与产品关联实现
255
              TemplateProductDefaults = productDefaults
919c1b6a   李曜臣   1
256
          };
49755ef0   李曜臣   6-12代码优化
257
258
259
  
          await FillTemplateScopeOnDtoAsync(dto, template);
          return dto;
919c1b6a   李曜臣   1
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
      }
  
      [UnitOfWork]
      public async Task<LabelTemplateGetOutputDto> CreateAsync(LabelTemplateCreateInputVo input)
      {
          var code = input.TemplateCode?.Trim();
          var name = input.TemplateName?.Trim();
          if (string.IsNullOrWhiteSpace(code))
          {
              throw new UserFriendlyException("模板编码不能为空");
          }
          if (string.IsNullOrWhiteSpace(name))
          {
              throw new UserFriendlyException("模板名称不能为空");
          }
  
14afbc16   李曜臣   2026-6-22
276
277
          var duplicated = await LabelTemplateQueryHelper.ProjectListColumns(
                  _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>())
919c1b6a   李曜臣   1
278
279
280
281
282
283
              .AnyAsync(x => !x.IsDeleted && x.TemplateCode == code);
          if (duplicated)
          {
              throw new UserFriendlyException("模板编码已存在");
          }
  
49755ef0   李曜臣   6-12代码优化
284
285
          var scope = await LabelTemplateScopeHelper.ResolveScopeForSaveAsync(_dbContext.SqlSugarClient, input);
  
919c1b6a   李曜臣   1
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
          var now = DateTime.Now;
          var templateId = _guidGenerator.Create().ToString();
          var entity = new FlLabelTemplateDbEntity
          {
              Id = templateId,
              IsDeleted = false,
              CreationTime = now,
              CreatorId = CurrentUser?.Id?.ToString(),
              LastModifierId = CurrentUser?.Id?.ToString(),
              LastModificationTime = now,
              ConcurrencyStamp = string.Empty,
              TemplateCode = code,
              TemplateName = name,
              LabelType = input.LabelType,
              Unit = string.IsNullOrWhiteSpace(input.Unit) ? "inch" : input.Unit.Trim(),
              Width = input.Width,
              Height = input.Height,
49755ef0   李曜臣   6-12代码优化
303
              AppliedLocationType = scope.AppliedLocationType,
919c1b6a   李曜臣   1
304
305
              ShowRuler = input.ShowRuler,
              ShowGrid = input.ShowGrid,
540ac0e3   杨鑫   前端修改bug
306
              BorderType = NormalizeTemplateBorderType(input.BorderType),
4cb354d4   杨鑫   提交
307
              PrintOrientationType = NormalizePrintOrientationType(input.PrintOrientationType),
919c1b6a   李曜臣   1
308
309
310
311
312
313
              VersionNo = 1,
              State = input.State
          };
  
          await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
  
49755ef0   李曜臣   6-12代码优化
314
          await RebuildTemplateElementsAndDefaultsAsync(
a4baaa73   李曜臣   模板与产品关联实现
315
316
              entity.Id,
              input.Elements,
a4baaa73   李曜臣   模板与产品关联实现
317
              new List<LabelTemplateProductDefaultDto>());
919c1b6a   李曜臣   1
318
  
49755ef0   李曜臣   6-12代码优化
319
320
321
322
323
324
325
326
          await LabelTemplateScopeHelper.SaveTemplateScopeAsync(
              _dbContext.SqlSugarClient,
              _guidGenerator,
              entity.Id,
              scope,
              CurrentUser?.Id?.ToString(),
              now);
  
14afbc16   李曜臣   2026-6-22
327
328
329
330
331
332
          await LabelTemplateScopeSchemaHelper.SetAppliedScopeTypesAsync(
              _dbContext.SqlSugarClient,
              entity.Id,
              scope.AppliedPartnerType,
              scope.AppliedRegionType);
  
919c1b6a   李曜臣   1
333
334
335
336
337
338
          return await GetAsync(code);
      }
  
      [UnitOfWork]
      public async Task<LabelTemplateGetOutputDto> UpdateAsync(string id, LabelTemplateUpdateInputVo input)
      {
14afbc16   李曜臣   2026-6-22
339
340
          var template = await LabelTemplateQueryHelper.ProjectListColumns(
                  _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>())
919c1b6a   李曜臣   1
341
342
343
344
345
346
347
348
349
350
              .FirstAsync(x => !x.IsDeleted && x.TemplateCode == id);
          if (template is null)
          {
              throw new UserFriendlyException("模板不存在");
          }
  
          var code = input.TemplateCode?.Trim();
          var name = input.TemplateName?.Trim();
          if (!string.IsNullOrWhiteSpace(code) && !string.Equals(code, template.TemplateCode, StringComparison.OrdinalIgnoreCase))
          {
14afbc16   李曜臣   2026-6-22
351
352
              var duplicated = await LabelTemplateQueryHelper.ProjectListColumns(
                      _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>())
919c1b6a   李曜臣   1
353
354
355
356
357
358
359
                  .AnyAsync(x => !x.IsDeleted && x.TemplateCode == code);
              if (duplicated)
              {
                  throw new UserFriendlyException("模板编码已存在");
              }
          }
  
49755ef0   李曜臣   6-12代码优化
360
361
          var scope = await LabelTemplateScopeHelper.ResolveScopeForSaveAsync(_dbContext.SqlSugarClient, input);
  
919c1b6a   李曜臣   1
362
363
364
365
366
          template.TemplateName = name ?? template.TemplateName;
          template.LabelType = input.LabelType;
          template.Unit = string.IsNullOrWhiteSpace(input.Unit) ? template.Unit : input.Unit.Trim();
          template.Width = input.Width;
          template.Height = input.Height;
49755ef0   李曜臣   6-12代码优化
367
          template.AppliedLocationType = scope.AppliedLocationType;
919c1b6a   李曜臣   1
368
369
          template.ShowRuler = input.ShowRuler;
          template.ShowGrid = input.ShowGrid;
540ac0e3   杨鑫   前端修改bug
370
          template.BorderType = NormalizeTemplateBorderType(input.BorderType);
4cb354d4   杨鑫   提交
371
          template.PrintOrientationType = NormalizePrintOrientationType(input.PrintOrientationType);
919c1b6a   李曜臣   1
372
373
374
375
376
377
378
379
380
381
382
          template.State = input.State;
          template.VersionNo = template.VersionNo + 1;
          template.LastModifierId = CurrentUser?.Id?.ToString();
          template.LastModificationTime = DateTime.Now;
          if (!string.IsNullOrWhiteSpace(code))
          {
              template.TemplateCode = code;
          }
  
          await _dbContext.SqlSugarClient.Updateable(template).ExecuteCommandAsync();
  
49755ef0   李曜臣   6-12代码优化
383
          await RebuildTemplateElementsAndDefaultsAsync(
a4baaa73   李曜臣   模板与产品关联实现
384
385
              template.Id,
              input.Elements,
a4baaa73   李曜臣   模板与产品关联实现
386
              input.TemplateProductDefaults);
919c1b6a   李曜臣   1
387
  
49755ef0   李曜臣   6-12代码优化
388
389
390
391
392
393
394
395
          await LabelTemplateScopeHelper.SaveTemplateScopeAsync(
              _dbContext.SqlSugarClient,
              _guidGenerator,
              template.Id,
              scope,
              CurrentUser?.Id?.ToString(),
              template.LastModificationTime ?? DateTime.Now);
  
14afbc16   李曜臣   2026-6-22
396
397
398
399
400
401
          await LabelTemplateScopeSchemaHelper.SetAppliedScopeTypesAsync(
              _dbContext.SqlSugarClient,
              template.Id,
              scope.AppliedPartnerType,
              scope.AppliedRegionType);
  
919c1b6a   李曜臣   1
402
403
404
405
406
407
          return await GetAsync(template.TemplateCode);
      }
  
      [UnitOfWork]
      public async Task DeleteAsync(string id)
      {
14afbc16   李曜臣   2026-6-22
408
409
          var template = await LabelTemplateQueryHelper.ProjectListColumns(
                  _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>())
919c1b6a   李曜臣   1
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
              .FirstAsync(x => !x.IsDeleted && x.TemplateCode == id);
          if (template is null)
          {
              return;
          }
  
          var used = await _dbContext.SqlSugarClient.Queryable<FlLabelDbEntity>()
              .AnyAsync(x => !x.IsDeleted && x.TemplateId == template.Id);
  
          if (used)
          {
              throw new UserFriendlyException("该模板已被标签引用,无法删除");
          }
  
          template.IsDeleted = true;
          template.LastModifierId = CurrentUser?.Id?.ToString();
          template.LastModificationTime = DateTime.Now;
          await _dbContext.SqlSugarClient.Updateable(template).ExecuteCommandAsync();
  
          // 删除子表数据(子表无 IsDeleted 字段)
          await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplateElementDbEntity>()
              .Where(x => x.TemplateId == template.Id)
              .ExecuteCommandAsync();
          await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplateLocationDbEntity>()
              .Where(x => x.TemplateId == template.Id)
              .ExecuteCommandAsync();
14afbc16   李曜臣   2026-6-22
436
437
438
439
440
441
442
443
444
          if (await LabelTemplateScopeSchemaHelper.HasPartnerRegionScopeTablesAsync(_dbContext.SqlSugarClient))
          {
              await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplatePartnerDbEntity>()
                  .Where(x => x.TemplateId == template.Id)
                  .ExecuteCommandAsync();
              await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplateRegionDbEntity>()
                  .Where(x => x.TemplateId == template.Id)
                  .ExecuteCommandAsync();
          }
a4baaa73   李曜臣   模板与产品关联实现
445
446
447
          await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplateProductDefaultDbEntity>()
              .Where(x => x.TemplateId == template.Id)
              .ExecuteCommandAsync();
919c1b6a   李曜臣   1
448
449
      }
  
49755ef0   李曜臣   6-12代码优化
450
      private async Task RebuildTemplateElementsAndDefaultsAsync(
919c1b6a   李曜臣   1
451
452
          string templateDbId,
          List<LabelTemplateElementDto> elements,
a4baaa73   李曜臣   模板与产品关联实现
453
          List<LabelTemplateProductDefaultDto>? templateProductDefaults)
919c1b6a   李曜臣   1
454
455
456
457
458
459
460
461
      {
          // elements 重建
          await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplateElementDbEntity>()
              .Where(x => x.TemplateId == templateDbId)
              .ExecuteCommandAsync();
  
          if (elements is not null && elements.Count > 0)
          {
919c1b6a   李曜臣   1
462
463
              var rows = elements.Select(e =>
              {
a4baaa73   李曜臣   模板与产品关联实现
464
                  var elementName = EnsureElementName(e.ElementName);
919c1b6a   李曜臣   1
465
466
467
468
469
470
471
472
                  object? cfg = e.ConfigJson;
                  var configJson = cfg == null ? null : JsonSerializer.Serialize(cfg);
                  return new FlLabelTemplateElementDbEntity
                  {
                      Id = _guidGenerator.Create().ToString(),
                      TemplateId = templateDbId,
                      ElementKey = e.Id,
                      ElementType = e.ElementType,
58d2e61c   杨鑫   最新代码
473
                      TypeAdd = string.IsNullOrWhiteSpace(e.TypeAdd) ? null : e.TypeAdd.Trim(),
a4baaa73   李曜臣   模板与产品关联实现
474
                      ElementName = elementName,
919c1b6a   李曜臣   1
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
                      PosX = e.PosX,
                      PosY = e.PosY,
                      Width = e.Width,
                      Height = e.Height,
                      Rotation = string.IsNullOrWhiteSpace(e.Rotation) ? "horizontal" : e.Rotation,
                      BorderType = string.IsNullOrWhiteSpace(e.BorderType) ? "none" : e.BorderType,
                      ZIndex = e.ZIndex,
                      OrderNum = e.OrderNum,
                      ValueSourceType = string.IsNullOrWhiteSpace(e.ValueSourceType) ? "FIXED" : e.ValueSourceType,
                      BindingExpr = e.BindingExpr,
                      AutoQueryKey = e.AutoQueryKey,
                      InputKey = e.InputKey,
                      IsRequiredInput = e.IsRequiredInput,
                      ConfigJson = configJson
                  };
              }).ToList();
  
              await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync();
          }
  
a4baaa73   李曜臣   模板与产品关联实现
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
          // 模板-产品-标签类型默认值:仅在显式传入时重建,避免普通编辑误清空
          if (templateProductDefaults is not null)
          {
              var duplicateCheckSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
              foreach (var row in templateProductDefaults)
              {
                  var productId = row.ProductId?.Trim();
                  var labelTypeId = row.LabelTypeId?.Trim();
                  if (string.IsNullOrWhiteSpace(productId) || string.IsNullOrWhiteSpace(labelTypeId))
                  {
                      continue;
                  }
  
                  var key = $"{productId}::{labelTypeId}";
                  if (!duplicateCheckSet.Add(key))
                  {
                      throw new UserFriendlyException($"模板默认值绑定重复:产品[{productId}]与标签类型[{labelTypeId}]只能存在一条");
                  }
              }
  
              await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplateProductDefaultDbEntity>()
                  .Where(x => x.TemplateId == templateDbId)
                  .ExecuteCommandAsync();
  
              if (templateProductDefaults.Count > 0)
              {
                  var rows = templateProductDefaults.Select((x, idx) =>
                  {
                      var productId = x.ProductId?.Trim();
                      var labelTypeId = x.LabelTypeId?.Trim();
                      if (string.IsNullOrWhiteSpace(productId))
                      {
                          throw new UserFriendlyException("模板默认值绑定中,产品Id不能为空");
                      }
  
                      if (string.IsNullOrWhiteSpace(labelTypeId))
                      {
                          throw new UserFriendlyException("模板默认值绑定中,标签类型Id不能为空");
                      }
  
                      var json = x.DefaultValues is null ? null : JsonSerializer.Serialize(x.DefaultValues);
                      return new FlLabelTemplateProductDefaultDbEntity
                      {
                          Id = _guidGenerator.Create().ToString(),
                          TemplateId = templateDbId,
                          ProductId = productId,
                          LabelTypeId = labelTypeId,
                          DefaultValuesJson = json,
                          OrderNum = x.OrderNum <= 0 ? idx + 1 : x.OrderNum
                      };
                  }).ToList();
  
                  await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync();
              }
          }
      }
  
49755ef0   李曜臣   6-12代码优化
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
      private const string EmptyDisplay = "无";
  
      private async Task FillTemplateScopeOnDtoAsync(LabelTemplateGetOutputDto dto, FlLabelTemplateDbEntity template)
      {
          var scopeMap = await LabelTemplateScopeHelper.BuildScopeDisplayMapAsync(
              _dbContext.SqlSugarClient, new List<FlLabelTemplateDbEntity> { template });
          scopeMap.TryGetValue(template.Id, out var scope);
  
          dto.Company = scope?.Company ?? string.Empty;
          dto.Region = scope?.Region ?? string.Empty;
          dto.Location = scope?.Location ?? string.Empty;
          dto.AppliedPartnerType = scope?.AppliedPartnerType ?? LabelTemplateScopeHelper.ScopeAll;
          dto.AppliedRegionType = scope?.AppliedRegionType ?? LabelTemplateScopeHelper.ScopeAll;
          dto.AppliedLocationType = scope?.AppliedLocationType ?? template.AppliedLocationType;
          dto.PartnerIds = scope?.PartnerIds ?? new List<string>();
          dto.CompanyIds = scope?.PartnerIds ?? new List<string>();
          dto.RegionIds = scope?.RegionIds ?? new List<string>();
          dto.GroupIds = scope?.RegionIds ?? new List<string>();
          dto.LocationIds = scope?.LocationIds ?? new List<string>();
          dto.AppliedLocationIds = dto.LocationIds;
      }
  
a4baaa73   李曜臣   模板与产品关联实现
574
575
576
577
578
579
580
581
582
      private static string EnsureElementName(string? elementName)
      {
          var normalizedName = elementName?.Trim();
          if (string.IsNullOrWhiteSpace(normalizedName))
          {
              throw new UserFriendlyException("组件名字不能为空");
          }
  
          return normalizedName;
919c1b6a   李曜臣   1
583
584
585
586
587
      }
  
      private static PagedResultWithPageDto<T> BuildPagedResult<T>(int skipCount, int maxResultCount, int total, List<T> items)
      {
          var pageSize = maxResultCount <= 0 ? items.Count : maxResultCount;
143afd59   杨鑫   打印,标签
588
          var pageIndex = pageSize <= 0 ? 1 : PagedQueryConvention.PageIndexFromSkipCount(skipCount);
919c1b6a   李曜臣   1
589
590
591
592
593
594
595
596
597
598
599
600
601
602
          var totalPages = pageSize <= 0 ? 0 : (int)Math.Ceiling(total / (double)pageSize);
          return new PagedResultWithPageDto<T>
          {
              PageIndex = pageIndex,
              PageSize = pageSize,
              TotalCount = total,
              TotalPages = totalPages,
              Items = items
          };
      }
  
      private static PagedResultWithPageDto<T> BuildPagedResult<T>(int skipCount, int maxResultCount, RefAsync<int> total, List<T> items)
      {
          var pageSize = maxResultCount <= 0 ? items.Count : maxResultCount;
143afd59   杨鑫   打印,标签
603
          var pageIndex = pageSize <= 0 ? 1 : PagedQueryConvention.PageIndexFromSkipCount(skipCount);
919c1b6a   李曜臣   1
604
605
606
607
608
609
610
611
612
613
          var totalPages = pageSize <= 0 ? 0 : (int)Math.Ceiling(total.Value / (double)pageSize);
          return new PagedResultWithPageDto<T>
          {
              PageIndex = pageIndex,
              PageSize = pageSize,
              TotalCount = total.Value,
              TotalPages = totalPages,
              Items = items
          };
      }
540ac0e3   杨鑫   前端修改bug
614
615
616
617
618
619
  
      private static string NormalizeTemplateBorderType(string? raw)
      {
          var v = (raw ?? string.Empty).Trim().ToLowerInvariant();
          return v is "line" or "dotted" ? v : "none";
      }
4cb354d4   杨鑫   提交
620
621
622
623
624
625
  
      private static string NormalizePrintOrientationType(string? raw)
      {
          var v = (raw ?? string.Empty).Trim().ToLowerInvariant();
          return v == "horizontal" ? "horizontal" : "vertical";
      }
919c1b6a   李曜臣   1
626
  }