UserRepository.cs 40 KB

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