UserRepository.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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. var userIds = await departmentUserRepository.GetUserIdsByDepartmentIdsAsync(new List<int>() { departmentId });
  619. return await _repository.GetAllAsync(Q.WhereIn(nameof(User.Id), userIds));
  620. }
  621. public async Task<IEnumerable<int>> GetUserIdListByDepartmentIdAsync(int departmentId)
  622. {
  623. return await _repository.GetAllAsync<int>(Q
  624. .Select(nameof(User.Id))
  625. .Where(nameof(User.DepartmentId), departmentId)
  626. );
  627. }
  628. public async Task<IEnumerable<int>> GetUserIdListByRoleIdAsync(int roleId)
  629. {
  630. return await _repository.GetAllAsync<int>(Q
  631. .Select(nameof(User.Id))
  632. .Where(nameof(User.RoleId), roleId)
  633. );
  634. }
  635. /// <summary>
  636. /// 创建环信用户
  637. /// </summary>
  638. /// <param name="request"></param>
  639. /// <returns></returns>
  640. public async Task<bool> CreateMiUserAsync(User request)
  641. {
  642. try
  643. {
  644. var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
  645. HttpClient httpClient = new HttpClient(); //http对象
  646. HttpResponseMessage response = await httpClient.PostAsync(
  647. $"{imServiceUrl}/users",
  648. new JsonContent(new { username = request.Phone, password = "123456", nickname = request.Name }));
  649. if (response.IsSuccessStatusCode)
  650. {
  651. string result = await response.Content.ReadAsStringAsync();
  652. //成功后修改用户
  653. var userEntity = await GetByPhoneAsync(request.Phone);
  654. userEntity.ImId = request.Phone;
  655. await _repository.UpdateAsync(userEntity);
  656. }
  657. else
  658. {
  659. //出现请求环信失败
  660. // throw new BusinessException("创建用户失败");
  661. }
  662. }
  663. catch (Exception e)
  664. {
  665. throw new BusinessException(e.Message);
  666. }
  667. return true;
  668. }
  669. /// <summary>
  670. /// 用户模糊查询
  671. /// </summary>
  672. /// <param name="request"></param>
  673. /// <returns></returns>
  674. public async Task<IEnumerable<UserInfoResult>> SearchUserNameAsync(SearchUserNameRequest request)
  675. {
  676. var departments = new List<Department>();
  677. var notInUserIds = "";
  678. if (request.UserIds.Count > 0)
  679. {
  680. if (!request.IsShow)
  681. {
  682. notInUserIds = "and Id not in(";
  683. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  684. notInUserIds = "and a.Id not in(";
  685. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  686. notInUserIds = "and Id not in(";
  687. foreach (var userId in request.UserIds)
  688. {
  689. notInUserIds += $"{userId},";
  690. }
  691. notInUserIds = notInUserIds.Remove(notInUserIds.Length - 1, 1);
  692. notInUserIds += ")";
  693. }
  694. }
  695. var sql = $"select * from tede_user where (Name like '%{request.Key}%' or Phone like '%{request.Key}%' or Email like '%{request.Key}%') {notInUserIds}";
  696. if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  697. 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}";
  698. if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
  699. {
  700. //递归获取部门Id
  701. departments = await GetDepartmentAsync(request.DepartmentId, departments);
  702. var departmentValue = $"({request.DepartmentId},";
  703. foreach (var item in departments)
  704. departmentValue += $"{item.Id},";
  705. departmentValue = departmentValue.Remove(departmentValue.Length - 1, 1);
  706. departmentValue += ")";
  707. 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}";
  708. }
  709. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  710. var database = new Database(databaseType, _connectionString);
  711. var connection = database.GetConnection();
  712. var result = await connection.QueryAsync<UserInfoResult>(sql);
  713. foreach (var item in result)
  714. {
  715. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  716. //获取上级
  717. departments = new List<Department>();
  718. departments = await GetUpDepartmentAsync(item.DepartmentId, departments);
  719. foreach (var department in departments)
  720. item.DepartmentName = "-" + department.Name + item.DepartmentName;
  721. if (!string.IsNullOrWhiteSpace(item.DepartmentName))
  722. item.DepartmentName = item.DepartmentName.Remove(0, 1);
  723. if (request.IsShow)
  724. if (request.UserIds.Contains(item.Id))
  725. item.IsDisable = true;
  726. }
  727. return result;
  728. }
  729. public async Task<List<Entity.Department>> GetUpDepartmentAsync(int id, List<Department> departments)
  730. {
  731. var sql = $"select * from tede_department where Id={id}";
  732. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  733. var database = new Database(databaseType, _connectionString);
  734. var connection = database.GetConnection();
  735. var result = await connection.QueryFirstOrDefaultAsync<Department>(sql);
  736. if (result == null)
  737. return departments;
  738. departments.Add(result);
  739. await GetUpDepartmentAsync(result.ParentId, departments);
  740. return departments;
  741. }
  742. public async Task<List<Entity.Department>> GetDepartmentAsync(int pid, List<Department> departments)
  743. {
  744. var sql = $"select * from tede_department where ParentId={pid}";
  745. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  746. var database = new Database(databaseType, _connectionString);
  747. var connection = database.GetConnection();
  748. var result = await connection.QueryAsync<Department>(sql);
  749. if (result.Count() == 0)
  750. return departments;
  751. departments.AddRange(result);
  752. foreach (var item in result)
  753. await GetDepartmentAsync(item.Id, departments);
  754. return departments;
  755. }
  756. /// <summary>
  757. /// 查询所有用户
  758. /// </summary>
  759. /// <returns></returns>
  760. public async Task<IEnumerable<User>> FindAllUserAsync(SqlKata.Query query)
  761. {
  762. return await _repository.GetAllAsync(query);
  763. }
  764. /// <summary>
  765. /// 根据Guid获取用户数据
  766. /// </summary>
  767. /// <param name="guid"></param>
  768. /// <returns></returns>
  769. public async Task<UserDetail> GetGuidAsync(string guid)
  770. {
  771. var user = await _repository.GetAsync(Q.Where(nameof(User.Guid), guid));
  772. user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  773. user.QRCoder = StringUtils.AddDomain(user.QRCoder);
  774. return _mapper.Map<UserDetail>(user);
  775. }
  776. public async Task<int> CountAsync(Query query)
  777. {
  778. return await _repository.CountAsync(query);
  779. }
  780. public async Task<IEnumerable<User>> GetAllAsync(Query query)
  781. {
  782. return await _repository.GetAllAsync(query);
  783. }
  784. public async Task<IEnumerable<int>> GetAllIntsAsync(Query query)
  785. {
  786. return await _repository.GetAllAsync<int>(query);
  787. }
  788. public Task<IEnumerable<User>> FindAllUserAsync()
  789. {
  790. throw new NotImplementedException();
  791. }
  792. /// <summary>
  793. /// 获取用户未读数据
  794. /// </summary>
  795. /// <param name="userId"></param>
  796. /// <returns></returns>
  797. public async Task<UserCountResult> GetUserCountAsync(int userId)
  798. {
  799. var result = new UserCountResult();
  800. var noticeConstValue = AllTypeConst.Notice.GetHashCode();
  801. var missiveConstValue = AllTypeConst.Missive.GetHashCode();
  802. var anonymityConstValue = AllTypeConst.Anonymity.GetHashCode();
  803. 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}))";
  804. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  805. var database = new Database(databaseType, _connectionString);
  806. var connection = database.GetConnection();
  807. var noticeCount = await connection.ExecuteScalarAsync<int>(sql);
  808. // 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)";
  809. // var missiveCount = await connection.ExecuteScalarAsync<int>(sql);
  810. // //sql = $"SELECT count(1) FROM tede_admin_verify where AdminId={userId} and DisposeType=0";
  811. // // noticeCount += await connection.ExecuteScalarAsync<int>(sql);
  812. // result.noticeCount = noticeCount;
  813. result.noticeCount = noticeCount;
  814. return result;
  815. }
  816. /// <summary>
  817. /// 获取工作用户选择审核和抄送人
  818. /// </summary>
  819. /// <param name="userIds"></param>
  820. /// <param name="flowId"></param>
  821. /// <returns></returns>
  822. public async Task<List<Entity.User>> GeFlowUsers(List<int> userIds, int flowId, string type)
  823. {
  824. string strSql = "";
  825. if (userIds.Count > 0)
  826. {
  827. strSql = "and UserId not in(";
  828. foreach (var item in userIds)
  829. {
  830. strSql += $"{item},";
  831. }
  832. strSql = strSql.Remove(strSql.Length - 1, 1);
  833. strSql += ")";
  834. }
  835. string sql = $" select * from tede_user where Id in( SELECT UserId FROM tede_flow_todo where FlowId={flowId} and Type='{type}' {strSql})";
  836. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  837. var database = new Database(databaseType, _connectionString);
  838. var connection = database.GetConnection();
  839. var result = await connection.QueryAsync<User>(sql);
  840. foreach (var item in result)
  841. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  842. return result.ToList();
  843. }
  844. public async Task<List<JobUserResult>> ElasticSearchUser()
  845. {
  846. var sql = "select * from tede_user where IsUpload=0 limit 0,100";
  847. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  848. var database = new Database(databaseType, _connectionString);
  849. var connection = database.GetConnection();
  850. var items = await connection.QueryAsync<JobUserResult>(sql);
  851. return items.ToList();
  852. }
  853. public async Task<bool> UpdateAsync(SqlKata.Query query)
  854. {
  855. return await _repository.UpdateAsync(query) > 0;
  856. }
  857. //public async Task<UserDetail> GetUserDetailJoinAsync(int userId)
  858. //{
  859. // var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
  860. // var database = new Database(databaseType, _connectionString);
  861. // var connection = database.GetConnection();
  862. // var result = connection.Query<UserDetail, Department, UserDetail>(
  863. // "SELECT a.*,b.Name FROM tede_user a inner join tede_department b on a.DepartmentId=b.Id where a.id=@Id;",
  864. // (userDetail,department) =>
  865. // {
  866. // userDetail.DepartmentName = department.Name;
  867. // return userDetail;
  868. // }, new {Id = userId}, splitOn: "Name");
  869. // return result.ToList()[0];
  870. //}
  871. /// <summary>
  872. /// vip用户
  873. /// </summary>
  874. /// <param name="request"></param>
  875. /// <returns></returns>
  876. public async Task<PagedList<UserDetail>> GetUserVipDetail(UserSearchVipRequest request)
  877. {
  878. var result = new PagedList<UserDetail>();
  879. var query = Q.NewQuery();
  880. if (!string.IsNullOrEmpty(request.KeyWord))
  881. query.WhereLike(nameof(User.Name), $"%{request.KeyWord}%");
  882. if (request.VipPort > 0)
  883. query.Where(nameof(User.Port), request.VipPort);
  884. if (request.VipTypeId > 0)
  885. query.Where(nameof(User.TypeId), request.VipTypeId);
  886. if (request.IsDisable > 0)
  887. query.Where(nameof(User.IsDisable), request.IsDisable == 1);
  888. if (request.IsFreeze > 0)
  889. query.Where(nameof(User.IsFreeze), request.IsFreeze == 1);
  890. if (request.IsVip > 0)
  891. query.Where(nameof(User.IsVip), request.IsVip == 1);
  892. if (request.BeginAccumulativePrice > 0 || request.EndAccumulativePrice > 0)
  893. {
  894. query.Where(nameof(User.AccumulativePrice), ">=", request.BeginAccumulativePrice);
  895. query.Where(nameof(User.AccumulativePrice), "<=", request.EndAccumulativePrice);
  896. }
  897. if (request.RenewalCount > 0)
  898. query.Where(nameof(User.RenewalCount), request.RenewalCount);
  899. result.Total = await _repository.CountAsync(query);
  900. if (!string.IsNullOrEmpty(request.Sort) && request.Sort.Equals("AccumulativePrice"))
  901. query.OrderByDesc(nameof(User.AccumulativePrice));
  902. else
  903. query.OrderByDesc(nameof(User.CreatedDate));
  904. var items = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
  905. result.Items = items.Select(n => _mapper.Map<UserDetail>(n));
  906. return result;
  907. }
  908. /// <summary>
  909. /// 根据用户ID获取用户信息
  910. /// </summary>
  911. /// <param name="userIds"></param>
  912. /// <returns></returns>
  913. public async Task<IEnumerable<UserInfoResult>> GetUserInfoResultsAsync(IEnumerable<int> userIds, string keyWord = "")
  914. {
  915. userIds = userIds.Distinct();
  916. if (userIds.Count() == 0)
  917. return new List<UserInfoResult>();
  918. var sqlStr = "";
  919. foreach (var item in userIds)
  920. sqlStr += $"{item},";
  921. sqlStr = sqlStr.Remove(sqlStr.Length - 1, 1);
  922. var sql = $@"select * from tede_user where id in({sqlStr})";
  923. if (!string.IsNullOrEmpty(keyWord))
  924. sql += $@" and (Name like '%{keyWord}%' or phone like '%{keyWord}%' or Email like '%{keyWord}%')";
  925. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  926. var database = new Database(databaseType, _connectionString);
  927. var connection = database.GetConnection();
  928. var result = await connection.QueryAsync<UserInfoResult>(sql);
  929. foreach (var item in result)
  930. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  931. return result;
  932. }
  933. /// <summary>
  934. /// 获取不是好友的用户 排除部门
  935. /// </summary>
  936. /// <param name="keyword"></param>
  937. /// <param name="userIds"></param>
  938. /// <returns></returns>
  939. public async Task<IEnumerable<UserInfoResult>> GetUserInfoNoFriendsResults(string keyword, IEnumerable<int> userIds)
  940. {
  941. userIds = userIds.Distinct();
  942. var sqlStr = "";
  943. foreach (var item in userIds)
  944. sqlStr += $"{item},";
  945. sqlStr = !string.IsNullOrEmpty(sqlStr) ? sqlStr.Remove(sqlStr.Length - 1, 1) : "";
  946. var sql = $@"select * from tede_user where 1=1 ";
  947. if (!string.IsNullOrEmpty(sqlStr))
  948. sql += " and id not in({sqlStr})";
  949. if (!string.IsNullOrEmpty(keyword))
  950. sql += $@" and (Name like '%{keyword}%' or phone like '%{keyword}%' or Email like '%{keyword}%')";
  951. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  952. var database = new Database(databaseType, _connectionString);
  953. var connection = database.GetConnection();
  954. var result = await connection.QueryAsync<UserInfoResult>(sql);
  955. foreach (var item in result)
  956. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  957. return result;
  958. }
  959. /// <summary>
  960. /// 搜索好友部门用户
  961. /// </summary>
  962. /// <param name="keyword"></param>
  963. /// <param name="userIds"></param>
  964. /// <returns></returns>
  965. public async Task<IEnumerable<UserInfoResult>> GetSearchUserInfoResults(string keyword, IEnumerable<int> userIds)
  966. {
  967. userIds = userIds.Distinct();
  968. var sqlStr = "";
  969. foreach (var item in userIds)
  970. sqlStr += $"{item},";
  971. sqlStr = string.IsNullOrEmpty(sqlStr) ? "" : sqlStr.Remove(sqlStr.Length - 1, 1);
  972. var sql = $@"select * from tede_user where 1=1 ";
  973. if (!string.IsNullOrEmpty(sqlStr))
  974. sql += " and id in({sqlStr})";
  975. if (!string.IsNullOrEmpty(keyword))
  976. sql += " and (Name like '%{keyword}%' or phone like '%{keyword}%' or Email like '%{keyword}%')";
  977. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  978. var database = new Database(databaseType, _connectionString);
  979. var connection = database.GetConnection();
  980. var result = await connection.QueryAsync<UserInfoResult>(sql);
  981. foreach (var item in result)
  982. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  983. return result;
  984. }
  985. /// <summary>
  986. /// 获取用户工作我的审批未读数量
  987. /// </summary>
  988. /// <param name="userId"></param>
  989. /// <returns></returns>
  990. public async Task<int> GetUserUReadFlowTodoCountAsync(int userId)
  991. {
  992. string sql = $@"SELECT
  993. count(1)
  994. FROM
  995. tede_flow_todo
  996. WHERE
  997. FlowId IN (SELECT
  998. SonId
  999. FROM
  1000. tede_notice
  1001. WHERE
  1002. userId ={userId} AND TypeValue = 15
  1003. AND IsDelete = 0)
  1004. AND Type = 'ApproverCheck' and IsRead=0";
  1005. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  1006. var database = new Database(databaseType, _connectionString);
  1007. var connection = database.GetConnection();
  1008. var result = await connection.ExecuteScalarAsync<int>(sql);
  1009. return result;
  1010. }
  1011. }
  1012. }