UserRepository.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. {
  374. user.HistoryAvatarUrl = user.AvatarUrl;
  375. user.AvatarUrl = StringUtils.RemoveDomain(request.AvatarUrl);
  376. }
  377. user.Email = request.Email;
  378. if (!string.IsNullOrWhiteSpace(request.Phone))
  379. user.Phone = request.Phone;
  380. user.QRCoder = StringUtils.RemoveDomain(user.QRCoder);
  381. if (request.IsDisable > 0)
  382. user.IsDisable = request.IsDisable == 1;
  383. if (request.IsFreeze > 0)
  384. user.IsFreeze = request.IsFreeze == 1;
  385. if (request.IsVip > 0)
  386. user.IsVip = request.IsVip == 1;
  387. if (request.IsLeader > 0)
  388. user.IsLeader = request.IsLeader == 1;
  389. if (request.IsMute > 0)
  390. user.IsMute = request.IsMute == 1;
  391. if (!string.IsNullOrWhiteSpace(request.DisableTiem))
  392. user.DisableTiem = Convert.ToDateTime(request.DisableTiem);
  393. return await UpdateAsync(user);
  394. }
  395. /// <summary>
  396. /// 用户分页列表
  397. /// </summary>
  398. /// <param name="request"></param>
  399. /// <returns></returns>
  400. public async Task<PagedList<UserResult>> GetPagedListAsync(UserPageSearchRequest request)
  401. {
  402. var pagedList = new PagedList<UserResult>
  403. {
  404. Total = await GetCountAsync(request.DepartmentId, request.RoleId, request.Keyword)
  405. };
  406. var list = await GetPageListAsync(request.Page, request.PerPage, request.DepartmentId, request.RoleId,
  407. request.Keyword);
  408. var items = list.Select(user => _mapper.Map<UserResult>(user)).ToList();
  409. foreach (var item in items)
  410. {
  411. //获取部门
  412. var department = await _departmentRepository.GetAsync(item.DepartmentId);
  413. if (department != null)
  414. item.DepartmentName = department.Name;
  415. var role = await _roleRepository.GetAsync(item.RoleId);
  416. if (role != null)
  417. item.RoleName = role.Name;
  418. }
  419. pagedList.Items = items;
  420. return pagedList;
  421. }
  422. public async Task<List<UserResult>> GetListAsync(ArticleSearchRequest request)
  423. {
  424. var list = await GetListAsync(request.DepartmentId, request.RoleId, request.Keyword);
  425. var allList = new List<UserResult>();
  426. foreach (var user in list)
  427. {
  428. var result = _mapper.Map<UserResult>(user);
  429. allList.Add(result);
  430. }
  431. return allList;
  432. }
  433. /// <summary>
  434. /// 更新excel用户数据
  435. /// </summary>
  436. /// <param name="request"></param>
  437. /// <returns></returns>
  438. public async Task<bool> UpdateUserExcelAsync(List<User> request)
  439. {
  440. try
  441. {
  442. foreach (var item in request)
  443. {
  444. var user = await _repository.GetAsync(Q.Where(nameof(User.Phone), item.Phone));
  445. if (user != null)
  446. {
  447. continue;
  448. }
  449. var userId = await _repository.InsertAsync(item);
  450. //
  451. user = await _repository.GetAsync(userId);
  452. var resultPath =
  453. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath), item.Guid);
  454. user.QRCoder = resultPath.RelativePath;
  455. await _repository.UpdateAsync(user);
  456. await CreateMiUserAsync(item);
  457. }
  458. }
  459. catch (Exception e)
  460. {
  461. throw new BusinessException(e.Message);
  462. }
  463. return true;
  464. }
  465. /// <summary>
  466. /// 私信
  467. /// </summary>
  468. /// <param name="request"></param>
  469. /// <returns></returns>
  470. public async Task<bool> UpdateUserPrivateLetterAsync(UserPrivateLetterRequest request)
  471. {
  472. var user = await _repository.GetAsync(request.Id);
  473. if (user == null)
  474. throw new BusinessException("该用户不存在");
  475. user.IsPrivateLetter = !user.IsPrivateLetter;
  476. return await _repository.UpdateAsync(user);
  477. }
  478. /// <summary>
  479. /// 通知
  480. /// </summary>
  481. /// <param name="request"></param>
  482. /// <returns></returns>
  483. public async Task<bool> UpdateUserNoticeAsync(UserNoticeRequest request)
  484. {
  485. var user = await _repository.GetAsync(request.Id);
  486. if (user == null)
  487. throw new BusinessException("该用户不存在");
  488. user.IsNotice = !user.IsNotice;
  489. return await _repository.UpdateAsync(user);
  490. }
  491. /// <summary>
  492. /// 回复
  493. /// </summary>
  494. /// <param name="request"></param>
  495. /// <returns></returns>
  496. public async Task<bool> UpdateUserReplyAsync(UserReplyRequest request)
  497. {
  498. var user = await _repository.GetAsync(request.Id);
  499. if (user == null)
  500. throw new BusinessException("该用户不存在");
  501. user.IsReply = !user.IsReply;
  502. return await _repository.UpdateAsync(user);
  503. }
  504. /// <summary>
  505. /// 静音
  506. /// </summary>
  507. /// <param name="request"></param>
  508. /// <returns></returns>
  509. public async Task<bool> UpdateUserMuteAsync(UserMuteRequest request)
  510. {
  511. var user = await _repository.GetAsync(request.Id);
  512. if (user == null)
  513. throw new BusinessException("该用户不存在");
  514. user.IsMute = !user.IsMute;
  515. return await _repository.UpdateAsync(user);
  516. }
  517. /// <summary>
  518. /// 震动
  519. /// </summary>
  520. /// <param name="request"></param>
  521. /// <returns></returns>
  522. public async Task<bool> UpdateUserShakeAsync(UserShakeRequest request)
  523. {
  524. var user = await _repository.GetAsync(request.Id);
  525. if (user == null)
  526. throw new BusinessException("该用户不存在");
  527. user.IsShake = !user.IsShake;
  528. return await _repository.UpdateAsync(user);
  529. }
  530. /// <summary>
  531. /// 用户修改密码
  532. /// </summary>
  533. /// <param name="request"></param>
  534. /// <returns></returns>
  535. public async Task<bool> UpdateUserPhoneAsync(UserUpdatePhoneRequest request)
  536. {
  537. var key = $"login:{request.Phone}";
  538. var code = await _cache.GetStringAsync(key);
  539. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  540. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  541. var user = await GetAsync(request.UserId);
  542. //用户不存在,自动注册
  543. if (user == null)
  544. {
  545. throw new BusinessException("该用户不存在");
  546. }
  547. user.Phone = request.Phone;
  548. return await _repository.UpdateAsync(user);
  549. }
  550. /// <summary>
  551. /// 用户邮箱验证
  552. /// </summary>
  553. /// <param name="request"></param>
  554. /// <returns></returns>
  555. public async Task<bool> SendEmailVerifyCodeAsync(UserEmailVerifyCodeRequest request)
  556. {
  557. //默认配置
  558. ConfigInfo configInfo = new ConfigInfo();
  559. var code = RandomGenerator.GetNumberString(6);
  560. var key = $"email:{request.Email}";
  561. //if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
  562. MailManager.Send(configInfo, request.Email, "邮箱验证", "邮箱验证", $"验证号码:{code}", out var message);
  563. if (!string.IsNullOrEmpty(message))
  564. {
  565. throw new BusinessException(message);
  566. }
  567. //保存验证码
  568. await _cache.SetAsync(key, code, new DistributedCacheEntryOptions
  569. {
  570. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
  571. });
  572. return true;
  573. }
  574. /// <summary>
  575. /// 用户修改密码
  576. /// </summary>
  577. /// <param name="request"></param>
  578. /// <returns></returns>
  579. public async Task<bool> UpdateUserEmailAsync(UserUpdateEmailRequest request)
  580. {
  581. var key = $"email:{request.Email}";
  582. var code = await _cache.GetStringAsync(key);
  583. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  584. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  585. var user = await _repository.GetAsync(request.UserId);
  586. //用户不存在,自动注册
  587. if (user == null)
  588. {
  589. throw new BusinessException("该用户不存在");
  590. }
  591. user.Email = request.Email;
  592. return await _repository.UpdateAsync(user);
  593. }
  594. /// <summary>
  595. /// 根据部门ID获取用户
  596. /// </summary>
  597. /// <param name="departmentId"></param>
  598. /// <returns></returns>
  599. public async Task<IEnumerable<User>> GetUserByDepartmentIdAsync(int departmentId)
  600. {
  601. return await _repository.GetAllAsync(Q.Where(nameof(User.DepartmentId), departmentId));
  602. }
  603. public async Task<IEnumerable<int>> GetUserIdListByDepartmentIdAsync(int departmentId)
  604. {
  605. return await _repository.GetAllAsync<int>(Q
  606. .Select(nameof(User.Id))
  607. .Where(nameof(User.DepartmentId), departmentId)
  608. );
  609. }
  610. public async Task<IEnumerable<int>> GetUserIdListByRoleIdAsync(int roleId)
  611. {
  612. return await _repository.GetAllAsync<int>(Q
  613. .Select(nameof(User.Id))
  614. .Where(nameof(User.RoleId), roleId)
  615. );
  616. }
  617. /// <summary>
  618. /// 创建环信用户
  619. /// </summary>
  620. /// <param name="request"></param>
  621. /// <returns></returns>
  622. public async Task<bool> CreateMiUserAsync(User request)
  623. {
  624. try
  625. {
  626. var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
  627. HttpClient httpClient = new HttpClient(); //http对象
  628. HttpResponseMessage response = await httpClient.PostAsync(
  629. $"{imServiceUrl}/users",
  630. new JsonContent(new { username = request.Phone, password = "123456", nickname = request.Name }));
  631. if (response.IsSuccessStatusCode)
  632. {
  633. string result = await response.Content.ReadAsStringAsync();
  634. //成功后修改用户
  635. var userEntity = await GetByPhoneAsync(request.Phone);
  636. userEntity.ImId = request.Phone;
  637. await _repository.UpdateAsync(userEntity);
  638. }
  639. else
  640. {
  641. //出现请求环信失败
  642. // throw new BusinessException("创建用户失败");
  643. }
  644. }
  645. catch (Exception e)
  646. {
  647. throw new BusinessException(e.Message);
  648. }
  649. return true;
  650. }
  651. /// <summary>
  652. /// 用户模糊查询
  653. /// </summary>
  654. /// <param name="request"></param>
  655. /// <returns></returns>
  656. public async Task<IEnumerable<UserInfoResult>> SearchUserNameAsync(SearchUserNameRequest request)
  657. {
  658. var departments = new List<Department>();
  659. var notInUserIds = "";
  660. if (request.UserIds.Count > 0)
  661. {
  662. if (!request.IsShow)
  663. {
  664. notInUserIds = "and Id not in(";
  665. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  666. notInUserIds = "and a.Id not in(";
  667. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  668. notInUserIds = "and Id not in(";
  669. foreach (var userId in request.UserIds)
  670. {
  671. notInUserIds += $"{userId},";
  672. }
  673. notInUserIds = notInUserIds.Remove(notInUserIds.Length - 1, 1);
  674. notInUserIds += ")";
  675. }
  676. }
  677. var sql = $"select * from tede_user where (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  678. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  679. 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}";
  680. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  681. {
  682. //递归获取部门Id
  683. departments = await GetDepartmentAsync(request.DepartmentId, departments);
  684. var departmentValue = $"({request.DepartmentId},";
  685. foreach (var item in departments)
  686. departmentValue += $"{item.Id},";
  687. departmentValue = departmentValue.Remove(departmentValue.Length - 1, 1);
  688. departmentValue += ")";
  689. 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}";
  690. }
  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.QueryAsync<UserInfoResult>(sql);
  695. foreach (var item in result)
  696. {
  697. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  698. //获取上级
  699. departments = new List<Department>();
  700. departments = await GetUpDepartmentAsync(item.DepartmentId, departments);
  701. foreach (var department in departments)
  702. item.DepartmentName = "-" + department.Name + item.DepartmentName;
  703. if (!string.IsNullOrWhiteSpace(item.DepartmentName))
  704. item.DepartmentName = item.DepartmentName.Remove(0, 1);
  705. if (request.IsShow)
  706. if (request.UserIds.Contains(item.Id))
  707. item.IsDisable = true;
  708. }
  709. return result;
  710. }
  711. public async Task<List<Entity.Department>> GetUpDepartmentAsync(int id, List<Department> departments)
  712. {
  713. var sql = $"select * from tede_department where Id={id}";
  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.QueryFirstOrDefaultAsync<Department>(sql);
  718. if (result == null)
  719. return departments;
  720. departments.Add(result);
  721. await GetUpDepartmentAsync(result.ParentId, departments);
  722. return departments;
  723. }
  724. public async Task<List<Entity.Department>> GetDepartmentAsync(int pid, List<Department> departments)
  725. {
  726. var sql = $"select * from tede_department where ParentId={pid}";
  727. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  728. var database = new Database(databaseType, _connectionString);
  729. var connection = database.GetConnection();
  730. var result = await connection.QueryAsync<Department>(sql);
  731. if (result.Count() == 0)
  732. return departments;
  733. departments.AddRange(result);
  734. foreach (var item in result)
  735. await GetDepartmentAsync(item.Id, departments);
  736. return departments;
  737. }
  738. /// <summary>
  739. /// 查询所有用户
  740. /// </summary>
  741. /// <returns></returns>
  742. public async Task<IEnumerable<User>> FindAllUserAsync(SqlKata.Query query)
  743. {
  744. return await _repository.GetAllAsync(query);
  745. }
  746. /// <summary>
  747. /// 根据Guid获取用户数据
  748. /// </summary>
  749. /// <param name="guid"></param>
  750. /// <returns></returns>
  751. public async Task<UserDetail> GetGuidAsync(string guid)
  752. {
  753. var user = await _repository.GetAsync(Q.Where(nameof(User.Guid), guid));
  754. user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  755. user.QRCoder = StringUtils.AddDomain(user.QRCoder);
  756. return _mapper.Map<UserDetail>(user);
  757. }
  758. public async Task<int> CountAsync(Query query)
  759. {
  760. return await _repository.CountAsync(query);
  761. }
  762. public async Task<IEnumerable<User>> GetAllAsync(Query query)
  763. {
  764. return await _repository.GetAllAsync(query);
  765. }
  766. public Task<IEnumerable<User>> FindAllUserAsync()
  767. {
  768. throw new NotImplementedException();
  769. }
  770. /// <summary>
  771. /// 获取用户未读数据
  772. /// </summary>
  773. /// <param name="userId"></param>
  774. /// <returns></returns>
  775. public async Task<UserCountResult> GetUserCountAsync(int userId)
  776. {
  777. var result = new UserCountResult();
  778. 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()})";
  779. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  780. var database = new Database(databaseType, _connectionString);
  781. var connection = database.GetConnection();
  782. var noticeCount = await connection.ExecuteScalarAsync<int>(sql);
  783. 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)";
  784. var missiveCount = await connection.ExecuteScalarAsync<int>(sql);
  785. sql = $"SELECT count(1) FROM tede_admin_verify where AdminId={userId} and DisposeType=0";
  786. noticeCount += await connection.ExecuteScalarAsync<int>(sql);
  787. result.noticeCount = noticeCount;
  788. result.missiveCount = missiveCount;
  789. return result;
  790. }
  791. /// <summary>
  792. /// 获取工作用户选择审核和抄送人
  793. /// </summary>
  794. /// <param name="userIds"></param>
  795. /// <param name="flowId"></param>
  796. /// <returns></returns>
  797. public async Task<List<Entity.User>> GeFlowUsers(List<int> userIds, int flowId, string type)
  798. {
  799. string strSql = "";
  800. if (userIds.Count > 0)
  801. {
  802. strSql = "and UserId not in(";
  803. foreach (var item in userIds)
  804. {
  805. strSql += $"{item},";
  806. }
  807. strSql = strSql.Remove(strSql.Length - 1, 1);
  808. strSql += ")";
  809. }
  810. string sql = $" select * from tede_user where Id in( SELECT UserId FROM tede_flow_todo where FlowId={flowId} and Type='{type}' {strSql})";
  811. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  812. var database = new Database(databaseType, _connectionString);
  813. var connection = database.GetConnection();
  814. var result = await connection.QueryAsync<User>(sql);
  815. foreach (var item in result)
  816. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  817. return result.ToList();
  818. }
  819. public async Task<List<JobUserResult>> ElasticSearchUser()
  820. {
  821. var sql = "select * from tede_user where IsUpload=0 limit 0,100";
  822. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  823. var database = new Database(databaseType, _connectionString);
  824. var connection = database.GetConnection();
  825. var items = await connection.QueryAsync<JobUserResult>(sql);
  826. return items.ToList();
  827. }
  828. public async Task<bool> UpdateAsync(SqlKata.Query query)
  829. {
  830. return await _repository.UpdateAsync(query) > 0;
  831. }
  832. //public async Task<UserDetail> GetUserDetailJoinAsync(int userId)
  833. //{
  834. // var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
  835. // var database = new Database(databaseType, _connectionString);
  836. // var connection = database.GetConnection();
  837. // var result = connection.Query<UserDetail, Department, UserDetail>(
  838. // "SELECT a.*,b.Name FROM tede_user a inner join tede_department b on a.DepartmentId=b.Id where a.id=@Id;",
  839. // (userDetail,department) =>
  840. // {
  841. // userDetail.DepartmentName = department.Name;
  842. // return userDetail;
  843. // }, new {Id = userId}, splitOn: "Name");
  844. // return result.ToList()[0];
  845. //}
  846. /// <summary>
  847. /// vip用户
  848. /// </summary>
  849. /// <param name="request"></param>
  850. /// <returns></returns>
  851. public async Task<PagedList<UserDetail>> GetUserVipDetail(UserSearchVipRequest request)
  852. {
  853. var result = new PagedList<UserDetail>();
  854. var query = Q.NewQuery();
  855. if (!string.IsNullOrEmpty(request.KeyWord))
  856. query.WhereLike(nameof(User.Name), $"%{request.KeyWord}%");
  857. if (request.VipPort > 0)
  858. query.Where(nameof(User.Port), request.VipPort);
  859. if (request.VipTypeId > 0)
  860. query.Where(nameof(User.TypeId), request.VipTypeId);
  861. if (request.IsDisable > 0)
  862. query.Where(nameof(User.IsDisable), request.IsDisable == 1);
  863. if (request.IsFreeze > 0)
  864. query.Where(nameof(User.IsFreeze), request.IsFreeze == 1);
  865. if (request.IsVip > 0)
  866. query.Where(nameof(User.IsVip), request.IsVip == 1);
  867. if (request.BeginAccumulativePrice > 0 || request.EndAccumulativePrice > 0)
  868. {
  869. query.Where(nameof(User.AccumulativePrice), ">=", request.BeginAccumulativePrice);
  870. query.Where(nameof(User.AccumulativePrice), "<=", request.EndAccumulativePrice);
  871. }
  872. if (request.RenewalCount > 0)
  873. query.Where(nameof(User.RenewalCount), request.RenewalCount);
  874. result.Total = await _repository.CountAsync(query);
  875. if (!string.IsNullOrEmpty(request.Sort) && request.Sort.Equals("AccumulativePrice"))
  876. query.OrderByDesc(nameof(User.AccumulativePrice));
  877. else
  878. query.OrderByDesc(nameof(User.CreatedDate));
  879. var items = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
  880. result.Items = items.Select(n => _mapper.Map<UserDetail>(n));
  881. return result;
  882. }
  883. }
  884. }