UserRepository.cs 50 KB

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