TeamMemberAppService.cs
30.1 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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
using System.IO;
using FoodLabeling.Application.Contracts.Dtos.Common;
using FoodLabeling.Application.Contracts.Dtos.TeamMember;
using FoodLabeling.Application.Contracts.IServices;
using FoodLabeling.Application.Helpers;
using FoodLabeling.Application.Options;
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Guids;
using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.Rbac.Domain.Entities.ValueObjects;
using Yi.Framework.Rbac.Domain.Helpers;
using Yi.Framework.Rbac.Domain.Managers;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace FoodLabeling.Application.Services;
/// <summary>
/// 成员(Team Member)服务,对外仅在 food-labeling-us 暴露
/// </summary>
public class TeamMemberAppService : ApplicationService, ITeamMemberAppService
{
private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
private readonly UserManager _userManager;
private readonly ISqlSugarDbContext _dbContext;
private readonly IGuidGenerator _guidGenerator;
private readonly IOptionsSnapshot<FoodLabelingBatchImportOptions> _batchImportOptions;
public TeamMemberAppService(
ISqlSugarRepository<UserAggregateRoot, Guid> userRepository,
UserManager userManager,
ISqlSugarDbContext dbContext,
IGuidGenerator guidGenerator,
IOptionsSnapshot<FoodLabelingBatchImportOptions> batchImportOptions)
{
_userRepository = userRepository;
_userManager = userManager;
_dbContext = dbContext;
_guidGenerator = guidGenerator;
_batchImportOptions = batchImportOptions;
}
/// <inheritdoc />
public async Task<PagedResultWithPageDto<TeamMemberGetListOutputDto>> GetListAsync(TeamMemberGetListInputVo input)
{
var pageIndex = PagedQueryConvention.PageIndexFromSkipCount(input.SkipCount);
var pageSize = input.MaxResultCount;
RefAsync<int> total = 0;
var scopeLocationIds = await LocationScopeBindingHelper.ResolveFilteredLocationIdsForListAsync(
_dbContext.SqlSugarClient, input.PartnerId, input.GroupId, input.LocationId);
var query = await BuildFilteredUserQueryAsync(input, scopeLocationIds);
var users = await query
.OrderByIF(!string.IsNullOrWhiteSpace(input.Sorting), input.Sorting!)
.OrderByDescending(u => u.CreationTime)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var items = await MapUsersToOutputAsync(
users,
scopeLocationIds,
restrictAssignedLocationsToFilter: scopeLocationIds is not null);
var totalCount = (long)total;
return new PagedResultWithPageDto<TeamMemberGetListOutputDto>
{
PageIndex = pageIndex,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
Items = items
};
}
/// <inheritdoc />
public async Task<TeamMemberGetOutputDto> GetAsync(Guid id)
{
var user = await _userRepository.GetByIdAsync(id);
if (user is null || user.IsDeleted)
{
throw new UserFriendlyException("成员不存在");
}
var userIdString = id.ToString();
var links = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
.Where(x => !x.IsDeleted && x.UserId == userIdString)
.ToListAsync();
var locationIds = links.Select(x => x.LocationId).Distinct().ToList();
var locations = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
.Where(x => !x.IsDeleted)
.WhereIF(locationIds.Count > 0, x => locationIds.Contains(x.Id.ToString()))
.Select(x => new { x.Id, x.LocationCode, x.LocationName })
.ToListAsync();
var assigned = locations.Select(x => new TeamMemberAssignedLocationDto
{
Id = x.Id.ToString(),
LocationCode = x.LocationCode,
LocationName = x.LocationName
}).ToList();
var role = await _dbContext.SqlSugarClient.Queryable<UserRoleEntity>().FirstAsync(x => x.UserId == id);
var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
_dbContext.SqlSugarClient, locationIds);
var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
_dbContext.SqlSugarClient, locationIds);
return new TeamMemberGetOutputDto
{
Id = user.Id,
FullName = user.Name ?? string.Empty,
UserName = user.UserName,
Email = user.Email,
Phone = user.Phone,
State = user.State,
RoleId = role?.RoleId,
PartnerIds = partnerIds,
RegionIds = regionIds,
GroupIds = regionIds,
LocationIds = locationIds,
AssignedLocations = assigned
};
}
/// <inheritdoc />
public async Task<TeamMemberGetOutputDto> CreateAsync(TeamMemberCreateInputVo input)
{
var mergedLocationIds = await ResolveTeamMemberLocationIdsForSaveAsync(input);
var user = new UserAggregateRoot
{
UserName = input.UserName.Trim(),
Name = input.FullName.Trim(),
Nick = input.FullName.Trim(),
Email = input.Email?.Trim(),
Phone = input.Phone,
State = input.State,
EncryPassword = new EncryPasswordValueObject(input.Password.Trim())
};
EntityHelper.TrySetId(user, _guidGenerator.Create);
user.BuildPassword();
await _userManager.CreateAsync(user);
if (input.RoleId != null)
{
await _userManager.GiveUserSetRoleAsync(new List<Guid> { user.Id }, new List<Guid> { input.RoleId.Value });
}
await UpsertUserLocationsAsync(user.Id, mergedLocationIds);
return await GetAsync(user.Id);
}
/// <inheritdoc />
public async Task<TeamMemberGetOutputDto> UpdateAsync(Guid id, TeamMemberUpdateInputVo input)
{
var mergedLocationIds = await ResolveTeamMemberLocationIdsForSaveAsync(input);
var user = await _userRepository.GetByIdAsync(id);
if (user is null || user.IsDeleted)
{
throw new UserFriendlyException("成员不存在");
}
user.Name = input.FullName.Trim();
user.UserName = input.UserName.Trim();
user.Email = input.Email?.Trim();
user.Phone = input.Phone;
user.State = input.State;
var passwordChanged = false;
if (!string.IsNullOrWhiteSpace(input.Password))
{
UserPasswordHelper.ApplyPlainPassword(user, input.Password);
passwordChanged = true;
}
await _userRepository.UpdateAsync(user);
if (passwordChanged)
{
await UserPasswordHelper.EnsurePasswordColumnsPersistedAsync(
_userRepository,
user.Id,
user.EncryPassword.Password,
user.EncryPassword.Salt);
}
if (input.RoleId != null)
{
await _userManager.GiveUserSetRoleAsync(new List<Guid> { id }, new List<Guid> { input.RoleId.Value });
}
else
{
await _userManager.GiveUserSetRoleAsync(new List<Guid> { id }, new List<Guid>());
}
await UpsertUserLocationsAsync(id, mergedLocationIds);
return await GetAsync(id);
}
/// <inheritdoc />
public async Task DeleteAsync(Guid id)
{
var user = await _userRepository.GetByIdAsync(id);
if (user is null || user.IsDeleted)
{
return;
}
user.IsDeleted = true;
await _userRepository.UpdateAsync(user);
var userIdString = id.ToString();
var currentUserId = CurrentUser?.Id?.ToString();
await _dbContext.SqlSugarClient.Updateable<UserLocationDbEntity>()
.SetColumns(x => new UserLocationDbEntity
{
IsDeleted = true,
LastModificationTime = DateTime.Now,
LastModifierId = currentUserId
})
.Where(x => x.UserId == userIdString && !x.IsDeleted)
.ExecuteCommandAsync();
}
/// <inheritdoc />
public Task<IActionResult> DownloadTeamMemberImportTemplateAsync()
{
var opt = _batchImportOptions.Value;
var dir = opt.TemplateDirectory?.Trim();
if (string.IsNullOrWhiteSpace(dir))
{
throw new UserFriendlyException("未配置批量导入模板目录 FoodLabeling:BatchImport:TemplateDirectory");
}
var fileName = opt.TeamMemberTemplateFileName?.Trim();
if (string.IsNullOrWhiteSpace(fileName))
{
throw new UserFriendlyException("未配置模板文件名 FoodLabeling:BatchImport:TeamMemberTemplateFileName");
}
var fullPath = Path.Combine(dir, fileName);
if (!File.Exists(fullPath))
{
throw new UserFriendlyException($"模板文件不存在:{fullPath}");
}
var stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
return Task.FromResult<IActionResult>(new FileStreamResult(stream, contentType)
{
FileDownloadName = fileName
});
}
/// <inheritdoc />
public async Task<IActionResult> ExportTeamMembersPdfAsync([FromQuery] TeamMemberGetListInputVo input)
{
QuestPDF.Settings.License = LicenseType.Community;
var scopeLocationIds = await LocationScopeBindingHelper.ResolveFilteredLocationIdsForListAsync(
_dbContext.SqlSugarClient, input.PartnerId, input.GroupId, input.LocationId);
var query = await BuildFilteredUserQueryAsync(input, scopeLocationIds);
var users = await query
.OrderByIF(!string.IsNullOrWhiteSpace(input.Sorting), input.Sorting!)
.OrderByDescending(u => u.CreationTime)
.ToListAsync();
var rows = await MapUsersToOutputAsync(
users,
scopeLocationIds,
restrictAssignedLocationsToFilter: scopeLocationIds is not null);
var fileName = $"team-members_{Clock.Now:yyyy-MM-dd_HH-mm-ss}.pdf";
var document = Document.Create(container =>
{
container.Page(page =>
{
page.Margin(22);
page.DefaultTextStyle(x => x.FontSize(8));
page.Header().Text("Team Members").SemiBold().FontSize(16);
page.Content().PaddingTop(8).Table(table =>
{
table.ColumnsDefinition(c =>
{
c.RelativeColumn(1.4f);
c.RelativeColumn(1.6f);
c.RelativeColumn(1.1f);
c.RelativeColumn(1.1f);
c.RelativeColumn(2.2f);
c.RelativeColumn(0.7f);
});
static IContainer CellHeader(IContainer c) =>
c.Background(Colors.Grey.Lighten3).Padding(4).DefaultTextStyle(x => x.SemiBold());
table.Cell().Element(CellHeader).Text("Name");
table.Cell().Element(CellHeader).Text("Email");
table.Cell().Element(CellHeader).Text("Phone");
table.Cell().Element(CellHeader).Text("Role");
table.Cell().Element(CellHeader).Text("Assigned Locations");
table.Cell().Element(CellHeader).Text("Status");
foreach (var e in rows)
{
var locText = e.AssignedLocations.Count == 0
? "无"
: string.Join("; ",
e.AssignedLocations.Select(a =>
$"{a.LocationCode} - {a.LocationName}"));
var status = e.State ? "Active" : "Inactive";
table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
.Text(e.FullName ?? string.Empty);
table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
.Text(e.Email ?? "无");
table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
.Text(e.Phone?.ToString() ?? "无");
table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
.Text(string.IsNullOrWhiteSpace(e.RoleName) ? "无" : e.RoleName);
table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
.Text(locText);
table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
.Text(status);
}
});
});
});
var stream = new MemoryStream();
document.GeneratePdf(stream);
stream.Position = 0;
return new FileStreamResult(stream, "application/pdf") { FileDownloadName = fileName };
}
/// <inheritdoc />
public async Task<TeamMemberBatchImportResultDto> ImportTeamMembersBatchAsync(
[FromForm] TeamMemberBatchImportInputVo input)
{
if (input?.File is null || input.File.Length == 0)
{
throw new UserFriendlyException("请上传 Excel 文件(form 字段名:file)");
}
var opt = _batchImportOptions.Value;
if (input.File.Length > opt.MaxUploadBytes)
{
throw new UserFriendlyException($"文件过大,最大允许 {opt.MaxUploadBytes / 1024 / 1024} MB");
}
var ext = Path.GetExtension(input.File.FileName)?.ToLowerInvariant();
if (ext != ".xlsx")
{
throw new UserFriendlyException("仅支持 .xlsx 格式的 Excel 文件");
}
var roleMap = await BuildRoleNameToIdMapAsync();
await using var uploadStream = input.File.OpenReadStream();
var parseErrors = new List<TeamMemberBatchImportErrorDto>();
var rows = TeamMemberBatchExcelHelper.ParseImportWorkbook(
uploadStream,
opt.MaxImportRows <= 0 ? 5000 : opt.MaxImportRows,
roleMap,
opt.TeamMemberImportDefaultPassword?.Trim() ?? string.Empty,
out var headerErrors);
parseErrors.AddRange(headerErrors);
var result = new TeamMemberBatchImportResultDto();
if (rows.Count == 0 && parseErrors.Count > 0)
{
result.Errors = parseErrors;
result.FailCount = parseErrors.Count;
return result;
}
foreach (var (rowNum, vo) in rows)
{
try
{
vo.LocationIds = await ResolveLocationIdsFromImportTokensAsync(vo.LocationIds);
await CreateAsync(vo);
result.SuccessCount++;
}
catch (UserFriendlyException ex)
{
result.FailCount++;
result.Errors.Add(new TeamMemberBatchImportErrorDto
{
RowNumber = rowNum,
UserName = vo.UserName,
Message = ex.Message
});
}
}
result.Errors.InsertRange(0, parseErrors);
return result;
}
/// <inheritdoc />
public async Task<TeamMemberBulkUpdateResultDto> UpdateTeamMembersBulkAsync(
[FromBody] TeamMemberBulkUpdateInputVo input)
{
if (input?.Items is null || input.Items.Count == 0)
{
throw new UserFriendlyException("请至少提交一条编辑数据(items 不能为空)");
}
var opt = _batchImportOptions.Value;
var maxItems = opt.MaxBulkUpdateItems <= 0 ? 500 : opt.MaxBulkUpdateItems;
if (input.Items.Count > maxItems)
{
throw new UserFriendlyException($"单次批量编辑最多允许 {maxItems} 条,请分批提交");
}
var effectiveCount = input.Items.Count(static x => x is not null && x.Id != Guid.Empty);
if (effectiveCount == 0)
{
throw new UserFriendlyException("没有有效的成员 Id(请为待保存行填写 id)");
}
var result = new TeamMemberBulkUpdateResultDto();
for (var i = 0; i < input.Items.Count; i++)
{
var item = input.Items[i];
if (item is null || item.Id == Guid.Empty)
{
continue;
}
try
{
await UpdateAsync(item.Id, item);
result.SuccessCount++;
}
catch (UserFriendlyException ex)
{
result.FailCount++;
result.Errors.Add(new TeamMemberBulkUpdateErrorDto
{
RowNumber = i + 1,
Id = item.Id,
Message = ex.Message
});
}
}
return result;
}
private async Task<Dictionary<string, Guid>> BuildRoleNameToIdMapAsync()
{
var roles = await _dbContext.SqlSugarClient.Queryable<RoleAggregateRoot>()
.Where(r => !r.IsDeleted)
.Select(r => new { r.Id, r.RoleName })
.ToListAsync();
return roles
.Where(r => !string.IsNullOrWhiteSpace(r.RoleName))
.GroupBy(r => TeamMemberBatchExcelHelper.NormalizeRoleKey(r.RoleName!))
.ToDictionary(g => g.Key, g => g.First().Id);
}
private async Task<List<string>> ResolveLocationIdsFromImportTokensAsync(List<string> tokens)
{
var result = new List<string>();
foreach (var raw in tokens)
{
var s = raw.Trim();
if (string.IsNullOrEmpty(s))
{
continue;
}
var idx = s.IndexOf(" -", StringComparison.Ordinal);
var key = idx > 0 ? s[..idx].Trim() : s.Trim();
if (Guid.TryParse(key, out var gid))
{
var byId = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
.Where(x => !x.IsDeleted && x.Id == gid)
.FirstAsync();
if (byId is null)
{
throw new UserFriendlyException($"无效门店 Id:{key}");
}
result.Add(byId.Id.ToString());
continue;
}
var byCode = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
.Where(x => !x.IsDeleted && x.LocationCode == key)
.FirstAsync();
if (byCode is null)
{
throw new UserFriendlyException($"未找到门店编码:{key}");
}
result.Add(byCode.Id.ToString());
}
return result.Distinct().ToList();
}
private async Task<ISugarQueryable<UserAggregateRoot>> BuildFilteredUserQueryAsync(
TeamMemberGetListInputVo input,
List<string>? scopeLocationIds)
{
var keyword = input.Keyword?.Trim();
var query = _userRepository._DbQueryable
.Where(u => !u.IsDeleted)
.WhereIF(!string.IsNullOrWhiteSpace(keyword),
u => (u.Name != null && u.Name.Contains(keyword!)) ||
u.UserName.Contains(keyword!) ||
(u.Email != null && u.Email.Contains(keyword!)) ||
(u.Phone != null && u.Phone.ToString()!.Contains(keyword!)))
.WhereIF(input.State != null, u => u.State == input.State);
if (input.RoleId != null)
{
var userIds = await _dbContext.SqlSugarClient.Queryable<UserRoleEntity>()
.Where(ur => ur.RoleId == input.RoleId.Value)
.Select(ur => ur.UserId)
.ToListAsync();
query = query.Where(u => userIds.Contains(u.Id));
}
if (scopeLocationIds is not null)
{
if (scopeLocationIds.Count == 0)
{
query = query.Where(_ => false);
}
else
{
var scopeSet = new HashSet<string>(scopeLocationIds, StringComparer.Ordinal);
var userIdStrs = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
.Where(x => !x.IsDeleted && scopeSet.Contains(x.LocationId))
.Select(x => x.UserId)
.ToListAsync();
var allowed = new HashSet<string>(userIdStrs);
query = query.Where(u => allowed.Contains(u.Id.ToString()));
}
}
return query;
}
private async Task<List<TeamMemberGetListOutputDto>> MapUsersToOutputAsync(
List<UserAggregateRoot> users,
List<string>? scopeLocationIds,
bool restrictAssignedLocationsToFilter)
{
if (users.Count == 0)
{
return new List<TeamMemberGetListOutputDto>();
}
var userIds = users.Select(x => x.Id).ToList();
var userIdStrings = userIds.Select(x => x.ToString()).ToList();
var userRolePairs = await _dbContext.SqlSugarClient.Queryable<UserRoleEntity, RoleAggregateRoot>((ur, r) => ur.RoleId == r.Id)
.Where(ur => userIds.Contains(ur.UserId))
.Select((ur, r) => new { ur.UserId, r.Id, r.RoleName })
.ToListAsync();
var roleMap = userRolePairs
.GroupBy(x => x.UserId)
.ToDictionary(g => g.Key, g => g.FirstOrDefault());
var userLocQuery = _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
.Where(x => !x.IsDeleted)
.Where(x => userIdStrings.Contains(x.UserId));
if (restrictAssignedLocationsToFilter && scopeLocationIds is { Count: > 0 })
{
var scopeSet = new HashSet<string>(scopeLocationIds, StringComparer.Ordinal);
userLocQuery = userLocQuery.Where(x => scopeSet.Contains(x.LocationId));
}
var userLocations = await userLocQuery.ToListAsync();
var locationIds = userLocations.Select(x => x.LocationId).Distinct().ToList();
var locations = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
.Where(x => !x.IsDeleted)
.WhereIF(locationIds.Count > 0, x => locationIds.Contains(x.Id.ToString()))
.Select(x => new { x.Id, x.LocationCode, x.LocationName })
.ToListAsync();
var locationMap = locations.ToDictionary(x => x.Id.ToString(), x => x);
var assignedMap = userLocations
.GroupBy(x => x.UserId)
.ToDictionary(
g => g.Key,
g => g.Select(x =>
{
if (locationMap.TryGetValue(x.LocationId, out var loc))
{
return new TeamMemberAssignedLocationDto
{
Id = loc.Id.ToString(),
LocationCode = loc.LocationCode,
LocationName = loc.LocationName
};
}
return null;
}).Where(x => x != null).Cast<TeamMemberAssignedLocationDto>().ToList());
var scopeIdsMap = await BuildTeamMemberScopeIdsMapAsync(assignedMap);
return users.Select(u =>
{
roleMap.TryGetValue(u.Id, out var role);
assignedMap.TryGetValue(u.Id.ToString(), out var assigned);
scopeIdsMap.TryGetValue(u.Id.ToString(), out var scopeIds);
return new TeamMemberGetListOutputDto
{
Id = u.Id,
FullName = u.Name ?? string.Empty,
UserName = u.UserName,
Email = u.Email,
Phone = u.Phone,
State = u.State,
RoleId = role?.Id,
RoleName = role?.RoleName,
PartnerIds = scopeIds?.PartnerIds ?? new List<string>(),
RegionIds = scopeIds?.RegionIds ?? new List<string>(),
AssignedLocations = assigned ?? new List<TeamMemberAssignedLocationDto>()
};
}).ToList();
}
private async Task<Dictionary<string, TeamMemberScopeIds>> BuildTeamMemberScopeIdsMapAsync(
Dictionary<string, List<TeamMemberAssignedLocationDto>> assignedMap)
{
var result = new Dictionary<string, TeamMemberScopeIds>(StringComparer.Ordinal);
foreach (var (userId, assigned) in assignedMap)
{
var locationIds = assigned
.Select(x => x.Id)
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.Distinct(StringComparer.Ordinal)
.ToList();
if (locationIds.Count == 0)
{
result[userId] = new TeamMemberScopeIds();
continue;
}
var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
_dbContext.SqlSugarClient, locationIds);
var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
_dbContext.SqlSugarClient, locationIds);
result[userId] = new TeamMemberScopeIds
{
PartnerIds = partnerIds,
RegionIds = regionIds
};
}
return result;
}
private sealed class TeamMemberScopeIds
{
public List<string> PartnerIds { get; init; } = new();
public List<string> RegionIds { get; init; } = new();
}
private Task<List<string>> ResolveTeamMemberLocationIdsForSaveAsync(TeamMemberUpdateInputVo input) =>
ResolveTeamMemberLocationIdsForSaveAsync(new TeamMemberCreateInputVo
{
PartnerId = input.PartnerId,
PartnerIds = input.PartnerIds,
RegionIds = input.RegionIds,
GroupIds = input.GroupIds,
LocationIds = input.LocationIds
});
private async Task<List<string>> ResolveTeamMemberLocationIdsForSaveAsync(TeamMemberCreateInputVo input)
{
var partnerIds = NormalizePartnerIds(input);
var regionIds = NormalizeRegionIds(input);
var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
_dbContext.SqlSugarClient, partnerIds, regionIds, input.LocationIds);
if (merged.Count == 0)
{
throw new UserFriendlyException("成员必须至少分配一个门店(公司/区域/门店至少选一项)");
}
await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(_dbContext.SqlSugarClient, merged);
return merged;
}
private static List<string> NormalizePartnerIds(TeamMemberCreateInputVo input)
{
var merged = new HashSet<string>(StringComparer.Ordinal);
if (!string.IsNullOrWhiteSpace(input.PartnerId))
{
merged.Add(input.PartnerId.Trim());
}
foreach (var id in LocationScopeBindingHelper.NormalizeIds(input.PartnerIds))
{
merged.Add(id);
}
return merged.OrderBy(x => x, StringComparer.Ordinal).ToList();
}
private static List<string> NormalizeRegionIds(TeamMemberCreateInputVo 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();
}
private async Task UpsertUserLocationsAsync(Guid userId, List<string> locationIds)
{
var now = DateTime.Now;
var userIdString = userId.ToString();
var wanted = locationIds.Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim()).Distinct().ToList();
var currentUserId = CurrentUser?.Id?.ToString();
var validCount = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
.Where(x => !x.IsDeleted)
.Where(x => wanted.Contains(x.Id.ToString()))
.CountAsync();
if (validCount != wanted.Count)
{
throw new UserFriendlyException("存在无效门店,请刷新后重试");
}
var existing = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
.Where(x => x.UserId == userIdString)
.ToListAsync();
var existingActive = existing.Where(x => !x.IsDeleted).ToList();
var existingActiveSet = existingActive.Select(x => x.LocationId).ToHashSet();
var toDelete = existingActive.Where(x => !wanted.Contains(x.LocationId)).ToList();
if (toDelete.Count > 0)
{
var ids = toDelete.Select(x => x.Id).ToList();
await _dbContext.SqlSugarClient.Updateable<UserLocationDbEntity>()
.SetColumns(x => new UserLocationDbEntity
{
IsDeleted = true,
LastModificationTime = now,
LastModifierId = currentUserId
})
.Where(x => ids.Contains(x.Id))
.ExecuteCommandAsync();
}
var toInsert = wanted.Where(x => !existingActiveSet.Contains(x)).ToList();
if (toInsert.Count > 0)
{
var rows = toInsert.Select(locationId => new UserLocationDbEntity
{
Id = _guidGenerator.Create().ToString(),
IsDeleted = false,
CreationTime = now,
CreatorId = currentUserId,
UserId = userIdString,
LocationId = locationId,
ConcurrencyStamp = string.Empty
}).ToList();
await _dbContext.SqlSugarClient.Insertable(rows).ExecuteCommandAsync();
}
}
}