LabelTemplateScopeHelper.cs
22.5 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
using FoodLabeling.Application.Contracts.Dtos.LabelTemplate;
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Entities;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Guids;
namespace FoodLabeling.Application.Helpers;
/// <summary>
/// 标签模板适用 Company / Region / Location:各维度独立 ALL/SPECIFIED + 多选落库。
/// </summary>
public static class LabelTemplateScopeHelper
{
public const string ScopeAll = "ALL";
public const string ScopeSpecified = "SPECIFIED";
public const string AllCompaniesDisplay = "All Companies";
public const string AllRegionsDisplay = "All Regions";
public const string AllLocationsDisplay = "All Locations";
public const string EmptyDisplay = "无";
public sealed class LabelTemplateScopeSaveResult
{
public string AppliedPartnerType { get; init; } = ScopeAll;
public string AppliedRegionType { get; init; } = ScopeAll;
public string AppliedLocationType { get; init; } = ScopeAll;
public List<string> PartnerIds { get; init; } = new();
public List<string> RegionIds { get; init; } = new();
public List<string> LocationIds { get; init; } = new();
}
public sealed class LabelTemplateScopeDisplay
{
public string Company { get; init; } = AllCompaniesDisplay;
public string Region { get; init; } = AllRegionsDisplay;
public string Location { get; init; } = AllLocationsDisplay;
public string AppliedPartnerType { get; init; } = ScopeAll;
public string AppliedRegionType { get; init; } = ScopeAll;
public string AppliedLocationType { get; init; } = ScopeAll;
public List<string> PartnerIds { get; init; } = new();
public List<string> RegionIds { get; init; } = new();
public List<string> LocationIds { get; init; } = new();
}
/// <summary>
/// 解析新增/编辑入参中的 Company / Region / Location 范围。
/// </summary>
public static async Task<LabelTemplateScopeSaveResult> ResolveScopeForSaveAsync(
ISqlSugarClient db,
LabelTemplateCreateInputVo input)
{
var partnerIds = NormalizePartnerIds(input);
var regionIds = NormalizeRegionIds(input);
var locationIds = MergeExplicitLocationIds(input);
var partnerType = ResolveDimensionType(
input.AppliedPartnerType,
partnerIds,
input.PartnerIds is not null || input.CompanyIds is not null);
var regionType = ResolveDimensionType(
input.AppliedRegionType,
regionIds,
input.RegionIds is not null || input.GroupIds is not null);
var locationType = ResolveDimensionType(
input.AppliedLocationType,
locationIds,
input.LocationIds is not null || input.AppliedLocationIds is not null);
ValidateDimensionType("Company", partnerType);
ValidateDimensionType("Region", regionType);
ValidateDimensionType("Location", locationType);
if (string.Equals(partnerType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) && partnerIds.Count == 0)
{
throw new UserFriendlyException("指定适用 Company 时,partnerIds/companyIds 不能为空");
}
if (string.Equals(regionType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) && regionIds.Count == 0)
{
throw new UserFriendlyException("指定适用 Region 时,regionIds/groupIds 不能为空");
}
if (string.Equals(locationType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) && locationIds.Count == 0)
{
throw new UserFriendlyException("指定适用门店时,locationIds/appliedLocationIds 不能为空");
}
if (partnerIds.Count > 0)
{
await ValidatePartnerIdsExistAsync(db, partnerIds);
}
if (regionIds.Count > 0)
{
await ValidateRegionIdsExistAsync(db, regionIds);
}
if (locationIds.Count > 0)
{
await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(db, locationIds);
}
var anySpecified = string.Equals(partnerType, ScopeSpecified, StringComparison.OrdinalIgnoreCase)
|| string.Equals(regionType, ScopeSpecified, StringComparison.OrdinalIgnoreCase)
|| string.Equals(locationType, ScopeSpecified, StringComparison.OrdinalIgnoreCase);
if (anySpecified)
{
var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
db,
string.Equals(partnerType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) ? partnerIds : null,
string.Equals(regionType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) ? regionIds : null,
string.Equals(locationType, ScopeSpecified, StringComparison.OrdinalIgnoreCase) ? locationIds : null);
if (merged.Count == 0)
{
throw new UserFriendlyException("指定适用范围后至少需要匹配到一个有效门店");
}
}
return new LabelTemplateScopeSaveResult
{
AppliedPartnerType = partnerType,
AppliedRegionType = regionType,
AppliedLocationType = locationType,
PartnerIds = partnerIds,
RegionIds = regionIds,
LocationIds = locationIds
};
}
public static async Task SaveTemplateScopeAsync(
ISqlSugarClient db,
IGuidGenerator guidGenerator,
string templateId,
LabelTemplateScopeSaveResult scope,
string? currentUserId,
DateTime now)
{
var hasExtendedScope = await LabelTemplateScopeSchemaHelper.HasPartnerRegionScopeTablesAsync(db);
if (hasExtendedScope)
{
await db.Deleteable<FlLabelTemplatePartnerDbEntity>()
.Where(x => x.TemplateId == templateId)
.ExecuteCommandAsync();
await db.Deleteable<FlLabelTemplateRegionDbEntity>()
.Where(x => x.TemplateId == templateId)
.ExecuteCommandAsync();
}
await db.Deleteable<FlLabelTemplateLocationDbEntity>()
.Where(x => x.TemplateId == templateId)
.ExecuteCommandAsync();
if (hasExtendedScope
&& string.Equals(scope.AppliedPartnerType, ScopeSpecified, StringComparison.OrdinalIgnoreCase)
&& scope.PartnerIds.Count > 0)
{
var rows = scope.PartnerIds.Select(pid => new FlLabelTemplatePartnerDbEntity
{
Id = guidGenerator.Create().ToString(),
TemplateId = templateId,
PartnerId = pid,
CreationTime = now,
CreatorId = currentUserId
}).ToList();
await db.Insertable(rows).ExecuteCommandAsync();
}
if (hasExtendedScope
&& string.Equals(scope.AppliedRegionType, ScopeSpecified, StringComparison.OrdinalIgnoreCase)
&& scope.RegionIds.Count > 0)
{
var rows = scope.RegionIds.Select(gid => new FlLabelTemplateRegionDbEntity
{
Id = guidGenerator.Create().ToString(),
TemplateId = templateId,
GroupId = gid,
CreationTime = now,
CreatorId = currentUserId
}).ToList();
await db.Insertable(rows).ExecuteCommandAsync();
}
if (string.Equals(scope.AppliedLocationType, ScopeSpecified, StringComparison.OrdinalIgnoreCase)
&& scope.LocationIds.Count > 0)
{
var rows = scope.LocationIds.Select(locId => new FlLabelTemplateLocationDbEntity
{
Id = guidGenerator.Create().ToString(),
TemplateId = templateId,
LocationId = locId
}).ToList();
await db.Insertable(rows).ExecuteCommandAsync();
}
}
/// <summary>
/// 批量加载模板适用范围展示与 Id 数组(详情/列表)。
/// </summary>
public static async Task<Dictionary<string, LabelTemplateScopeDisplay>> BuildScopeDisplayMapAsync(
ISqlSugarClient db,
IReadOnlyList<FlLabelTemplateDbEntity> templates)
{
var result = new Dictionary<string, LabelTemplateScopeDisplay>(StringComparer.Ordinal);
if (templates.Count == 0)
{
return result;
}
var templateIds = templates.Select(x => x.Id).Distinct(StringComparer.Ordinal).ToList();
var hasExtendedScope = await LabelTemplateScopeSchemaHelper.HasPartnerRegionScopeTablesAsync(db);
var partnerLinks = hasExtendedScope
? await db.Queryable<FlLabelTemplatePartnerDbEntity>()
.Where(x => templateIds.Contains(x.TemplateId))
.ToListAsync()
: new List<FlLabelTemplatePartnerDbEntity>();
var regionLinks = hasExtendedScope
? await db.Queryable<FlLabelTemplateRegionDbEntity>()
.Where(x => templateIds.Contains(x.TemplateId))
.ToListAsync()
: new List<FlLabelTemplateRegionDbEntity>();
var locationLinks = await db.Queryable<FlLabelTemplateLocationDbEntity>()
.Where(x => templateIds.Contains(x.TemplateId))
.ToListAsync();
var partnerIdSet = partnerLinks.Select(x => x.PartnerId).Distinct(StringComparer.Ordinal).ToList();
var regionIdSet = regionLinks.Select(x => x.GroupId).Distinct(StringComparer.Ordinal).ToList();
var locationIdSet = locationLinks.Select(x => x.LocationId).Distinct(StringComparer.Ordinal).ToList();
var partnerNameById = new Dictionary<string, string>(StringComparer.Ordinal);
if (partnerIdSet.Count > 0)
{
var partners = await db.Queryable<FlPartnerDbEntity>()
.Where(x => !x.IsDeleted && partnerIdSet.Contains(x.Id))
.ToListAsync();
foreach (var p in partners)
{
var name = p.PartnerName?.Trim();
partnerNameById[p.Id] = string.IsNullOrEmpty(name) ? p.Id : name;
}
}
var regionNameById = new Dictionary<string, string>(StringComparer.Ordinal);
if (regionIdSet.Count > 0)
{
var groups = await db.Queryable<FlGroupDbEntity>()
.Where(x => !x.IsDeleted && regionIdSet.Contains(x.Id))
.ToListAsync();
foreach (var g in groups)
{
var name = g.GroupName?.Trim();
regionNameById[g.Id] = string.IsNullOrEmpty(name) ? g.Id : name;
}
}
var locById = new Dictionary<string, LocationAggregateRoot>(StringComparer.Ordinal);
if (locationIdSet.Count > 0)
{
var guidList = locationIdSet.Where(x => Guid.TryParse(x, out _)).Select(Guid.Parse).ToList();
if (guidList.Count > 0)
{
var locs = await db.Queryable<LocationAggregateRoot>()
.Where(x => !x.IsDeleted && guidList.Contains(x.Id))
.ToListAsync();
foreach (var loc in locs)
{
locById[loc.Id.ToString()] = loc;
}
}
}
foreach (var template in templates)
{
var locationType = NormalizeScopeType(template.AppliedLocationType, ScopeAll);
var pIds = LocationScopeBindingHelper.NormalizeIds(
partnerLinks.Where(x => x.TemplateId == template.Id).Select(x => x.PartnerId).ToList());
var rIds = LocationScopeBindingHelper.NormalizeIds(
regionLinks.Where(x => x.TemplateId == template.Id).Select(x => x.GroupId).ToList());
var lIds = LocationScopeBindingHelper.NormalizeIds(
locationLinks.Where(x => x.TemplateId == template.Id).Select(x => x.LocationId).ToList());
var partnerType = pIds.Count > 0 ? ScopeSpecified : ScopeAll;
var regionType = rIds.Count > 0 ? ScopeSpecified : ScopeAll;
if (hasExtendedScope
&& pIds.Count == 0
&& lIds.Count > 0)
{
pIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(db, lIds);
if (pIds.Count > 0)
{
partnerType = ScopeSpecified;
}
}
if (hasExtendedScope
&& rIds.Count == 0
&& lIds.Count > 0)
{
rIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(db, lIds);
if (rIds.Count > 0)
{
regionType = ScopeSpecified;
}
}
if (lIds.Count == 0 && !string.Equals(locationType, ScopeSpecified, StringComparison.OrdinalIgnoreCase))
{
locationType = ScopeAll;
}
else if (lIds.Count > 0)
{
locationType = ScopeSpecified;
}
var companyDisplay = string.Equals(partnerType, ScopeAll, StringComparison.OrdinalIgnoreCase)
? AllCompaniesDisplay
: FormatNames(pIds.Select(id => partnerNameById.TryGetValue(id, out var n) ? n : id));
var regionDisplay = string.Equals(regionType, ScopeAll, StringComparison.OrdinalIgnoreCase)
? AllRegionsDisplay
: FormatNames(rIds.Select(id => regionNameById.TryGetValue(id, out var n) ? n : id));
var locationDisplay = string.Equals(locationType, ScopeAll, StringComparison.OrdinalIgnoreCase)
? AllLocationsDisplay
: FormatLocationNames(lIds, locById);
result[template.Id] = new LabelTemplateScopeDisplay
{
Company = companyDisplay,
Region = regionDisplay,
Location = locationDisplay,
AppliedPartnerType = partnerType,
AppliedRegionType = regionType,
AppliedLocationType = locationType,
PartnerIds = pIds,
RegionIds = rIds,
LocationIds = lIds
};
}
return result;
}
/// <summary>
/// 列表权限:按当前用户可见门店筛选模板(各维度 AND)。
/// </summary>
public static async Task<ISugarQueryable<FlLabelTemplateDbEntity>> ApplyTemplateScopeFilterAsync(
ISqlSugarClient db,
ISugarQueryable<FlLabelTemplateDbEntity> query,
List<string>? scopedLocationIds)
{
if (scopedLocationIds is null)
{
return query;
}
var hasExtendedScope = await LabelTemplateScopeSchemaHelper.HasPartnerRegionScopeTablesAsync(db);
if (scopedLocationIds.Count == 0)
{
return hasExtendedScope
? query.Where(t =>
t.AppliedLocationType == ScopeAll
&& !SqlFunc.Subqueryable<FlLabelTemplateLocationDbEntity>()
.Where(l => l.TemplateId == t.Id)
.Any()
&& !SqlFunc.Subqueryable<FlLabelTemplatePartnerDbEntity>()
.Where(p => p.TemplateId == t.Id)
.Any()
&& !SqlFunc.Subqueryable<FlLabelTemplateRegionDbEntity>()
.Where(r => r.TemplateId == t.Id)
.Any())
: query.Where(t =>
t.AppliedLocationType == ScopeAll
&& !SqlFunc.Subqueryable<FlLabelTemplateLocationDbEntity>()
.Where(l => l.TemplateId == t.Id)
.Any());
}
if (!hasExtendedScope)
{
return query.Where(t =>
t.AppliedLocationType == ScopeAll
|| SqlFunc.Subqueryable<FlLabelTemplateLocationDbEntity>()
.Where(l => l.TemplateId == t.Id && scopedLocationIds.Contains(l.LocationId))
.Any());
}
var scopedPartnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
db, scopedLocationIds);
var scopedGroupIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
db, scopedLocationIds);
return query.Where(t =>
(
t.AppliedLocationType == ScopeAll
&& !SqlFunc.Subqueryable<FlLabelTemplateLocationDbEntity>()
.Where(l => l.TemplateId == t.Id)
.Any()
&& !SqlFunc.Subqueryable<FlLabelTemplatePartnerDbEntity>()
.Where(p => p.TemplateId == t.Id)
.Any()
&& !SqlFunc.Subqueryable<FlLabelTemplateRegionDbEntity>()
.Where(r => r.TemplateId == t.Id)
.Any()
)
|| (
(!SqlFunc.Subqueryable<FlLabelTemplatePartnerDbEntity>()
.Where(p => p.TemplateId == t.Id)
.Any()
|| SqlFunc.Subqueryable<FlLabelTemplatePartnerDbEntity>()
.Where(p => p.TemplateId == t.Id && scopedPartnerIds.Contains(p.PartnerId))
.Any())
&& (!SqlFunc.Subqueryable<FlLabelTemplateRegionDbEntity>()
.Where(r => r.TemplateId == t.Id)
.Any()
|| SqlFunc.Subqueryable<FlLabelTemplateRegionDbEntity>()
.Where(r => r.TemplateId == t.Id && scopedGroupIds.Contains(r.GroupId))
.Any())
&& (t.AppliedLocationType == ScopeAll
|| SqlFunc.Subqueryable<FlLabelTemplateLocationDbEntity>()
.Where(l => l.TemplateId == t.Id && scopedLocationIds.Contains(l.LocationId))
.Any())
));
}
private static string ResolveDimensionType(string? type, List<string> ids, bool hasArrayInPayload)
{
if (ids.Count > 0)
{
return ScopeSpecified;
}
var normalized = (type ?? ScopeAll).Trim().ToUpperInvariant();
if (hasArrayInPayload && string.Equals(normalized, ScopeAll, StringComparison.OrdinalIgnoreCase))
{
return ScopeAll;
}
return string.Equals(normalized, ScopeSpecified, StringComparison.OrdinalIgnoreCase)
? ScopeSpecified
: ScopeAll;
}
private static void ValidateDimensionType(string label, string type)
{
if (type != ScopeAll && type != ScopeSpecified)
{
throw new UserFriendlyException($"适用{label}范围不合法(ALL/SPECIFIED)");
}
}
private static string NormalizeScopeType(string? type, string fallback)
{
var t = (type ?? fallback).Trim().ToUpperInvariant();
return t == ScopeSpecified ? ScopeSpecified : ScopeAll;
}
public static List<string> NormalizePartnerIds(LabelTemplateCreateInputVo input)
{
var merged = new HashSet<string>(StringComparer.Ordinal);
foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.PartnerIds))
{
merged.Add(id);
}
foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.CompanyIds))
{
merged.Add(id);
}
return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
}
public static List<string> NormalizeRegionIds(LabelTemplateCreateInputVo input)
{
var merged = new HashSet<string>(StringComparer.Ordinal);
foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.RegionIds))
{
merged.Add(id);
}
foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.GroupIds))
{
merged.Add(id);
}
return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
}
public static List<string> MergeExplicitLocationIds(LabelTemplateCreateInputVo input)
{
var merged = new HashSet<string>(StringComparer.Ordinal);
foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.LocationIds))
{
merged.Add(id);
}
foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.AppliedLocationIds))
{
merged.Add(id);
}
return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
}
private static async Task ValidatePartnerIdsExistAsync(ISqlSugarClient db, List<string> partnerIds)
{
if (partnerIds.Count == 0)
{
return;
}
var count = await db.Queryable<FlPartnerDbEntity>()
.Where(x => !x.IsDeleted && partnerIds.Contains(x.Id))
.CountAsync();
if (count != partnerIds.Count)
{
throw new UserFriendlyException("存在无效的 Company(partnerIds/companyIds),请刷新后重试");
}
}
private static async Task ValidateRegionIdsExistAsync(ISqlSugarClient db, List<string> regionIds)
{
if (regionIds.Count == 0)
{
return;
}
var count = await db.Queryable<FlGroupDbEntity>()
.Where(x => !x.IsDeleted && regionIds.Contains(x.Id))
.CountAsync();
if (count != regionIds.Count)
{
throw new UserFriendlyException("存在无效的 Region(regionIds/groupIds),请刷新后重试");
}
}
private static string FormatNames(IEnumerable<string> names)
{
var list = names
.Select(x => x?.Trim())
.Where(x => !string.IsNullOrEmpty(x))
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(x => x, StringComparer.OrdinalIgnoreCase)
.ToList();
return list.Count > 0 ? string.Join(", ", list) : EmptyDisplay;
}
private static string FormatLocationNames(
List<string> locationIds,
Dictionary<string, LocationAggregateRoot> locById)
{
var names = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var lid in locationIds)
{
if (!locById.TryGetValue(lid, out var loc))
{
continue;
}
var locName = loc.LocationName?.Trim();
if (string.IsNullOrEmpty(locName))
{
locName = loc.LocationCode?.Trim();
}
if (!string.IsNullOrEmpty(locName))
{
names.Add(locName);
}
}
return names.Count > 0
? string.Join(", ", names.OrderBy(x => x, StringComparer.OrdinalIgnoreCase))
: EmptyDisplay;
}
}