UserRepository.cs 37 KB

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