LabelRegionScopeHelper.cs
12.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
using FoodLabeling.Application.Services.DbModels;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Guids;
namespace FoodLabeling.Application.Helpers;
/// <summary>
/// 标签适用 Region(<c>fl_group.Id</c>)范围:支持全选(ALL)、单选/多选(SPECIFIED + <c>fl_label_region</c>)。
/// </summary>
public static class LabelRegionScopeHelper
{
public const string AppliedRegionAll = "ALL";
public const string AppliedRegionSpecified = "SPECIFIED";
public const string AllRegionsDisplay = "All Regions";
public sealed class LabelRegionScopeSaveResult
{
public string AppliedRegionType { get; init; } = AppliedRegionSpecified;
public List<string> RegionIds { get; init; } = new();
public string? LocationId { get; init; }
}
public sealed class LabelRegionScopeDisplay
{
public string Region { get; init; } = string.Empty;
public List<string> RegionIds { get; init; } = new();
public List<string> GroupIds { get; init; } = new();
}
/// <summary>
/// 解析新增/编辑入参中的 Region 范围与落库门店 Id。
/// </summary>
public static async Task<LabelRegionScopeSaveResult> ResolveScopeForSaveAsync(
ISqlSugarClient db,
string? appliedRegionType,
IReadOnlyList<string>? regionIds,
IReadOnlyList<string>? groupIds,
string? locationId,
IReadOnlyList<string>? locationIds)
{
var mergedRegionIds = NormalizeRegionIds(regionIds, groupIds);
var type = (appliedRegionType ?? AppliedRegionAll).Trim().ToUpperInvariant();
var hasScopeArrays = regionIds is not null || groupIds is not null || locationIds is not null;
if (mergedRegionIds.Count > 0)
{
type = AppliedRegionSpecified;
}
else if (hasScopeArrays && string.Equals(type, AppliedRegionAll, StringComparison.OrdinalIgnoreCase))
{
type = AppliedRegionAll;
}
if (type != AppliedRegionAll && type != AppliedRegionSpecified)
{
throw new UserFriendlyException("适用 Region 范围不合法(ALL/SPECIFIED)");
}
if (string.Equals(type, AppliedRegionAll, StringComparison.OrdinalIgnoreCase))
{
var loc = locationId?.Trim();
if (!string.IsNullOrWhiteSpace(loc))
{
await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(db, new List<string> { loc });
}
return new LabelRegionScopeSaveResult
{
AppliedRegionType = AppliedRegionAll,
RegionIds = new List<string>(),
LocationId = string.IsNullOrWhiteSpace(loc) ? null : loc
};
}
if (mergedRegionIds.Count == 0 && string.IsNullOrWhiteSpace(locationId))
{
throw new UserFriendlyException("请选择适用 Region(regionIds),或指定门店 locationId");
}
await ValidateRegionIdsExistAsync(db, mergedRegionIds);
var explicitLocationId = locationId?.Trim();
var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(locationIds);
var mergedLocations = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
db, (IReadOnlyList<string>?)null, mergedRegionIds, explicitLocationIds);
string? resolvedLocationId;
if (!string.IsNullOrWhiteSpace(explicitLocationId))
{
if (mergedLocations.Count > 0 && !mergedLocations.Contains(explicitLocationId, StringComparer.Ordinal))
{
throw new UserFriendlyException("所选门店不在指定 Region 范围内");
}
await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(db, new List<string> { explicitLocationId });
resolvedLocationId = explicitLocationId;
}
else if (mergedLocations.Count == 0)
{
throw new UserFriendlyException("所选 Region 下无有效门店,请检查 Region 或补充 locationId");
}
else if (mergedLocations.Count == 1)
{
resolvedLocationId = mergedLocations[0];
}
else
{
resolvedLocationId = mergedLocations[0];
}
return new LabelRegionScopeSaveResult
{
AppliedRegionType = AppliedRegionSpecified,
RegionIds = mergedRegionIds,
LocationId = resolvedLocationId
};
}
public static async Task SaveLabelRegionsAsync(
ISqlSugarClient db,
IGuidGenerator guidGenerator,
string labelId,
string appliedRegionType,
IReadOnlyList<string> regionIds,
string? currentUserId,
DateTime now)
{
var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
if (!schema.HasLabelRegionTable)
{
return;
}
await db.Deleteable<FlLabelRegionDbEntity>()
.Where(x => x.LabelId == labelId)
.ExecuteCommandAsync();
if (!string.Equals(appliedRegionType, AppliedRegionSpecified, StringComparison.OrdinalIgnoreCase)
|| regionIds.Count == 0)
{
return;
}
var rows = regionIds.Select(gid => new FlLabelRegionDbEntity
{
Id = guidGenerator.Create().ToString(),
LabelId = labelId,
GroupId = gid,
CreationTime = now,
CreatorId = currentUserId
}).ToList();
await db.Insertable(rows).ExecuteCommandAsync();
}
public static async Task<List<string>> GetRegionIdsForLabelAsync(ISqlSugarClient db, string labelId)
{
var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
if (!schema.HasLabelRegionTable)
{
return new List<string>();
}
return LocationScopeBindingHelper.NormalizeIds(
await db.Queryable<FlLabelRegionDbEntity>()
.Where(x => x.LabelId == labelId)
.Select(x => x.GroupId)
.ToListAsync());
}
public static async Task<LabelRegionScopeDisplay> BuildScopeDisplayAsync(
ISqlSugarClient db,
string labelId,
string? appliedRegionType,
string? locationId)
{
if (string.Equals(appliedRegionType, AppliedRegionAll, StringComparison.OrdinalIgnoreCase))
{
return new LabelRegionScopeDisplay
{
Region = AllRegionsDisplay,
RegionIds = new List<string>(),
GroupIds = new List<string>()
};
}
var regionIds = await GetRegionIdsForLabelAsync(db, labelId);
if (regionIds.Count == 0 && !string.IsNullOrWhiteSpace(locationId))
{
regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
db, new List<string> { locationId.Trim() });
}
if (regionIds.Count == 0)
{
return new LabelRegionScopeDisplay
{
Region = "无",
RegionIds = new List<string>(),
GroupIds = new List<string>()
};
}
var names = await db.Queryable<FlGroupDbEntity>()
.Where(g => !g.IsDeleted && regionIds.Contains(g.Id))
.OrderBy(g => g.GroupName)
.Select(g => g.GroupName)
.ToListAsync();
var regionText = names.Count > 0
? string.Join(", ", names.Where(n => !string.IsNullOrWhiteSpace(n)).Select(n => n!.Trim()).Distinct())
: "无";
return new LabelRegionScopeDisplay
{
Region = regionText,
RegionIds = regionIds,
GroupIds = regionIds
};
}
/// <summary>
/// 列表/筛选:标签是否落在指定 Region(<c>fl_group.Id</c>)或关联门店范围内。
/// </summary>
public static ISugarQueryable<FlLabelDbEntity> ApplyLabelRegionListFilter(
ISugarQueryable<FlLabelDbEntity> query,
string groupId,
List<string>? scopedLocationIds,
LabelRegionSchemaHelper.LabelRegionSchemaStatus schema)
{
var gid = groupId.Trim();
if (scopedLocationIds is not { Count: > 0 })
{
return query.Where(_ => false);
}
if (!schema.HasLabelRegionTable && !schema.HasAppliedRegionTypeColumn)
{
return query.Where(l => scopedLocationIds.Contains(l.LocationId));
}
if (!schema.HasLabelRegionTable)
{
return query.Where(
"(AppliedRegionType = @all OR LocationId IN (@locs))",
new { all = AppliedRegionAll, locs = scopedLocationIds });
}
if (!schema.HasAppliedRegionTypeColumn)
{
return query.Where(l =>
SqlFunc.Subqueryable<FlLabelRegionDbEntity>()
.Where(lr => lr.LabelId == l.Id && lr.GroupId == gid)
.Any() ||
scopedLocationIds.Contains(l.LocationId));
}
return query.Where(
"""
(AppliedRegionType = @all
OR EXISTS (SELECT 1 FROM fl_label_region lr WHERE lr.LabelId = fl_label.Id AND lr.GroupId = @gid)
OR LocationId IN (@locs))
""",
new { all = AppliedRegionAll, gid, locs = scopedLocationIds });
}
/// <summary>
/// 解析门店所属的 Region Id(用于 App 树、打印校验)。
/// </summary>
public static async Task<List<string>> ResolveGroupIdsForLocationAsync(ISqlSugarClient db, string locationId)
{
return await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
db, new List<string> { locationId.Trim() });
}
/// <summary>
/// 标签是否适用于指定门店(LocationId 命中、Region 关联或 ALL)。
/// </summary>
/// <summary>
/// 校验标签是否适用于当前门店(否则抛出友好异常)。
/// </summary>
public static async Task EnsureLabelAppliesToLocationAsync(
ISqlSugarClient db,
string labelId,
string locationId)
{
var label = await db.Queryable<FlLabelDbEntity>()
.FirstAsync(x => !x.IsDeleted && x.Id == labelId);
var groupIds = await ResolveGroupIdsForLocationAsync(db, locationId);
if (!await LabelAppliesToLocationAsync(db, label, locationId, groupIds))
{
throw new UserFriendlyException("该标签不属于当前门店或未配置适用 Region");
}
}
public static async Task<bool> LabelAppliesToLocationAsync(
ISqlSugarClient db,
FlLabelDbEntity label,
string locationId,
List<string> groupIdsForLocation)
{
var appliedType = await LabelRegionSchemaHelper.GetAppliedRegionTypeForLabelAsync(
db, label.Id, label.AppliedRegionType);
if (string.Equals(appliedType, AppliedRegionAll, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (!string.IsNullOrWhiteSpace(label.LocationId) &&
string.Equals(label.LocationId.Trim(), locationId, StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (groupIdsForLocation.Count == 0)
{
return false;
}
var schema = await LabelRegionSchemaHelper.GetStatusAsync(db);
if (!schema.HasLabelRegionTable)
{
return false;
}
return await db.Queryable<FlLabelRegionDbEntity>()
.AnyAsync(lr => lr.LabelId == label.Id && groupIdsForLocation.Contains(lr.GroupId));
}
private static List<string> NormalizeRegionIds(
IReadOnlyList<string>? regionIds,
IReadOnlyList<string>? groupIds)
{
var merged = new HashSet<string>(StringComparer.Ordinal);
foreach (var id in LocationScopeBindingHelper.NormalizeIds(regionIds))
{
merged.Add(id);
}
foreach (var id in LocationScopeBindingHelper.NormalizeIds(groupIds))
{
merged.Add(id);
}
return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
}
private static async Task ValidateRegionIdsExistAsync(ISqlSugarClient db, List<string> regionIds)
{
if (regionIds.Count == 0)
{
return;
}
var count = await db.Queryable<FlGroupDbEntity>()
.Where(g => !g.IsDeleted && regionIds.Contains(g.Id))
.CountAsync();
if (count != regionIds.Count)
{
throw new UserFriendlyException("存在无效的 Region Id,请刷新后重试");
}
}
}