UserRepository.cs 39 KB

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