UserRepository.cs 37 KB

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