TeamMemberAppService.cs
13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
using FoodLabeling.Application.Helpers;
using FoodLabeling.Application.Contracts.Dtos.Common;
using FoodLabeling.Application.Contracts.Dtos.TeamMember;
using FoodLabeling.Application.Contracts.IServices;
using FoodLabeling.Application.Services.DbModels;
using FoodLabeling.Domain.Entities;
using SqlSugar;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Guids;
using Yi.Framework.Rbac.Domain.Entities;
using Yi.Framework.Rbac.Domain.Managers;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace FoodLabeling.Application.Services;
/// <summary>
/// 成员(Team Member/Manager)服务,对外仅在 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;
public TeamMemberAppService(
ISqlSugarRepository<UserAggregateRoot, Guid> userRepository,
UserManager userManager,
ISqlSugarDbContext dbContext,
IGuidGenerator guidGenerator)
{
_userRepository = userRepository;
_userManager = userManager;
_dbContext = dbContext;
_guidGenerator = guidGenerator;
}
/// <summary>
/// 成员分页列表(含角色与已分配门店)
/// </summary>
public async Task<PagedResultWithPageDto<TeamMemberGetListOutputDto>> GetListAsync(TeamMemberGetListInputVo input)
{
var pageIndex = PagedQueryConvention.PageIndexFromSkipCount(input.SkipCount);
var pageSize = input.MaxResultCount;
var keyword = input.Keyword?.Trim();
RefAsync<int> total = 0;
// 先按 user 表筛选分页,再批量补齐角色与门店
var users = await _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)
.OrderByIF(!string.IsNullOrWhiteSpace(input.Sorting), input.Sorting!)
.OrderByDescending(u => u.CreationTime)
.ToPageListAsync(input.SkipCount, input.MaxResultCount, total);
var userIds = users.Select(x => x.Id).ToList();
var userIdStrings = userIds.Select(x => x.ToString()).ToList();
// user-role: 仅取第一个角色(原型表格展示单角色)
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());
// user-location
var userLocations = await _dbContext.SqlSugarClient.Queryable<UserLocationDbEntity>()
.Where(x => !x.IsDeleted)
.WhereIF(!string.IsNullOrWhiteSpace(input.LocationId), x => x.LocationId == input.LocationId)
.Where(x => userIdStrings.Contains(x.UserId))
.ToListAsync();
// 如果按 LocationId 过滤,需要反向过滤掉无关联的 user
if (!string.IsNullOrWhiteSpace(input.LocationId))
{
var allowedUserIds = userLocations.Select(x => x.UserId).ToHashSet();
users = users.Where(u => allowedUserIds.Contains(u.Id.ToString())).ToList();
}
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 items = users.Select(u =>
{
roleMap.TryGetValue(u.Id, out var role);
assignedMap.TryGetValue(u.Id.ToString(), out var assigned);
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,
AssignedLocations = assigned ?? new List<TeamMemberAssignedLocationDto>()
};
}).ToList();
var totalCount = (long)total;
return new PagedResultWithPageDto<TeamMemberGetListOutputDto>
{
PageIndex = pageIndex,
PageSize = pageSize,
TotalCount = totalCount,
TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
Items = items
};
}
/// <summary>
/// 成员详情(带门店ID列表)
/// </summary>
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);
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,
LocationIds = locationIds,
AssignedLocations = assigned
};
}
/// <summary>
/// 新增成员(同步设置角色与门店)
/// </summary>
public async Task<TeamMemberGetOutputDto> CreateAsync(TeamMemberCreateInputVo input)
{
if (input.LocationIds is null || input.LocationIds.Count == 0)
{
throw new UserFriendlyException("成员必须至少分配一个门店");
}
var user = new UserAggregateRoot(input.UserName.Trim(), input.Password, input.Phone, input.FullName.Trim())
{
Name = input.FullName.Trim(),
Email = input.Email?.Trim(),
State = input.State
};
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, input.LocationIds);
return await GetAsync(user.Id);
}
/// <summary>
/// 编辑成员(同步设置角色与门店)
/// </summary>
public async Task<TeamMemberGetOutputDto> UpdateAsync(Guid id, TeamMemberUpdateInputVo input)
{
if (input.LocationIds is null || input.LocationIds.Count == 0)
{
throw new UserFriendlyException("成员必须至少分配一个门店");
}
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;
if (!string.IsNullOrWhiteSpace(input.Password))
{
user.EncryPassword.Password = input.Password;
user.BuildPassword();
}
await _userRepository.UpdateAsync(user);
// 角色:覆盖式设置(只保留一个)
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, input.LocationIds);
return await GetAsync(id);
}
/// <summary>
/// 删除成员(逻辑删除 user;并逻辑删除关联表)
/// </summary>
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();
}
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();
}
}
}