UserRepository.cs 37 KB

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