UserRepository.cs 38 KB

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