1
0

UserService.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.Extensions.Options;
  7. using ZhonTai.Admin.Core.Attributes;
  8. using ZhonTai.Admin.Core.Configs;
  9. using ZhonTai.Common.Helpers;
  10. using ZhonTai.Admin.Core.Dto;
  11. using ZhonTai.Admin.Domain.Api;
  12. using ZhonTai.Admin.Domain.PermissionApi;
  13. using ZhonTai.Admin.Domain.Role;
  14. using ZhonTai.Admin.Domain.RolePermission;
  15. using ZhonTai.Admin.Domain.Tenant;
  16. using ZhonTai.Admin.Domain.User;
  17. using ZhonTai.Admin.Domain.UserRole;
  18. using ZhonTai.Admin.Services.Auth.Dto;
  19. using ZhonTai.Admin.Services.User.Dto;
  20. using ZhonTai.DynamicApi;
  21. using ZhonTai.DynamicApi.Attributes;
  22. using ZhonTai.Admin.Core.Helpers;
  23. using ZhonTai.Admin.Core.Consts;
  24. using ZhonTai.Admin.Domain.UserStaff;
  25. using ZhonTai.Admin.Domain.Org;
  26. using System.Data;
  27. using ZhonTai.Admin.Domain.TenantPermission;
  28. using FreeSql;
  29. using ZhonTai.Admin.Domain.User.Dto;
  30. using ZhonTai.Admin.Domain.RoleOrg;
  31. using ZhonTai.Admin.Domain.UserOrg;
  32. namespace ZhonTai.Admin.Services.User;
  33. /// <summary>
  34. /// 用户服务
  35. /// </summary>
  36. [Order(10)]
  37. [DynamicApi(Area = AdminConsts.AreaName)]
  38. public partial class UserService : BaseService, IUserService, IDynamicApi
  39. {
  40. private AppConfig _appConfig => LazyGetRequiredService<AppConfig>();
  41. private IUserRepository _userRepository => LazyGetRequiredService<IUserRepository>();
  42. private IOrgRepository _orgRepository => LazyGetRequiredService<IOrgRepository>();
  43. private ITenantRepository _tenantRepository => LazyGetRequiredService<ITenantRepository>();
  44. private IApiRepository _apiRepository => LazyGetRequiredService<IApiRepository>();
  45. private IUserStaffRepository _staffRepository => LazyGetRequiredService<IUserStaffRepository>();
  46. private IUserRoleRepository _userRoleRepository => LazyGetRequiredService<IUserRoleRepository>();
  47. private IRoleOrgRepository _roleOrgRepository => LazyGetRequiredService<IRoleOrgRepository>();
  48. private IUserOrgRepository _userOrgRepository => LazyGetRequiredService<IUserOrgRepository>();
  49. public UserService()
  50. {
  51. }
  52. /// <summary>
  53. /// 查询用户
  54. /// </summary>
  55. /// <param name="id"></param>
  56. /// <returns></returns>
  57. public async Task<UserGetOutput> GetAsync(long id)
  58. {
  59. var userEntity = await _userRepository.Select
  60. .WhereDynamic(id)
  61. .IncludeMany(a => a.Roles.Select(b => new RoleEntity { Id = b.Id, Name = b.Name }))
  62. .IncludeMany(a => a.Orgs.Select(b => new OrgEntity { Id = b.Id, Name = b.Name }))
  63. .ToOneAsync(a => new
  64. {
  65. a.Id,
  66. a.UserName,
  67. a.Name,
  68. a.Mobile,
  69. a.Email,
  70. a.Roles,
  71. a.Orgs,
  72. a.OrgId,
  73. a.ManagerUserId,
  74. ManagerUserName = a.ManagerUser.Name,
  75. Staff = new
  76. {
  77. a.Staff.JobNumber,
  78. a.Staff.Sex,
  79. a.Staff.Position,
  80. a.Staff.Introduce
  81. }
  82. });
  83. var output = Mapper.Map<UserGetOutput>(userEntity);
  84. return output;
  85. }
  86. /// <summary>
  87. /// 查询分页
  88. /// </summary>
  89. /// <param name="input"></param>
  90. /// <returns></returns>
  91. [HttpPost]
  92. public async Task<PageOutput<UserGetPageOutput>> GetPageAsync(PageInput<UserGetPageDto> input)
  93. {
  94. var orgId = input.Filter?.OrgId;
  95. var list = await _userRepository.Select
  96. .WhereIf(orgId.HasValue && orgId > 0, a => _userOrgRepository.Where(b => b.UserId == a.Id && b.OrgId == orgId).Any())
  97. .Where(a=>a.Type != UserType.Member)
  98. .WhereDynamicFilter(input.DynamicFilter)
  99. .Count(out var total)
  100. .OrderByDescending(true, a => a.Id)
  101. .IncludeMany(a => a.Roles.Select(b => new RoleEntity { Name = b.Name }))
  102. .Page(input.CurrentPage, input.PageSize)
  103. .ToListAsync(a => new UserGetPageOutput { Roles = a.Roles });
  104. if(orgId.HasValue && orgId > 0)
  105. {
  106. var managerUserIds = await _userOrgRepository.Select.Where(a => a.OrgId == orgId && a.IsManager == true).ToListAsync(a => a.UserId);
  107. if (managerUserIds.Any())
  108. {
  109. var managerUsers = list.Where(a => managerUserIds.Contains(a.Id));
  110. foreach (var managerUser in managerUsers)
  111. {
  112. managerUser.IsManager = true;
  113. }
  114. }
  115. }
  116. var data = new PageOutput<UserGetPageOutput>()
  117. {
  118. List = Mapper.Map<List<UserGetPageOutput>>(list),
  119. Total = total
  120. };
  121. return data;
  122. }
  123. /// <summary>
  124. /// 查询登录用户信息
  125. /// </summary>
  126. /// <param name="id"></param>
  127. /// <returns></returns>
  128. [NonAction]
  129. public async Task<AuthLoginOutput> GetLoginUserAsync(long id)
  130. {
  131. var output = new ResultOutput<AuthLoginOutput>();
  132. var entityDto = await _userRepository.Select.DisableGlobalFilter(FilterNames.Tenant)
  133. .WhereDynamic(id).ToOneAsync<AuthLoginOutput>();
  134. if (_appConfig.Tenant && entityDto?.TenantId.Value > 0)
  135. {
  136. var tenant = await _tenantRepository.Select.DisableGlobalFilter(FilterNames.Tenant)
  137. .WhereDynamic(entityDto.TenantId).ToOneAsync(a => new { a.TenantType, a.DbKey });
  138. entityDto.TenantType = tenant.TenantType;
  139. entityDto.DbKey = tenant.DbKey;
  140. }
  141. return entityDto;
  142. }
  143. /// <summary>
  144. /// 获得数据权限
  145. /// </summary>
  146. /// <returns></returns>
  147. [NonAction]
  148. public async Task<DataPermissionDto> GetDataPermissionAsync()
  149. {
  150. if (!(User?.Id > 0))
  151. {
  152. return null;
  153. }
  154. var key = CacheKeys.DataPermission + User.Id;
  155. return await Cache.GetOrSetAsync(key, async () =>
  156. {
  157. using (_userRepository.DataFilter.Disable(FilterNames.Self, FilterNames.Data))
  158. {
  159. var user = await _userRepository.Select
  160. .IncludeMany(a => a.Roles.Select(b => new RoleEntity
  161. {
  162. Id = b.Id,
  163. DataScope = b.DataScope
  164. }))
  165. .WhereDynamic(User.Id)
  166. .ToOneAsync(a => new
  167. {
  168. a.OrgId,
  169. a.Roles
  170. });
  171. if (user == null)
  172. return null;
  173. //数据范围
  174. DataScope dataScope = DataScope.Self;
  175. var customRoleIds = new List<long>();
  176. user.Roles?.ToList().ForEach(role =>
  177. {
  178. if (role.DataScope == DataScope.Custom)
  179. {
  180. customRoleIds.Add(role.Id);
  181. }
  182. else if (role.DataScope <= dataScope)
  183. {
  184. dataScope = role.DataScope;
  185. }
  186. });
  187. //部门列表
  188. var orgIds = new List<long>();
  189. if (dataScope != DataScope.All)
  190. {
  191. //本部门
  192. if (dataScope == DataScope.Dept)
  193. {
  194. orgIds.Add(user.OrgId);
  195. }
  196. //本部门和下级部门
  197. else if (dataScope == DataScope.DeptWithChild)
  198. {
  199. orgIds = await _orgRepository
  200. .Where(a => a.Id == user.OrgId)
  201. .AsTreeCte()
  202. .ToListAsync(a => a.Id);
  203. }
  204. //指定部门
  205. if (customRoleIds.Count > 0)
  206. {
  207. var customRoleOrgIds = await _roleOrgRepository.Select.Where(a => customRoleIds.Contains(a.RoleId)).ToListAsync(a => a.OrgId);
  208. orgIds = orgIds.Concat(customRoleOrgIds).ToList();
  209. }
  210. }
  211. return new DataPermissionDto
  212. {
  213. OrgId = user.OrgId,
  214. OrgIds = orgIds.Distinct().ToList(),
  215. DataScope = dataScope
  216. };
  217. }
  218. });
  219. }
  220. /// <summary>
  221. /// 查询用户基本信息
  222. /// </summary>
  223. /// <returns></returns>
  224. [Login]
  225. public async Task<UserGetBasicOutput> GetBasicAsync()
  226. {
  227. if (!(User?.Id > 0))
  228. {
  229. throw ResultOutput.Exception("未登录!");
  230. }
  231. var data = await _userRepository.GetAsync<UserGetBasicOutput>(User.Id);
  232. data.Mobile = DataMaskHelper.PhoneMask(data.Mobile);
  233. data.Email = DataMaskHelper.EmailMask(data.Email);
  234. return data;
  235. }
  236. /// <summary>
  237. /// 查询用户权限信息
  238. /// </summary>
  239. /// <returns></returns>
  240. public async Task<IList<UserPermissionsOutput>> GetPermissionsAsync()
  241. {
  242. var key = CacheKeys.UserPermissions + User.Id;
  243. var result = await Cache.GetOrSetAsync(key, async () =>
  244. {
  245. if (User.TenantAdmin)
  246. {
  247. var cloud = LazyGetRequiredService<FreeSqlCloud>();
  248. var db = cloud.Use(DbKeys.AppDb);
  249. return await db.Select<ApiEntity>()
  250. .Where(a => db.Select<TenantPermissionEntity, PermissionApiEntity>()
  251. .InnerJoin((b, c) => b.PermissionId == c.PermissionId && b.TenantId == User.TenantId)
  252. .Where((b, c) => c.ApiId == a.Id).Any())
  253. .ToListAsync<UserPermissionsOutput>();
  254. }
  255. return await _apiRepository
  256. .Where(a => _apiRepository.Orm.Select<UserRoleEntity, RolePermissionEntity, PermissionApiEntity>()
  257. .InnerJoin((b, c, d) => b.RoleId == c.RoleId && b.UserId == User.Id)
  258. .InnerJoin((b, c, d) => c.PermissionId == d.PermissionId)
  259. .Where((b, c, d) => d.ApiId == a.Id).Any())
  260. .ToListAsync<UserPermissionsOutput>();
  261. });
  262. return result;
  263. }
  264. /// <summary>
  265. /// 新增用户
  266. /// </summary>
  267. /// <param name="input"></param>
  268. /// <returns></returns>
  269. [AdminTransaction]
  270. public virtual async Task<long> AddAsync(UserAddInput input)
  271. {
  272. if (await _userRepository.Select.AnyAsync(a => a.UserName == input.UserName))
  273. {
  274. throw ResultOutput.Exception($"账号已存在");
  275. }
  276. if (input.Mobile.NotNull() && await _userRepository.Select.AnyAsync(a => a.Mobile == input.Mobile))
  277. {
  278. throw ResultOutput.Exception($"手机号已存在");
  279. }
  280. if (input.Email.NotNull() && await _userRepository.Select.AnyAsync(a => a.Email == input.Email))
  281. {
  282. throw ResultOutput.Exception($"邮箱已存在");
  283. }
  284. // 用户信息
  285. if (input.Password.IsNull())
  286. {
  287. input.Password = _appConfig.DefaultPassword;
  288. }
  289. input.Password = MD5Encrypt.Encrypt32(input.Password);
  290. var entity = Mapper.Map<UserEntity>(input);
  291. entity.Type = UserType.DefaultUser;
  292. var user = await _userRepository.InsertAsync(entity);
  293. var userId = user.Id;
  294. //用户角色
  295. if (input.RoleIds != null && input.RoleIds.Any())
  296. {
  297. var roles = input.RoleIds.Select(roleId => new UserRoleEntity
  298. {
  299. UserId = userId,
  300. RoleId = roleId
  301. }).ToList();
  302. await _userRoleRepository.InsertAsync(roles);
  303. }
  304. // 员工信息
  305. var staff = input.Staff == null ? new UserStaffEntity() : Mapper.Map<UserStaffEntity>(input.Staff);
  306. staff.Id = userId;
  307. await _staffRepository.InsertAsync(staff);
  308. //所属部门
  309. if (input.OrgIds != null && input.OrgIds.Any())
  310. {
  311. var orgs = input.OrgIds.Select(orgId => new UserOrgEntity
  312. {
  313. UserId = userId,
  314. OrgId = orgId
  315. }).ToList();
  316. await _userOrgRepository.InsertAsync(orgs);
  317. }
  318. return userId;
  319. }
  320. /// <summary>
  321. /// 新增会员
  322. /// </summary>
  323. /// <param name="input"></param>
  324. /// <returns></returns>
  325. public virtual async Task<long> AddMemberAsync(UserAddMemberInput input)
  326. {
  327. using (_userRepository.DataFilter.DisableAll())
  328. {
  329. if (await _userRepository.Select.AnyAsync(a => a.UserName == input.UserName))
  330. {
  331. throw ResultOutput.Exception($"账号已存在");
  332. }
  333. if (input.Mobile.NotNull() && await _userRepository.Select.AnyAsync(a => a.Mobile == input.Mobile))
  334. {
  335. throw ResultOutput.Exception($"手机号已存在");
  336. }
  337. if (input.Email.NotNull() && await _userRepository.Select.AnyAsync(a => a.Email == input.Email))
  338. {
  339. throw ResultOutput.Exception($"邮箱已存在");
  340. }
  341. // 用户信息
  342. if (input.Password.IsNull())
  343. {
  344. input.Password = _appConfig.DefaultPassword;
  345. }
  346. input.Password = MD5Encrypt.Encrypt32(input.Password);
  347. var entity = Mapper.Map<UserEntity>(input);
  348. entity.Type = UserType.Member;
  349. var user = await _userRepository.InsertAsync(entity);
  350. return user.Id;
  351. }
  352. }
  353. /// <summary>
  354. /// 修改会员
  355. /// </summary>
  356. /// <param name="input"></param>
  357. /// <returns></returns>
  358. [AdminTransaction]
  359. public virtual async Task UpdateMemberAsync(UserUpdateMemberInput input)
  360. {
  361. var user = await _userRepository.GetAsync(input.Id);
  362. if (!(user?.Id > 0))
  363. {
  364. throw ResultOutput.Exception("用户不存在");
  365. }
  366. if (await _userRepository.Select.AnyAsync(a => a.Id != input.Id && a.UserName == input.UserName))
  367. {
  368. throw ResultOutput.Exception($"账号已存在");
  369. }
  370. if (input.Mobile.NotNull() && await _userRepository.Select.AnyAsync(a => a.Id != input.Id && a.Mobile == input.Mobile))
  371. {
  372. throw ResultOutput.Exception($"手机号已存在");
  373. }
  374. if (input.Email.NotNull() && await _userRepository.Select.AnyAsync(a => a.Id != input.Id && a.Email == input.Email))
  375. {
  376. throw ResultOutput.Exception($"邮箱已存在");
  377. }
  378. Mapper.Map(input, user);
  379. await _userRepository.UpdateAsync(user);
  380. }
  381. /// <summary>
  382. /// 修改用户
  383. /// </summary>
  384. /// <param name="input"></param>
  385. /// <returns></returns>
  386. [AdminTransaction]
  387. public virtual async Task UpdateAsync(UserUpdateInput input)
  388. {
  389. var user = await _userRepository.GetAsync(input.Id);
  390. if (!(user?.Id > 0))
  391. {
  392. throw ResultOutput.Exception("用户不存在");
  393. }
  394. if (input.Id == input.ManagerUserId)
  395. {
  396. throw ResultOutput.Exception("直属主管不能是自己");
  397. }
  398. if (await _userRepository.Select.AnyAsync(a => a.Id != input.Id && a.UserName == input.UserName))
  399. {
  400. throw ResultOutput.Exception($"账号已存在");
  401. }
  402. if (input.Mobile.NotNull() && await _userRepository.Select.AnyAsync(a => a.Id != input.Id && a.Mobile == input.Mobile))
  403. {
  404. throw ResultOutput.Exception($"手机号已存在");
  405. }
  406. if (input.Email.NotNull() && await _userRepository.Select.AnyAsync(a => a.Id != input.Id && a.Email == input.Email))
  407. {
  408. throw ResultOutput.Exception($"邮箱已存在");
  409. }
  410. Mapper.Map(input, user);
  411. await _userRepository.UpdateAsync(user);
  412. var userId = user.Id;
  413. // 用户角色
  414. await _userRoleRepository.DeleteAsync(a => a.UserId == userId);
  415. if (input.RoleIds != null && input.RoleIds.Any())
  416. {
  417. var roles = input.RoleIds.Select(roleId => new UserRoleEntity
  418. {
  419. UserId = userId,
  420. RoleId = roleId
  421. }).ToList();
  422. await _userRoleRepository.InsertAsync(roles);
  423. }
  424. // 员工信息
  425. var staff = await _staffRepository.GetAsync(userId);
  426. staff ??= new UserStaffEntity();
  427. Mapper.Map(input.Staff, staff);
  428. staff.Id = userId;
  429. await _staffRepository.InsertOrUpdateAsync(staff);
  430. //所属部门
  431. await _userOrgRepository.DeleteAsync(a => a.UserId == userId);
  432. if (input.OrgIds != null && input.OrgIds.Any())
  433. {
  434. var orgs = input.OrgIds.Select(orgId => new UserOrgEntity
  435. {
  436. UserId = userId,
  437. OrgId = orgId
  438. }).ToList();
  439. await _userOrgRepository.InsertAsync(orgs);
  440. }
  441. await Cache.DelAsync(CacheKeys.DataPermission + user.Id);
  442. }
  443. /// <summary>
  444. /// 更新用户基本信息
  445. /// </summary>
  446. /// <param name="input"></param>
  447. /// <returns></returns>
  448. [Login]
  449. public async Task UpdateBasicAsync(UserUpdateBasicInput input)
  450. {
  451. var entity = await _userRepository.GetAsync(User.Id);
  452. entity = Mapper.Map(input, entity);
  453. await _userRepository.UpdateAsync(entity);
  454. }
  455. /// <summary>
  456. /// 修改用户密码
  457. /// </summary>
  458. /// <param name="input"></param>
  459. /// <returns></returns>
  460. [Login]
  461. public async Task ChangePasswordAsync(UserChangePasswordInput input)
  462. {
  463. if (input.ConfirmPassword != input.NewPassword)
  464. {
  465. throw ResultOutput.Exception("新密码和确认密码不一致");
  466. }
  467. var entity = await _userRepository.GetAsync(User.Id);
  468. var oldPassword = MD5Encrypt.Encrypt32(input.OldPassword);
  469. if (oldPassword != entity.Password)
  470. {
  471. throw ResultOutput.Exception("旧密码不正确");
  472. }
  473. entity.Password = MD5Encrypt.Encrypt32(input.NewPassword);
  474. await _userRepository.UpdateAsync(entity);
  475. }
  476. /// <summary>
  477. /// 重置密码
  478. /// </summary>
  479. /// <param name="input"></param>
  480. /// <returns></returns>
  481. public async Task<string> ResetPasswordAsync(UserResetPasswordInput input)
  482. {
  483. var entity = await _userRepository.GetAsync(input.Id);
  484. var password = input.Password;
  485. if (password.IsNull())
  486. {
  487. password = _appConfig.DefaultPassword;
  488. }
  489. if (password.IsNull())
  490. {
  491. password = "111111";
  492. }
  493. entity.Password = MD5Encrypt.Encrypt32(password);
  494. await _userRepository.UpdateAsync(entity);
  495. return password;
  496. }
  497. /// <summary>
  498. /// 设置主管
  499. /// </summary>
  500. /// <param name="input"></param>
  501. /// <returns></returns>
  502. public async Task SetManagerAsync(UserSetManagerInput input)
  503. {
  504. var entity = await _userOrgRepository.Where(a => a.UserId == input.UserId && a.OrgId == input.OrgId).FirstAsync();
  505. entity.IsManager = input.IsManager;
  506. await _userOrgRepository.UpdateAsync(entity);
  507. }
  508. /// <summary>
  509. /// 彻底删除用户
  510. /// </summary>
  511. /// <param name="id"></param>
  512. /// <returns></returns>
  513. [AdminTransaction]
  514. public virtual async Task DeleteAsync(long id)
  515. {
  516. var user = await _userRepository.Select.WhereDynamic(id).ToOneAsync(a => new { a.Type });
  517. if(user == null)
  518. {
  519. throw ResultOutput.Exception("用户不存在");
  520. }
  521. if(user.Type == UserType.PlatformAdmin || user.Type == UserType.TenantAdmin)
  522. {
  523. throw ResultOutput.Exception("平台管理员禁止删除");
  524. }
  525. //删除用户角色
  526. await _userRoleRepository.DeleteAsync(a => a.UserId == id);
  527. //删除用户所属部门
  528. await _userOrgRepository.DeleteAsync(a => a.UserId == id);
  529. //删除员工
  530. await _staffRepository.DeleteAsync(a => a.Id == id);
  531. //删除用户
  532. await _userRepository.DeleteAsync(a => a.Id == id);
  533. await Cache.DelAsync(CacheKeys.DataPermission + id);
  534. }
  535. /// <summary>
  536. /// 批量彻底删除用户
  537. /// </summary>
  538. /// <param name="ids"></param>
  539. /// <returns></returns>
  540. [AdminTransaction]
  541. public virtual async Task BatchDeleteAsync(long[] ids)
  542. {
  543. var admin = await _userRepository.Select.Where(a => ids.Contains(a.Id) &&
  544. (a.Type == UserType.PlatformAdmin || a.Type == UserType.TenantAdmin)).AnyAsync();
  545. if (admin)
  546. {
  547. throw ResultOutput.Exception("平台管理员禁止删除");
  548. }
  549. //删除用户角色
  550. await _userRoleRepository.DeleteAsync(a => ids.Contains(a.UserId));
  551. //删除用户所属部门
  552. await _userOrgRepository.DeleteAsync(a => ids.Contains(a.UserId));
  553. //删除员工
  554. await _staffRepository.DeleteAsync(a => ids.Contains(a.Id));
  555. //删除用户
  556. await _userRepository.DeleteAsync(a => ids.Contains(a.Id));
  557. foreach (var userId in ids)
  558. {
  559. await Cache.DelAsync(CacheKeys.DataPermission + userId);
  560. }
  561. }
  562. /// <summary>
  563. /// 删除用户
  564. /// </summary>
  565. /// <param name="id"></param>
  566. /// <returns></returns>
  567. [AdminTransaction]
  568. public virtual async Task SoftDeleteAsync(long id)
  569. {
  570. var user = await _userRepository.Select.WhereDynamic(id).ToOneAsync(a => new { a.Type });
  571. if (user == null)
  572. {
  573. throw ResultOutput.Exception("用户不存在");
  574. }
  575. if (user.Type == UserType.PlatformAdmin || user.Type == UserType.TenantAdmin)
  576. {
  577. throw ResultOutput.Exception("平台管理员禁止删除");
  578. }
  579. await _userRoleRepository.DeleteAsync(a => a.UserId == id);
  580. await _userOrgRepository.DeleteAsync(a => a.UserId == id);
  581. await _staffRepository.SoftDeleteAsync(a => a.Id == id);
  582. await _userRepository.SoftDeleteAsync(id);
  583. await Cache.DelAsync(CacheKeys.DataPermission + id);
  584. }
  585. /// <summary>
  586. /// 批量删除用户
  587. /// </summary>
  588. /// <param name="ids"></param>
  589. /// <returns></returns>
  590. [AdminTransaction]
  591. public virtual async Task BatchSoftDeleteAsync(long[] ids)
  592. {
  593. var admin = await _userRepository.Select.Where(a => ids.Contains(a.Id) &&
  594. (a.Type == UserType.PlatformAdmin || a.Type == UserType.TenantAdmin)).AnyAsync();
  595. if (admin)
  596. {
  597. throw ResultOutput.Exception("平台管理员禁止删除");
  598. }
  599. await _userRoleRepository.DeleteAsync(a => ids.Contains(a.UserId));
  600. await _userOrgRepository.DeleteAsync(a => ids.Contains(a.UserId));
  601. await _staffRepository.SoftDeleteAsync(a => ids.Contains(a.Id));
  602. await _userRepository.SoftDeleteAsync(ids);
  603. foreach (var userId in ids)
  604. {
  605. await Cache.DelAsync(CacheKeys.DataPermission + userId);
  606. }
  607. }
  608. /// <summary>
  609. /// 上传头像
  610. /// </summary>
  611. /// <param name="file"></param>
  612. /// <param name="autoUpdate"></param>
  613. /// <returns></returns>
  614. [HttpPost]
  615. [Login]
  616. public async Task<string> AvatarUpload([FromForm] IFormFile file, bool autoUpdate = false)
  617. {
  618. var uploadConfig = LazyGetRequiredService<IOptionsMonitor<UploadConfig>>().CurrentValue;
  619. var uploadHelper = LazyGetRequiredService<UploadHelper>();
  620. var config = uploadConfig.Avatar;
  621. var fileInfo = await uploadHelper.UploadAsync(file, config, new { User.Id });
  622. if (autoUpdate)
  623. {
  624. var entity = await _userRepository.GetAsync(User.Id);
  625. entity.Avatar = fileInfo.FileRelativePath;
  626. await _userRepository.UpdateAsync(entity);
  627. }
  628. return fileInfo.FileRelativePath;
  629. }
  630. }