LabelTemplateAppService.cs
17.3 KB
1
2
3
4
5
6
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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
163
164
165
166
167
168
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
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
424
425
426
427
428
429
430
using System.Text.Json;
using FoodLabeling.Application.Helpers;
using FoodLabeling.Application.Contracts.Dtos.Common;
using FoodLabeling.Application.Contracts.Dtos.LabelTemplate;
using FoodLabeling.Application.Contracts.IServices;
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Entities;
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)
{
RefAsync<int> total = 0;
var keyword = input.Keyword?.Trim();
var locationId = input.LocationId?.Trim();
var specifiedTemplateIds = new HashSet<string>();
if (!string.IsNullOrWhiteSpace(locationId))
{
var rows = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateLocationDbEntity>()
.Where(x => x.LocationId == locationId)
.Select(x => x.TemplateId)
.ToListAsync();
specifiedTemplateIds = rows.ToHashSet();
}
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);
if (!string.IsNullOrWhiteSpace(locationId))
{
query = query.Where(x => x.AppliedLocationType == "ALL" || specifiedTemplateIds.Contains(x.Id));
}
query = !string.IsNullOrWhiteSpace(input.Sorting)
? query.OrderBy(input.Sorting)
: query.OrderByDescending(x => x.LastModificationTime ?? x.CreationTime);
var pageEntities = await query.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var templateIds = pageEntities.Select(x => x.Id).ToList();
// element count (Contents)
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();
var elementCountMap = elementCounts.ToDictionary(x => x.TemplateId, x => (int)x.Count);
// applied locations (for LocationText)
var templateLocationRows = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateLocationDbEntity>()
.Where(x => templateIds.Contains(x.TemplateId))
.ToListAsync();
var locationIdSet = templateLocationRows.Select(x => x.LocationId).Where(x => !string.IsNullOrWhiteSpace(x)).Distinct().ToList();
var locationGuidList = locationIdSet
.Where(x => Guid.TryParse(x, out _))
.Select(Guid.Parse)
.Distinct()
.ToList();
var locationMap = new Dictionary<Guid, LocationAggregateRoot>();
if (locationGuidList.Count > 0)
{
var locations = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
.Where(x => !x.IsDeleted)
.Where(x => locationGuidList.Contains(x.Id))
.ToListAsync();
locationMap = locations.ToDictionary(x => x.Id, x => x);
}
string GetFirstLocationName(string templateDbId)
{
var first = templateLocationRows.FirstOrDefault(x => x.TemplateId == templateDbId);
if (first is null) return "Specified";
if (Guid.TryParse(first.LocationId, out var gid) && locationMap.TryGetValue(gid, out var loc))
{
return loc.LocationName ?? loc.LocationCode;
}
return "Specified";
}
var items = pageEntities.Select(x =>
{
var lastEdited = x.LastModificationTime ?? x.CreationTime;
var contentsCount = elementCountMap.TryGetValue(x.Id, out var c) ? c : 0;
var locationText = x.AppliedLocationType == "ALL" ? "All Locations" : GetFirstLocationName(x.Id);
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,
LocationText = locationText,
ContentsCount = contentsCount,
SizeText = sizeText,
VersionNo = x.VersionNo,
LastEdited = lastEdited
};
}).ToList();
return BuildPagedResult(input.SkipCount, input.MaxResultCount, total, items);
}
public async Task<LabelTemplateGetOutputDto> GetAsync(string id)
{
var template = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
.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,
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();
}
var appliedLocationIds = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateLocationDbEntity>()
.Where(x => x.TemplateId == template.Id)
.Select(x => x.LocationId)
.ToListAsync();
return new LabelTemplateGetOutputDto
{
Id = template.TemplateCode,
TemplateCode = template.TemplateCode,
TemplateName = template.TemplateName,
LabelType = template.LabelType,
Unit = template.Unit,
Width = template.Width,
Height = template.Height,
AppliedLocationType = template.AppliedLocationType,
ShowRuler = template.ShowRuler,
ShowGrid = template.ShowGrid,
VersionNo = template.VersionNo,
State = template.State,
Elements = MapElements(),
AppliedLocationIds = appliedLocationIds
};
}
[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("模板名称不能为空");
}
var duplicated = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
.AnyAsync(x => !x.IsDeleted && x.TemplateCode == code);
if (duplicated)
{
throw new UserFriendlyException("模板编码已存在");
}
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,
AppliedLocationType = string.IsNullOrWhiteSpace(input.AppliedLocationType) ? "ALL" : input.AppliedLocationType.Trim(),
ShowRuler = input.ShowRuler,
ShowGrid = input.ShowGrid,
VersionNo = 1,
State = input.State
};
await _dbContext.SqlSugarClient.Insertable(entity).ExecuteCommandAsync();
await RebuildTemplateElementsAndLocationsAsync(entity.Id, input.Elements, entity.AppliedLocationType, input.AppliedLocationIds);
return await GetAsync(code);
}
[UnitOfWork]
public async Task<LabelTemplateGetOutputDto> UpdateAsync(string id, LabelTemplateUpdateInputVo input)
{
var template = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
.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))
{
var duplicated = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
.AnyAsync(x => !x.IsDeleted && x.TemplateCode == code);
if (duplicated)
{
throw new UserFriendlyException("模板编码已存在");
}
}
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;
template.AppliedLocationType = string.IsNullOrWhiteSpace(input.AppliedLocationType) ? template.AppliedLocationType : input.AppliedLocationType.Trim();
template.ShowRuler = input.ShowRuler;
template.ShowGrid = input.ShowGrid;
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();
await RebuildTemplateElementsAndLocationsAsync(template.Id, input.Elements, template.AppliedLocationType, input.AppliedLocationIds);
return await GetAsync(template.TemplateCode);
}
[UnitOfWork]
public async Task DeleteAsync(string id)
{
var template = await _dbContext.SqlSugarClient.Queryable<FlLabelTemplateDbEntity>()
.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();
}
private async Task RebuildTemplateElementsAndLocationsAsync(
string templateDbId,
List<LabelTemplateElementDto> elements,
string appliedLocationType,
List<string> appliedLocationIds)
{
// elements 重建
await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplateElementDbEntity>()
.Where(x => x.TemplateId == templateDbId)
.ExecuteCommandAsync();
if (elements is not null && elements.Count > 0)
{
var now = DateTime.Now;
var rows = elements.Select(e =>
{
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,
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();
}
// applied locations 重建
await _dbContext.SqlSugarClient.Deleteable<FlLabelTemplateLocationDbEntity>()
.Where(x => x.TemplateId == templateDbId)
.ExecuteCommandAsync();
if (string.Equals(appliedLocationType, "SPECIFIED", StringComparison.OrdinalIgnoreCase))
{
var ids = appliedLocationIds?.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct().ToList() ?? new();
if (ids.Count == 0)
{
throw new UserFriendlyException("指定门店模板必须至少选择一个门店");
}
var locRows = ids.Select(locId => new FlLabelTemplateLocationDbEntity
{
Id = _guidGenerator.Create().ToString(),
TemplateId = templateDbId,
LocationId = locId
}).ToList();
await _dbContext.SqlSugarClient.Insertable(locRows).ExecuteCommandAsync();
}
}
private static PagedResultWithPageDto<T> BuildPagedResult<T>(int skipCount, int maxResultCount, int total, List<T> items)
{
var pageSize = maxResultCount <= 0 ? items.Count : maxResultCount;
var pageIndex = pageSize <= 0 ? 1 : PagedQueryConvention.PageIndexFromSkipCount(skipCount);
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;
var pageIndex = pageSize <= 0 ? 1 : PagedQueryConvention.PageIndexFromSkipCount(skipCount);
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
};
}
}