1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net.Http;
- using System.Threading.Tasks;
- using AutoMapper;
- using GxPress.Common.Extensions;
- using GxPress.Common.AppOptions;
- using GxPress.Common.Exceptions;
- using GxPress.Common.Page;
- using GxPress.Common.Tools;
- using GxPress.Entity;
- using GxPress.EnumConst;
- using GxPress.Repository.Interface;
- using GxPress.Request.User;
- using GxPress.Result.User;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Options;
- using Newtonsoft.Json;
- using SqlKata;
- using SS.Mail.Core;
- using Datory;
- using Microsoft.Extensions.Caching.Distributed;
- using Dapper;
- using GxPress.Result.App.User;
- using GxPress.Result.Job;
- using GxPress.Common.Http;
- using GxPress.Repository.Interface.DepartmentUser;
- using GxPress.Request.App.GroupUser;
- using GxPress.Result.App.GroupUser;
- using SqlKata.Extensions;
- namespace GxPress.Repository.Implement
- {
- public class UserRepository : IUserRepository
- {
- private readonly Repository<User> _repository;
- private readonly Repository<Department> _departmentRepository;
- private readonly Repository<Role> _roleRepository;
- private readonly IMapper _mapper;
- private readonly IWebHostEnvironment _environment;
- private readonly IDistributedCache _cache;
- //private readonly string _connectionString;
- //private readonly string _databaseTypestr;
- private readonly string _connectionString;
- private readonly string _databaseTypeStr;
- private readonly IDepartmentUserRepository departmentUserRepository;
- public UserRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper,
- IWebHostEnvironment environment, IDistributedCache cache, IDepartmentUserRepository departmentUserRepository)
- {
- _databaseTypeStr = dbOptionsAccessor.CurrentValue.DatabaseType;
- _connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
- // _databaseType
- // str = dbOptionsAccessor.CurrentValue.DatabaseType;
- var databaseType =
- StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
- //_connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
- var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
- _repository = new Repository<User>(database);
- _environment = environment;
- _departmentRepository = new Repository<Department>(database);
- _roleRepository = new Repository<Role>(database);
- _mapper = mapper;
- _cache = cache;
- this.departmentUserRepository = departmentUserRepository;
- }
- public IDatabase Database => _repository.Database;
- public string TableName => _repository.TableName;
- public List<TableColumn> TableColumns => _repository.TableColumns;
- /// <summary>
- /// 根据id集合查询用户
- /// </summary>
- /// <param name="ids"></param>
- /// <returns></returns>
- public async Task<IEnumerable<User>> UserListInsAsync(List<int> ids)
- {
- return await _repository.GetAllAsync(Q.WhereIn(nameof(User.Id), ids).Where(nameof(User.IsDelete), false));
- }
- /// <summary>
- /// 根据姓名查询用户
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- public async Task<IEnumerable<UserInfoResult>> UserByNameAsync(string name)
- {
- var result = await _repository.GetAllAsync(Q.WhereLike(nameof(User.Name), $"%{name}%").Where(nameof(User.IsDelete), false));
- foreach (var item in result)
- item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
- return result.Select(n => _mapper.Map<UserInfoResult>(n));
- }
- public async Task<UserDetail> GetDetailAsync(int id)
- {
- var user = await GetAsync(id);
- user.QRCoder = StringUtils.AddDomain(user.QRCoder);
- user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
- if (!string.IsNullOrEmpty(user.HistoryAvatarUrl))
- user.HistoryAvatarUrl = StringUtils.AddDomain(user.HistoryAvatarUrl);
- var userDetail = _mapper.Map<UserDetail>(user);
- // if (user.DepartmentId > 0)
- // {
- // var department = await _departmentRepository.GetAsync(user.DepartmentId);
- // userDetail.DepartmentName = department.Name;
- // }
- return userDetail;
- }
- public async Task<int> GetUserCount(string beginTime, string endTime)
- {
- return await _repository.CountAsync(Q.WhereDate(nameof(User.CreatedDate), ">=", beginTime).WhereDate(nameof(User.CreatedDate), "<=", endTime).Where(nameof(User.IsDelete), false));
- }
- public async Task<User> GetAsync(int id)
- {
- var user = await _repository.GetAsync(Q.Where(nameof(User.Id), id).Where(nameof(User.IsDelete), false));
- return user;
- }
- public async Task<UserInfoResult> GetUserInfoAsync(int id)
- {
- var user = await _repository.GetAsync<UserInfoResult>(Q.Where(nameof(User.Id), id).Where(nameof(User.IsDelete), false));
- return user;
- }
- public async Task<User> GetAsync(SqlKata.Query query)
- {
- var user = await _repository.GetAsync(query.Where(nameof(User.IsDelete), false));
- return user;
- }
- public async Task<string> GetNameAsync(int id)
- {
- if (id <= 0) return string.Empty;
- return await _repository.GetAsync<string>(Q
- .Select(nameof(User.Name))
- .Where(nameof(User.Id), id).Where(nameof(User.IsDelete), false)
- );
- }
- public async Task<string> GetAvatarUrlAsync(int id)
- {
- if (id <= 0) return string.Empty;
- var avatarUrl = await _repository.GetAsync<string>(Q
- .Select(nameof(User.AvatarUrl))
- .Where(nameof(User.Id), id).Where(nameof(User.IsDelete), false)
- );
- return StringUtils.AddDomainMin(avatarUrl);
- }
- public string GetAvatarUrl(User user)
- {
- if (user == null) return string.Empty;
- return StringUtils.AddDomainMin(user.AvatarUrl);
- }
- public async Task<User> GetByPhoneAsync(string phone)
- {
- return await _repository.GetAsync(Q.Where(nameof(User.Phone), phone).Where(nameof(User.IsDelete), false));
- }
- /// <summary>
- /// openId微信认证
- /// </summary>
- /// <param name="openId"></param>
- /// /// <returns></returns>
- public async Task<User> GetByOpenIdAsync(string openId)
- {
- return await _repository.GetAsync(Q.Where(nameof(User.OpenId), openId).Where(nameof(User.IsDelete), false));
- }
- /// <summary>
- /// 绑定微信
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateByOpendIdAsync(UserSignInRequest request)
- {
- var key = $"login:{request.Phone}";
- var user = new User();
- var code = _cache.GetString(key).Replace("\"", "");
- if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
- if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
- user = await GetByPhoneAsync(request.Phone);
- //用户不存在,自动注册
- if (user == null)
- throw new BusinessException("用户不存在");
- return await _repository.UpdateAsync(Q.Where(nameof(User.Phone), request.Phone).Set(nameof(User.OpenId), request.OpenId)) > 0;
- }
- public async Task<bool> DeleteUsersAsync(IEnumerable<int> userIds)
- {
- return await _repository.UpdateAsync(Q.WhereIn(nameof(User.Id), userIds).Set(nameof(User.IsDelete), true)) > 0;
- }
- public async Task<bool> ChangeRoleAsync(IEnumerable<int> userIds, int roleId)
- {
- return await _repository.UpdateAsync(Q
- .Set(nameof(User.RoleId), roleId)
- .WhereIn(nameof(User.Id), userIds)
- ) > 0;
- }
- public async Task<bool> ChangeDepartmentAsync(IEnumerable<int> userIds, int departmentId)
- {
- return await _repository.UpdateAsync(Q
- .Set(nameof(User.DepartmentId), departmentId)
- .WhereIn(nameof(User.Id), userIds)
- ) > 0;
- }
- public async Task<bool> UpdateAsync(User user)
- {
- return await _repository.UpdateAsync(user);
- }
- public async Task<bool> UpdateDisableAsync(UserUpdateDisableRequest request)
- {
- return await _repository.UpdateAsync(Q.WhereIn(nameof(User.Id), request.Ids).Set(nameof(User.IsDisable), request.IsDisable)) > 0;
- }
- public async Task<int> GetCountAsync(int departmentId, int roleId, string keyword)
- {
- var query = Q.NewQuery();
- if (departmentId > 0)
- {
- query.Where(nameof(User.DepartmentId), departmentId);
- }
- if (roleId > 0)
- {
- query.Where(nameof(User.RoleId), roleId);
- }
- if (!string.IsNullOrEmpty(keyword))
- {
- keyword = "%" + keyword + "%";
- query.Where(q =>
- q.WhereLike(nameof(User.Name), keyword)
- .OrWhereLike(nameof(User.Email), keyword)
- .OrWhereLike(nameof(User.Phone), keyword)
- );
- }
- return await _repository.CountAsync(query.Where(nameof(User.IsDelete), false));
- }
- /// <summary>
- /// Set the limit and offset for a given page.
- /// </summary>
- /// <param name="page"></param>
- /// <param name="perPage"></param>
- /// <param name="departmentId"></param>
- /// <param name="roleId"></param>
- /// <param name="keyword"></param>
- /// <returns></returns>
- public async Task<IEnumerable<User>> GetPageListAsync(int page, int perPage, int departmentId, int roleId,
- string keyword)
- {
- var query = Q.ForPage(page, perPage);
- if (departmentId > 0)
- {
- query.Where(nameof(User.DepartmentId), departmentId);
- }
- if (roleId > 0)
- {
- query.Where(nameof(User.RoleId), roleId);
- }
- if (!string.IsNullOrEmpty(keyword))
- {
- keyword = "%" + keyword + "%";
- query.Where(q =>
- q.WhereLike(nameof(User.Name), keyword)
- .OrWhereLike(nameof(User.Email), keyword)
- .OrWhereLike(nameof(User.Phone), keyword)
- );
- }
- return await _repository.GetAllAsync(query.Where(nameof(User.IsDelete), false));
- }
- public async Task<IEnumerable<User>> GetListAsync(int departmentId, int roleId, string keyword)
- {
- var query = Q.NewQuery();
- if (departmentId > 0)
- {
- query.Where(nameof(User.DepartmentId), departmentId);
- }
- if (roleId > 0)
- {
- query.Where(nameof(User.RoleId), roleId);
- }
- if (!string.IsNullOrEmpty(keyword))
- {
- query.Where(q =>
- q.WhereLike(nameof(User.Name), keyword)
- .OrWhereLike(nameof(User.Email), keyword)
- .OrWhereLike(nameof(User.Phone), keyword)
- );
- }
- return await _repository.GetAllAsync(query.Where(nameof(User.IsDelete), false));
- }
- /// <summary>
- /// 登录
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<UserSignInResult> SignInAsync(UserSignInRequest request)
- {
- var result = new UserSignInResult();
- var key = $"login:{request.Phone}";
- try
- {
- var user = new User();
- if (string.IsNullOrWhiteSpace(request.OpenId))
- {
- var code = _cache.GetString(key).Replace("\"", "");
- if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
- if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
- user = await GetByPhoneAsync(request.Phone);
- //用户不存在,自动注册
- if (user == null)
- throw new BusinessException("用户不存在");
- }
- else
- user = await GetByOpenIdAsync(request.OpenId);
- result.UserId = user.Id;
- result.DepartmentId = user.DepartmentId;
- result.User = _mapper.Map<UserResult>(user);
- if (result.User != null)
- result.User.AvatarUrl = StringUtils.AddDomain(result.User.AvatarUrl);
- //修改登录时间
- user.LoginTime = DateTime.Now;
- await _repository.UpdateAsync(user);
- return result;
- }
- catch (System.Exception)
- {
- throw new BusinessException("验证码或手机号错误");
- }
- }
- public async Task<int> InsertAsync(User user)
- {
- if (user == null) throw new Exception("用户不能为空");
- if (string.IsNullOrEmpty(user.Name)) throw new Exception("用户不能为空");
- if (!string.IsNullOrEmpty(user.Phone) &&
- await _repository.ExistsAsync(Q.Where(nameof(User.Phone), user.Phone)))
- {
- throw new Exception("用户手机号已存在,请更换手机号");
- }
- //头像处理
- user.AvatarUrl = StringUtils.RemoveDomain(user.AvatarUrl);
- user.IsUpload = false;
- user.Id = await _repository.InsertAsync(user);
- user = await _repository.GetAsync(user.Id);
- //创建二维码
- var qrCodeData = new { key = QRCodeTypeConst.UserInfo, value = user.Guid };
- var resultPath =
- FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath),
- JsonConvert.SerializeObject(qrCodeData));
- user.QRCoder = resultPath.RelativePath;
- await _repository.UpdateAsync(user);
- return user.Id;
- }
- /// <summary>
- /// 删除用户
- /// </summary>
- /// <param name="id"></param>
- /// <returns></returns>
- public async Task<bool> DeleteAsync(int id)
- {
- var user = await GetAsync(id);
- if (user == null) throw new BusinessException("该用户不存在");
- return await DeleteAsync(id);
- }
- /// <summary>
- /// 删除用户
- /// </summary>
- /// <param name="ids"></param>
- /// <returns></returns>
- public async Task<bool> DeleteAsync(List<int> ids)
- {
- return await _repository.UpdateAsync(Q.WhereIn(nameof(User.Id), ids).Set(nameof(User.IsDelete), true)) > 0;
- }
- /// <summary>
- /// 更新用户信息
- /// </summary>
- /// <param name="id"></param>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateAsync(int id, UserInfoRequest request)
- {
- var user = await GetAsync(id);
- if (user == null) throw new BusinessException("该用户不存在");
- if (request.DepartmentId.Count() > 0)
- {
- await departmentUserRepository.AddDepartmentUserAsync(request.DepartmentId, id);
- }
- if (!string.IsNullOrEmpty(request.Nick))
- user.Nick = request.Nick;
- if (!string.IsNullOrEmpty(request.Description))
- user.Description = request.Description;
- if (!string.IsNullOrEmpty(request.Gender))
- user.Gender = request.Gender;
- if (!string.IsNullOrEmpty(request.Name))
- user.Name = request.Name;
- if (!string.IsNullOrEmpty(request.Position))
- user.Position = request.Position;
- if (request.RoleId > 0)
- user.RoleId = request.RoleId;
- if (!string.IsNullOrEmpty(request.Signature))
- user.Signature = request.Signature;
- //修改部门
- if (!string.IsNullOrEmpty(request.DepartmentName))
- user.DepartmentName = request.DepartmentName;
- //用户头像
- if (!string.IsNullOrEmpty(request.AvatarUrl))
- {
- user.HistoryAvatarUrl = user.AvatarUrl;
- user.AvatarUrl = StringUtils.RemoveDomain(request.AvatarUrl);
- }
- user.Email = request.Email;
- if (!string.IsNullOrWhiteSpace(request.Phone))
- user.Phone = request.Phone;
- user.QRCoder = StringUtils.RemoveDomain(user.QRCoder);
- if (request.IsDisable > 0)
- user.IsDisable = request.IsDisable == 1;
- if (request.IsFreeze > 0)
- user.IsFreeze = request.IsFreeze == 1;
- if (request.IsVip > 0)
- user.IsVip = request.IsVip == 1;
- if (request.IsLeader > 0)
- user.IsLeader = request.IsLeader == 1;
- if (request.IsMute > 0)
- user.IsMute = request.IsMute == 1;
- if (!string.IsNullOrWhiteSpace(request.DisableTiem))
- user.DisableTiem = Convert.ToDateTime(request.DisableTiem);
- return await UpdateAsync(user);
- }
- /// <summary>
- /// 用户分页列表
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<PagedList<UserResult>> GetPagedListAsync(UserPageSearchRequest request)
- {
- var pagedList = new PagedList<UserResult>
- {
- Total = await GetCountAsync(request.DepartmentId, request.RoleId, request.Keyword)
- };
- var list = await GetPageListAsync(request.Page, request.PerPage, request.DepartmentId, request.RoleId,
- request.Keyword);
- var items = list.Select(user => _mapper.Map<UserResult>(user)).ToList();
- foreach (var item in items)
- {
- //获取部门
- // var department = await _departmentRepository.GetAsync(item.DepartmentId);
- // if (department != null)
- // item.DepartmentName = department.Name;
- var role = await _roleRepository.GetAsync(item.RoleId);
- if (role != null)
- item.RoleName = role.Name;
- }
- pagedList.Items = items;
- return pagedList;
- }
- public async Task<List<UserResult>> GetListAsync(ArticleSearchRequest request)
- {
- var list = await GetListAsync(request.DepartmentId, request.RoleId, request.Keyword);
- var allList = new List<UserResult>();
- foreach (var user in list)
- {
- var result = _mapper.Map<UserResult>(user);
- allList.Add(result);
- }
- return allList;
- }
- /// <summary>
- /// 更新excel用户数据
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateUserExcelAsync(List<User> request)
- {
- try
- {
- foreach (var item in request)
- {
- var user = await _repository.GetAsync(Q.Where(nameof(User.Phone), item.Phone));
- if (user != null)
- {
- continue;
- }
- var userId = await _repository.InsertAsync(item);
- //
- user = await _repository.GetAsync(userId);
- var resultPath =
- FileHelper.SaveQRCodeFile(StringUtils.GetWebRootPath(_environment.WebRootPath), item.Guid);
- user.QRCoder = resultPath.RelativePath;
- await _repository.UpdateAsync(user);
- await CreateMiUserAsync(item);
- }
- }
- catch (Exception e)
- {
- throw new BusinessException(e.Message);
- }
- return true;
- }
- /// <summary>
- /// 私信
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateUserPrivateLetterAsync(UserPrivateLetterRequest request)
- {
- var user = await _repository.GetAsync(request.Id);
- if (user == null)
- throw new BusinessException("该用户不存在");
- user.IsPrivateLetter = !user.IsPrivateLetter;
- return await _repository.UpdateAsync(user);
- }
- /// <summary>
- /// 通知
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateUserNoticeAsync(UserNoticeRequest request)
- {
- var user = await _repository.GetAsync(request.Id);
- if (user == null)
- throw new BusinessException("该用户不存在");
- user.IsNotice = !user.IsNotice;
- return await _repository.UpdateAsync(user);
- }
- /// <summary>
- /// 回复
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateUserReplyAsync(UserReplyRequest request)
- {
- var user = await _repository.GetAsync(request.Id);
- if (user == null)
- throw new BusinessException("该用户不存在");
- user.IsReply = !user.IsReply;
- return await _repository.UpdateAsync(user);
- }
- /// <summary>
- /// 静音
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateUserMuteAsync(UserMuteRequest request)
- {
- var user = await _repository.GetAsync(request.Id);
- if (user == null)
- throw new BusinessException("该用户不存在");
- user.IsMute = !user.IsMute;
- return await _repository.UpdateAsync(user);
- }
- /// <summary>
- /// 震动
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateUserShakeAsync(UserShakeRequest request)
- {
- var user = await _repository.GetAsync(request.Id);
- if (user == null)
- throw new BusinessException("该用户不存在");
- user.IsShake = !user.IsShake;
- return await _repository.UpdateAsync(user);
- }
- /// <summary>
- /// 用户修改密码
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateUserPhoneAsync(UserUpdatePhoneRequest request)
- {
- var key = $"login:{request.Phone}";
- var code = await _cache.GetStringAsync(key);
- if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
- if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
- var user = await GetAsync(request.UserId);
- //用户不存在,自动注册
- if (user == null)
- {
- throw new BusinessException("该用户不存在");
- }
- user.Phone = request.Phone;
- return await _repository.UpdateAsync(user);
- }
- /// <summary>
- /// 用户邮箱验证
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> SendEmailVerifyCodeAsync(UserEmailVerifyCodeRequest request)
- {
- //默认配置
- ConfigInfo configInfo = new ConfigInfo();
- var code = RandomGenerator.GetNumberString(6);
- var key = $"email:{request.Email}";
- //if (await RedisHelper.ExistsAsync(key)) throw new BusinessException("发送太频繁");
- MailManager.Send(configInfo, request.Email, "邮箱验证", "邮箱验证", $"验证号码:{code}", out var message);
- if (!string.IsNullOrEmpty(message))
- {
- throw new BusinessException(message);
- }
- //保存验证码
- await _cache.SetAsync(key, code, new DistributedCacheEntryOptions
- {
- AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(300)
- });
- return true;
- }
- /// <summary>
- /// 用户修改密码
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> UpdateUserEmailAsync(UserUpdateEmailRequest request)
- {
- var key = $"email:{request.Email}";
- var code = await _cache.GetStringAsync(key);
- if (string.IsNullOrEmpty(code)) throw new BusinessException("验证码已过期");
- if (!request.Code.Equals(code, StringComparison.OrdinalIgnoreCase)) throw new BusinessException("验证码错误");
- var user = await _repository.GetAsync(request.UserId);
- //用户不存在,自动注册
- if (user == null)
- {
- throw new BusinessException("该用户不存在");
- }
- user.Email = request.Email;
- return await _repository.UpdateAsync(user);
- }
- /// <summary>
- /// 根据部门ID获取用户
- /// </summary>
- /// <param name="departmentId"></param>
- /// <returns></returns>
- public async Task<IEnumerable<User>> GetUserByDepartmentIdAsync(int departmentId)
- {
- var userIds = await departmentUserRepository.GetUserIdsByDepartmentIdsAsync(new List<int>() { departmentId });
- return await _repository.GetAllAsync(Q.WhereIn(nameof(User.Id), userIds).Where(nameof(User.IsDelete), false));
- }
- public async Task<IEnumerable<int>> GetUserIdListByDepartmentIdAsync(int departmentId)
- {
- return await _repository.GetAllAsync<int>(Q
- .Select(nameof(User.Id))
- .Where(nameof(User.DepartmentId), departmentId)
- );
- }
- public async Task<IEnumerable<int>> GetUserIdListByRoleIdAsync(int roleId)
- {
- return await _repository.GetAllAsync<int>(Q
- .Select(nameof(User.Id))
- .Where(nameof(User.RoleId), roleId).Where(nameof(User.IsDelete), false)
- );
- }
- /// <summary>
- /// 创建环信用户
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<bool> CreateMiUserAsync(User request)
- {
- try
- {
- var imServiceUrl = ConfigHelper.GetValue("ServiceAddress:ImUrl");
- HttpClient httpClient = new HttpClient(); //http对象
- HttpResponseMessage response = await httpClient.PostAsync(
- $"{imServiceUrl}/users",
- new JsonContent(new { username = request.Phone, password = "123456", nickname = request.Name }));
- if (response.IsSuccessStatusCode)
- {
- string result = await response.Content.ReadAsStringAsync();
- //成功后修改用户
- var userEntity = await GetByPhoneAsync(request.Phone);
- userEntity.ImId = request.Phone;
- await _repository.UpdateAsync(userEntity);
- }
- else
- {
- //出现请求环信失败
- // throw new BusinessException("创建用户失败");
- }
- }
- catch (Exception e)
- {
- throw new BusinessException(e.Message);
- }
- return true;
- }
- /// <summary>
- /// 用户模糊查询
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<IEnumerable<UserInfoResult>> SearchUserNameAsync(SearchUserNameRequest request)
- {
- var departments = new List<Department>();
- var notInUserIds = "";
- if (request.UserIds.Count > 0)
- {
- if (!request.IsShow)
- {
- notInUserIds = "and Id not in(";
- if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
- notInUserIds = "and a.Id not in(";
- if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
- notInUserIds = "and Id not in(";
- foreach (var userId in request.UserIds)
- {
- notInUserIds += $"{userId},";
- }
- notInUserIds = notInUserIds.Remove(notInUserIds.Length - 1, 1);
- notInUserIds += ")";
- }
- }
- 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}";
- if (request.SearchType == 2 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
- sql = $@"select a.* from tede_user a inner join tede_address_book_group_user c on a.Id=c.UserId
- where 1=1 and a.IsDelete=0 and c.AddressBookGroupId={request.DepartmentId}
- and (a.Name like '%{request.Key}%' or a.Phone like '%{request.Key}%' or a.Email like '%{request.Key}%') {notInUserIds}";
- if (request.SearchType == 1 && !string.IsNullOrWhiteSpace(request.Key) && request.DepartmentId > 0)
- {
- //递归获取部门Id
- departments = await GetDepartmentAsync(request.DepartmentId, departments);
- var departmentValue = $"({request.DepartmentId},";
- foreach (var item in departments)
- departmentValue += $"{item.Id},";
- departmentValue = departmentValue.Remove(departmentValue.Length - 1, 1);
- departmentValue += ")";
- 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}";
- }
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var result = await connection.QueryAsync<UserInfoResult>(sql);
- foreach (var item in result)
- {
- item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
- //获取上级
- departments = new List<Department>();
- departments = await GetUpDepartmentAsync(item.DepartmentId, departments);
- foreach (var department in departments)
- item.DepartmentName = "-" + department.Name + item.DepartmentName;
- if (!string.IsNullOrWhiteSpace(item.DepartmentName))
- item.DepartmentName = item.DepartmentName.Remove(0, 1);
- if (request.IsShow)
- if (request.UserIds.Contains(item.Id))
- item.IsDisable = true;
- }
- return result;
- }
- public async Task<List<Entity.Department>> GetUpDepartmentAsync(int id, List<Department> departments)
- {
- var sql = $"select * from tede_department where Id={id}";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var result = await connection.QueryFirstOrDefaultAsync<Department>(sql);
- if (result == null)
- return departments;
- departments.Add(result);
- await GetUpDepartmentAsync(result.ParentId, departments);
- return departments;
- }
- public async Task<List<Entity.Department>> GetDepartmentAsync(int pid, List<Department> departments)
- {
- var sql = $"select * from tede_department where ParentId={pid}";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var result = await connection.QueryAsync<Department>(sql);
- if (result.Count() == 0)
- return departments;
- departments.AddRange(result);
- foreach (var item in result)
- await GetDepartmentAsync(item.Id, departments);
- return departments;
- }
- /// <summary>
- /// 查询所有用户
- /// </summary>
- /// <returns></returns>
- public async Task<IEnumerable<User>> FindAllUserAsync(SqlKata.Query query)
- {
- return await _repository.GetAllAsync(query.Where(nameof(User.IsDelete), false));
- }
- /// <summary>
- /// 根据Guid获取用户数据
- /// </summary>
- /// <param name="guid"></param>
- /// <returns></returns>
- public async Task<UserDetail> GetGuidAsync(string guid)
- {
- var user = await _repository.GetAsync(Q.Where(nameof(User.Guid), guid));
- user.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
- user.QRCoder = StringUtils.AddDomain(user.QRCoder);
- return _mapper.Map<UserDetail>(user);
- }
- public async Task<int> CountAsync(Query query)
- {
- return await _repository.CountAsync(query.Where(nameof(User.IsDelete), false));
- }
- public async Task<IEnumerable<User>> GetAllAsync(Query query)
- {
- return await _repository.GetAllAsync(query.Where(nameof(User.IsDelete), false));
- }
- public async Task<IEnumerable<int>> GetAllIntsAsync(Query query)
- {
- return await _repository.GetAllAsync<int>(query.Where(nameof(User.IsDelete), false));
- }
- public Task<IEnumerable<User>> FindAllUserAsync()
- {
- throw new NotImplementedException();
- }
- /// <summary>
- /// 获取用户未读数据
- /// </summary>
- /// <param name="userId"></param>
- /// <returns></returns>
- public async Task<UserCountResult> GetUserCountAsync(int userId)
- {
- var result = new UserCountResult();
- var noticeConstValue = AllTypeConst.Notice.GetHashCode();
- var missiveConstValue = AllTypeConst.Missive.GetHashCode();
- var anonymityConstValue = AllTypeConst.Anonymity.GetHashCode();
- string sql = $@"SELECT
- COUNT(1)
- FROM
-
- tede_middle a
- INNER JOIN
- tede_notice b ON a.MiddleId = b.Id
- WHERE
- a.FolderType = {AllTypeConst.Inbox.GetHashCode()} AND a.UserId = {userId}
- AND b.NoticeType = 1
- AND a.IsDelete = 0
- AND a.MiddleId IN (SELECT
- SourceId
- FROM
- tede_addressee
- WHERE
- UserId = {userId} AND IsRead = 0
- AND IsDelete = 0
- AND SourceType IN ({noticeConstValue} ,{missiveConstValue}, {anonymityConstValue}))";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var noticeCount = await connection.ExecuteScalarAsync<int>(sql);
- // 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)";
- // var missiveCount = await connection.ExecuteScalarAsync<int>(sql);
- // //sql = $"SELECT count(1) FROM tede_admin_verify where AdminId={userId} and DisposeType=0";
- // // noticeCount += await connection.ExecuteScalarAsync<int>(sql);
- // result.noticeCount = noticeCount;
- result.noticeCount = noticeCount;
- return result;
- }
- /// <summary>
- /// 获取工作用户选择审核和抄送人
- /// </summary>
- /// <param name="userIds"></param>
- /// <param name="flowId"></param>
- /// <returns></returns>
- public async Task<List<Entity.User>> GeFlowUsers(List<int> userIds, int flowId, string type)
- {
- string strSql = "";
- if (userIds.Count > 0)
- {
- strSql = "and UserId not in(";
- foreach (var item in userIds)
- {
- strSql += $"{item},";
- }
- strSql = strSql.Remove(strSql.Length - 1, 1);
- strSql += ")";
- }
- 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})";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var result = await connection.QueryAsync<User>(sql);
- foreach (var item in result)
- item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
- return result.ToList();
- }
- public async Task<List<JobUserResult>> ElasticSearchUser()
- {
- var sql = "select * from tede_user where IsUpload=0 limit 0,100";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var items = await connection.QueryAsync<JobUserResult>(sql);
- return items.ToList();
- }
- public async Task<bool> UpdateAsync(SqlKata.Query query)
- {
- return await _repository.UpdateAsync(query) > 0;
- }
- //public async Task<UserDetail> GetUserDetailJoinAsync(int userId)
- //{
- // var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypestr, DatabaseType.MySql);
- // var database = new Database(databaseType, _connectionString);
- // var connection = database.GetConnection();
- // var result = connection.Query<UserDetail, Department, UserDetail>(
- // "SELECT a.*,b.Name FROM tede_user a inner join tede_department b on a.DepartmentId=b.Id where a.id=@Id;",
- // (userDetail,department) =>
- // {
- // userDetail.DepartmentName = department.Name;
- // return userDetail;
- // }, new {Id = userId}, splitOn: "Name");
- // return result.ToList()[0];
- //}
- /// <summary>
- /// vip用户
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<PagedList<UserDetail>> GetUserVipDetail(UserSearchVipRequest request)
- {
- var result = new PagedList<UserDetail>();
- var query = Q.NewQuery();
- query.Where(nameof(User.IsDelete), false);
- if (!string.IsNullOrEmpty(request.KeyWord))
- query.WhereLike(nameof(User.Name), $"%{request.KeyWord}%");
- if (request.VipPort > 0)
- query.Where(nameof(User.Port), request.VipPort);
- if (request.VipTypeId > 0)
- query.Where(nameof(User.TypeId), request.VipTypeId);
- if (request.IsDisable > 0)
- query.Where(nameof(User.IsDisable), request.IsDisable == 1);
- if (request.IsFreeze > 0)
- query.Where(nameof(User.IsFreeze), request.IsFreeze == 1);
- if (request.IsVip > 0)
- query.Where(nameof(User.IsVip), request.IsVip == 1);
- if (request.BeginAccumulativePrice > 0 || request.EndAccumulativePrice > 0)
- {
- query.Where(nameof(User.AccumulativePrice), ">=", request.BeginAccumulativePrice);
- query.Where(nameof(User.AccumulativePrice), "<=", request.EndAccumulativePrice);
- }
- if (request.RenewalCount > 0)
- query.Where(nameof(User.RenewalCount), request.RenewalCount);
- result.Total = await _repository.CountAsync(query);
- if (!string.IsNullOrEmpty(request.Sort) && request.Sort.Equals("AccumulativePrice"))
- query.OrderByDesc(nameof(User.AccumulativePrice));
- else
- query.OrderByDesc(nameof(User.CreatedDate));
- var items = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
- result.Items = items.Select(n => _mapper.Map<UserDetail>(n));
- return result;
- }
- /// <summary>
- /// 根据用户ID获取用户信息
- /// </summary>
- /// <param name="userIds"></param>
- /// <returns></returns>
- public async Task<IEnumerable<UserInfoResult>> GetUserInfoResultsAsync(IEnumerable<int> userIds, string keyWord = "")
- {
- userIds = userIds.Distinct();
- if (userIds.Count() == 0)
- return new List<UserInfoResult>();
- var sqlStr = "";
- foreach (var item in userIds)
- sqlStr += $"{item},";
- sqlStr = sqlStr.Remove(sqlStr.Length - 1, 1);
- var sql = $@"select * from tede_user where 1=1 and IsDelete=0 and id in({sqlStr})";
- if (!string.IsNullOrEmpty(keyWord))
- sql += $@" and (Name like '%{keyWord}%' or phone like '%{keyWord}%' or Email like '%{keyWord}%')";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var result = await connection.QueryAsync<UserInfoResult>(sql);
- foreach (var item in result)
- item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
- return result;
- }
- /// <summary>
- /// 获取不是好友的用户 排除部门
- /// </summary>
- /// <param name="keyword"></param>
- /// <param name="userIds"></param>
- /// <returns></returns>
- public async Task<IEnumerable<UserInfoResult>> GetUserInfoNoFriendsResults(string keyword, IEnumerable<int> userIds)
- {
- userIds = userIds.Distinct();
- var sqlStr = "";
- foreach (var item in userIds)
- sqlStr += $"{item},";
- sqlStr = !string.IsNullOrEmpty(sqlStr) ? sqlStr.Remove(sqlStr.Length - 1, 1) : "";
- var sql = $@"select * from tede_user where 1=1 and IsDelete=0 ";
- if (!string.IsNullOrEmpty(sqlStr))
- sql += $@" and id not in({sqlStr})";
- if (!string.IsNullOrEmpty(keyword))
- sql += $@" and (Name like '%{keyword}%' or phone like '%{keyword}%' or Email like '%{keyword}%')";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var result = await connection.QueryAsync<UserInfoResult>(sql);
- foreach (var item in result)
- item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
- return result;
- }
- /// <summary>
- /// 搜索好友部门用户
- /// </summary>
- /// <param name="keyword"></param>
- /// <param name="userIds"></param>
- /// <returns></returns>
- public async Task<IEnumerable<UserInfoResult>> GetSearchUserInfoResults(string keyword, IEnumerable<int> userIds)
- {
- userIds = userIds.Distinct();
- var sqlStr = "";
- foreach (var item in userIds)
- sqlStr += $"{item},";
- sqlStr = string.IsNullOrEmpty(sqlStr) ? "" : sqlStr.Remove(sqlStr.Length - 1, 1);
- var sql = $@"select * from tede_user where 1=1 and IsDelete=0 ";
- if (!string.IsNullOrEmpty(sqlStr))
- sql += $@" and id in({sqlStr})";
- if (!string.IsNullOrEmpty(keyword))
- sql += $@" and (Name like '%{keyword}%' or phone like '%{keyword}%' or Email like '%{keyword}%')";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var result = await connection.QueryAsync<UserInfoResult>(sql);
- foreach (var item in result)
- item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
- return result;
- }
- /// <summary>
- /// 获取用户工作我的审批未读数量
- /// </summary>
- /// <param name="userId"></param>
- /// <returns></returns>
- public async Task<int> GetUserUReadFlowTodoCountAsync(int userId)
- {
- var folderTypeConst = AllTypeConst.Inbox.GetHashCode();
- var myCheckedConst = AllTypeConst.MyChecked.GetHashCode();
- string sql = $@"SELECT
- count(1)
- FROM
- tede_flow_todo a
- INNER JOIN
- tede_notice b ON a.FlowId = b.SourceId
- INNER JOIN
- tede_middle c ON c.MiddleId = b.Id
- WHERE
- 1 = 1 AND b.TypeValue ={myCheckedConst} and c.FolderType={folderTypeConst}
- AND a.Type = 'ApproverCheck'
- and c.UserId={userId}
- AND a.IsDone = 0
- AND c.IsDelete = 0";
- var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
- var database = new Database(databaseType, _connectionString);
- var connection = database.GetConnection();
- var result = await connection.ExecuteScalarAsync<int>(sql);
- return result;
- }
- /// <summary>
- /// 获取小组用户
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<IEnumerable<GroupUserListResult>> GetGroupUserAsync(GroupUserFindRequest request)
- {
- return await GetGroupUsersAsync(request);
- }
- /// <summary>
- /// 获取小组用户
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- public async Task<IEnumerable<GroupUserListResult>> GetGroupUsersAsync(GroupUserFindRequest request)
- {
- // var enjoy = new SqlKata.Query("tede_user_middle");
- // enjoy.Where("MiddleType", 10);
- // enjoy.SelectRaw("GROUP_CONCAT(SourceName Separator'、')");
- // var userCount = new SqlKata.Query("tede_user");
- // userCount.Where("Id", ">", 0).AsCount("Id");
- // var userName = new SqlKata.Query("tede_user");
- // userName.WhereExists(n => n.From("tede_flow").Where("tede_flow.Id", 632).WhereColumns("tede_user.Id", "=", "tede_flow.UserId"));
- // userName.Select("Name");
- var query = new SqlKata.Query("tede_user");
- query.Join("tede_department as a", "a.Id", "tede_user.DepartmentId");
- query.Join("tede_group_user as b", "b.UserId", "tede_user.Id");
- query.Where("b.GroupId", request.GroupId);
- if (!string.IsNullOrEmpty(request.KeyWord))
- query.Where(n => n.OrWhereLike("tede_user.Name", $"%{request.KeyWord}").OrWhereLike("tede_user.Phone", $"%{request.KeyWord}").OrWhereLike("tede_user.Email", $"%{request.KeyWord}"));
- if (request.TypeId == 1)
- query.WhereIn("b.GroupUserRoleId", new List<int> { 1, 2 });
- if (request.TypeId == 2)
- query.Where("b.GroupUserRoleId", 3);
- query.Select(
- "b.{Id, GroupUserRoleId, CreatedDate,GroupId}",
- "tede_user.{Id AS UserId, Name, AvatarUrl,Email,ImId}",
- "a.{Name AS DepartmentName}");
- //query.Select(userCount, "UserCount");
- //query.Select(enjoy, "EnjoyName");
- //query.Select(userName,"UserName");
- var result = await _repository.GetAllAsync<GroupUserListResult>(query);
- foreach (var item in result)
- {
- item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
- item.Email = string.IsNullOrEmpty(item.Email) ? string.Empty : item.Email;
- }
- return result;
- }
- }
- }
|