UserRepository.cs 38 KB

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