UserRepository.cs 37 KB

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