Blame view

美国版/Food Labeling Management Code/Yi.Abp.Net8/module/food-labeling-us/FoodLabeling.Application/Services/TeamMemberAppService.cs 40 KB
a7684ddb   李曜臣   批量导入导出,批量编辑
1
  using System.IO;
dbc9750f   李曜臣   成员模块实现
2
3
4
  using FoodLabeling.Application.Contracts.Dtos.Common;
  using FoodLabeling.Application.Contracts.Dtos.TeamMember;
  using FoodLabeling.Application.Contracts.IServices;
a7684ddb   李曜臣   批量导入导出,批量编辑
5
6
  using FoodLabeling.Application.Helpers;
  using FoodLabeling.Application.Options;
dbc9750f   李曜臣   成员模块实现
7
8
  using FoodLabeling.Application.Services.DbModels;
  using FoodLabeling.Domain.Entities;
a7684ddb   李曜臣   批量导入导出,批量编辑
9
10
11
12
13
  using Microsoft.AspNetCore.Mvc;
  using Microsoft.Extensions.Options;
  using QuestPDF.Fluent;
  using QuestPDF.Helpers;
  using QuestPDF.Infrastructure;
dbc9750f   李曜臣   成员模块实现
14
15
16
17
18
19
  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;
07d5dea2   李曜臣   5-18代码优化
20
21
  using Yi.Framework.Rbac.Domain.Entities.ValueObjects;
  using Yi.Framework.Rbac.Domain.Helpers;
dbc9750f   李曜臣   成员模块实现
22
23
24
25
26
27
  using Yi.Framework.Rbac.Domain.Managers;
  using Yi.Framework.SqlSugarCore.Abstractions;
  
  namespace FoodLabeling.Application.Services;
  
  /// <summary>
a7684ddb   李曜臣   批量导入导出,批量编辑
28
  /// 成员(Team Member)服务,对外仅在 food-labeling-us 暴露
dbc9750f   李曜臣   成员模块实现
29
30
31
32
33
34
35
  /// </summary>
  public class TeamMemberAppService : ApplicationService, ITeamMemberAppService
  {
      private readonly ISqlSugarRepository<UserAggregateRoot, Guid> _userRepository;
      private readonly UserManager _userManager;
      private readonly ISqlSugarDbContext _dbContext;
      private readonly IGuidGenerator _guidGenerator;
a7684ddb   李曜臣   批量导入导出,批量编辑
36
      private readonly IOptionsSnapshot<FoodLabelingBatchImportOptions> _batchImportOptions;
dbc9750f   李曜臣   成员模块实现
37
38
39
40
41
  
      public TeamMemberAppService(
          ISqlSugarRepository<UserAggregateRoot, Guid> userRepository,
          UserManager userManager,
          ISqlSugarDbContext dbContext,
a7684ddb   李曜臣   批量导入导出,批量编辑
42
43
          IGuidGenerator guidGenerator,
          IOptionsSnapshot<FoodLabelingBatchImportOptions> batchImportOptions)
dbc9750f   李曜臣   成员模块实现
44
45
46
47
48
      {
          _userRepository = userRepository;
          _userManager = userManager;
          _dbContext = dbContext;
          _guidGenerator = guidGenerator;
a7684ddb   李曜臣   批量导入导出,批量编辑
49
          _batchImportOptions = batchImportOptions;
dbc9750f   李曜臣   成员模块实现
50
51
      }
  
a7684ddb   李曜臣   批量导入导出,批量编辑
52
      /// <inheritdoc />
dbc9750f   李曜臣   成员模块实现
53
54
      public async Task<PagedResultWithPageDto<TeamMemberGetListOutputDto>> GetListAsync(TeamMemberGetListInputVo input)
      {
143afd59   杨鑫   打印,标签
55
          var pageIndex = PagedQueryConvention.PageIndexFromSkipCount(input.SkipCount);
dbc9750f   李曜臣   成员模块实现
56
          var pageSize = input.MaxResultCount;
dbc9750f   李曜臣   成员模块实现
57
58
          RefAsync<int> total = 0;
  
49755ef0   李曜臣   6-12代码优化
59
60
61
62
63
64
          var scopeLocationIds = await TeamMemberListScopeHelper.ResolveListLocationIdsAsync(
              CurrentUser,
              _dbContext,
              input.PartnerId,
              input.GroupId,
              input.LocationId);
07d5dea2   李曜臣   5-18代码优化
65
66
  
          var query = await BuildFilteredUserQueryAsync(input, scopeLocationIds);
a7684ddb   李曜臣   批量导入导出,批量编辑
67
          var users = await query
dbc9750f   李曜臣   成员模块实现
68
69
70
71
              .OrderByIF(!string.IsNullOrWhiteSpace(input.Sorting), input.Sorting!)
              .OrderByDescending(u => u.CreationTime)
              .ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
  
a7684ddb   李曜臣   批量导入导出,批量编辑
72
73
          var items = await MapUsersToOutputAsync(
              users,
07d5dea2   李曜臣   5-18代码优化
74
75
              scopeLocationIds,
              restrictAssignedLocationsToFilter: scopeLocationIds is not null);
dbc9750f   李曜臣   成员模块实现
76
77
78
79
80
81
82
83
84
85
86
87
  
          var totalCount = (long)total;
          return new PagedResultWithPageDto<TeamMemberGetListOutputDto>
          {
              PageIndex = pageIndex,
              PageSize = pageSize,
              TotalCount = totalCount,
              TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
              Items = items
          };
      }
  
a7684ddb   李曜臣   批量导入导出,批量编辑
88
      /// <inheritdoc />
dbc9750f   李曜臣   成员模块实现
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
      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);
  
