UserRepository.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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. return await UpdateAsync(user);
  361. }
  362. /// <summary>
  363. /// 用户分页列表
  364. /// </summary>
  365. /// <param name="request"></param>
  366. /// <returns></returns>
  367. public async Task<PagedList<UserResult>> GetPagedListAsync(UserPageSearchRequest request)
  368. {
  369. var pagedList = new PagedList<UserResult>
  370. {
  371. Total = await GetCountAsync(request.DepartmentId, request.RoleId, request.Keyword)
  372. };
  373. var list = await GetPageListAsync(request.Page, request.PerPage, request.DepartmentId, request.RoleId,
  374. request.Keyword);
  375. var items = list.Select(user => _mapper.Map<UserResult>(user)).ToList();
  376. foreach (var item in items)
  377. {
  378. //获取部门
  379. var department = await _departmentRepository.GetAsync(item.DepartmentId);
  380. if (department != null)
  381. item.DepartmentName = department.Name;
  382. var role = await _roleRepository.GetAsync(item.RoleId);
  383. if (role != null)
  384. item.RoleName = role.Name;
  385. }
  386. pagedList.Items = items;
  387. return pagedList;
  388. }
  389. public async Task<List<UserResult>> GetListAsync(ArticleSearchRequest request)
  390. {
  391. var list = await GetListAsync(request.DepartmentId, request.RoleId, request.Keyword);
  392. var allList = new List<UserResult>();
  393. foreach (var user in list)
  394. {
  395. var result = _mapper.Map<UserResult>(user);
  396. allList.Add(result);
  397. }
  398. return allList;
  399. }
  400. /// <summary>
  401. /// 更新excel用户数据
  402. /// </summary>
  403. /// <param name="request"></param>
  404. /// <returns></returns>
  405. public async Task<bool> UpdateUserExcelAsync(List<User> request)
  406. {
  407. try
  408. {
  409. foreach (var item in request)
  410. {
  411. var user = await _repository.GetAsync(Q.Where(nameof(User.Phone), item.Phone));
  412. if (user != null)
  413. {
  414. continue;
  415. }
  416. var userId = await _repository.InsertAsync(item);
  417. //
  418. user = await _repository.GetAsync(userId);
  419. var resultPath =
  420. FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath), item.Guid);
  421. user.QRCoder = resultPath.RelativePath;
  422. await _repository.UpdateAsync(user);
  423. await CreateMiUserAsync(item);
  424. }
  425. }
  426. catch (Exception e)
  427. {
  428. throw new BusinessException(e.Message);
  429. }
  430. return true;
  431. }
  432. /// <summary>
  433. /// 私信
  434. /// </summary>
  435. /// <param name="request"></param>
  436. /// <returns></returns>
  437. public async Task<bool> UpdateUserPrivateLetterAsync(UserPrivateLetterRequest request)
  438. {
  439. var user = await _repository.GetAsync(request.Id);
  440. if (user == null)
  441. throw new BusinessException("该用户不存在");
  442. user.IsPrivateLetter = !user.IsPrivateLetter;
  443. return await _repository.UpdateAsync(user);
  444. }
  445. /// <summary>
  446. /// 通知
  447. /// </summary>
  448. /// <param name="request"></param>
  449. /// <returns></returns>
  450. public async Task<bool> UpdateUserNoticeAsync(UserNoticeRequest request)
  451. {
  452. var user = await _repository.GetAsync(request.Id);
  453. if (user == null)
  454. throw new BusinessException("该用户不存在");
  455. user.IsNotice = !user.IsNotice;
  456. return await _repository.UpdateAsync(user);
  457. }
  458. /// <summary>
  459. /// 回复
  460. /// </summary>
  461. /// <param name="request"></param>
  462. /// <returns></returns>
  463. public async Task<bool> UpdateUserReplyAsync(UserReplyRequest request)
  464. {
  465. var user = await _repository.GetAsync(request.Id);
  466. if (user == null)
  467. throw new BusinessException("该用户不存在");
  468. user.IsReply = !user.IsReply;
  469. return await _repository.UpdateAsync(user);
  470. }
  471. /// <summary>
  472. /// 静音
  473. /// </summary>
  474. /// <param name="request"></param>
  475. /// <returns></returns>
  476. public async Task<bool> UpdateUserMuteAsync(UserMuteRequest request)
  477. {
  478. var user = await _repository.GetAsync(request.Id);
  479. if (user == null)
  480. throw new BusinessException("该用户不存在");
  481. user.IsMute = !user.IsMute;
  482. return await _repository.UpdateAsync(user);
  483. }
  484. /// <summary>
  485. /// 震动
  486. /// </summary>
  487. /// <param name="request"></param>
  488. /// <returns></returns>
  489. public async Task<bool> UpdateUserShakeAsync(UserShakeRequest request)
  490. {
  491. var user = await _repository.GetAsync(request.Id);
  492. if (user == null)
  493. throw new BusinessException("该用户不存在");
  494. user.IsShake = !user.IsShake;
  495. return await _repository.UpdateAsync(user);
  496. }
  497. /// <summary>
  498. /// 用户修改密码
  499. /// </summary>
  500. /// <param name="request"></param>
  501. /// <returns></returns>
  502. public async Task<bool> UpdateUserPhoneAsync(UserUpdatePhoneRequest request)
  503. {
  504. var key = $"login:{request.Phone}";
  505. var code = await _cache.GetStringAsync(key);
  506. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  507. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  508. var user = await GetAsync(request.UserId);
  509. //用户不存在,自动注册
  510. if (user == null)
  511. {
  512. throw new BusinessException("该用户不存在");
  513. }
  514. user.Phone = request.Phone;
  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> SendEmailVerifyCodeAsync(UserEmailVerifyCodeRequest request)
  523. {
  524. //默认配置
  525. ConfigInfo configInfo = new ConfigInfo();
  526. var code = RandomGenerator.GetNumberString(6);
  527. var key = $"email:{request.Email}";
  528. //if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
  529. MailManager.Send(configInfo, request.Email, "邮箱验证", "邮箱验证", $"验证号码:{code}", out var message);
  530. if (!string.IsNullOrEmpty(message))
  531. {
  532. throw new BusinessException(message);
  533. }
  534. //保存验证码
  535. await _cache.SetAsync(key, code, new DistributedCacheEntryOptions
  536. {
  537. AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
  538. });
  539. return true;
  540. }
  541. /// <summary>
  542. /// 用户修改密码
  543. /// </summary>
  544. /// <param name="request"></param>
  545. /// <returns></returns>
  546. public async Task<bool> UpdateUserEmailAsync(UserUpdateEmailRequest request)
  547. {
  548. var key = $"email:{request.Email}";
  549. var code = await _cache.GetStringAsync(key);
  550. if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
  551. if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
  552. var user = await _repository.GetAsync(request.UserId);
  553. //用户不存在,自动注册
  554. if (user == null)
  555. {
  556. throw new BusinessException("该用户不存在");
  557. }
  558. user.Email = request.Email;
  559. return await _repository.UpdateAsync(user);
  560. }
  561. /// <summary>
  562. /// 根据部门ID获取用户
  563. /// </summary>
  564. /// <param name="departmentId"></param>
  565. /// <returns></returns>
  566. public async Task<IEnumerable<User>> GetUserByDepartmentIdAsync(int departmentId)
  567. {
  568. return await _repository.GetAllAsync(Q.Where(nameof(User.DepartmentId), departmentId));
  569. }
  570. public async Task<IEnumerable<int>> GetUserIdListByDepartmentIdAsync(int departmentId)
  571. {
  572. return await _repository.GetAllAsync<int>(Q
  573. .Select(nameof(User.Id))
  574. .Where(nameof(User.DepartmentId), departmentId)
  575. );
  576. }
  577. public async Task<IEnumerable<int>> GetUserIdListByRoleIdAsync(int roleId)
  578. {
  579. return await _repository.GetAllAsync<int>(Q
  580. .Select(nameof(User.Id))
  581. .Where(nameof(User.RoleId), roleId)
  582. );
  583. }
  584. /// <summary>
  585. /// 创建环信用户
  586. /// </summary>
  587. /// <param name="request"></param>
  588. /// <returns></returns>
  589. public async Task<bool> CreateMiUserAsync(User request)
  590. {
  591. try
  592. {
  593. var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
  594. var httpClientHandler=new HttpClientHandler{ServerCertificateCustomValidationCallback=HttpClientHandler.DangerousAcceptAnyServerCertificateValidator};
  595. HttpClient httpClient = new HttpClient(httpClientHandler); //http对象
  596. HttpResponseMessage response = await httpClient.PostAsync(
  597. $"{imServiceUrl}/users",
  598. new JsonContent(new { username = request.Phone, password = "123456", nickname = request.Name }));
  599. if (response.IsSuccessStatusCode)
  600. {
  601. string result = await response.Content.ReadAsStringAsync();
  602. //成功后修改用户
  603. var userEntity = await GetByPhoneAsync(request.Phone);
  604. userEntity.ImId = request.Phone;
  605. await _repository.UpdateAsync(userEntity);
  606. }
  607. else
  608. {
  609. //出现请求环信失败
  610. // throw new BusinessException("创建用户失败");
  611. }
  612. }
  613. catch (Exception e)
  614. {
  615. throw new BusinessException(e.Message);
  616. }
  617. return true;
  618. }
  619. /// <summary>
  620. /// 用户模糊查询
  621. /// </summary>
  622. /// <param name="request"></param>
  623. /// <returns></returns>
  624. public async Task<IEnumerable<UserInfoResult>> SearchUserNameAsync(SearchUserNameRequest request)
  625. {
  626. var departments = new List<Department>();
  627. var notInUserIds = "";
  628. if (request.UserIds.Count > 0)
  629. {
  630. if (!request.IsShow)
  631. {
  632. notInUserIds = "and Id not in(";
  633. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  634. notInUserIds = "and a.Id not in(";
  635. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  636. notInUserIds = "and Id not in(";
  637. foreach (var userId in request.UserIds)
  638. {
  639. notInUserIds += $"{userId},";
  640. }
  641. notInUserIds = notInUserIds.Remove(notInUserIds.Length - 1, 1);
  642. notInUserIds += ")";
  643. }
  644. }
  645. var sql = $"select * from ccpph.tede_user where (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  646. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  647. 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}";
  648. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  649. {
  650. //递归获取部门Id
  651. departments = await GetDepartmentAsync(request.DepartmentId, departments);
  652. var departmentValue = $"({request.DepartmentId},";
  653. foreach (var item in departments)
  654. departmentValue += $"{item.Id},";
  655. departmentValue = departmentValue.Remove(departmentValue.Length - 1, 1);
  656. departmentValue += ")";
  657. 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}";
  658. }
  659. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  660. var database = new Database(databaseType, _connectionString);
  661. var connection = database.GetConnection();
  662. var result = await connection.QueryAsync<UserInfoResult>(sql);
  663. foreach (var item in result)
  664. {
  665. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  666. //获取上级
  667. departments = new List<Department>();
  668. departments = await GetUpDepartmentAsync(item.DepartmentId, departments);
  669. foreach (var department in departments)
  670. item.DepartmentName = "-" + department.Name + item.DepartmentName;
  671. if (!string.IsNullOrWhiteSpace(item.DepartmentName))
  672. item.DepartmentName = item.DepartmentName.Remove(0, 1);
  673. if (request.IsShow)
  674. if (request.UserIds.Contains(item.Id))
  675. item.IsDisable = true;
  676. }
  677. return result;
  678. }
  679. public async Task<List<Entity.Department>> GetUpDepartmentAsync(int id, List<Department> departments)
  680. {
  681. var sql = $"select * from ccpph.tede_department where Id={id}";
  682. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  683. var database = new Database(databaseType, _connectionString);
  684. var connection = database.GetConnection();
  685. var result = await connection.QueryFirstOrDefaultAsync<Department>(sql);
  686. if (result == null)
  687. return departments;
  688. departments.Add(result);
  689. await GetUpDepartmentAsync(result.ParentId, departments);
  690. return departments;
  691. }
  692. public async Task<List<Entity.Department>> GetDepartmentAsync(int pid, List<Department> departments)
  693. {
  694. var sql = $"select * from ccpph.tede_department where ParentId={pid}";
  695. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  696. var database = new Database(databaseType, _connectionString);
  697. var connection = database.GetConnection();
  698. var result = await connection.QueryAsync<Department>(sql);
  699. if (result.Count() == 0)
  700. return departments;
  701. departments.AddRange(result);
  702. foreach (var item in result)
  703. await GetDepartmentAsync(item.Id, departments);
  704. return departments;
  705. }
  706. /// <summary>
  707. /// 查询所有用户
  708. /// </summary>
  709. /// <returns></returns>
  710. public async Task<IEnumerable<User>> FindAllUserAsync(SqlKata.Query query)
  711. {
  712. return await _repository.GetAllAsync(query);
  713. }
  714. /// <summary>
  715. /// 根据Guid获取用户数据
  716. /// </summary>
  717. /// <param name="guid"></param>
  718. /// <returns></returns>
  719. public async Task<UserDetail> GetGuidAsync(string guid)
  720. {
  721. var user = await _repository.GetAsync(Q.Where(nameof(User.Guid), guid));
  722. user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  723. user.QRCoder = StringUtils.AddDomain(user.QRCoder);
  724. return _mapper.Map<UserDetail>(user);
  725. }
  726. public async Task<int> CountAsync(Query query)
  727. {
  728. return await _repository.CountAsync(query);
  729. }
  730. public async Task<IEnumerable<User>> GetAllAsync(Query query)
  731. {
  732. return await _repository.GetAllAsync(query);
  733. }
  734. public Task<IEnumerable<User>> FindAllUserAsync()
  735. {
  736. throw new NotImplementedException();
  737. }
  738. /// <summary>
  739. /// 获取用户未读数据
  740. /// </summary>
  741. /// <param name="userId"></param>
  742. /// <returns></returns>
  743. public async Task<UserCountResult> GetUserCountAsync(int userId)
  744. {
  745. var result = new UserCountResult();
  746. 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)";
  747. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  748. var database = new Database(databaseType, _connectionString);
  749. var connection = database.GetConnection();
  750. var noticeCount = await connection.ExecuteScalarAsync<int>(sql);
  751. 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)";
  752. var missiveCount = await connection.ExecuteScalarAsync<int>(sql);
  753. sql = $"SELECT count(1) FROM ccpph.tede_admin_verify where AdminId={userId} and DisposeType=0";
  754. noticeCount += await connection.ExecuteScalarAsync<int>(sql);
  755. result.noticeCount = noticeCount;
  756. result.missiveCount = missiveCount;
  757. return result;
  758. }
  759. /// <summary>
  760. /// 获取工作用户选择审核和抄送人
  761. /// </summary>
  762. /// <param name="userIds"></param>
  763. /// <param name="flowId"></param>
  764. /// <returns></returns>
  765. public async Task<List<Entity.User>> GeFlowUsers(List<int> userIds, int flowId, string type)
  766. {
  767. string strSql = "";
  768. if (userIds.Count > 0)
  769. {
  770. strSql = "and UserId not in(";
  771. foreach (var item in userIds)
  772. {
  773. strSql += $"{item},";
  774. }
  775. strSql = strSql.Remove(strSql.Length - 1, 1);
  776. strSql += ")";
  777. }
  778. string sql = $" select * from ccpph.tede_user where Id in( SELECT UserId FROM ccpph.tede_flow_todo where FlowId={flowId} and Type='{type}' {strSql})";
  779. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  780. var database = new Database(databaseType, _connectionString);
  781. var connection = database.GetConnection();
  782. var result = await connection.QueryAsync<User>(sql);
  783. foreach (var item in result)
  784. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  785. return result.ToList();
  786. }
  787. public async Task<List<JobUserResult>> ElasticSearchUser()
  788. {
  789. var sql = "select * from ccpph.tede_user where IsUpload=0 limit 0,100";
  790. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  791. var database = new Database(databaseType, _connectionString);
  792. var connection = database.GetConnection();
  793. var items = await connection.QueryAsync<JobUserResult>(sql);
  794. return items.ToList();
  795. }
  796. public async Task<bool> UpdateAsync(SqlKata.Query query)
  797. {
  798. return await _repository.UpdateAsync(query) > 0;
  799. }
  800. //public async Task<UserDetail> GetUserDetailJoinAsync(int userId)
  801. //{
  802. // var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
  803. // var database = new Database(databaseType, _connectionString);
  804. // var connection = database.GetConnection();
  805. // var result = connection.Query<UserDetail, Department, UserDetail>(
  806. // "SELECT a.*,b.Name FROM ccpph.tede_user a inner join ccpph.tede_department b on a.DepartmentId=b.Id where a.id=@Id;",
  807. // (userDetail,department) =>
  808. // {
  809. // userDetail.DepartmentName = department.Name;
  810. // return userDetail;
  811. // }, new {Id = userId}, splitOn: "Name");
  812. // return result.ToList()[0];
  813. //}
  814. }
  815. }