UserRepository.cs 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Http;
  5. using System.Threading.Tasks;
  6. using AutoMapper;
  7. using GxPress.Common.Extensions;
  8. using GxPress.Common.AppOptions;
  9. using GxPress.Common.Exceptions;
  10. using GxPress.Common.Page;
  11. using GxPress.Common.Tools;
  12. using GxPress.Entity;
  13. using GxPress.EnumConst;
  14. using GxPress.Repository.Interface;
  15. using GxPress.Request.User;
  16. using GxPress.Result.User;
  17. using Microsoft.AspNetCore.Hosting;
  18. using Microsoft.Extensions.Options;
  19. using Newtonsoft.Json;
  20. using SqlKata;
  21. using SS.Mail.Core;
  22. using Datory;
  23. using Microsoft.Extensions.Caching.Distributed;
  24. using Dapper;
  25. using GxPress.Result.App.User;
  26. using GxPress.Result.Job;
  27. using GxPress.Common.Http;
  28. using System.Net;
  29. using System.Threading;
  30. using Newtonsoft.Json.Linq;
  31. using Microsoft.Extensions.Logging;
  32. namespace GxPress.Repository.Implement
  33. {
  34. public class UserRepository : IUserRepository
  35. {
  36. private readonly Repository<User> _repository;
  37. private readonly Repository<Department> _departmentRepository;
  38. private readonly Repository<Role> _roleRepository;
  39. private readonly IMapper _mapper;
  40. private readonly IWebHostEnvironment _environment;
  41. private readonly ILogger<UserRepository> _logger;
  42. private readonly IDistributedCache _cache;
  43. //private readonly string _connectionString;
  44. //private readonly string _databaseTypestr;
  45. private readonly string _connectionString;
  46. private readonly string _databaseTypeStr;
  47. public UserRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper,
  48. IWebHostEnvironment environment, IDistributedCache cache, ILogger<UserRepository> logger)
  49. {
  50. _databaseTypeStr = dbOptionsAccessor.CurrentValue.DatabaseType;
  51. _connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
  52. // _databaseType
  53. // str = dbOptionsAccessor.CurrentValue.DatabaseType;
  54. var databaseType =
  55. StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
  56. //_connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
  57. var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
  58. _repository = new Repository<User>(database);
  59. _environment = environment;
  60. _departmentRepository = new Repository<Department>(database);
  61. _roleRepository = new Repository<Role>(database);
  62. _mapper = mapper;
  63. _cache = cache;
  64. _logger = logger;
  65. }
  66. public IDatabase Database => _repository.Database;
  67. public string TableName => _repository.TableName;
  68. public List<TableColumn> TableColumns => _repository.TableColumns;
  69. /// <summary>
  70. /// 根据id集合查询用户
  71. /// </summary>
  72. /// <param name="ids"></param>
  73. /// <returns></returns>
  74. public async Task<IEnumerable<User>> UserListInsAsync(List<int> ids)
  75. {
  76. return await _repository.GetAllAsync(Q.WhereIn(nameof(User.Id), ids));
  77. }
  78. /// <summary>
  79. /// 根据姓名查询用户
  80. /// </summary>
  81. /// <param name="name"></param>
  82. /// <returns></returns>
  83. public async Task<IEnumerable<UserInfoResult>> UserByNameAsync(string name)
  84. {
  85. var result = await _repository.GetAllAsync(Q.WhereLike(nameof(User.Name), $"%{name}%"));
  86. foreach (var item in result)
  87. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  88. return result.Select(n => _mapper.Map<UserInfoResult>(n));
  89. }
  90. public async Task<UserDetail> GetDetailAsync(int id)
  91. {
  92. var user = await _repository.GetAsync(id);
  93. user.QRCoder = StringUtils.AddDomain(user.QRCoder);
  94. user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  95. var userDetail = _mapper.Map<UserDetail>(user);
  96. if (user.DepartmentId > 0)
  97. {
  98. var department = await _departmentRepository.GetAsync(user.DepartmentId);
  99. userDetail.DepartmentName = department.Name;
  100. }
  101. return userDetail;
  102. }
  103. public async Task<User> GetAsync(int id)
  104. {
  105. var user = await _repository.GetAsync(id);
  106. return user;
  107. }
  108. public async Task<User> GetAsync(SqlKata.Query query)
  109. {
  110. var user = await _repository.GetAsync(query);
  111. return user;
  112. }
  113. public async Task<string> GetNameAsync(int id)
  114. {
  115. if (id <= 0) return string.Empty;
  116. return await _repository.GetAsync<string>(Q
  117. .Select(nameof(User.Name))
  118. .Where(nameof(User.Id), id)
  119. );
  120. }
  121. public async Task<string> GetAvatarUrlAsync(int id)
  122. {
  123. if (id <= 0) return string.Empty;
  124. var avatarUrl = await _repository.GetAsync<string>(Q
  125. .Select(nameof(User.AvatarUrl))
  126. .Where(nameof(User.Id), id)
  127. );
  128. return StringUtils.AddDomainMin(avatarUrl);
  129. }
  130. public string GetAvatarUrl(User user)
  131. {
  132. if (user == null) return string.Empty;
  133. return StringUtils.AddDomainMin(user.AvatarUrl);
  134. }
  135. public async Task<User> GetByPhoneAsync(string phone)
  136. {
  137. return await _repository.GetAsync(Q.Where(nameof(User.Phone), phone));
  138. }
  139. /// <summary>
  140. /// openId微信认证
  141. /// </summary>
  142. /// <param name="openId"></param>
  143. /// /// <returns></returns>
  144. public async Task<User> GetByOpenIdAsync(string openId)
  145. {
  146. return await _repository.GetAsync(Q.Where(nameof(User.OpenId), openId));
  147. }
  148. /// <summary>
  149. /// 绑定微信
  150. /// </summary>
  151. /// <param name="request"></param>
  152. /// <returns></returns>
  153. public async Task<bool> UpdateByOpendIdAsync(UserSignInRequest request)
  154. {
  155. var key = $"login:{request.Phone}";
  156. var user = new User();
  157. var code = _cache.GetString(key).Replace("\"", "");
  158. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  159. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  160. user = await GetByPhoneAsync(request.Phone);
  161. //用户不存在,自动注册
  162. if (user == null)
  163. throw new BusinessException("用户不存在");
  164. return await _repository.UpdateAsync(Q.Where(nameof(User.Phone), request.Phone).Set(nameof(User.OpenId), request.OpenId)) > 0;
  165. }
  166. public async Task<bool> DeleteUsersAsync(IEnumerable<int> userIds)
  167. {
  168. return await _repository.DeleteAsync(Q.WhereIn(nameof(User.Id), userIds)) > 0;
  169. }
  170. public async Task<bool> ChangeRoleAsync(IEnumerable<int> userIds, int roleId)
  171. {
  172. return await _repository.UpdateAsync(Q
  173. .Set(nameof(User.RoleId), roleId)
  174. .WhereIn(nameof(User.Id), userIds)
  175. ) > 0;
  176. }
  177. public async Task<bool> ChangeDepartmentAsync(IEnumerable<int> userIds, int departmentId)
  178. {
  179. return await _repository.UpdateAsync(Q
  180. .Set(nameof(User.DepartmentId), departmentId)
  181. .WhereIn(nameof(User.Id), userIds)
  182. ) > 0;
  183. }
  184. public async Task<bool> UpdateAsync(User user)
  185. {
  186. return await _repository.UpdateAsync(user);
  187. }
  188. public async Task<int> GetCountAsync(int departmentId, int roleId, string keyword)
  189. {
  190. var query = Q.NewQuery();
  191. if (departmentId > 0)
  192. {
  193. query.Where(nameof(User.DepartmentId), departmentId);
  194. }
  195. if (roleId > 0)
  196. {
  197. query.Where(nameof(User.RoleId), roleId);
  198. }
  199. if (!string.IsNullOrEmpty(keyword))
  200. {
  201. keyword = "%" + keyword + "%";
  202. query.Where(q =>
  203. q.WhereLike(nameof(User.Name), keyword)
  204. .OrWhereLike(nameof(User.Email), keyword)
  205. .OrWhereLike(nameof(User.Phone), keyword)
  206. );
  207. }
  208. return await _repository.CountAsync(query);
  209. }
  210. /// <summary>
  211. /// Set the limit and offset for a given page.
  212. /// </summary>
  213. /// <param name="page"></param>
  214. /// <param name="perPage"></param>
  215. /// <param name="departmentId"></param>
  216. /// <param name="roleId"></param>
  217. /// <param name="keyword"></param>
  218. /// <returns></returns>
  219. public async Task<IEnumerable<User>> GetPageListAsync(int page, int perPage, int departmentId, int roleId,
  220. string keyword)
  221. {
  222. var query = Q.ForPage(page, perPage);
  223. if (departmentId > 0)
  224. {
  225. query.Where(nameof(User.DepartmentId), departmentId);
  226. }
  227. if (roleId > 0)
  228. {
  229. query.Where(nameof(User.RoleId), roleId);
  230. }
  231. if (!string.IsNullOrEmpty(keyword))
  232. {
  233. keyword = "%" + keyword + "%";
  234. query.Where(q =>
  235. q.WhereLike(nameof(User.Name), keyword)
  236. .OrWhereLike(nameof(User.Email), keyword)
  237. .OrWhereLike(nameof(User.Phone), keyword)
  238. );
  239. }
  240. return await _repository.GetAllAsync(query);
  241. }
  242. public async Task<IEnumerable<User>> GetListAsync(int departmentId, int roleId, string keyword)
  243. {
  244. var query = Q.NewQuery();
  245. if (departmentId > 0)
  246. {
  247. query.Where(nameof(User.DepartmentId), departmentId);
  248. }
  249. if (roleId > 0)
  250. {
  251. query.Where(nameof(User.RoleId), roleId);
  252. }
  253. if (!string.IsNullOrEmpty(keyword))
  254. {
  255. query.Where(q =>
  256. q.WhereLike(nameof(User.Name), keyword)
  257. .OrWhereLike(nameof(User.Email), keyword)
  258. .OrWhereLike(nameof(User.Phone), keyword)
  259. );
  260. }
  261. return await _repository.GetAllAsync(query);
  262. }
  263. /// <summary>
  264. /// 登录
  265. /// </summary>
  266. /// <param name="request"></param>
  267. /// <returns></returns>
  268. public async Task<UserSignInResult> SignInAsync(UserSignInRequest request)
  269. {
  270. var result = new UserSignInResult();
  271. var key = $"login:{request.Phone}";
  272. try
  273. {
  274. var user = new User();
  275. if (string.IsNullOrWhiteSpace(request.OpenId))
  276. {
  277. // var code = _cache.GetString(key).Replace("\"", "");
  278. var code = "123456";
  279. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  280. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  281. user = await GetByPhoneAsync(request.Phone);
  282. //用户不存在,自动注册
  283. if (user == null)
  284. {
  285. user = new User();
  286. user.Name = request.Phone;
  287. user.Phone = request.Phone;
  288. user.Id = await InsertAsync(user);
  289. result.UserId = user.Id;
  290. result.DepartmentId = user.DepartmentId;
  291. result.User = _mapper.Map<UserResult>(user);
  292. result.IsAddUser = true;
  293. result.UserEntity = user;
  294. return result;
  295. }
  296. }
  297. else
  298. user = await GetByOpenIdAsync(request.OpenId);
  299. result.UserId = user.Id;
  300. result.DepartmentId = user.DepartmentId;
  301. result.User = _mapper.Map<UserResult>(user);
  302. return result;
  303. }
  304. catch (System.Exception)
  305. {
  306. throw new BusinessException("验证码或手机号错误");
  307. }
  308. }
  309. public async Task<int> InsertAsync(User user)
  310. {
  311. if (user == null) throw new Exception("用户不能为空");
  312. if (string.IsNullOrEmpty(user.Name)) throw new Exception("用户不能为空");
  313. if (!string.IsNullOrEmpty(user.Phone) &&
  314. await _repository.ExistsAsync(Q.Where(nameof(User.Phone), user.Phone)))
  315. {
  316. throw new Exception("用户手机号已存在,请更换手机号");
  317. }
  318. //头像处理
  319. user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
  320. user.IsUpload = false;
  321. user.Id = await _repository.InsertAsync(user);
  322. user = await _repository.GetAsync(user.Id);
  323. //创建二维码
  324. var qrCodeData = new { key = QRCodeTypeConst.UserInfo, value = user.Guid };
  325. var resultPath =
  326. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
  327. JsonConvert.SerializeObject(qrCodeData));
  328. user.QRCoder = resultPath.RelativePath;
  329. await _repository.UpdateAsync(user);
  330. return user.Id;
  331. }
  332. /// <summary>
  333. /// 删除用户
  334. /// </summary>
  335. /// <param name="id"></param>
  336. /// <returns></returns>
  337. public async Task<bool> DeleteAsync(int id)
  338. {
  339. var user = await GetAsync(id);
  340. if (user == null) throw new BusinessException("该用户不存在");
  341. return await DeleteAsync(id);
  342. }
  343. /// <summary>
  344. /// 更新用户信息
  345. /// </summary>
  346. /// <param name="id"></param>
  347. /// <param name="request"></param>
  348. /// <returns></returns>
  349. public async Task<bool> UpdateAsync(int id, User request)
  350. {
  351. var user = await GetAsync(id);
  352. if (user == null) throw new BusinessException("该用户不存在");
  353. if (request.DepartmentId > 0)
  354. user.DepartmentId = request.DepartmentId;
  355. if (!string.IsNullOrEmpty(request.Nick))
  356. user.Nick = request.Nick;
  357. if (!string.IsNullOrEmpty(request.Description))
  358. user.Description = request.Description;
  359. if (!string.IsNullOrEmpty(request.Gender))
  360. user.Gender = request.Gender;
  361. if (!string.IsNullOrEmpty(request.Name))
  362. user.Name = request.Name;
  363. if (!string.IsNullOrEmpty(request.Position))
  364. user.Position = request.Position;
  365. if (request.RoleId > 0)
  366. user.RoleId = request.RoleId;
  367. if (!string.IsNullOrEmpty(request.Signature))
  368. user.Signature = request.Signature;
  369. //用户头像
  370. if (!string.IsNullOrEmpty(request.AvatarUrl))
  371. user.AvatarUrl = StringUtils.RemoveDomain(request.AvatarUrl);
  372. else
  373. user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
  374. user.Email = request.Email;
  375. if (!string.IsNullOrWhiteSpace(request.Phone))
  376. user.Phone = request.Phone;
  377. user.QRCoder = StringUtils.RemoveDomain(user.QRCoder);
  378. return await UpdateAsync(user);
  379. }
  380. /// <summary>
  381. /// 用户分页列表
  382. /// </summary>
  383. /// <param name="request"></param>
  384. /// <returns></returns>
  385. public async Task<PagedList<UserResult>> GetPagedListAsync(UserPageSearchRequest request)
  386. {
  387. var pagedList = new PagedList<UserResult>
  388. {
  389. Total = await GetCountAsync(request.DepartmentId, request.RoleId, request.Keyword)
  390. };
  391. var list = await GetPageListAsync(request.Page, request.PerPage, request.DepartmentId, request.RoleId,
  392. request.Keyword);
  393. var items = list.Select(user => _mapper.Map<UserResult>(user)).ToList();
  394. foreach (var item in items)
  395. {
  396. //获取部门
  397. var department = await _departmentRepository.GetAsync(item.DepartmentId);
  398. if (department != null)
  399. item.DepartmentName = department.Name;
  400. var role = await _roleRepository.GetAsync(item.RoleId);
  401. if (role != null)
  402. item.RoleName = role.Name;
  403. }
  404. pagedList.Items = items;
  405. return pagedList;
  406. }
  407. public async Task<List<UserResult>> GetListAsync(ArticleSearchRequest request)
  408. {
  409. var list = await GetListAsync(request.DepartmentId, request.RoleId, request.Keyword);
  410. var allList = new List<UserResult>();
  411. foreach (var user in list)
  412. {
  413. var result = _mapper.Map<UserResult>(user);
  414. allList.Add(result);
  415. }
  416. return allList;
  417. }
  418. /// <summary>
  419. /// 更新excel用户数据
  420. /// </summary>
  421. /// <param name="request"></param>
  422. /// <returns></returns>
  423. public async Task<bool> UpdateUserExcelAsync(List<User> request)
  424. {
  425. try
  426. {
  427. foreach (var item in request)
  428. {
  429. var user = await _repository.GetAsync(Q.Where(nameof(User.Phone), item.Phone));
  430. if (user != null)
  431. {
  432. continue;
  433. }
  434. var userId = await _repository.InsertAsync(item);
  435. //
  436. user = await _repository.GetAsync(userId);
  437. var resultPath =
  438. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath), item.Guid);
  439. user.QRCoder = resultPath.RelativePath;
  440. await _repository.UpdateAsync(user);
  441. await CreateMiUserAsync(item);
  442. }
  443. }
  444. catch (Exception e)
  445. {
  446. throw new BusinessException(e.Message);
  447. }
  448. return true;
  449. }
  450. /// <summary>
  451. /// 私信
  452. /// </summary>
  453. /// <param name="request"></param>
  454. /// <returns></returns>
  455. public async Task<bool> UpdateUserPrivateLetterAsync(UserPrivateLetterRequest request)
  456. {
  457. var user = await _repository.GetAsync(request.Id);
  458. if (user == null)
  459. throw new BusinessException("该用户不存在");
  460. user.IsPrivateLetter = !user.IsPrivateLetter;
  461. return await _repository.UpdateAsync(user);
  462. }
  463. /// <summary>
  464. /// 通知
  465. /// </summary>
  466. /// <param name="request"></param>
  467. /// <returns></returns>
  468. public async Task<bool> UpdateUserNoticeAsync(UserNoticeRequest request)
  469. {
  470. var user = await _repository.GetAsync(request.Id);
  471. if (user == null)
  472. throw new BusinessException("该用户不存在");
  473. user.IsNotice = !user.IsNotice;
  474. return await _repository.UpdateAsync(user);
  475. }
  476. /// <summary>
  477. /// 回复
  478. /// </summary>
  479. /// <param name="request"></param>
  480. /// <returns></returns>
  481. public async Task<bool> UpdateUserReplyAsync(UserReplyRequest request)
  482. {
  483. var user = await _repository.GetAsync(request.Id);
  484. if (user == null)
  485. throw new BusinessException("该用户不存在");
  486. user.IsReply = !user.IsReply;
  487. return await _repository.UpdateAsync(user);
  488. }
  489. /// <summary>
  490. /// 静音
  491. /// </summary>
  492. /// <param name="request"></param>
  493. /// <returns></returns>
  494. public async Task<bool> UpdateUserMuteAsync(UserMuteRequest request)
  495. {
  496. var user = await _repository.GetAsync(request.Id);
  497. if (user == null)
  498. throw new BusinessException("该用户不存在");
  499. user.IsMute = !user.IsMute;
  500. return await _repository.UpdateAsync(user);
  501. }
  502. /// <summary>
  503. /// 震动
  504. /// </summary>
  505. /// <param name="request"></param>
  506. /// <returns></returns>
  507. public async Task<bool> UpdateUserShakeAsync(UserShakeRequest request)
  508. {
  509. var user = await _repository.GetAsync(request.Id);
  510. if (user == null)
  511. throw new BusinessException("该用户不存在");
  512. user.IsShake = !user.IsShake;
  513. return await _repository.UpdateAsync(user);
  514. }
  515. /// <summary>
  516. /// 用户修改密码
  517. /// </summary>
  518. /// <param name="request"></param>
  519. /// <returns></returns>
  520. public async Task<bool> UpdateUserPhoneAsync(UserUpdatePhoneRequest request)
  521. {
  522. var key = $"login:{request.Phone}";
  523. var code = await _cache.GetStringAsync(key);
  524. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  525. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  526. var user = await GetAsync(request.UserId);
  527. //用户不存在,自动注册
  528. if (user == null)
  529. {
  530. throw new BusinessException("该用户不存在");
  531. }
  532. user.Phone = request.Phone;
  533. return await _repository.UpdateAsync(user);
  534. }
  535. /// <summary>
  536. /// 用户邮箱验证
  537. /// </summary>
  538. /// <param name="request"></param>
  539. /// <returns></returns>
  540. public async Task<bool> SendEmailVerifyCodeAsync(UserEmailVerifyCodeRequest request)
  541. {
  542. //默认配置
  543. ConfigInfo configInfo = new ConfigInfo();
  544. var code = RandomGenerator.GetNumberString(6);
  545. var key = $"email:{request.Email}";
  546. //if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
  547. MailManager.Send(configInfo, request.Email, "邮箱验证", "邮箱验证", $"验证号码:{code}", out var message);
  548. if (!string.IsNullOrEmpty(message))
  549. {
  550. throw new BusinessException(message);
  551. }
  552. //保存验证码
  553. await _cache.SetAsync(key, code, new DistributedCacheEntryOptions
  554. {
  555. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
  556. });
  557. return true;
  558. }
  559. /// <summary>
  560. /// 用户修改密码
  561. /// </summary>
  562. /// <param name="request"></param>
  563. /// <returns></returns>
  564. public async Task<bool> UpdateUserEmailAsync(UserUpdateEmailRequest request)
  565. {
  566. var key = $"email:{request.Email}";
  567. var code = await _cache.GetStringAsync(key);
  568. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  569. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  570. var user = await _repository.GetAsync(request.UserId);
  571. //用户不存在,自动注册
  572. if (user == null)
  573. {
  574. throw new BusinessException("该用户不存在");
  575. }
  576. user.Email = request.Email;
  577. return await _repository.UpdateAsync(user);
  578. }
  579. /// <summary>
  580. /// 根据部门ID获取用户
  581. /// </summary>
  582. /// <param name="departmentId"></param>
  583. /// <returns></returns>
  584. public async Task<IEnumerable<User>> GetUserByDepartmentIdAsync(int departmentId)
  585. {
  586. return await _repository.GetAllAsync(Q.Where(nameof(User.DepartmentId), departmentId));
  587. }
  588. public async Task<IEnumerable<int>> GetUserIdListByDepartmentIdAsync(int departmentId)
  589. {
  590. return await _repository.GetAllAsync<int>(Q
  591. .Select(nameof(User.Id))
  592. .Where(nameof(User.DepartmentId), departmentId)
  593. );
  594. }
  595. public async Task<IEnumerable<int>> GetUserIdListByRoleIdAsync(int roleId)
  596. {
  597. return await _repository.GetAllAsync<int>(Q
  598. .Select(nameof(User.Id))
  599. .Where(nameof(User.RoleId), roleId)
  600. );
  601. }
  602. /// <summary>
  603. /// 创建环信用户
  604. /// </summary>
  605. /// <param name="request"></param>
  606. /// <returns></returns>
  607. public async Task<bool> CreateMiUserAsync(User request)
  608. {
  609. try
  610. {
  611. var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
  612. string result = HttpClientHelper.GetResponseData("{\"username\":\"" + request.Phone + "\", \"password\": \"123456\",\"nickname\":\"" + request.Name + "\"}", $"{imServiceUrl}/users");
  613. if (!string.IsNullOrEmpty(result))
  614. {
  615. _logger.LogDebug(result);
  616. _logger.LogError(result);
  617. var model = JsonConvert.DeserializeObject<dynamic>(result);
  618. var entities = model["entities"];
  619. var jtokenEntities = (JToken)entities;
  620. request.Phone = jtokenEntities[0]["username"].ToString();
  621. //成功后修改用户
  622. var userEntity = await GetByPhoneAsync(request.Phone);
  623. userEntity.ImId = request.Phone;
  624. await _repository.UpdateAsync(userEntity);
  625. }
  626. }
  627. catch (Exception e)
  628. {
  629. throw new BusinessException(e.Message);
  630. }
  631. return true;
  632. }
  633. /// <summary>
  634. /// 用户模糊查询
  635. /// </summary>
  636. /// <param name="request"></param>
  637. /// <returns></returns>
  638. public async Task<IEnumerable<UserInfoResult>> SearchUserNameAsync(SearchUserNameRequest request)
  639. {
  640. var departments = new List<Department>();
  641. var notInUserIds = "";
  642. if (request.UserIds.Count > 0)
  643. {
  644. if (!request.IsShow)
  645. {
  646. notInUserIds = "and Id not in(";
  647. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  648. notInUserIds = "and a.Id not in(";
  649. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  650. notInUserIds = "and Id not in(";
  651. foreach (var userId in request.UserIds)
  652. {
  653. notInUserIds += $"{userId},";
  654. }
  655. notInUserIds = notInUserIds.Remove(notInUserIds.Length - 1, 1);
  656. notInUserIds += ")";
  657. }
  658. }
  659. var sql = $"select * from ccpph.tede_user where (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  660. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  661. sql = $"select a.* from ccpph.tede_user a inner join ccpph.tede_address_book_group_user c on a.Id=c.UserId where c.AddressBookGroupId={request.DepartmentId} and (a.Name like '%{request.Key}%' or a.Phone like '%{request.Key}%' or a.Email like '%{request.Key}%') {notInUserIds}";
  662. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  663. {
  664. //递归获取部门Id
  665. departments = await GetDepartmentAsync(request.DepartmentId, departments);
  666. var departmentValue = $"({request.DepartmentId},";
  667. foreach (var item in departments)
  668. departmentValue += $"{item.Id},";
  669. departmentValue = departmentValue.Remove(departmentValue.Length - 1, 1);
  670. departmentValue += ")";
  671. sql = $"select * from ccpph.tede_user where DepartmentId in {departmentValue} and (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  672. }
  673. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  674. var database = new Database(databaseType, _connectionString);
  675. var connection = database.GetConnection();
  676. var result = await connection.QueryAsync<UserInfoResult>(sql);
  677. foreach (var item in result)
  678. {
  679. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  680. //获取上级
  681. departments = new List<Department>();
  682. departments = await GetUpDepartmentAsync(item.DepartmentId, departments);
  683. foreach (var department in departments)
  684. item.DepartmentName = "-" + department.Name + item.DepartmentName;
  685. if (!string.IsNullOrWhiteSpace(item.DepartmentName))
  686. item.DepartmentName = item.DepartmentName.Remove(0, 1);
  687. if (request.IsShow)
  688. if (request.UserIds.Contains(item.Id))
  689. item.IsDisable = true;
  690. }
  691. return result;
  692. }
  693. public async Task<List<Entity.Department>> GetUpDepartmentAsync(int id, List<Department> departments)
  694. {
  695. var sql = $"select * from ccpph.tede_department where Id={id}";
  696. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  697. var database = new Database(databaseType, _connectionString);
  698. var connection = database.GetConnection();
  699. var result = await connection.QueryFirstOrDefaultAsync<Department>(sql);
  700. if (result == null)
  701. return departments;
  702. departments.Add(result);
  703. await GetUpDepartmentAsync(result.ParentId, departments);
  704. return departments;
  705. }
  706. public async Task<List<Entity.Department>> GetDepartmentAsync(int pid, List<Department> departments)
  707. {
  708. var sql = $"select * from ccpph.tede_department where ParentId={pid}";
  709. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  710. var database = new Database(databaseType, _connectionString);
  711. var connection = database.GetConnection();
  712. var result = await connection.QueryAsync<Department>(sql);
  713. if (result.Count() == 0)
  714. return departments;
  715. departments.AddRange(result);
  716. foreach (var item in result)
  717. await GetDepartmentAsync(item.Id, departments);
  718. return departments;
  719. }
  720. /// <summary>
  721. /// 查询所有用户
  722. /// </summary>
  723. /// <returns></returns>
  724. public async Task<IEnumerable<User>> FindAllUserAsync(SqlKata.Query query)
  725. {
  726. return await _repository.GetAllAsync(query);
  727. }
  728. /// <summary>
  729. /// 根据Guid获取用户数据
  730. /// </summary>
  731. /// <param name="guid"></param>
  732. /// <returns></returns>
  733. public async Task<UserDetail> GetGuidAsync(string guid)
  734. {
  735. var user = await _repository.GetAsync(Q.Where(nameof(User.Guid), guid));
  736. user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  737. user.QRCoder = StringUtils.AddDomain(user.QRCoder);
  738. return _mapper.Map<UserDetail>(user);
  739. }
  740. public async Task<IEnumerable<Entity.User>> GetAllUserIm()
  741. {
  742. string sql = "SELECT * FROM ccpph.tede_user where ImId is null or ImId=''";
  743. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  744. var database = new Database(databaseType, _connectionString);
  745. var connection = database.GetConnection();
  746. return await connection.QueryAsync<User>(sql);
  747. }
  748. public async Task<int> CountAsync(Query query)
  749. {
  750. return await _repository.CountAsync(query);
  751. }
  752. public async Task<IEnumerable<User>> GetAllAsync(Query query)
  753. {
  754. return await _repository.GetAllAsync(query);
  755. }
  756. /// <summary>
  757. /// 根据用户ID获取哦手机号码
  758. /// </summary>
  759. /// <param name="userIds"></param>
  760. /// <returns></returns>
  761. public async Task<IEnumerable<string>> GetUserIdsAsync(List<int> userIds)
  762. {
  763. return await _repository.GetAllAsync<string>(Q.Select(nameof(User.Phone)).WhereIn(nameof(User.Id), userIds));
  764. }
  765. public Task<IEnumerable<User>> FindAllUserAsync()
  766. {
  767. throw new NotImplementedException();
  768. }
  769. /// <summary>
  770. /// 获取用户未读数据
  771. /// </summary>
  772. /// <param name="userId"></param>
  773. /// <returns></returns>
  774. public async Task<UserCountResult> GetUserCountAsync(int userId)
  775. {
  776. var result = new UserCountResult();
  777. string sql = $"select count(1) from ccpph.tede_middle where FolderType=1 and UserId={userId} and MiddleId in (select NoticeId from ccpph.tede_notice_addressee where UserId={userId} and IsRead=0 and IsDelete=0)";
  778. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  779. var database = new Database(databaseType, _connectionString);
  780. var connection = database.GetConnection();
  781. var noticeCount = await connection.ExecuteScalarAsync<int>(sql);
  782. sql = $"select count(1) from ccpph.tede_middle where FolderType=5 and UserId={userId} and MiddleId in (select MissiveId from ccpph.tede_missive_addressee where UserId={userId} and IsDelete=0 and IsRead=0)";
  783. var missiveCount = await connection.ExecuteScalarAsync<int>(sql);
  784. sql = $"SELECT count(1) FROM ccpph.tede_admin_verify where AdminId={userId} and DisposeType=0";
  785. noticeCount += await connection.ExecuteScalarAsync<int>(sql);
  786. result.noticeCount = noticeCount;
  787. result.missiveCount = missiveCount;
  788. return result;
  789. }
  790. /// <summary>
  791. /// 获取工作用户选择审核和抄送人
  792. /// </summary>
  793. /// <param name="userIds"></param>
  794. /// <param name="flowId"></param>
  795. /// <returns></returns>
  796. public async Task<List<Entity.User>> GeFlowUsers(List<int> userIds, int flowId, string type)
  797. {
  798. string strSql = "";
  799. if (userIds.Count > 0)
  800. {
  801. strSql = "and UserId not in(";
  802. foreach (var item in userIds)
  803. {
  804. strSql += $"{item},";
  805. }
  806. strSql = strSql.Remove(strSql.Length - 1, 1);
  807. strSql += ")";
  808. }
  809. string sql = $" select * from ccpph.tede_user where Id in( SELECT UserId FROM ccpph.tede_flow_todo where FlowId={flowId} and Type='{type}' {strSql})";
  810. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  811. var database = new Database(databaseType, _connectionString);
  812. var connection = database.GetConnection();
  813. var result = await connection.QueryAsync<User>(sql);
  814. foreach (var item in result)
  815. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  816. return result.ToList();
  817. }
  818. public async Task<List<JobUserResult>> ElasticSearchUser()
  819. {
  820. var sql = "select * from ccpph.tede_user where IsUpload=0 limit 0,100";
  821. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  822. var database = new Database(databaseType, _connectionString);
  823. var connection = database.GetConnection();
  824. var items = await connection.QueryAsync<JobUserResult>(sql);
  825. return items.ToList();
  826. }
  827. public async Task<bool> UpdateAsync(SqlKata.Query query)
  828. {
  829. return await _repository.UpdateAsync(query) > 0;
  830. }
  831. //public async Task<UserDetail> GetUserDetailJoinAsync(int userId)
  832. //{
  833. // var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
  834. // var database = new Database(databaseType, _connectionString);
  835. // var connection = database.GetConnection();
  836. // var result = connection.Query<UserDetail, Department, UserDetail>(
  837. // "SELECT a.*,b.Name FROM ccpph.tede_user a inner join ccpph.tede_department b on a.DepartmentId=b.Id where a.id=@Id;",
  838. // (userDetail,department) =>
  839. // {
  840. // userDetail.DepartmentName = department.Name;
  841. // return userDetail;
  842. // }, new {Id = userId}, splitOn: "Name");
  843. // return result.ToList()[0];
  844. //}
  845. }
  846. }