UserRepository.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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<int> GetUserCount(string beginTime, string endTime)
  98. {
  99. return await _repository.CountAsync(Q.WhereDate(nameof(User.CreatedDate), ">=", beginTime).WhereDate(nameof(User.CreatedDate), "<=", endTime));
  100. }
  101. public async Task<User> GetAsync(int id)
  102. {
  103. var user = await _repository.GetAsync(id);
  104. return user;
  105. }
  106. public async Task<User> GetAsync(SqlKata.Query query)
  107. {
  108. var user = await _repository.GetAsync(query);
  109. return user;
  110. }
  111. public async Task<string> GetNameAsync(int id)
  112. {
  113. if (id <= 0) return string.Empty;
  114. return await _repository.GetAsync<string>(Q
  115. .Select(nameof(User.Name))
  116. .Where(nameof(User.Id), id)
  117. );
  118. }
  119. public async Task<string> GetAvatarUrlAsync(int id)
  120. {
  121. if (id <= 0) return string.Empty;
  122. var avatarUrl = await _repository.GetAsync<string>(Q
  123. .Select(nameof(User.AvatarUrl))
  124. .Where(nameof(User.Id), id)
  125. );
  126. return StringUtils.AddDomainMin(avatarUrl);
  127. }
  128. public string GetAvatarUrl(User user)
  129. {
  130. if (user == null) return string.Empty;
  131. return StringUtils.AddDomainMin(user.AvatarUrl);
  132. }
  133. public async Task<User> GetByPhoneAsync(string phone)
  134. {
  135. return await _repository.GetAsync(Q.Where(nameof(User.Phone), phone));
  136. }
  137. /// <summary>
  138. /// openId微信认证
  139. /// </summary>
  140. /// <param name="openId"></param>
  141. /// /// <returns></returns>
  142. public async Task<User> GetByOpenIdAsync(string openId)
  143. {
  144. return await _repository.GetAsync(Q.Where(nameof(User.OpenId), openId));
  145. }
  146. /// <summary>
  147. /// 绑定微信
  148. /// </summary>
  149. /// <param name="request"></param>
  150. /// <returns></returns>
  151. public async Task<bool> UpdateByOpendIdAsync(UserSignInRequest request)
  152. {
  153. var key = $"login:{request.Phone}";
  154. var user = new User();
  155. var code = _cache.GetString(key).Replace("\"", "");
  156. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  157. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  158. user = await GetByPhoneAsync(request.Phone);
  159. //用户不存在,自动注册
  160. if (user == null)
  161. throw new BusinessException("用户不存在");
  162. return await _repository.UpdateAsync(Q.Where(nameof(User.Phone), request.Phone).Set(nameof(User.OpenId), request.OpenId)) > 0;
  163. }
  164. public async Task<bool> DeleteUsersAsync(IEnumerable<int> userIds)
  165. {
  166. return await _repository.DeleteAsync(Q.WhereIn(nameof(User.Id), userIds)) > 0;
  167. }
  168. public async Task<bool> ChangeRoleAsync(IEnumerable<int> userIds, int roleId)
  169. {
  170. return await _repository.UpdateAsync(Q
  171. .Set(nameof(User.RoleId), roleId)
  172. .WhereIn(nameof(User.Id), userIds)
  173. ) > 0;
  174. }
  175. public async Task<bool> ChangeDepartmentAsync(IEnumerable<int> userIds, int departmentId)
  176. {
  177. return await _repository.UpdateAsync(Q
  178. .Set(nameof(User.DepartmentId), departmentId)
  179. .WhereIn(nameof(User.Id), userIds)
  180. ) > 0;
  181. }
  182. public async Task<bool> UpdateAsync(User user)
  183. {
  184. return await _repository.UpdateAsync(user);
  185. }
  186. public async Task<bool> UpdateDisableAsync(UserUpdateDisableRequest request)
  187. {
  188. return await _repository.UpdateAsync(Q.WhereIn(nameof(User.Id), request.Ids).Set(nameof(User.IsDisable), request.IsDisable)) > 0;
  189. }
  190. public async Task<int> GetCountAsync(int departmentId, int roleId, string keyword)
  191. {
  192. var query = Q.NewQuery();
  193. if (departmentId > 0)
  194. {
  195. query.Where(nameof(User.DepartmentId), departmentId);
  196. }
  197. if (roleId > 0)
  198. {
  199. query.Where(nameof(User.RoleId), roleId);
  200. }
  201. if (!string.IsNullOrEmpty(keyword))
  202. {
  203. keyword = "%" + keyword + "%";
  204. query.Where(q =>
  205. q.WhereLike(nameof(User.Name), keyword)
  206. .OrWhereLike(nameof(User.Email), keyword)
  207. .OrWhereLike(nameof(User.Phone), keyword)
  208. );
  209. }
  210. return await _repository.CountAsync(query);
  211. }
  212. /// <summary>
  213. /// Set the limit and offset for a given page.
  214. /// </summary>
  215. /// <param name="page"></param>
  216. /// <param name="perPage"></param>
  217. /// <param name="departmentId"></param>
  218. /// <param name="roleId"></param>
  219. /// <param name="keyword"></param>
  220. /// <returns></returns>
  221. public async Task<IEnumerable<User>> GetPageListAsync(int page, int perPage, int departmentId, int roleId,
  222. string keyword)
  223. {
  224. var query = Q.ForPage(page, perPage);
  225. if (departmentId > 0)
  226. {
  227. query.Where(nameof(User.DepartmentId), departmentId);
  228. }
  229. if (roleId > 0)
  230. {
  231. query.Where(nameof(User.RoleId), roleId);
  232. }
  233. if (!string.IsNullOrEmpty(keyword))
  234. {
  235. keyword = "%" + keyword + "%";
  236. query.Where(q =>
  237. q.WhereLike(nameof(User.Name), keyword)
  238. .OrWhereLike(nameof(User.Email), keyword)
  239. .OrWhereLike(nameof(User.Phone), keyword)
  240. );
  241. }
  242. return await _repository.GetAllAsync(query);
  243. }
  244. public async Task<IEnumerable<User>> GetListAsync(int departmentId, int roleId, string keyword)
  245. {
  246. var query = Q.NewQuery();
  247. if (departmentId > 0)
  248. {
  249. query.Where(nameof(User.DepartmentId), departmentId);
  250. }
  251. if (roleId > 0)
  252. {
  253. query.Where(nameof(User.RoleId), roleId);
  254. }
  255. if (!string.IsNullOrEmpty(keyword))
  256. {
  257. query.Where(q =>
  258. q.WhereLike(nameof(User.Name), keyword)
  259. .OrWhereLike(nameof(User.Email), keyword)
  260. .OrWhereLike(nameof(User.Phone), keyword)
  261. );
  262. }
  263. return await _repository.GetAllAsync(query);
  264. }
  265. /// <summary>
  266. /// 登录
  267. /// </summary>
  268. /// <param name="request"></param>
  269. /// <returns></returns>
  270. public async Task<UserSignInResult> SignInAsync(UserSignInRequest request)
  271. {
  272. var result = new UserSignInResult();
  273. var key = $"login:{request.Phone}";
  274. try
  275. {
  276. var user = new User();
  277. if (string.IsNullOrWhiteSpace(request.OpenId))
  278. {
  279. var code = _cache.GetString(key).Replace("\"", "");
  280. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  281. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  282. user = await GetByPhoneAsync(request.Phone);
  283. //用户不存在,自动注册
  284. if (user == null)
  285. throw new BusinessException("用户不存在");
  286. }
  287. else
  288. user = await GetByOpenIdAsync(request.OpenId);
  289. result.UserId = user.Id;
  290. result.DepartmentId = user.DepartmentId;
  291. result.User = _mapper.Map<UserResult>(user);
  292. //修改登录时间
  293. user.LoginTime = DateTime.Now;
  294. await _repository.UpdateAsync(user);
  295. return result;
  296. }
  297. catch (System.Exception)
  298. {
  299. throw new BusinessException("验证码或手机号错误");
  300. }
  301. }
  302. public async Task<int> InsertAsync(User user)
  303. {
  304. if (user == null) throw new Exception("用户不能为空");
  305. if (string.IsNullOrEmpty(user.Name)) throw new Exception("用户不能为空");
  306. if (!string.IsNullOrEmpty(user.Phone) &&
  307. await _repository.ExistsAsync(Q.Where(nameof(User.Phone), user.Phone)))
  308. {
  309. throw new Exception("用户手机号已存在,请更换手机号");
  310. }
  311. //头像处理
  312. user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
  313. user.IsUpload = false;
  314. user.Id = await _repository.InsertAsync(user);
  315. user = await _repository.GetAsync(user.Id);
  316. //创建二维码
  317. var qrCodeData = new { key = QRCodeTypeConst.UserInfo, value = user.Guid };
  318. var resultPath =
  319. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
  320. JsonConvert.SerializeObject(qrCodeData));
  321. user.QRCoder = resultPath.RelativePath;
  322. await _repository.UpdateAsync(user);
  323. return user.Id;
  324. }
  325. /// <summary>
  326. /// 删除用户
  327. /// </summary>
  328. /// <param name="id"></param>
  329. /// <returns></returns>
  330. public async Task<bool> DeleteAsync(int id)
  331. {
  332. var user = await GetAsync(id);
  333. if (user == null) throw new BusinessException("该用户不存在");
  334. return await DeleteAsync(id);
  335. }
  336. /// <summary>
  337. /// 删除用户
  338. /// </summary>
  339. /// <param name="ids"></param>
  340. /// <returns></returns>
  341. public async Task<bool> DeleteAsync(List<int> ids)
  342. {
  343. return await _repository.DeleteAsync(Q.WhereIn(nameof(User.Id), ids)) > 0;
  344. }
  345. /// <summary>
  346. /// 更新用户信息
  347. /// </summary>
  348. /// <param name="id"></param>
  349. /// <param name="request"></param>
  350. /// <returns></returns>
  351. public async Task<bool> UpdateAsync(int id, UserInfoRequest request)
  352. {
  353. var user = await GetAsync(id);
  354. if (user == null) throw new BusinessException("该用户不存在");
  355. if (request.DepartmentId > 0)
  356. user.DepartmentId = request.DepartmentId;
  357. if (!string.IsNullOrEmpty(request.Nick))
  358. user.Nick = request.Nick;
  359. if (!string.IsNullOrEmpty(request.Description))
  360. user.Description = request.Description;
  361. if (!string.IsNullOrEmpty(request.Gender))
  362. user.Gender = request.Gender;
  363. if (!string.IsNullOrEmpty(request.Name))
  364. user.Name = request.Name;
  365. if (!string.IsNullOrEmpty(request.Position))
  366. user.Position = request.Position;
  367. if (request.RoleId > 0)
  368. user.RoleId = request.RoleId;
  369. if (!string.IsNullOrEmpty(request.Signature))
  370. user.Signature = request.Signature;
  371. //用户头像
  372. if (!string.IsNullOrEmpty(request.AvatarUrl))
  373. user.AvatarUrl = StringUtils.RemoveDomain(request.AvatarUrl);
  374. else
  375. user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
  376. user.Email = request.Email;
  377. if (!string.IsNullOrWhiteSpace(request.Phone))
  378. user.Phone = request.Phone;
  379. user.QRCoder = StringUtils.RemoveDomain(user.QRCoder);
  380. if (request.IsDisable > 0)
  381. user.IsDisable = request.IsDisable == 1;
  382. if (request.IsFreeze > 0)
  383. user.IsFreeze = request.IsFreeze == 1;
  384. if (request.IsVip > 0)
  385. user.IsVip = request.IsVip == 1;
  386. if (!string.IsNullOrWhiteSpace(request.DisableTiem))
  387. user.DisableTiem = Convert.ToDateTime(request.DisableTiem);
  388. return await UpdateAsync(user);
  389. }
  390. /// <summary>
  391. /// 用户分页列表
  392. /// </summary>
  393. /// <param name="request"></param>
  394. /// <returns></returns>
  395. public async Task<PagedList<UserResult>> GetPagedListAsync(UserPageSearchRequest request)
  396. {
  397. var pagedList = new PagedList<UserResult>
  398. {
  399. Total = await GetCountAsync(request.DepartmentId, request.RoleId, request.Keyword)
  400. };
  401. var list = await GetPageListAsync(request.Page, request.PerPage, request.DepartmentId, request.RoleId,
  402. request.Keyword);
  403. var items = list.Select(user => _mapper.Map<UserResult>(user)).ToList();
  404. foreach (var item in items)
  405. {
  406. //获取部门
  407. var department = await _departmentRepository.GetAsync(item.DepartmentId);
  408. if (department != null)
  409. item.DepartmentName = department.Name;
  410. var role = await _roleRepository.GetAsync(item.RoleId);
  411. if (role != null)
  412. item.RoleName = role.Name;
  413. }
  414. pagedList.Items = items;
  415. return pagedList;
  416. }
  417. public async Task<List<UserResult>> GetListAsync(ArticleSearchRequest request)
  418. {
  419. var list = await GetListAsync(request.DepartmentId, request.RoleId, request.Keyword);
  420. var allList = new List<UserResult>();
  421. foreach (var user in list)
  422. {
  423. var result = _mapper.Map<UserResult>(user);
  424. allList.Add(result);
  425. }
  426. return allList;
  427. }
  428. /// <summary>
  429. /// 更新excel用户数据
  430. /// </summary>
  431. /// <param name="request"></param>
  432. /// <returns></returns>
  433. public async Task<bool> UpdateUserExcelAsync(List<User> request)
  434. {
  435. try
  436. {
  437. foreach (var item in request)
  438. {
  439. var user = await _repository.GetAsync(Q.Where(nameof(User.Phone), item.Phone));
  440. if (user != null)
  441. {
  442. continue;
  443. }
  444. var userId = await _repository.InsertAsync(item);
  445. //
  446. user = await _repository.GetAsync(userId);
  447. var resultPath =
  448. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath), item.Guid);
  449. user.QRCoder = resultPath.RelativePath;
  450. await _repository.UpdateAsync(user);
  451. await CreateMiUserAsync(item);
  452. }
  453. }
  454. catch (Exception e)
  455. {
  456. throw new BusinessException(e.Message);
  457. }
  458. return true;
  459. }
  460. /// <summary>
  461. /// 私信
  462. /// </summary>
  463. /// <param name="request"></param>
  464. /// <returns></returns>
  465. public async Task<bool> UpdateUserPrivateLetterAsync(UserPrivateLetterRequest request)
  466. {
  467. var user = await _repository.GetAsync(request.Id);
  468. if (user == null)
  469. throw new BusinessException("该用户不存在");
  470. user.IsPrivateLetter = !user.IsPrivateLetter;
  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> UpdateUserNoticeAsync(UserNoticeRequest request)
  479. {
  480. var user = await _repository.GetAsync(request.Id);
  481. if (user == null)
  482. throw new BusinessException("该用户不存在");
  483. user.IsNotice = !user.IsNotice;
  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> UpdateUserReplyAsync(UserReplyRequest request)
  492. {
  493. var user = await _repository.GetAsync(request.Id);
  494. if (user == null)
  495. throw new BusinessException("该用户不存在");
  496. user.IsReply = !user.IsReply;
  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> UpdateUserMuteAsync(UserMuteRequest request)
  505. {
  506. var user = await _repository.GetAsync(request.Id);
  507. if (user == null)
  508. throw new BusinessException("该用户不存在");
  509. user.IsMute = !user.IsMute;
  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> UpdateUserShakeAsync(UserShakeRequest request)
  518. {
  519. var user = await _repository.GetAsync(request.Id);
  520. if (user == null)
  521. throw new BusinessException("该用户不存在");
  522. user.IsShake = !user.IsShake;
  523. return await _repository.UpdateAsync(user);
  524. }
  525. /// <summary>
  526. /// 用户修改密码
  527. /// </summary>
  528. /// <param name="request"></param>
  529. /// <returns></returns>
  530. public async Task<bool> UpdateUserPhoneAsync(UserUpdatePhoneRequest request)
  531. {
  532. var key = $"login:{request.Phone}";
  533. var code = await _cache.GetStringAsync(key);
  534. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  535. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  536. var user = await GetAsync(request.UserId);
  537. //用户不存在,自动注册
  538. if (user == null)
  539. {
  540. throw new BusinessException("该用户不存在");
  541. }
  542. user.Phone = request.Phone;
  543. return await _repository.UpdateAsync(user);
  544. }
  545. /// <summary>
  546. /// 用户邮箱验证
  547. /// </summary>
  548. /// <param name="request"></param>
  549. /// <returns></returns>
  550. public async Task<bool> SendEmailVerifyCodeAsync(UserEmailVerifyCodeRequest request)
  551. {
  552. //默认配置
  553. ConfigInfo configInfo = new ConfigInfo();
  554. var code = RandomGenerator.GetNumberString(6);
  555. var key = $"email:{request.Email}";
  556. //if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
  557. MailManager.Send(configInfo, request.Email, "邮箱验证", "邮箱验证", $"验证号码:{code}", out var message);
  558. if (!string.IsNullOrEmpty(message))
  559. {
  560. throw new BusinessException(message);
  561. }
  562. //保存验证码
  563. await _cache.SetAsync(key, code, new DistributedCacheEntryOptions
  564. {
  565. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
  566. });
  567. return true;
  568. }
  569. /// <summary>
  570. /// 用户修改密码
  571. /// </summary>
  572. /// <param name="request"></param>
  573. /// <returns></returns>
  574. public async Task<bool> UpdateUserEmailAsync(UserUpdateEmailRequest request)
  575. {
  576. var key = $"email:{request.Email}";
  577. var code = await _cache.GetStringAsync(key);
  578. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  579. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  580. var user = await _repository.GetAsync(request.UserId);
  581. //用户不存在,自动注册
  582. if (user == null)
  583. {
  584. throw new BusinessException("该用户不存在");
  585. }
  586. user.Email = request.Email;
  587. return await _repository.UpdateAsync(user);
  588. }
  589. /// <summary>
  590. /// 根据部门ID获取用户
  591. /// </summary>
  592. /// <param name="departmentId"></param>
  593. /// <returns></returns>
  594. public async Task<IEnumerable<User>> GetUserByDepartmentIdAsync(int departmentId)
  595. {
  596. return await _repository.GetAllAsync(Q.Where(nameof(User.DepartmentId), departmentId));
  597. }
  598. public async Task<IEnumerable<int>> GetUserIdListByDepartmentIdAsync(int departmentId)
  599. {
  600. return await _repository.GetAllAsync<int>(Q
  601. .Select(nameof(User.Id))
  602. .Where(nameof(User.DepartmentId), departmentId)
  603. );
  604. }
  605. public async Task<IEnumerable<int>> GetUserIdListByRoleIdAsync(int roleId)
  606. {
  607. return await _repository.GetAllAsync<int>(Q
  608. .Select(nameof(User.Id))
  609. .Where(nameof(User.RoleId), roleId)
  610. );
  611. }
  612. /// <summary>
  613. /// 创建环信用户
  614. /// </summary>
  615. /// <param name="request"></param>
  616. /// <returns></returns>
  617. public async Task<bool> CreateMiUserAsync(User request)
  618. {
  619. try
  620. {
  621. var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
  622. HttpClient httpClient = new HttpClient(); //http对象
  623. HttpResponseMessage response = await httpClient.PostAsync(
  624. $"{imServiceUrl}/users",
  625. new JsonContent(new { username = request.Phone, password = "123456", nickname = request.Name }));
  626. if (response.IsSuccessStatusCode)
  627. {
  628. string result = await response.Content.ReadAsStringAsync();
  629. //成功后修改用户
  630. var userEntity = await GetByPhoneAsync(request.Phone);
  631. userEntity.ImId = request.Phone;
  632. await _repository.UpdateAsync(userEntity);
  633. }
  634. else
  635. {
  636. //出现请求环信失败
  637. // throw new BusinessException("创建用户失败");
  638. }
  639. }
  640. catch (Exception e)
  641. {
  642. throw new BusinessException(e.Message);
  643. }
  644. return true;
  645. }
  646. /// <summary>
  647. /// 用户模糊查询
  648. /// </summary>
  649. /// <param name="request"></param>
  650. /// <returns></returns>
  651. public async Task<IEnumerable<UserInfoResult>> SearchUserNameAsync(SearchUserNameRequest request)
  652. {
  653. var departments = new List<Department>();
  654. var notInUserIds = "";
  655. if (request.UserIds.Count > 0)
  656. {
  657. if (!request.IsShow)
  658. {
  659. notInUserIds = "and Id not in(";
  660. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  661. notInUserIds = "and a.Id not in(";
  662. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  663. notInUserIds = "and Id not in(";
  664. foreach (var userId in request.UserIds)
  665. {
  666. notInUserIds += $"{userId},";
  667. }
  668. notInUserIds = notInUserIds.Remove(notInUserIds.Length - 1, 1);
  669. notInUserIds += ")";
  670. }
  671. }
  672. var sql = $"select * from tede_user where (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  673. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  674. sql = $"select a.* from tede_user a inner join 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}";
  675. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  676. {
  677. //递归获取部门Id
  678. departments = await GetDepartmentAsync(request.DepartmentId, departments);
  679. var departmentValue = $"({request.DepartmentId},";
  680. foreach (var item in departments)
  681. departmentValue += $"{item.Id},";
  682. departmentValue = departmentValue.Remove(departmentValue.Length - 1, 1);
  683. departmentValue += ")";
  684. sql = $"select * from tede_user where DepartmentId in {departmentValue} and (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  685. }
  686. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  687. var database = new Database(databaseType, _connectionString);
  688. var connection = database.GetConnection();
  689. var result = await connection.QueryAsync<UserInfoResult>(sql);
  690. foreach (var item in result)
  691. {
  692. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  693. //获取上级
  694. departments = new List<Department>();
  695. departments = await GetUpDepartmentAsync(item.DepartmentId, departments);
  696. foreach (var department in departments)
  697. item.DepartmentName = "-" + department.Name + item.DepartmentName;
  698. if (!string.IsNullOrWhiteSpace(item.DepartmentName))
  699. item.DepartmentName = item.DepartmentName.Remove(0, 1);
  700. if (request.IsShow)
  701. if (request.UserIds.Contains(item.Id))
  702. item.IsDisable = true;
  703. }
  704. return result;
  705. }
  706. public async Task<List<Entity.Department>> GetUpDepartmentAsync(int id, List<Department> departments)
  707. {
  708. var sql = $"select * from tede_department where Id={id}";
  709. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  710. var database = new Database(databaseType, _connectionString);
  711. var connection = database.GetConnection();
  712. var result = await connection.QueryFirstOrDefaultAsync<Department>(sql);
  713. if (result == null)
  714. return departments;
  715. departments.Add(result);
  716. await GetUpDepartmentAsync(result.ParentId, departments);
  717. return departments;
  718. }
  719. public async Task<List<Entity.Department>> GetDepartmentAsync(int pid, List<Department> departments)
  720. {
  721. var sql = $"select * from tede_department where ParentId={pid}";
  722. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  723. var database = new Database(databaseType, _connectionString);
  724. var connection = database.GetConnection();
  725. var result = await connection.QueryAsync<Department>(sql);
  726. if (result.Count() == 0)
  727. return departments;
  728. departments.AddRange(result);
  729. foreach (var item in result)
  730. await GetDepartmentAsync(item.Id, departments);
  731. return departments;
  732. }
  733. /// <summary>
  734. /// 查询所有用户
  735. /// </summary>
  736. /// <returns></returns>
  737. public async Task<IEnumerable<User>> FindAllUserAsync(SqlKata.Query query)
  738. {
  739. return await _repository.GetAllAsync(query);
  740. }
  741. /// <summary>
  742. /// 根据Guid获取用户数据
  743. /// </summary>
  744. /// <param name="guid"></param>
  745. /// <returns></returns>
  746. public async Task<UserDetail> GetGuidAsync(string guid)
  747. {
  748. var user = await _repository.GetAsync(Q.Where(nameof(User.Guid), guid));
  749. user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  750. user.QRCoder = StringUtils.AddDomain(user.QRCoder);
  751. return _mapper.Map<UserDetail>(user);
  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 tede_middle where FolderType={AllTypeConst.Notice.GetHashCode()} and UserId={userId} and MiddleId in (select SourceId from tede_addressee where UserId={userId} and IsRead=0 and IsDelete=0 and SourceType={AllTypeConst.Notice.GetHashCode()})";
  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 tede_middle where FolderType={AllTypeConst.Missive.GetHashCode()} and UserId={userId} and MiddleId in (select SourceId from tede_addressee where UserId={userId} and SourceType={AllTypeConst.Missive.GetHashCode()} and IsDelete=0 and IsRead=0)";
  779. var missiveCount = await connection.ExecuteScalarAsync<int>(sql);
  780. sql = $"SELECT count(1) FROM 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 tede_user where Id in( SELECT UserId FROM 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 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 tede_user a inner join 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. /// <summary>
  842. /// vip用户
  843. /// </summary>
  844. /// <param name="request"></param>
  845. /// <returns></returns>
  846. public async Task<PagedList<UserDetail>> GetUserVipDetail(UserSearchVipRequest request)
  847. {
  848. var result = new PagedList<UserDetail>();
  849. var query = Q.NewQuery();
  850. if (!string.IsNullOrEmpty(request.KeyWord))
  851. query.WhereLike(nameof(User.Name), $"%{request.KeyWord}%");
  852. if (request.VipPort > 0)
  853. query.Where(nameof(User.Port), request.VipPort);
  854. if (request.VipTypeId > 0)
  855. query.Where(nameof(User.TypeId), request.VipTypeId);
  856. if (request.IsDisable > 0)
  857. query.Where(nameof(User.IsDisable), request.IsDisable == 1);
  858. if (request.IsFreeze > 0)
  859. query.Where(nameof(User.IsFreeze), request.IsFreeze == 1);
  860. if (request.IsVip > 0)
  861. query.Where(nameof(User.IsVip), request.IsVip == 1);
  862. if (request.BeginAccumulativePrice > 0 || request.EndAccumulativePrice > 0)
  863. {
  864. query.Where(nameof(User.AccumulativePrice), ">=", request.BeginAccumulativePrice);
  865. query.Where(nameof(User.AccumulativePrice), "<=", request.EndAccumulativePrice);
  866. }
  867. if (request.RenewalCount > 0)
  868. query.Where(nameof(User.RenewalCount), request.RenewalCount);
  869. result.Total = await _repository.CountAsync(query);
  870. if (!string.IsNullOrEmpty(request.Sort)&&request.Sort.Equals("AccumulativePrice"))
  871. query.OrderByDesc(nameof(User.AccumulativePrice));
  872. else
  873. query.OrderByDesc(nameof(User.CreatedDate));
  874. var items = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
  875. result.Items = items.Select(n => _mapper.Map<UserDetail>(n));
  876. return result;
  877. }
  878. }
  879. }