UserRepository.cs 44 KB

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