UserRepository.cs 37 KB

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