10fd1324   李曜臣   5-17接口优化
118
119
120
121
122
          var partnerIds = await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
              _dbContext.SqlSugarClient, locationIds);
          var regionIds = await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
              _dbContext.SqlSugarClient, locationIds);
  
14afbc16   李曜臣   2026-6-22
123
124
125
126
127
128
129
130
          if (await TeamMemberRoleHelper.IsCompanyAdminRoleAsync(_dbContext.SqlSugarClient, role?.RoleId) &&
              partnerIds.Count > 0)
          {
              (regionIds, assigned) = await ApplyCompanyAdminDisplayScopeAsync(
                  role?.RoleId, partnerIds, regionIds, assigned);
              locationIds = assigned.Select(x => x.Id).ToList();
          }
  
dbc9750f   李曜臣   成员模块实现
131
132
133
134
135
136
137
138
139
          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,
10fd1324   李曜臣   5-17接口优化
140
141
142
              PartnerIds = partnerIds,
              RegionIds = regionIds,
              GroupIds = regionIds,
dbc9750f   李曜臣   成员模块实现
143
144
145
146
147
              LocationIds = locationIds,
              AssignedLocations = assigned
          };
      }
  
a7684ddb   李曜臣   批量导入导出,批量编辑
148
      /// <inheritdoc />
dbc9750f   李曜臣   成员模块实现
149
150
      public async Task<TeamMemberGetOutputDto> CreateAsync(TeamMemberCreateInputVo input)
      {
14afbc16   李曜臣   2026-6-22
151
          var mergedLocationIds = await ResolveTeamMemberLocationIdsForSaveAsync(input, input.RoleId);
dbc9750f   李曜臣   成员模块实现
152
  
07d5dea2   李曜臣   5-18代码优化
153
          var user = new UserAggregateRoot
dbc9750f   李曜臣   成员模块实现
154
          {
07d5dea2   李曜臣   5-18代码优化
155
              UserName = input.UserName.Trim(),
dbc9750f   李曜臣   成员模块实现
156
              Name = input.FullName.Trim(),
07d5dea2   李曜臣   5-18代码优化
157
              Nick = input.FullName.Trim(),
dbc9750f   李曜臣   成员模块实现
158
              Email = input.Email?.Trim(),
07d5dea2   李曜臣   5-18代码优化
159
160
161
              Phone = input.Phone,
              State = input.State,
              EncryPassword = new EncryPasswordValueObject(input.Password.Trim())
dbc9750f   李曜臣   成员模块实现
162
163
164
165
166
167
168
169
170
171
172
173
          };
  
          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 });
          }
  
10fd1324   李曜臣   5-17接口优化
174
          await UpsertUserLocationsAsync(user.Id, mergedLocationIds);
dbc9750f   李曜臣   成员模块实现
175
176
177
178
  
          return await GetAsync(user.Id);
      }
  
a7684ddb   李曜臣   批量导入导出,批量编辑
179
      /// <inheritdoc />
