UserRepository.cs 38 KB

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