UserRepository.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  287. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  288. user = await GetByPhoneAsync(request.Phone);
  289. }
  290. //用户不存在,自动注册
  291. if (user == null)
  292. {
  293. user = new User();
  294. user.Name = request.Phone;
  295. user.Phone = request.Phone;
  296. user.Gender = "Male";
  297. user.Id = await InsertAsync(user);
  298. result.UserId = user.Id;
  299. result.DepartmentId = user.DepartmentId;
  300. result.User = _mapper.Map<UserResult>(user);
  301. result.IsAddUser = true;
  302. result.UserEntity = user;
  303. return result;
  304. }
  305. }
  306. else
  307. user = await GetByOpenIdAsync(request.OpenId);
  308. result.UserId = user.Id;
  309. result.DepartmentId = user.DepartmentId;
  310. result.User = _mapper.Map<UserResult>(user);
  311. return result;
  312. }
  313. catch (System.Exception)
  314. {
  315. throw new BusinessException("验证码或手机号错误");
  316. }
  317. }
  318. public async Task<int> InsertAsync(User user)
  319. {
  320. if (user == null) throw new Exception("用户不能为空");
  321. if (string.IsNullOrEmpty(user.Name)) throw new Exception("用户不能为空");
  322. if (!string.IsNullOrEmpty(user.Phone) &&
  323. await _repository.ExistsAsync(Q.Where(nameof(User.Phone), user.Phone)))
  324. {
  325. throw new Exception("用户手机号已存在,请更换手机号");
  326. }
  327. //头像处理
  328. user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
  329. user.IsUpload = false;
  330. user.Id = await _repository.InsertAsync(user);
  331. user = await _repository.GetAsync(user.Id);
  332. //创建二维码
  333. var qrCodeData = new { key = QRCodeTypeConst.UserInfo, value = user.Guid };
  334. var resultPath =
  335. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
  336. JsonConvert.SerializeObject(qrCodeData));
  337. user.QRCoder = resultPath.RelativePath;
  338. await _repository.UpdateAsync(user);
  339. return user.Id;
  340. }
  341. /// <summary>
  342. /// 删除用户
  343. /// </summary>
  344. /// <param name="id"></param>
  345. /// <returns></returns>
  346. public async Task<bool> DeleteAsync(int id)
  347. {
  348. var user = await GetAsync(id);
  349. if (user == null) throw new BusinessException("该用户不存在");
  350. return await DeleteAsync(id);
  351. }
  352. /// <summary>
  353. /// 更新用户信息
  354. /// </summary>
  355. /// <param name="id"></param>
  356. /// <param name="request"></param>
  357. /// <returns></returns>
  358. public async Task<bool> UpdateAsync(int id, User request)
  359. {
  360. var user = await GetAsync(id);
  361. if (user == null) throw new BusinessException("该用户不存在");
  362. if (request.DepartmentId > 0)
  363. user.DepartmentId = request.DepartmentId;
  364. if (!string.IsNullOrEmpty(request.Nick))
  365. user.Nick = request.Nick;
  366. if (!string.IsNullOrEmpty(request.Description))
  367. user.Description = request.Description;
  368. if (!string.IsNullOrEmpty(request.Gender))
  369. user.Gender = request.Gender;
  370. if (!string.IsNullOrEmpty(request.Name))
  371. user.Name = request.Name;
  372. if (!string.IsNullOrEmpty(request.Position))
  373. user.Position = request.Position;
  374. if (request.RoleId > 0)
  375. user.RoleId = request.RoleId;
  376. if (!string.IsNullOrEmpty(request.Signature))
  377. user.Signature = request.Signature;
  378. //用户头像
  379. if (!string.IsNullOrEmpty(request.AvatarUrl))
  380. user.AvatarUrl = StringUtils.RemoveDomain(request.AvatarUrl);
  381. else
  382. user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
  383. user.Email = request.Email;
  384. if (!string.IsNullOrWhiteSpace(request.Phone))
  385. user.Phone = request.Phone;
  386. user.QRCoder = StringUtils.RemoveDomain(user.QRCoder);
  387. return await UpdateAsync(user);
  388. }
  389. /// <summary>
  390. /// 用户分页列表
  391. /// </summary>
  392. /// <param name="request"></param>
  393. /// <returns></returns>
  394. public async Task<PagedList<UserResult>> GetPagedListAsync(UserPageSearchRequest request)
  395. {
  396. var pagedList = new PagedList<UserResult>
  397. {
  398. Total = await GetCountAsync(request.DepartmentId, request.RoleId, request.Keyword)
  399. };
  400. var list = await GetPageListAsync(request.Page, request.PerPage, request.DepartmentId, request.RoleId,
  401. request.Keyword);
  402. var items = list.Select(user => _mapper.Map<UserResult>(user)).ToList();
  403. foreach (var item in items)
  404. {
  405. //获取部门
  406. var department = await _departmentRepository.GetAsync(item.DepartmentId);
  407. if (department != null)
  408. item.DepartmentName = department.Name;
  409. var role = await _roleRepository.GetAsync(item.RoleId);
  410. if (role != null)
  411. item.RoleName = role.Name;
  412. }
  413. pagedList.Items = items;
  414. return pagedList;
  415. }
  416. public async Task<List<UserResult>> GetListAsync(ArticleSearchRequest request)
  417. {
  418. var list = await GetListAsync(request.DepartmentId, request.RoleId, request.Keyword);
  419. var allList = new List<UserResult>();
  420. foreach (var user in list)
  421. {
  422. var result = _mapper.Map<UserResult>(user);
  423. allList.Add(result);
  424. }
  425. return allList;
  426. }
  427. /// <summary>
  428. /// 更新excel用户数据
  429. /// </summary>
  430. /// <param name="request"></param>
  431. /// <returns></returns>
  432. public async Task<bool> UpdateUserExcelAsync(List<User> request)
  433. {
  434. try
  435. {
  436. foreach (var item in request)
  437. {
  438. var user = await _repository.GetAsync(Q.Where(nameof(User.Phone), item.Phone));
  439. if (user != null)
  440. {
  441. continue;
  442. }
  443. var userId = await _repository.InsertAsync(item);
  444. //
  445. user = await _repository.GetAsync(userId);
  446. var resultPath =
  447. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath), item.Guid);
  448. user.QRCoder = resultPath.RelativePath;
  449. await _repository.UpdateAsync(user);
  450. await CreateMiUserAsync(item);
  451. }
  452. }
  453. catch (Exception e)
  454. {
  455. throw new BusinessException(e.Message);
  456. }
  457. return true;
  458. }
  459. /// <summary>
  460. /// 私信
  461. /// </summary>
  462. /// <param name="request"></param>
  463. /// <returns></returns>
  464. public async Task<bool> UpdateUserPrivateLetterAsync(UserPrivateLetterRequest request)
  465. {
  466. var user = await _repository.GetAsync(request.Id);
  467. if (user == null)
  468. throw new BusinessException("该用户不存在");
  469. user.IsPrivateLetter = !user.IsPrivateLetter;
  470. return await _repository.UpdateAsync(user);
  471. }
  472. /// <summary>
  473. /// 通知
  474. /// </summary>
  475. /// <param name="request"></param>
  476. /// <returns></returns>
  477. public async Task<bool> UpdateUserNoticeAsync(UserNoticeRequest request)
  478. {
  479. var user = await _repository.GetAsync(request.Id);
  480. if (user == null)
  481. throw new BusinessException("该用户不存在");
  482. user.IsNotice = !user.IsNotice;
  483. return await _repository.UpdateAsync(user);
  484. }
  485. /// <summary>
  486. /// 回复
  487. /// </summary>
  488. /// <param name="request"></param>
  489. /// <returns></returns>
  490. public async Task<bool> UpdateUserReplyAsync(UserReplyRequest request)
  491. {
  492. var user = await _repository.GetAsync(request.Id);
  493. if (user == null)
  494. throw new BusinessException("该用户不存在");
  495. user.IsReply = !user.IsReply;
  496. return await _repository.UpdateAsync(user);
  497. }
  498. /// <summary>
  499. /// 静音
  500. /// </summary>
  501. /// <param name="request"></param>
  502. /// <returns></returns>
  503. public async Task<bool> UpdateUserMuteAsync(UserMuteRequest request)
  504. {
  505. var user = await _repository.GetAsync(request.Id);
  506. if (user == null)
  507. throw new BusinessException("该用户不存在");
  508. user.IsMute = !user.IsMute;
  509. return await _repository.UpdateAsync(user);
  510. }
  511. /// <summary>
  512. /// 震动
  513. /// </summary>
  514. /// <param name="request"></param>
  515. /// <returns></returns>
  516. public async Task<bool> UpdateUserShakeAsync(UserShakeRequest request)
  517. {
  518. var user = await _repository.GetAsync(request.Id);
  519. if (user == null)
  520. throw new BusinessException("该用户不存在");
  521. user.IsShake = !user.IsShake;
  522. return await _repository.UpdateAsync(user);
  523. }
  524. /// <summary>
  525. /// 用户修改密码
  526. /// </summary>
  527. /// <param name="request"></param>
  528. /// <returns></returns>
  529. public async Task<bool> UpdateUserPhoneAsync(UserUpdatePhoneRequest request)
  530. {
  531. var key = $"login:{request.Phone}";
  532. var code = await _cache.GetStringAsync(key);
  533. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  534. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  535. var user = await GetAsync(request.UserId);
  536. //用户不存在,自动注册
  537. if (user == null)
  538. {
  539. throw new BusinessException("该用户不存在");
  540. }
  541. user.Phone = request.Phone;
  542. return await _repository.UpdateAsync(user);
  543. }
  544. /// <summary>
  545. /// 用户邮箱验证
  546. /// </summary>
  547. /// <param name="request"></param>
  548. /// <returns></returns>
  549. public async Task<bool> SendEmailVerifyCodeAsync(UserEmailVerifyCodeRequest request)
  550. {
  551. //默认配置
  552. ConfigInfo configInfo = new ConfigInfo();
  553. var code = RandomGenerator.GetNumberString(6);
  554. var key = $"email:{request.Email}";
  555. //if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
  556. MailManager.Send(configInfo, request.Email, "邮箱验证", "邮箱验证", $"验证号码:{code}", out var message);
  557. if (!string.IsNullOrEmpty(message))
  558. {
  559. throw new BusinessException(message);
  560. }
  561. //保存验证码
  562. await _cache.SetAsync(key, code, new DistributedCacheEntryOptions
  563. {
  564. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
  565. });
  566. return true;
  567. }
  568. /// <summary>
  569. /// 用户修改密码
  570. /// </summary>
  571. /// <param name="request"></param>
  572. /// <returns></returns>
  573. public async Task<bool> UpdateUserEmailAsync(UserUpdateEmailRequest request)
  574. {
  575. var key = $"email:{request.Email}";
  576. var code = await _cache.GetStringAsync(key);
  577. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  578. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  579. var user = await _repository.GetAsync(request.UserId);
  580. //用户不存在,自动注册
  581. if (user == null)
  582. {
  583. throw new BusinessException("该用户不存在");
  584. }
  585. user.Email = request.Email;
  586. return await _repository.UpdateAsync(user);
  587. }
  588. /// <summary>
  589. /// 根据部门ID获取用户
  590. /// </summary>
  591. /// <param name="departmentId"></param>
  592. /// <returns></returns>
  593. public async Task<IEnumerable<User>> GetUserByDepartmentIdAsync(int departmentId)
  594. {
  595. return await _repository.GetAllAsync(Q.Where(nameof(User.DepartmentId), departmentId));
  596. }
  597. public async Task<IEnumerable<int>> GetUserIdListByDepartmentIdAsync(int departmentId)
  598. {
  599. return await _repository.GetAllAsync<int>(Q
  600. .Select(nameof(User.Id))
  601. .Where(nameof(User.DepartmentId), departmentId)
  602. );
  603. }
  604. public async Task<IEnumerable<int>> GetUserIdListByRoleIdAsync(int roleId)
  605. {
  606. return await _repository.GetAllAsync<int>(Q
  607. .Select(nameof(User.Id))
  608. .Where(nameof(User.RoleId), roleId)
  609. );
  610. }
  611. /// <summary>
  612. /// 创建环信用户
  613. /// </summary>
  614. /// <param name="request"></param>
  615. /// <returns></returns>
  616. public async Task<bool> CreateMiUserAsync(User request)
  617. {
  618. try
  619. {
  620. var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
  621. string result = HttpClientHelper.GetResponseData("{\"username\":\"" + request.Phone + "\", \"password\": \"123456\",\"nickname\":\"" + request.Name + "\"}", $"{imServiceUrl}/users");
  622. if (!string.IsNullOrEmpty(result))
  623. {
  624. _logger.LogDebug(result);
  625. _logger.LogError(result);
  626. var model = JsonConvert.DeserializeObject<dynamic>(result);
  627. var entities = model["entities"];
  628. var jtokenEntities = (JToken)entities;
  629. request.Phone = jtokenEntities[0]["username"].ToString();
  630. //成功后修改用户
  631. var userEntity = await GetByPhoneAsync(request.Phone);
  632. userEntity.ImId = request.Phone;
  633. await _repository.UpdateAsync(userEntity);
  634. }
  635. }
  636. catch (Exception e)
  637. {
  638. throw new BusinessException(e.Message);
  639. }
  640. return true;
  641. }
  642. /// <summary>
  643. /// 用户模糊查询
  644. /// </summary>
  645. /// <param name="request"></param>
  646. /// <returns></returns>
  647. public async Task<IEnumerable<UserInfoResult>> SearchUserNameAsync(SearchUserNameRequest request)
  648. {
  649. var departments = new List<Department>();
  650. var notInUserIds = "";
  651. if (request.UserIds.Count > 0)
  652. {
  653. if (!request.IsShow)
  654. {
  655. notInUserIds = "and Id not in(";
  656. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  657. notInUserIds = "and a.Id not in(";
  658. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  659. notInUserIds = "and Id not in(";
  660. foreach (var userId in request.UserIds)
  661. {
  662. notInUserIds += $"{userId},";
  663. }
  664. notInUserIds = notInUserIds.Remove(notInUserIds.Length - 1, 1);
  665. notInUserIds += ")";
  666. }
  667. }
  668. var sql = $"select * from ccpph.tede_user where (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  669. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  670. 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}";
  671. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  672. {
  673. //递归获取部门Id
  674. departments = await GetDepartmentAsync(request.DepartmentId, departments);
  675. var departmentValue = $"({request.DepartmentId},";
  676. foreach (var item in departments)
  677. departmentValue += $"{item.Id},";
  678. departmentValue = departmentValue.Remove(departmentValue.Length - 1, 1);
  679. departmentValue += ")";
  680. 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}";
  681. }
  682. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  683. var database = new Database(databaseType, _connectionString);
  684. var connection = database.GetConnection();
  685. var result = await connection.QueryAsync<UserInfoResult>(sql);
  686. foreach (var item in result)
  687. {
  688. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  689. //获取上级
  690. departments = new List<Department>();
  691. departments = await GetUpDepartmentAsync(item.DepartmentId, departments);
  692. foreach (var department in departments)
  693. item.DepartmentName = "-" + department.Name + item.DepartmentName;
  694. if (!string.IsNullOrWhiteSpace(item.DepartmentName))
  695. item.DepartmentName = item.DepartmentName.Remove(0, 1);
  696. if (request.IsShow)
  697. if (request.UserIds.Contains(item.Id))
  698. item.IsDisable = true;
  699. }
  700. return result;
  701. }
  702. public async Task<List<Entity.Department>> GetUpDepartmentAsync(int id, List<Department> departments)
  703. {
  704. var sql = $"select * from ccpph.tede_department where Id={id}";
  705. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  706. var database = new Database(databaseType, _connectionString);
  707. var connection = database.GetConnection();
  708. var result = await connection.QueryFirstOrDefaultAsync<Department>(sql);
  709. if (result == null)
  710. return departments;
  711. departments.Add(result);
  712. await GetUpDepartmentAsync(result.ParentId, departments);
  713. return departments;
  714. }
  715. public async Task<List<Entity.Department>> GetDepartmentAsync(int pid, List<Department> departments)
  716. {
  717. var sql = $"select * from ccpph.tede_department where ParentId={pid}";
  718. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  719. var database = new Database(databaseType, _connectionString);
  720. var connection = database.GetConnection();
  721. var result = await connection.QueryAsync<Department>(sql);
  722. if (result.Count() == 0)
  723. return departments;
  724. departments.AddRange(result);
  725. foreach (var item in result)
  726. await GetDepartmentAsync(item.Id, departments);
  727. return departments;
  728. }
  729. /// <summary>
  730. /// 查询所有用户
  731. /// </summary>
  732. /// <returns></returns>
  733. public async Task<IEnumerable<User>> FindAllUserAsync(SqlKata.Query query)
  734. {
  735. return await _repository.GetAllAsync(query);
  736. }
  737. /// <summary>
  738. /// 根据Guid获取用户数据
  739. /// </summary>
  740. /// <param name="guid"></param>
  741. /// <returns></returns>
  742. public async Task<UserDetail> GetGuidAsync(string guid)
  743. {
  744. var user = await _repository.GetAsync(Q.Where(nameof(User.Guid), guid));
  745. user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  746. user.QRCoder = StringUtils.AddDomain(user.QRCoder);
  747. return _mapper.Map<UserDetail>(user);
  748. }
  749. public async Task<IEnumerable<Entity.User>> GetAllUserIm()
  750. {
  751. string sql = "SELECT * FROM ccpph.tede_user where ImId is null or ImId=''";
  752. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  753. var database = new Database(databaseType, _connectionString);
  754. var connection = database.GetConnection();
  755. return await connection.QueryAsync<User>(sql);
  756. }
  757. public async Task<int> CountAsync(Query query)
  758. {
  759. return await _repository.CountAsync(query);
  760. }
  761. public async Task<IEnumerable<User>> GetAllAsync(Query query)
  762. {
  763. return await _repository.GetAllAsync(query);
  764. }
  765. /// <summary>
  766. /// 根据用户ID获取哦手机号码
  767. /// </summary>
  768. /// <param name="userIds"></param>
  769. /// <returns></returns>
  770. public async Task<IEnumerable<string>> GetUserIdsAsync(List<int> userIds)
  771. {
  772. return await _repository.GetAllAsync<string>(Q.Select(nameof(User.Phone)).WhereIn(nameof(User.Id), userIds));
  773. }
  774. public Task<IEnumerable<User>> FindAllUserAsync()
  775. {
  776. throw new NotImplementedException();
  777. }
  778. /// <summary>
  779. /// 获取用户未读数据
  780. /// </summary>
  781. /// <param name="userId"></param>
  782. /// <returns></returns>
  783. public async Task<UserCountResult> GetUserCountAsync(int userId)
  784. {
  785. var result = new UserCountResult();
  786. 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)";
  787. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  788. var database = new Database(databaseType, _connectionString);
  789. var connection = database.GetConnection();
  790. var noticeCount = await connection.ExecuteScalarAsync<int>(sql);
  791. 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)";
  792. var missiveCount = await connection.ExecuteScalarAsync<int>(sql);
  793. sql = $"SELECT count(1) FROM ccpph.tede_admin_verify where AdminId={userId} and DisposeType=0";
  794. noticeCount += await connection.ExecuteScalarAsync<int>(sql);
  795. result.noticeCount = noticeCount;
  796. result.missiveCount = missiveCount;
  797. return result;
  798. }
  799. /// <summary>
  800. /// 获取工作用户选择审核和抄送人
  801. /// </summary>
  802. /// <param name="userIds"></param>
  803. /// <param name="flowId"></param>
  804. /// <returns></returns>
  805. public async Task<List<Entity.User>> GeFlowUsers(List<int> userIds, int flowId, string type)
  806. {
  807. string strSql = "";
  808. if (userIds.Count > 0)
  809. {
  810. strSql = "and UserId not in(";
  811. foreach (var item in userIds)
  812. {
  813. strSql += $"{item},";
  814. }
  815. strSql = strSql.Remove(strSql.Length - 1, 1);
  816. strSql += ")";
  817. }
  818. string sql = $" select * from ccpph.tede_user where Id in( SELECT UserId FROM ccpph.tede_flow_todo where FlowId={flowId} and Type='{type}' {strSql})";
  819. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  820. var database = new Database(databaseType, _connectionString);
  821. var connection = database.GetConnection();
  822. var result = await connection.QueryAsync<User>(sql);
  823. foreach (var item in result)
  824. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  825. return result.ToList();
  826. }
  827. public async Task<List<JobUserResult>> ElasticSearchUser()
  828. {
  829. var sql = "select * from ccpph.tede_user where IsUpload=0 limit 0,100";
  830. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  831. var database = new Database(databaseType, _connectionString);
  832. var connection = database.GetConnection();
  833. var items = await connection.QueryAsync<JobUserResult>(sql);
  834. return items.ToList();
  835. }
  836. public async Task<bool> UpdateAsync(SqlKata.Query query)
  837. {
  838. return await _repository.UpdateAsync(query) > 0;
  839. }
  840. //public async Task<UserDetail> GetUserDetailJoinAsync(int userId)
  841. //{
  842. // var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
  843. // var database = new Database(databaseType, _connectionString);
  844. // var connection = database.GetConnection();
  845. // var result = connection.Query<UserDetail, Department, UserDetail>(
  846. // "SELECT a.*,b.Name FROM ccpph.tede_user a inner join ccpph.tede_department b on a.DepartmentId=b.Id where a.id=@Id;",
  847. // (userDetail,department) =>
  848. // {
  849. // userDetail.DepartmentName = department.Name;
  850. // return userDetail;
  851. // }, new {Id = userId}, splitOn: "Name");
  852. // return result.ToList()[0];
  853. //}
  854. }
  855. }