dbc9750f   李曜臣   成员模块实现
180
181
      public async Task<TeamMemberGetOutputDto> UpdateAsync(Guid id, TeamMemberUpdateInputVo input)
      {
10fd1324   李曜臣   5-17接口优化
182
          var mergedLocationIds = await ResolveTeamMemberLocationIdsForSaveAsync(input);
dbc9750f   李曜臣   成员模块实现
183
184
185
186
187
188
189
190
191
192
193
194
195
  
          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;
  
07d5dea2   李曜臣   5-18代码优化
196
          var passwordChanged = false;
dbc9750f   李曜臣   成员模块实现
197
198
          if (!string.IsNullOrWhiteSpace(input.Password))
          {
07d5dea2   李曜臣   5-18代码优化
199
200
              UserPasswordHelper.ApplyPlainPassword(user, input.Password);
              passwordChanged = true;
dbc9750f   李曜臣   成员模块实现
201
202
203
          }
  
          await _userRepository.UpdateAsync(user);
07d5dea2   李曜臣   5-18代码优化
204
205
206
207
208
209
210
211
          if (passwordChanged)
          {
              await UserPasswordHelper.EnsurePasswordColumnsPersistedAsync(
                  _userRepository,
                  user.Id,
                  user.EncryPassword.Password,
                  user.EncryPassword.Salt);
          }
dbc9750f   李曜臣   成员模块实现
212
  
dbc9750f   李曜臣   成员模块实现
213
214
215
216
217
218
219
220
221
          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>());
          }
  
10fd1324   李曜臣   5-17接口优化
222
          await UpsertUserLocationsAsync(id, mergedLocationIds);
dbc9750f   李曜臣   成员模块实现
223
224
225
226
  
          return await GetAsync(id);
      }
  
a7684ddb   李曜臣   批量导入导出,批量编辑
227
      /// <inheritdoc />
dbc9750f   李曜臣   成员模块实现
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
      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();
      }
  
