UserRepository.cs 51 KB

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