UserRepository.cs 37 KB

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