a7684ddb   李曜臣   批量导入导出,批量编辑
252
253
254
255
      /// <inheritdoc />
      public Task<IActionResult> DownloadTeamMemberImportTemplateAsync()
      {
          var opt = _batchImportOptions.Value;
a7684ddb   李曜臣   批量导入导出,批量编辑
256
257
258
          var fileName = opt.TeamMemberTemplateFileName?.Trim();
          if (string.IsNullOrWhiteSpace(fileName))
          {
14afbc16   李曜臣   2026-6-22
259
              fileName = "Team-Member-批量导入模板.xlsx";
a7684ddb   李曜臣   批量导入导出,批量编辑
260
261
          }
  
14afbc16   李曜臣   2026-6-22
262
          var stream = TeamMemberBatchExcelHelper.BuildImportTemplateWorkbook();
a7684ddb   李曜臣   批量导入导出,批量编辑
263
264
265
266
267
268
269
270
271
272
273
274
          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;
  
49755ef0   李曜臣   6-12代码优化
275
276
277
278
279
280
          var scopeLocationIds = await TeamMemberListScopeHelper.ResolveListLocationIdsAsync(
              CurrentUser,
              _dbContext,
              input.PartnerId,
              input.GroupId,
              input.LocationId);
07d5dea2   李曜臣   5-18代码优化
281
282
  
          var query = await BuildFilteredUserQueryAsync(input, scopeLocationIds);
a7684ddb   李曜臣   批量导入导出,批量编辑
283
284
285
286
287
          var users = await query
              .OrderByIF(!string.IsNullOrWhiteSpace(input.Sorting), input.Sorting!)
              .OrderByDescending(u => u.CreationTime)
              .ToListAsync();
  
07d5dea2   李曜臣   5-18代码优化
288
289
290
291
          var rows = await MapUsersToOutputAsync(
              users,
              scopeLocationIds,
              restrictAssignedLocationsToFilter: scopeLocationIds is not null);
a7684ddb   李曜臣   批量导入导出,批量编辑
292
  
14afbc16   李曜臣   2026-6-22
293
294
295
          var regionNameMap = await LoadRegionNameMapAsync(
              rows.SelectMany(r => r.RegionIds).Distinct(StringComparer.Ordinal));
  
a7684ddb   李曜臣   批量导入导出,批量编辑
296
297
298
299
300
301
302
303
304
305
306
307
          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 =>
                      {
14afbc16   李曜臣   2026-6-22
308
309
310
311
                          c.RelativeColumn(1.3f);
                          c.RelativeColumn(1.5f);
                          c.RelativeColumn(1.0f);
                          c.RelativeColumn(1.0f);
a7684ddb   李曜臣   批量导入导出,批量编辑
312
                          c.RelativeColumn(1.4f);
14afbc16   李曜臣   2026-6-22
313
                          c.RelativeColumn(2.0f);
a7684ddb   李曜臣   批量导入导出,批量编辑
314
315
316
317
318
319
320
321
322
323
                          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");
14afbc16   李曜臣   2026-6-22
324
                      table.Cell().Element(CellHeader).Text("Region");
a7684ddb   李曜臣   批量导入导出,批量编辑
325
326
327
328
329
                      table.Cell().Element(CellHeader).Text("Assigned Locations");
                      table.Cell().Element(CellHeader).Text("Status");
  
                      foreach (var e in rows)
                      {
14afbc16   李曜臣   2026-6-22
330
331
332
333
334
335
336
                          var regionText = e.RegionIds.Count == 0
                              ? "无"
                              : string.Join("; ",
                                  e.RegionIds.Select(id =>
                                      regionNameMap.TryGetValue(id, out var name) && !string.IsNullOrWhiteSpace(name)
                                          ? name
                                          : id));
a7684ddb   李曜臣   批量导入导出,批量编辑
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
                          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)
14afbc16   李曜臣   2026-6-22
352
353
                              .Text(regionText);
                          table.Cell().BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2).Padding(3)
a7684ddb   李曜臣   批量导入导出,批量编辑
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
                              .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
              {
14afbc16   李曜臣   2026-6-22
412
413
414
415
416
417
418
419
420
421
                  if (vo.RegionIds is { Count: > 0 })
                  {
                      vo.RegionIds = await ResolveRegionIdsFromImportTokensAsync(vo.RegionIds);
                  }
  
                  if (vo.LocationIds is { Count: > 0 })
                  {
                      vo.LocationIds = await ResolveLocationIdsFromImportTokensAsync(vo.LocationIds);
                  }
  
a7684ddb   李曜臣   批量导入导出,批量编辑
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
                  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)
              {
14afbc16   李曜臣   2026-6-22
537
                  throw new UserFriendlyException($"未找到门店 LocationCode:{key}(亦可填 location.Id Guid)");
a7684ddb   李曜臣   批量导入导出,批量编辑
538
539
540
541
542
543
544
545
              }
  
              result.Add(byCode.Id.ToString());
          }
  
          return result.Distinct().ToList();
      }
  
14afbc16   李曜臣   2026-6-22
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
      private async Task<List<string>> ResolveRegionIdsFromImportTokensAsync(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 byId = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
                      .Where(x => !x.IsDeleted && x.Id == key)
                      .FirstAsync();
                  if (byId is null)
                  {
                      throw new UserFriendlyException($"无效 Region Id:{key}");
                  }
  
                  result.Add(byId.Id.Trim());
                  continue;
              }
  
              var matches = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
                  .Where(x => !x.IsDeleted)
                  .ToListAsync();
              matches = matches
                  .Where(x => string.Equals(x.GroupName?.Trim(), key, StringComparison.OrdinalIgnoreCase))
                  .ToList();
  
              if (matches.Count == 0)
              {
                  throw new UserFriendlyException($"未找到 Region:{key}(可填 fl_group.Id 或 GroupName)");
              }
  
              if (matches.Count > 1)
              {
                  throw new UserFriendlyException(
                      $"Region 名称「{key}」存在多条记录,请改用 fl_group.Id(Guid)");
              }
  
              result.Add(matches[0].Id.Trim());
          }
  
          return result.Distinct(StringComparer.Ordinal).ToList();
      }
  
      private async Task<Dictionary<string, string>> LoadRegionNameMapAsync(IEnumerable<string> regionIds)
      {
          var ids = regionIds
              .Where(x => !string.IsNullOrWhiteSpace(x))
              .Select(x => x.Trim())
              .Distinct(StringComparer.Ordinal)
              .ToList();
          if (ids.Count == 0)
          {
              return new Dictionary<string, string>(StringComparer.Ordinal);
          }
  
          var groups = await _dbContext.SqlSugarClient.Queryable<FlGroupDbEntity>()
              .Where(x => !x.IsDeleted && ids.Contains(x.Id))
              .Select(x => new { x.Id, x.GroupName })
              .ToListAsync();
  
          return groups
              .Where(x => !string.IsNullOrWhiteSpace(x.Id))
              .ToDictionary(
                  x => x.Id.Trim(),
                  x => x.GroupName?.Trim() ?? x.Id.Trim(),
                  StringComparer.Ordinal);
      }
  
