UserService.cs 23 KB

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