UserRepository.cs 40 KB

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