07d5dea2   李曜臣   5-18代码优化
623
624
625
      private async Task<ISugarQueryable<UserAggregateRoot>> BuildFilteredUserQueryAsync(
          TeamMemberGetListInputVo input,
          List<string>? scopeLocationIds)
a7684ddb   李曜臣   批量导入导出,批量编辑
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
      {
          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));
          }
  
07d5dea2   李曜臣   5-18代码优化
646
          if (scopeLocationIds is not null)
a7684ddb   李曜臣   批量导入导出,批量编辑
647
          {
07d5dea2   李曜臣   5-18代码优化
648
649
650
651
652
653
              if (scopeLocationIds.Count == 0)
              {
                  query = query.Where(_ => false);
              }
              else
              {
14afbc16   李曜臣   2026-6-22
654
655
656
657
                  var scopeGuidSet = TeamMemberListScopeHelper.ParseGuidHashSet(scopeLocationIds);
                  var userLocationLinks = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
                      .Where(x => !x.IsDeleted)
                      .Select(x => new { x.UserId, x.LocationId })
07d5dea2   李曜臣   5-18代码优化
658
                      .ToListAsync();
14afbc16   李曜臣   2026-6-22
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
  
                  var allowedUserGuids = userLocationLinks
                      .Where(x =>
                          Guid.TryParse(x.LocationId, out var locGuid) && scopeGuidSet.Contains(locGuid))
                      .Select(x => x.UserId)
                      .Select(TeamMemberListScopeHelper.NormalizeScopeKey)
                      .Where(x => !string.IsNullOrEmpty(x))
                      .Select(x => Guid.Parse(x))
                      .Distinct()
                      .ToList();
  
                  if (allowedUserGuids.Count == 0)
                  {
                      query = query.Where(_ => false);
                  }
                  else
                  {
                      query = query.Where(u => allowedUserGuids.Contains(u.Id));
                  }
07d5dea2   李曜臣   5-18代码优化
678
              }
a7684ddb   李曜臣   批量导入导出,批量编辑
679
680
681
682
683
684
685
          }
  
          return query;
      }
  
      private async Task<List<TeamMemberGetListOutputDto>> MapUsersToOutputAsync(
          List<UserAggregateRoot> users,
07d5dea2   李曜臣   5-18代码优化
686
          List<string>? scopeLocationIds,
a7684ddb   李曜臣   批量导入导出,批量编辑
687
688
689
690
691
692
693
694
          bool restrictAssignedLocationsToFilter)
      {
          if (users.Count == 0)
          {
              return new List<TeamMemberGetListOutputDto>();
          }
  
          var userIds = users.Select(x => x.Id).ToList();
14afbc16   李曜臣   2026-6-22
695
          var userGuidKeys = userIds.Select(TeamMemberListScopeHelper.UserKey).ToHashSet(StringComparer.Ordinal);
a7684ddb   李曜臣   批量导入导出,批量编辑
696
697
698
699
700
701
  
          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();
  
14afbc16   李曜臣   2026-6-22
702
          var roleIdByUser = userRolePairs
a7684ddb   李曜臣   批量导入导出,批量编辑
703
              .GroupBy(x => x.UserId)
14afbc16   李曜臣   2026-6-22
704
              .ToDictionary(g => g.Key, g => (Guid?)g.First().Id);
a7684ddb   李曜臣   批量导入导出,批量编辑
705
  
14afbc16   李曜臣   2026-6-22
706
          var allUserLocations = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
a7684ddb   李曜臣   批量导入导出,批量编辑
707
              .Where(x => !x.IsDeleted)
14afbc16   李曜臣   2026-6-22
708
709
710
711
712
713
              .Select(x => new { x.UserId, x.LocationId })
              .ToListAsync();
  
          var scopeGuidSet = scopeLocationIds is { Count: > 0 }
              ? TeamMemberListScopeHelper.ParseGuidHashSet(scopeLocationIds)
              : null;
a7684ddb   李曜臣   批量导入导出,批量编辑
714
  
14afbc16   李曜臣   2026-6-22
715
716
717
718
719
720
          var userLocations = allUserLocations
              .Where(x => userGuidKeys.Contains(TeamMemberListScopeHelper.NormalizeScopeKey(x.UserId)))
              .Where(x =>
                  scopeGuidSet is null ||
                  (Guid.TryParse(x.LocationId, out var locGuid) && scopeGuidSet.Contains(locGuid)))
              .ToList();
a7684ddb   李曜臣   批量导入导出,批量编辑
721
722
  
          var locationIds = userLocations.Select(x => x.LocationId).Distinct().ToList();
14afbc16   李曜臣   2026-6-22
723
          var locationGuidList = TeamMemberListScopeHelper.ParseGuidList(locationIds);
a7684ddb   李曜臣   批量导入导出,批量编辑
724
725
          var locations = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
              .Where(x => !x.IsDeleted)
14afbc16   李曜臣   2026-6-22
726
              .WhereIF(locationGuidList.Count > 0, x => locationGuidList.Contains(x.Id))
a7684ddb   李曜臣   批量导入导出,批量编辑
727
728
              .Select(x => new { x.Id, x.LocationCode, x.LocationName })
              .ToListAsync();
14afbc16   李曜臣   2026-6-22
729
730
731
          var locationMap = locations.ToDictionary(
              x => TeamMemberListScopeHelper.UserKey(x.Id),
              x => x);
a7684ddb   李曜臣   批量导入导出,批量编辑
732
733
  
          var assignedMap = userLocations
14afbc16   李曜臣   2026-6-22
734
              .GroupBy(x => TeamMemberListScopeHelper.NormalizeScopeKey(x.UserId))
a7684ddb   李曜臣   批量导入导出,批量编辑
735
736
737
738
              .ToDictionary(
                  g => g.Key,
                  g => g.Select(x =>
                  {
14afbc16   李曜臣   2026-6-22
739
740
741
742
743
744
745
746
747
748
749
750
                      var locKey = TeamMemberListScopeHelper.NormalizeScopeKey(x.LocationId);
                      if (locationMap.TryGetValue(locKey, out var loc))
                      {
                          return new TeamMemberAssignedLocationDto
                          {
                              Id = loc.Id.ToString(),
                              LocationCode = loc.LocationCode,
                              LocationName = loc.LocationName
                          };
                      }
  
                      if (locationMap.TryGetValue(x.LocationId, out loc))
a7684ddb   李曜臣   批量导入导出,批量编辑
751
752
753
754
755
756
757
758
759
760
761
762
                      {
                          return new TeamMemberAssignedLocationDto
                          {
                              Id = loc.Id.ToString(),
                              LocationCode = loc.LocationCode,
                              LocationName = loc.LocationName
                          };
                      }
  
                      return null;
                  }).Where(x => x != null).Cast<TeamMemberAssignedLocationDto>().ToList());
  
14afbc16   李曜臣   2026-6-22
763
          var scopeIdsMap = await BuildTeamMemberScopeIdsMapAsync(assignedMap, roleIdByUser);
10fd1324   李曜臣   5-17接口优化
764
  
14afbc16   李曜臣   2026-6-22
765
766
          var items = new List<TeamMemberGetListOutputDto>();
          foreach (var u in users)
a7684ddb   李曜臣   批量导入导出,批量编辑
767
          {
14afbc16   李曜臣   2026-6-22
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
              roleIdByUser.TryGetValue(u.Id, out var listRoleId);
              var roleName = userRolePairs.FirstOrDefault(x => x.UserId == u.Id)?.RoleName;
              var userKey = TeamMemberListScopeHelper.UserKey(u.Id);
              assignedMap.TryGetValue(userKey, out var assigned);
              scopeIdsMap.TryGetValue(userKey, out var scopeIds);
  
              var partnerIds = scopeIds?.PartnerIds ?? new List<string>();
              var regionIds = scopeIds?.RegionIds ?? new List<string>();
              var assignedLocations = assigned ?? new List<TeamMemberAssignedLocationDto>();
  
              (regionIds, assignedLocations) = await ApplyCompanyAdminDisplayScopeAsync(
                  listRoleId, partnerIds, regionIds, assignedLocations);
  
              var locationIdList = assignedLocations
                  .Select(x => x.Id)
                  .Where(x => !string.IsNullOrWhiteSpace(x))
                  .Distinct(StringComparer.OrdinalIgnoreCase)
                  .ToList();
a7684ddb   李曜臣   批量导入导出,批量编辑
786
  
14afbc16   李曜臣   2026-6-22
787
              items.Add(new TeamMemberGetListOutputDto
a7684ddb   李曜臣   批量导入导出,批量编辑
788
789
790
791
792
793
794
              {
                  Id = u.Id,
                  FullName = u.Name ?? string.Empty,
                  UserName = u.UserName,
                  Email = u.Email,
                  Phone = u.Phone,
                  State = u.State,
14afbc16   李曜臣   2026-6-22
795
796
797
798
799
800
801
802
803
804
                  RoleId = listRoleId,
                  RoleName = TeamMemberRoleHelper.FormatDisplayRoleName(roleName),
                  PartnerIds = partnerIds,
                  RegionIds = regionIds,
                  LocationIds = locationIdList,
                  AssignedLocations = assignedLocations
              });
          }
  
          return items;
a7684ddb   李曜臣   批量导入导出,批量编辑
805
806
      }
  
