UserRepository.cs 40 KB

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