UserRepository.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using AutoMapper;
  6. using GxPress.Common.Extensions;
  7. using GxPress.Common.AppOptions;
  8. using GxPress.Common.Exceptions;
  9. using GxPress.Common.Page;
  10. using GxPress.Common.Tools;
  11. using GxPress.Entity;
  12. using GxPress.EnumConst;
  13. using GxPress.Repository.Interface;
  14. using GxPress.Request.User;
  15. using GxPress.Result.User;
  16. using Microsoft.AspNetCore.Hosting;
  17. using Microsoft.Extensions.Options;
  18. using Newtonsoft.Json;
  19. using SqlKata;
  20. using SS.Mail.Core;
  21. using Datory;
  22. using Microsoft.Extensions.Caching.Distributed;
  23. using Dapper;
  24. using GxPress.Result.App.User;
  25. using GxPress.Result.Job;
  26. using GxPress.Common.Http;
  27. using Newtonsoft.Json.Linq;
  28. using Microsoft.Extensions.Logging;
  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 ILogger<UserRepository> _logger;
  39. private readonly IDistributedCache _cache;
  40. //private readonly string _connectionString;
  41. //private readonly string _databaseTypestr;
  42. private readonly string _connectionString;
  43. private readonly string _databaseTypeStr;
  44. public UserRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper,
  45. IWebHostEnvironment environment, IDistributedCache cache, ILogger<UserRepository> logger)
  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. _logger = logger;
  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).Where(nameof(User.IsDelete), false));
  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}%").Where(nameof(User.IsDelete), false));
  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. var userDetail = _mapper.Map<UserDetail>(user);
  93. if (user.DepartmentId > 0)
  94. {
  95. var department = await _departmentRepository.GetAsync(user.DepartmentId);
  96. userDetail.DepartmentName = department.Name;
  97. }
  98. return userDetail;
  99. }
  100. public async Task<User> GetAsync(int id)
  101. {
  102. var user = await _repository.GetAsync(id);
  103. return user;
  104. }
  105. public async Task<User> GetAsync(SqlKata.Query query)
  106. {
  107. var user = await _repository.GetAsync(query);
  108. return user;
  109. }
  110. public async Task<string> GetNameAsync(int id)
  111. {
  112. if (id <= 0) return string.Empty;
  113. var result = await _repository.GetAsync<string>(Q
  114. .Select(nameof(User.Name))
  115. .Where(nameof(User.Id), id)
  116. );
  117. if (string.IsNullOrWhiteSpace(result))
  118. return string.Empty;
  119. return result;
  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).Where(nameof(User.IsDelete), false));
  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).Where(nameof(User.IsDelete), false));
  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.UpdateAsync(Q.WhereIn(nameof(User.Id), userIds).Set(nameof(User.IsDelete), true)) > 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<int> GetCountAsync(int departmentId, int roleId, string keyword)
  189. {
  190. var query = Q.NewQuery();
  191. if (departmentId > 0)
  192. {
  193. query.Where(nameof(User.DepartmentId), departmentId);
  194. }
  195. if (roleId > 0)
  196. {
  197. query.Where(nameof(User.RoleId), roleId);
  198. }
  199. if (!string.IsNullOrEmpty(keyword))
  200. {
  201. keyword = "%" + keyword + "%";
  202. query.Where(q =>
  203. q.WhereLike(nameof(User.Name), keyword)
  204. .OrWhereLike(nameof(User.Email), keyword)
  205. .OrWhereLike(nameof(User.Phone), keyword)
  206. );
  207. }
  208. query.Where(nameof(User.IsDelete), false);
  209. return await _repository.CountAsync(query);
  210. }
  211. /// <summary>
  212. /// Set the limit and offset for a given page.
  213. /// </summary>
  214. /// <param name="page"></param>
  215. /// <param name="perPage"></param>
  216. /// <param name="departmentId"></param>
  217. /// <param name="roleId"></param>
  218. /// <param name="keyword"></param>
  219. /// <returns></returns>
  220. public async Task<IEnumerable<User>> GetPageListAsync(int page, int perPage, int departmentId, int roleId,
  221. string keyword)
  222. {
  223. var query = Q.ForPage(page, perPage);
  224. if (departmentId > 0)
  225. {
  226. query.Where(nameof(User.DepartmentId), departmentId);
  227. }
  228. if (roleId > 0)
  229. {
  230. query.Where(nameof(User.RoleId), roleId);
  231. }
  232. if (!string.IsNullOrEmpty(keyword))
  233. {
  234. keyword = "%" + keyword + "%";
  235. query.Where(q =>
  236. q.WhereLike(nameof(User.Name), keyword)
  237. .OrWhereLike(nameof(User.Email), keyword)
  238. .OrWhereLike(nameof(User.Phone), keyword)
  239. );
  240. }
  241. query.Where(nameof(User.IsDelete), false);
  242. return await _repository.GetAllAsync(query);
  243. }
  244. public async Task<IEnumerable<User>> GetListAsync(int departmentId, int roleId, string keyword)
  245. {
  246. var query = Q.NewQuery();
  247. if (departmentId > 0)
  248. {
  249. query.Where(nameof(User.DepartmentId), departmentId);
  250. }
  251. if (roleId > 0)
  252. {
  253. query.Where(nameof(User.RoleId), roleId);
  254. }
  255. if (!string.IsNullOrEmpty(keyword))
  256. {
  257. query.Where(q =>
  258. q.WhereLike(nameof(User.Name), keyword)
  259. .OrWhereLike(nameof(User.Email), keyword)
  260. .OrWhereLike(nameof(User.Phone), keyword)
  261. );
  262. }
  263. query.Where(nameof(User.IsDelete), false);
  264. return await _repository.GetAllAsync(query);
  265. }
  266. /// <summary>
  267. /// 登录
  268. /// </summary>
  269. /// <param name="request"></param>
  270. /// <returns></returns>
  271. public async Task<UserSignInResult> SignInAsync(UserSignInRequest request)
  272. {
  273. var result = new UserSignInResult();
  274. var key = $"login:{request.Phone}";
  275. try
  276. {
  277. var user = new User();
  278. if (string.IsNullOrWhiteSpace(request.OpenId))
  279. {
  280. //var code = _cache.GetString(key).Replace("\"", "");
  281. var dictionaryKeyValue = new Dictionary<string, string>();
  282. dictionaryKeyValue.Add("19977191891", "202088");
  283. dictionaryKeyValue.Add("17776699684", "202088");
  284. dictionaryKeyValue.Add("18978939733", "202088");
  285. if (dictionaryKeyValue.Any(n => n.Key == request.Phone) && dictionaryKeyValue.Any(n => n.Value == request.Code))
  286. {
  287. user = await GetByPhoneAsync(request.Phone);
  288. }
  289. else
  290. {
  291. //var code = "123456";
  292. var code = _cache.GetString(key).Replace("\"", "");
  293. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  294. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  295. user = await GetByPhoneAsync(request.Phone);
  296. }
  297. //用户不存在,自动注册
  298. if (user == null)
  299. {
  300. // user = new User();
  301. // user.Name = request.Phone;
  302. // user.Phone = request.Phone;
  303. // user.Gender = "Male";
  304. // user.Id = await InsertAsync(user);
  305. // result.UserId = user.Id;
  306. // result.DepartmentId = user.DepartmentId;
  307. // result.User = _mapper.Map<UserResult>(user);
  308. // result.IsAddUser = true;
  309. // result.UserEntity = user;
  310. // return result;
  311. throw new BusinessException("验证码或手机号错误");
  312. }
  313. }
  314. else
  315. user = await GetByOpenIdAsync(request.OpenId);
  316. result.UserId = user.Id;
  317. result.DepartmentId = user.DepartmentId;
  318. result.User = _mapper.Map<UserResult>(user);
  319. return result;
  320. }
  321. catch (System.Exception)
  322. {
  323. throw new BusinessException("验证码或手机号错误");
  324. }
  325. }
  326. public async Task<int> InsertAsync(User user)
  327. {
  328. if (user == null) throw new Exception("用户不能为空");
  329. if (string.IsNullOrEmpty(user.Name)) throw new Exception("用户不能为空");
  330. if (!string.IsNullOrEmpty(user.Phone) &&
  331. await _repository.ExistsAsync(Q.Where(nameof(User.Phone), user.Phone)))
  332. {
  333. throw new Exception("用户手机号已存在,请更换手机号");
  334. }
  335. //头像处理
  336. user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
  337. user.IsUpload = false;
  338. user.Id = await _repository.InsertAsync(user);
  339. user = await _repository.GetAsync(user.Id);
  340. //创建二维码
  341. var qrCodeData = new { key = QRCodeTypeConst.UserInfo, value = user.Guid };
  342. var resultPath =
  343. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
  344. JsonConvert.SerializeObject(qrCodeData));
  345. user.QRCoder = resultPath.RelativePath;
  346. await _repository.UpdateAsync(user);
  347. return user.Id;
  348. }
  349. /// <summary>
  350. /// 删除用户
  351. /// </summary>
  352. /// <param name="id"></param>
  353. /// <returns></returns>
  354. public async Task<bool> DeleteAsync(int id)
  355. {
  356. var user = await GetAsync(id);
  357. if (user == null) throw new BusinessException("该用户不存在");
  358. user.IsDelete = true;
  359. return await UpdateAsync(user);
  360. }
  361. /// <summary>
  362. /// 更新用户信息
  363. /// </summary>
  364. /// <param name="id"></param>
  365. /// <param name="request"></param>
  366. /// <returns></returns>
  367. public async Task<bool> UpdateAsync(int id, User request)
  368. {
  369. var user = await GetAsync(id);
  370. if (user == null) throw new BusinessException("该用户不存在");
  371. if (request.DepartmentId > 0)
  372. user.DepartmentId = request.DepartmentId;
  373. if (!string.IsNullOrEmpty(request.Nick))
  374. user.Nick = request.Nick;
  375. if (!string.IsNullOrEmpty(request.Description))
  376. user.Description = request.Description;
  377. if (!string.IsNullOrEmpty(request.Gender))
  378. user.Gender = request.Gender;
  379. if (!string.IsNullOrEmpty(request.Name))
  380. user.Name = request.Name;
  381. if (!string.IsNullOrEmpty(request.Position))
  382. user.Position = request.Position;
  383. if (request.RoleId > 0)
  384. user.RoleId = request.RoleId;
  385. if (!string.IsNullOrEmpty(request.Signature))
  386. user.Signature = request.Signature;
  387. //用户头像
  388. if (!string.IsNullOrEmpty(request.AvatarUrl))
  389. user.AvatarUrl = StringUtils.RemoveDomain(request.AvatarUrl);
  390. else
  391. user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
  392. user.Email = request.Email;
  393. if (!string.IsNullOrWhiteSpace(request.Phone))
  394. user.Phone = request.Phone;
  395. user.QRCoder = StringUtils.RemoveDomain(user.QRCoder);
  396. user.IsReport = request.IsReport;
  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).Where(nameof(User.IsDelete), false));
  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 = _cache.GetString(key).Replace("\"", "");
  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).Where(nameof(User.IsDelete), false));
  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).Where(nameof(User.IsDelete), false)
  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. string result = HttpClientHelper.GetResponseData("{\"username\":\"" + request.Phone + "\", \"password\": \"123456\",\"nickname\":\"" + request.Name + "\"}", $"{imServiceUrl}/users");
  632. if (!string.IsNullOrEmpty(result))
  633. {
  634. _logger.LogDebug(result);
  635. _logger.LogError(result);
  636. var model = JsonConvert.DeserializeObject<dynamic>(result);
  637. var entities = model["entities"];
  638. var jtokenEntities = (JToken)entities;
  639. request.Phone = jtokenEntities[0]["username"].ToString();
  640. //成功后修改用户
  641. var userEntity = await GetByPhoneAsync(request.Phone);
  642. userEntity.ImId = request.Phone;
  643. await _repository.UpdateAsync(userEntity);
  644. }
  645. }
  646. catch (Exception e)
  647. {
  648. throw new BusinessException(e.Message);
  649. }
  650. return true;
  651. }
  652. /// <summary>
  653. /// 用户模糊查询
  654. /// </summary>
  655. /// <param name="request"></param>
  656. /// <returns></returns>
  657. public async Task<IEnumerable<UserInfoResult>> SearchUserNameAsync(SearchUserNameRequest request)
  658. {
  659. var departments = new List<Department>();
  660. var notInUserIds = "";
  661. if (request.UserIds.Count > 0)
  662. {
  663. if (!request.IsShow)
  664. {
  665. notInUserIds = "and Id not in(";
  666. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  667. notInUserIds = "and a.Id not in(";
  668. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  669. notInUserIds = "and Id not in(";
  670. foreach (var userId in request.UserIds)
  671. {
  672. notInUserIds += $"{userId},";
  673. }
  674. notInUserIds = notInUserIds.Remove(notInUserIds.Length - 1, 1);
  675. notInUserIds += ")";
  676. }
  677. }
  678. var sql = $"select * from ccpph.tede_user where (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  679. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  680. 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}";
  681. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  682. {
  683. //递归获取部门Id
  684. departments = await GetDepartmentAsync(request.DepartmentId, departments);
  685. var departmentValue = $"({request.DepartmentId},";
  686. foreach (var item in departments)
  687. departmentValue += $"{item.Id},";
  688. departmentValue = departmentValue.Remove(departmentValue.Length - 1, 1);
  689. departmentValue += ")";
  690. 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}";
  691. }
  692. sql += " and IsDelete=0";
  693. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  694. var database = new Database(databaseType, _connectionString);
  695. var connection = database.GetConnection();
  696. var result = await connection.QueryAsync<UserInfoResult>(sql);
  697. foreach (var item in result)
  698. {
  699. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  700. //获取上级
  701. departments = new List<Department>();
  702. departments = await GetUpDepartmentAsync(item.DepartmentId, departments);
  703. foreach (var department in departments)
  704. item.DepartmentName = "-" + department.Name + item.DepartmentName;
  705. if (!string.IsNullOrWhiteSpace(item.DepartmentName))
  706. item.DepartmentName = item.DepartmentName.Remove(0, 1);
  707. if (request.IsShow)
  708. if (request.UserIds.Contains(item.Id))
  709. item.IsDisable = true;
  710. }
  711. return result;
  712. }
  713. public async Task<List<Entity.Department>> GetUpDepartmentAsync(int id, List<Department> departments)
  714. {
  715. var sql = $"select * from ccpph.tede_department where Id={id}";
  716. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  717. var database = new Database(databaseType, _connectionString);
  718. var connection = database.GetConnection();
  719. var result = await connection.QueryFirstOrDefaultAsync<Department>(sql);
  720. if (result == null)
  721. return departments;
  722. departments.Add(result);
  723. await GetUpDepartmentAsync(result.ParentId, departments);
  724. return departments;
  725. }
  726. public async Task<List<Entity.Department>> GetDepartmentAsync(int pid, List<Department> departments)
  727. {
  728. var sql = $"select * from ccpph.tede_department where ParentId={pid}";
  729. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  730. var database = new Database(databaseType, _connectionString);
  731. var connection = database.GetConnection();
  732. var result = await connection.QueryAsync<Department>(sql);
  733. if (result.Count() == 0)
  734. return departments;
  735. departments.AddRange(result);
  736. foreach (var item in result)
  737. await GetDepartmentAsync(item.Id, departments);
  738. return departments;
  739. }
  740. /// <summary>
  741. /// 查询所有用户
  742. /// </summary>
  743. /// <returns></returns>
  744. public async Task<IEnumerable<User>> FindAllUserAsync(SqlKata.Query query)
  745. {
  746. query.Where(nameof(User.IsDelete), false);
  747. return await _repository.GetAllAsync(query);
  748. }
  749. /// <summary>
  750. /// 根据Guid获取用户数据
  751. /// </summary>
  752. /// <param name="guid"></param>
  753. /// <returns></returns>
  754. public async Task<UserDetail> GetGuidAsync(string guid)
  755. {
  756. var user = await _repository.GetAsync(Q.Where(nameof(User.Guid), guid).Where(nameof(User.IsDelete), false));
  757. user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  758. user.QRCoder = StringUtils.AddDomain(user.QRCoder);
  759. return _mapper.Map<UserDetail>(user);
  760. }
  761. public async Task<IEnumerable<Entity.User>> GetAllUserIm()
  762. {
  763. string sql = "SELECT * FROM ccpph.tede_user where ImId is null or ImId='' and IsDelete=0";
  764. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  765. var database = new Database(databaseType, _connectionString);
  766. var connection = database.GetConnection();
  767. return await connection.QueryAsync<User>(sql);
  768. }
  769. public async Task<int> CountAsync(Query query)
  770. {
  771. query.Where(nameof(User.IsDelete), false);
  772. return await _repository.CountAsync(query);
  773. }
  774. public async Task<IEnumerable<User>> GetAllAsync(Query query)
  775. {
  776. query.Where(nameof(User.IsDelete), false);
  777. return await _repository.GetAllAsync(query);
  778. }
  779. /// <summary>
  780. /// 根据用户ID获取哦手机号码
  781. /// </summary>
  782. /// <param name="userIds"></param>
  783. /// <returns></returns>
  784. public async Task<IEnumerable<string>> GetUserIdsAsync(List<int> userIds)
  785. {
  786. return await _repository.GetAllAsync<string>(Q.Select(nameof(User.Phone)).WhereIn(nameof(User.Id), userIds).Where(nameof(User.IsDelete), false));
  787. }
  788. public Task<IEnumerable<User>> FindAllUserAsync()
  789. {
  790. throw new NotImplementedException();
  791. }
  792. /// <summary>
  793. /// 获取用户未读数据
  794. /// </summary>
  795. /// <param name="userId"></param>
  796. /// <returns></returns>
  797. public async Task<UserCountResult> GetUserCountAsync(int userId)
  798. {
  799. var result = new UserCountResult();
  800. 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)";
  801. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  802. var database = new Database(databaseType, _connectionString);
  803. var connection = database.GetConnection();
  804. var noticeCount = await connection.ExecuteScalarAsync<int>(sql);
  805. 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)";
  806. var missiveCount = await connection.ExecuteScalarAsync<int>(sql);
  807. sql = $"SELECT count(1) FROM ccpph.tede_admin_verify where AdminId={userId} and DisposeType=0";
  808. noticeCount += await connection.ExecuteScalarAsync<int>(sql);
  809. result.noticeCount = noticeCount;
  810. result.missiveCount = missiveCount;
  811. return result;
  812. }
  813. /// <summary>
  814. /// 获取工作用户选择审核和抄送人
  815. /// </summary>
  816. /// <param name="userIds"></param>
  817. /// <param name="flowId"></param>
  818. /// <returns></returns>
  819. public async Task<List<Entity.User>> GeFlowUsers(List<int> userIds, int flowId, string type)
  820. {
  821. string strSql = "";
  822. if (userIds.Count > 0)
  823. {
  824. strSql = "and UserId not in(";
  825. foreach (var item in userIds)
  826. {
  827. strSql += $"{item},";
  828. }
  829. strSql = strSql.Remove(strSql.Length - 1, 1);
  830. strSql += ")";
  831. }
  832. string sql = $" select * from ccpph.tede_user where Id in( SELECT UserId FROM ccpph.tede_flow_todo where FlowId={flowId} and Type='{type}' {strSql}) and IsDelete=0";
  833. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  834. var database = new Database(databaseType, _connectionString);
  835. var connection = database.GetConnection();
  836. var result = await connection.QueryAsync<User>(sql);
  837. foreach (var item in result)
  838. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  839. return result.ToList();
  840. }
  841. public async Task<List<JobUserResult>> ElasticSearchUser()
  842. {
  843. var sql = "select * from ccpph.tede_user where IsUpload=0 and IsDelete=0 limit 0,100";
  844. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  845. var database = new Database(databaseType, _connectionString);
  846. var connection = database.GetConnection();
  847. var items = await connection.QueryAsync<JobUserResult>(sql);
  848. return items.ToList();
  849. }
  850. public async Task<bool> UpdateAsync(SqlKata.Query query)
  851. {
  852. return await _repository.UpdateAsync(query) > 0;
  853. }
  854. //public async Task<UserDetail> GetUserDetailJoinAsync(int userId)
  855. //{
  856. // var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
  857. // var database = new Database(databaseType, _connectionString);
  858. // var connection = database.GetConnection();
  859. // var result = connection.Query<UserDetail, Department, UserDetail>(
  860. // "SELECT a.*,b.Name FROM ccpph.tede_user a inner join ccpph.tede_department b on a.DepartmentId=b.Id where a.id=@Id;",
  861. // (userDetail,department) =>
  862. // {
  863. // userDetail.DepartmentName = department.Name;
  864. // return userDetail;
  865. // }, new {Id = userId}, splitOn: "Name");
  866. // return result.ToList()[0];
  867. //}
  868. public async Task<IEnumerable<User>> GetChatUserAsync(int userId)
  869. {
  870. string sql = $@"SELECT
  871. c.*
  872. FROM
  873. tede_often_contact a
  874. INNER JOIN
  875. tede_middle b ON a.Id = b.MiddleId
  876. INNER JOIN
  877. tede_user c ON c.Id = a.ContactUserId
  878. WHERE
  879. FolderType = 10 and b.IsDelete=0 and a.UserId={userId} and ChatType=1";
  880. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  881. var database = new Database(databaseType, _connectionString);
  882. var connection = database.GetConnection();
  883. var items = await connection.QueryAsync<User>(sql);
  884. return items;
  885. }
  886. }
  887. }