UserRepository.cs 39 KB

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