10fd1324   李曜臣   5-17接口优化
807
      private async Task<Dictionary<string, TeamMemberScopeIds>> BuildTeamMemberScopeIdsMapAsync(
14afbc16   李曜臣   2026-6-22
808
809
          Dictionary<string, List<TeamMemberAssignedLocationDto>> assignedMap,
          Dictionary<Guid, Guid?> roleIdByUser)
10fd1324   李曜臣   5-17接口优化
810
811
812
813
814
815
816
817
818
819
      {
          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();
14afbc16   李曜臣   2026-6-22
820
821
822
823
824
825
826
827
828
829
830
831
832
833
  
              var partnerIds = locationIds.Count == 0
                  ? new List<string>()
                  : await LocationScopeBindingHelper.ResolvePartnerIdsFromLocationIdsAsync(
                      _dbContext.SqlSugarClient, locationIds);
              var regionIds = locationIds.Count == 0
                  ? new List<string>()
                  : await LocationScopeBindingHelper.ResolveGroupIdsFromLocationIdsAsync(
                      _dbContext.SqlSugarClient, locationIds);
  
              if (Guid.TryParse(userId, out var userGuid) &&
                  roleIdByUser.TryGetValue(userGuid, out var roleId) &&
                  await TeamMemberRoleHelper.IsCompanyAdminRoleAsync(_dbContext.SqlSugarClient, roleId) &&
                  partnerIds.Count > 0)
10fd1324   李曜臣   5-17接口优化
834
              {
14afbc16   李曜臣   2026-6-22
835
836
837
838
839
840
                  var allRegions = await LocationScopeBindingHelper.ResolveGroupIdsFromPartnerIdsAsync(
                      _dbContext.SqlSugarClient, partnerIds);
                  if (allRegions.Count > 0)
                  {
                      regionIds = allRegions;
                  }
10fd1324   李曜臣   5-17接口优化
841
842
              }
  
10fd1324   李曜臣   5-17接口优化
843
844
845
846
847
848
849
850
851
852
              result[userId] = new TeamMemberScopeIds
              {
                  PartnerIds = partnerIds,
                  RegionIds = regionIds
              };
          }
  
          return result;
      }
  
