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 _repository; private readonly Repository _departmentRepository; private readonly Repository _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 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(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql); //_connectionString = dbOptionsAccessor.CurrentValue.ConnectionString; var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString); _repository = new Repository(database); _environment = environment; _departmentRepository = new Repository(database); _roleRepository = new Repository(database); _mapper = mapper; _cache = cache; this.departmentUserRepository = departmentUserRepository; } public IDatabase Database => _repository.Database; public string TableName => _repository.TableName; public List TableColumns => _repository.TableColumns; /// /// 根据id集合查询用户 /// /// /// public async Task> UserListInsAsync(List ids) { return await _repository.GetAllAsync(Q.WhereIn(nameof(User.Id), ids).Where(nameof(User.IsDelete), false)); } /// /// 根据姓名查询用户 /// /// /// public async Task> 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(n)); } public async Task 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(user); // if (user.DepartmentId > 0) // { // var department = await _departmentRepository.GetAsync(user.DepartmentId); // userDetail.DepartmentName = department.Name; // } return userDetail; } public async Task 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 GetAsync(int id) { var user = await _repository.GetAsync(Q.Where(nameof(User.Id), id).Where(nameof(User.IsDelete), false)); return user; } public async Task GetUserInfoAsync(int id) { var user = await _repository.GetAsync(Q.Where(nameof(User.Id), id).Where(nameof(User.IsDelete), false)); return user; } public async Task GetAsync(SqlKata.Query query) { var user = await _repository.GetAsync(query.Where(nameof(User.IsDelete), false)); return user; } public async Task GetNameAsync(int id) { if (id <= 0) return string.Empty; return await _repository.GetAsync(Q .Select(nameof(User.Name)) .Where(nameof(User.Id), id).Where(nameof(User.IsDelete), false) ); } public async Task GetAvatarUrlAsync(int id) { if (id <= 0) return string.Empty; var avatarUrl = await _repository.GetAsync(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 GetByPhoneAsync(string phone) { return await _repository.GetAsync(Q.Where(nameof(User.Phone), phone).Where(nameof(User.IsDelete), false)); } /// /// openId微信认证 /// /// /// /// public async Task GetByOpenIdAsync(string openId) { return await _repository.GetAsync(Q.Where(nameof(User.OpenId), openId).Where(nameof(User.IsDelete), false)); } /// /// 绑定微信 /// /// /// public async Task 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 DeleteUsersAsync(IEnumerable userIds) { return await _repository.UpdateAsync(Q.WhereIn(nameof(User.Id), userIds).Set(nameof(User.IsDelete), true)) > 0; } public async Task ChangeRoleAsync(IEnumerable userIds, int roleId) { return await _repository.UpdateAsync(Q .Set(nameof(User.RoleId), roleId) .WhereIn(nameof(User.Id), userIds) ) > 0; } public async Task ChangeDepartmentAsync(IEnumerable userIds, int departmentId) { return await _repository.UpdateAsync(Q .Set(nameof(User.DepartmentId), departmentId) .WhereIn(nameof(User.Id), userIds) ) > 0; } public async Task UpdateAsync(User user) { return await _repository.UpdateAsync(user); } public async Task UpdateDisableAsync(UserUpdateDisableRequest request) { return await _repository.UpdateAsync(Q.WhereIn(nameof(User.Id), request.Ids).Set(nameof(User.IsDisable), request.IsDisable)) > 0; } public async Task 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)); } /// /// Set the limit and offset for a given page. /// /// /// /// /// /// /// public async Task> 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> 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)); } /// /// 登录 /// /// /// public async Task 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(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 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; } /// /// 删除用户 /// /// /// public async Task DeleteAsync(int id) { var user = await GetAsync(id); if (user == null) throw new BusinessException("该用户不存在"); return await DeleteAsync(id); } /// /// 删除用户 /// /// /// public async Task DeleteAsync(List ids) { return await _repository.UpdateAsync(Q.WhereIn(nameof(User.Id), ids).Set(nameof(User.IsDelete), true)) > 0; } /// /// 更新用户信息 /// /// /// /// public async Task 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); } /// /// 用户分页列表 /// /// /// public async Task> GetPagedListAsync(UserPageSearchRequest request) { var pagedList = new PagedList { 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(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> GetListAsync(ArticleSearchRequest request) { var list = await GetListAsync(request.DepartmentId, request.RoleId, request.Keyword); var allList = new List(); foreach (var user in list) { var result = _mapper.Map(user); allList.Add(result); } return allList; } /// /// 更新excel用户数据 /// /// /// public async Task UpdateUserExcelAsync(List 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; } /// /// 私信 /// /// /// public async Task 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); } /// /// 通知 /// /// /// public async Task 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); } /// /// 回复 /// /// /// public async Task 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); } /// /// 静音 /// /// /// public async Task 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); } /// /// 震动 /// /// /// public async Task 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); } /// /// 用户修改密码 /// /// /// public async Task 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); } /// /// 用户邮箱验证 /// /// /// public async Task 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; } /// /// 用户修改密码 /// /// /// public async Task 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); } /// /// 根据部门ID获取用户 /// /// /// public async Task> GetUserByDepartmentIdAsync(int departmentId) { var userIds = await departmentUserRepository.GetUserIdsByDepartmentIdsAsync(new List() { departmentId }); return await _repository.GetAllAsync(Q.WhereIn(nameof(User.Id), userIds).Where(nameof(User.IsDelete), false)); } public async Task> GetUserIdListByDepartmentIdAsync(int departmentId) { return await _repository.GetAllAsync(Q .Select(nameof(User.Id)) .Where(nameof(User.DepartmentId), departmentId) ); } public async Task> GetUserIdListByRoleIdAsync(int roleId) { return await _repository.GetAllAsync(Q .Select(nameof(User.Id)) .Where(nameof(User.RoleId), roleId).Where(nameof(User.IsDelete), false) ); } /// /// 创建环信用户 /// /// /// public async Task 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; } /// /// 用户模糊查询 /// /// /// public async Task> SearchUserNameAsync(SearchUserNameRequest request) { var departments = new List(); 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(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var result = await connection.QueryAsync(sql); foreach (var item in result) { item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl); //获取上级 departments = new List(); 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> GetUpDepartmentAsync(int id, List departments) { var sql = $"select * from tede_department where Id={id}"; var databaseType = StringUtils.ToEnum(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var result = await connection.QueryFirstOrDefaultAsync(sql); if (result == null) return departments; departments.Add(result); await GetUpDepartmentAsync(result.ParentId, departments); return departments; } public async Task> GetDepartmentAsync(int pid, List departments) { var sql = $"select * from tede_department where ParentId={pid}"; var databaseType = StringUtils.ToEnum(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var result = await connection.QueryAsync(sql); if (result.Count() == 0) return departments; departments.AddRange(result); foreach (var item in result) await GetDepartmentAsync(item.Id, departments); return departments; } /// /// 查询所有用户 /// /// public async Task> FindAllUserAsync(SqlKata.Query query) { return await _repository.GetAllAsync(query.Where(nameof(User.IsDelete), false)); } /// /// 根据Guid获取用户数据 /// /// /// public async Task 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(user); } public async Task CountAsync(Query query) { return await _repository.CountAsync(query.Where(nameof(User.IsDelete), false)); } public async Task> GetAllAsync(Query query) { return await _repository.GetAllAsync(query.Where(nameof(User.IsDelete), false)); } public async Task> GetAllIntsAsync(Query query) { return await _repository.GetAllAsync(query.Where(nameof(User.IsDelete), false)); } public Task> FindAllUserAsync() { throw new NotImplementedException(); } /// /// 获取用户未读数据 /// /// /// public async Task 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(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var noticeCount = await connection.ExecuteScalarAsync(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(sql); // //sql = $"SELECT count(1) FROM tede_admin_verify where AdminId={userId} and DisposeType=0"; // // noticeCount += await connection.ExecuteScalarAsync(sql); // result.noticeCount = noticeCount; result.noticeCount = noticeCount; return result; } /// /// 获取工作用户选择审核和抄送人 /// /// /// /// public async Task> GeFlowUsers(List 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(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var result = await connection.QueryAsync(sql); foreach (var item in result) item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl); return result.ToList(); } public async Task> ElasticSearchUser() { var sql = "select * from tede_user where IsUpload=0 limit 0,100"; var databaseType = StringUtils.ToEnum(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var items = await connection.QueryAsync(sql); return items.ToList(); } public async Task UpdateAsync(SqlKata.Query query) { return await _repository.UpdateAsync(query) > 0; } //public async Task GetUserDetailJoinAsync(int userId) //{ // var databaseType = StringUtils.ToEnum(_databaseTypestr, DatabaseType.MySql); // var database = new Database(databaseType, _connectionString); // var connection = database.GetConnection(); // var result = connection.Query( // "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]; //} /// /// vip用户 /// /// /// public async Task> GetUserVipDetail(UserSearchVipRequest request) { var result = new PagedList(); 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(n)); return result; } /// /// 根据用户ID获取用户信息 /// /// /// public async Task> GetUserInfoResultsAsync(IEnumerable userIds, string keyWord = "") { userIds = userIds.Distinct(); if (userIds.Count() == 0) return new List(); 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(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var result = await connection.QueryAsync(sql); foreach (var item in result) item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl); return result; } /// /// 获取不是好友的用户 排除部门 /// /// /// /// public async Task> GetUserInfoNoFriendsResults(string keyword, IEnumerable 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(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var result = await connection.QueryAsync(sql); foreach (var item in result) item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl); return result; } /// /// 搜索好友部门用户 /// /// /// /// public async Task> GetSearchUserInfoResults(string keyword, IEnumerable 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(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var result = await connection.QueryAsync(sql); foreach (var item in result) item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl); return result; } /// /// 获取用户工作我的审批未读数量 /// /// /// public async Task 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(_databaseTypeStr, DatabaseType.MySql); var database = new Database(databaseType, _connectionString); var connection = database.GetConnection(); var result = await connection.ExecuteScalarAsync(sql); return result; } /// /// 获取小组用户 /// /// /// public async Task> GetGroupUserAsync(GroupUserFindRequest request) { return await GetGroupUsersAsync(request); } /// /// 获取小组用户 /// /// /// public async Task> 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 { 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(query); foreach (var item in result) { item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl); item.Email = string.IsNullOrEmpty(item.Email) ? string.Empty : item.Email; } return result; } } }