14afbc16   李曜臣   2026-6-22
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
      /// <summary>
      /// Company Admin 列表/详情:展示所选 Company 下全部 Region 与门店。
      /// </summary>
      private async Task<(List<string> RegionIds, List<TeamMemberAssignedLocationDto> AssignedLocations)>
          ApplyCompanyAdminDisplayScopeAsync(
              Guid? roleId,
              List<string> partnerIds,
              List<string> regionIds,
              List<TeamMemberAssignedLocationDto> assigned)
      {
          if (!await TeamMemberRoleHelper.IsCompanyAdminRoleAsync(_dbContext.SqlSugarClient, roleId) ||
              partnerIds.Count == 0)
          {
              return (regionIds, assigned);
          }
  
          var allRegions = await LocationScopeBindingHelper.ResolveGroupIdsFromPartnerIdsAsync(
              _dbContext.SqlSugarClient, partnerIds);
          var allLocationIds = await LocationScopeBindingHelper.ResolveLocationIdsFromPartnerIdsAsync(
              _dbContext.SqlSugarClient, partnerIds);
          var allAssigned = await BuildAssignedLocationDtosAsync(allLocationIds);
  
          return (
              allRegions.Count > 0 ? allRegions : regionIds,
              allAssigned.Count > 0 ? allAssigned : assigned);
      }
  
      private async Task<List<TeamMemberAssignedLocationDto>> BuildAssignedLocationDtosAsync(
          IReadOnlyList<string> locationIds)
      {
          var ids = LocationScopeBindingHelper.NormalizeIds(locationIds);
          if (ids.Count == 0)
          {
              return new List<TeamMemberAssignedLocationDto>();
          }
  
          var guidList = ids
              .Select(x => Guid.TryParse(x, out var g) ? g : (Guid?)null)
              .Where(x => x.HasValue)
              .Select(x => x!.Value)
              .ToList();
          if (guidList.Count == 0)
          {
              return new List<TeamMemberAssignedLocationDto>();
          }
  
          var locations = await _dbContext.SqlSugarClient.Queryable<LocationAggregateRoot>()
              .Where(x => !x.IsDeleted && guidList.Contains(x.Id))
              .Select(x => new { x.Id, x.LocationCode, x.LocationName })
              .ToListAsync();
  
          return locations
              .OrderBy(x => x.LocationCode)
              .Select(x => new TeamMemberAssignedLocationDto
              {
                  Id = x.Id.ToString(),
                  LocationCode = x.LocationCode,
                  LocationName = x.LocationName
              })
              .ToList();
      }
  
10fd1324   李曜臣   5-17接口优化
915
916
917
918
919
920
921
922
923
924
925
926
927
928
      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
14afbc16   李曜臣   2026-6-22
929
          }, input.RoleId);
10fd1324   李曜臣   5-17接口优化
930
  
14afbc16   李曜臣   2026-6-22
931
932
933
      private async Task<List<string>> ResolveTeamMemberLocationIdsForSaveAsync(
          TeamMemberCreateInputVo input,
          Guid? roleId)
10fd1324   李曜臣   5-17接口优化
934
935
936
      {
          var partnerIds = NormalizePartnerIds(input);
          var regionIds = NormalizeRegionIds(input);
14afbc16   李曜臣   2026-6-22
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
          var explicitLocationIds = LocationScopeBindingHelper.NormalizeIds(input.LocationIds);
          var isCompanyAdmin = await TeamMemberRoleHelper.IsCompanyAdminRoleAsync(
              _dbContext.SqlSugarClient, roleId);
  
          if (isCompanyAdmin && partnerIds.Count > 0 &&
              regionIds.Count == 0 && explicitLocationIds.Count == 0)
          {
              var fromPartner = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
                  _dbContext.SqlSugarClient, partnerIds, null, null);
              if (fromPartner.Count == 0)
              {
                  throw new UserFriendlyException("Company Admin 需绑定公司下门店,所选公司下暂无可用门店");
              }
  
              await LocationScopeBindingHelper.ValidateLocationIdsExistAsync(_dbContext.SqlSugarClient, fromPartner);
              return fromPartner;
          }
  
10fd1324   李曜臣   5-17接口优化
955
956
957
958
959
          var merged = await LocationScopeBindingHelper.MergeToLocationIdsAsync(
              _dbContext.SqlSugarClient, partnerIds, regionIds, input.LocationIds);
  
          if (merged.Count == 0)
          {
14afbc16   李曜臣   2026-6-22
960
961
962
963
              throw new UserFriendlyException(
                  isCompanyAdmin
                      ? "Company Admin 必须选择 Company,或指定 Region / 门店"
                      : "成员必须至少分配一个门店(公司/区域/门店至少选一项)");
10fd1324   李曜臣   5-17接口优化
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
          }
  
          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();
      }
  
dbc9750f   李曜臣   成员模块实现
1002
1003
1004
1005
1006
1007
1008
      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();
  
dbc9750f   李曜臣   成员模块实现
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
          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();
  
dbc9750f   李曜臣   成员模块实现
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
          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();
          }
  
dbc9750f   李曜臣   成员模块实现
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
          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();
          }
      }
  }