You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

489 lines
18 KiB
C#

12 months ago
using DS.Module.Core;
using DS.Module.Core.Constants;
using DS.Module.Core.Data;
12 months ago
using DS.Module.Core.Extensions;
using DS.Module.Core.Helpers;
using DS.Module.SqlSugar;
12 months ago
using DS.Module.UserModule;
using DS.WMS.Core.Code.Dtos;
using DS.WMS.Core.Code.Entity;
using DS.WMS.Core.Sys.Dtos;
using DS.WMS.Core.Sys.Entity;
using DS.WMS.Core.Sys.Interface;
using DS.WMS.Core.TaskPlat.Dtos;
using Microsoft.AspNetCore.Http;
12 months ago
using Microsoft.Extensions.DependencyInjection;
using MiniExcelLibs;
using Org.BouncyCastle.Ocsp;
12 months ago
using SqlSugar;
using System.Data;
12 months ago
namespace DS.WMS.Core.Sys.Method;
12 months ago
/// <summary>
///
/// </summary>
public class UserService : IUserService
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
12 months ago
private readonly ICommonService _commonService;
12 months ago
/// <summary>
///
/// </summary>
/// <param name="serviceProvider"></param>
public UserService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
12 months ago
_commonService = _serviceProvider.GetRequiredService<ICommonService>();
12 months ago
}
/// <summary>
/// 列表查询
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public DataResult<List<UserViewModel>> GetListByPage(PageRequest request)
12 months ago
{
11 months ago
var query = _commonService.GetDataRuleFilter<SysUser>();
// var number =_commonService.GetSequenceNext<SysUser>();
12 months ago
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
12 months ago
var data = query
12 months ago
.Where(x => x.UserCode != "admin")
.Where(whereList).Select<UserViewModel>()
.ToQueryPage(request.PageCondition);
return data;
}
/// <summary>
/// 获取单个用户信息
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public DataResult<UserViewModel> GetUserInfo(string id)
{
11 months ago
var roleIds = db.Queryable<SysRoleUser>().Where(x => x.UserId == long.Parse(id)).Select(x => x.RoleId).ToArray();
11 months ago
var orgIds = db.Queryable<SysOrgUser>().Where(x => x.UserId == long.Parse(id)).Select(x => x.OrgId).ToArray();
4 months ago
var laneIds = db.Queryable<SysUserLane>().Where(x => x.UserId == long.Parse(id)).Select(x => x.LaneId).ToArray();
11 months ago
var data = db.Queryable<SysUser>()
12 months ago
.Where(x => x.Id == long.Parse(id))
12 months ago
.Select<UserViewModel>()
11 months ago
.Mapper(it =>
{
it.RoleIds = roleIds;
it.OrgIds = orgIds;
4 months ago
it.LaneIds = laneIds;
11 months ago
})
12 months ago
.First();
return DataResult<UserViewModel>.Success(data,MultiLanguageConst.DataQuerySuccess);
12 months ago
}
public async Task<DataResult> CheckUserCode(string code)
{
var isExist = await db.Queryable<SysUser>().Filter(null, true).Where(x => x.UserCode == code.Trim()).FirstAsync();
if (isExist != null)
{
return await Task.FromResult(DataResult.Failed("用户唯一编码已存在!", MultiLanguageConst.UserCodeExist));
}
return await Task.FromResult(DataResult.Successed("用户唯一编码检测成功!", MultiLanguageConst.DataQuerySuccess));
}
12 months ago
/// <summary>
/// 编辑用户信息
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
11 months ago
public DataResult EditUser(UserReq model)
12 months ago
{
11 months ago
if (model.Id == 0)
12 months ago
{
var isExist = db.Queryable<SysUser>().Filter(null,true).Where(x => x.UserCode == model.UserCode).First();
12 months ago
if (isExist != null)
{
return DataResult.Failed("用户唯一编码已存在!",MultiLanguageConst.UserCodeExist);
12 months ago
}
#region 用户数量检测
var tenant = db.Queryable<SysTenant>().Where(x=>x.Id ==long.Parse(user.TenantId)).First();
var userAuth = db.Queryable<SysTenantUserAuth>().First();
if (userAuth.IsNotNull())
{
var authNum = EncrypteHelper.DecryptData(userAuth.AuthNum, tenant.AppSecret);
var userCount = db.Queryable<SysUser>().Where(x=>x.IsUseSystem == true).Count();
if (userCount>= int.Parse(authNum))
{
return DataResult.Failed(string.Format("用户数量超出授权数量{0}", int.Parse(authNum)),MultiLanguageConst.UserAuthNumLimit);
}
}
#endregion
11 months ago
var data = model.MapTo<UserReq, SysUser>();
data.PinYinCode = data.UserName + "(" + PinYinUtil.GetFristLetter(data.UserName) + ")";
11 months ago
data.MD5Password = MD5Helper.MD5Encrypt(data.Password);
var entity = db.Insertable(data).RemoveDataCache($"{SqlSugarCacheConst.User}{user.TenantId}").ExecuteReturnEntity();
12 months ago
if (model.RoleIds.IsNotNull() && model.RoleIds.Count() > 0)
12 months ago
{
foreach (var item in model.RoleIds)
{
11 months ago
var roleUser = new SysRoleUser
12 months ago
{
11 months ago
RoleId = item,
UserId = entity.Id,
12 months ago
};
db.Insertable(roleUser).ExecuteCommand();
}
}
11 months ago
if (model.OrgIds.IsNotNull() && model.OrgIds.Count() > 0)
11 months ago
{
foreach (var item in model.OrgIds)
{
var orgUser = new SysOrgUser
{
OrgId = item,
UserId = entity.Id,
};
db.Insertable(orgUser).ExecuteCommand();
}
}
if (model.LaneIds.IsNotNull() && model.LaneIds.Count() > 0)
{
foreach (var item in model.LaneIds)
{
var laneUser = new SysUserLane
{
LaneId = item,
UserId = entity.Id,
};
db.Insertable(laneUser).ExecuteCommand();
}
}
return DataResult.Successed("添加成功!", entity.Id,MultiLanguageConst.DataCreateSuccess);
12 months ago
}
else
{
11 months ago
var userId = model.Id;
var info = db.Queryable<SysUser>().Where(x => x.Id == userId).First();
12 months ago
11 months ago
info = model.MapTo<UserReq, SysUser>();
info.PinYinCode = info.UserName + "(" + PinYinUtil.GetFristLetter(info.UserName) + ")";
12 months ago
db.Updateable(info).RemoveDataCache($"{SqlSugarCacheConst.User}{user.TenantId}").IgnoreColumns(it => new { it.TenantId,it.TenantName, it.Password,it.MD5Password }).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
12 months ago
#region 处理用户角色
11 months ago
var existRoles = db.Queryable<SysRoleUser>().Where(x => x.UserId == userId).Select(n => n.RoleId)
12 months ago
.ToArray();
11 months ago
11 months ago
IEnumerable<long?> delRoles = existRoles.AsQueryable().Except(model.RoleIds);
12 months ago
if (delRoles.Count() > 0)
{
11 months ago
db.Deleteable<SysRoleUser>()
.Where(it => it.UserId == userId && delRoles.Contains(it.RoleId))
12 months ago
.ExecuteCommand();
}
11 months ago
11 months ago
IEnumerable<long?> addRoles = model.RoleIds.AsQueryable().Except(existRoles);
if (addRoles.Count() > 0)
{
foreach (var item in addRoles)
{
var roleUser = new SysRoleUser
{
RoleId = item,
UserId = model.Id,
};
db.Insertable(roleUser).ExecuteCommand();
}
}
12 months ago
#endregion 处理用户角色
11 months ago
#region 处理用户机构
var existOrgs = db.Queryable<SysOrgUser>().Where(x => x.UserId == userId).Select(n => n.OrgId)
.ToArray();
IEnumerable<long?> delOrgs = existOrgs.AsQueryable().Except(model.OrgIds);
if (delOrgs.Count() > 0)
{
db.Deleteable<SysOrgUser>()
.Where(it => it.UserId == userId && delOrgs.Contains(it.OrgId))
.ExecuteCommand();
}
IEnumerable<long?> addOrgs = model.OrgIds.AsQueryable().Except(existOrgs);
if (addOrgs.Count() > 0)
{
foreach (var item in addOrgs)
{
var orgUser = new SysOrgUser
{
OrgId = item,
UserId = model.Id,
};
db.Insertable(orgUser).ExecuteCommand();
}
}
#endregion 处理用户机构
12 months ago
#region 处理用户航线
var existLanes = db.Queryable<SysUserLane>().Where(x => x.UserId == userId).Select(n => n.LaneId)
.ToArray();
IEnumerable<long?> delLanes = existLanes.AsQueryable().Except(model.LaneIds);
if (delLanes.Count() > 0)
{
db.Deleteable<SysUserLane>()
.Where(it => it.UserId == userId && delLanes.Contains(it.LaneId))
.ExecuteCommand();
}
4 months ago
IEnumerable<long?> addLanes = model.LaneIds.AsQueryable().Except(existLanes);
if (addLanes.Count() > 0)
{
foreach (var item in addLanes)
{
var laneUser = new SysUserLane
{
LaneId = item,
UserId = model.Id,
};
db.Insertable(laneUser).ExecuteCommand();
}
}
#endregion 处理用户航线
return DataResult.Successed("更新成功!",MultiLanguageConst.DataUpdateSuccess);
12 months ago
}
}
/// <summary>
/// 删除用户
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult> BatchDelUser(IdModel req)
{
if (req.Ids.Contains(long.Parse(user.UserId)))
{
return await Task.FromResult(DataResult.Failed("不能删除本人账号!"));
}
var list = await db.Queryable<SysUser>().Where(x => req.Ids.Contains(x.Id)).ToListAsync();
if (list.Count > 0)
{
foreach (var item in list)
{
var roleUsers = await db.Queryable<SysRoleUser>().Where(x => x.UserId == item.Id).ToListAsync();
if (roleUsers.Count > 0)
await db.Deleteable(roleUsers).ExecuteCommandAsync();
var orgUsers = await db.Queryable<SysOrgUser>().Where(x => x.UserId == item.Id).ToListAsync();
if (orgUsers.Count > 0)
await db.Deleteable(orgUsers).ExecuteCommandAsync();
var userLanes = await db.Queryable<SysUserLane>().Where(x => x.UserId == item.Id).ToListAsync();
if (userLanes.Count > 0)
await db.Deleteable(userLanes).ExecuteCommandAsync();
}
await db.Deleteable(list).RemoveDataCache($"{SqlSugarCacheConst.User}{user.TenantId}").ExecuteCommandAsync();
}
return await Task.FromResult(DataResult.Successed("删除成功!", MultiLanguageConst.DataDelSuccess));
}
/// <summary>
/// 查询客户端 用户拥有的菜单权限
/// </summary>
/// <returns></returns>
public async Task<DataResult<List<RouteItem>>> GetClientUserPermissions()
{
List<RouteItem> list = new List<RouteItem>();
var userId = long.Parse(user.UserId);
var userInfo = await db.Queryable<SysUser>().Where(x => x.Id == userId).FirstAsync();
var roleIds = await db.Queryable<SysRoleUser>().Where(x => x.UserId == userId).Select(x => x.RoleId).ToListAsync();
if (roleIds.Count == 0)
{
return await Task.FromResult(DataResult<List<RouteItem>>.Failed("该用户未绑定角色!"));
}
var permissions = await db.Queryable<SysRolePermission>().Where(x => roleIds.Contains(x.RoleId))
.Select(x => x.PermissionId).Distinct().ToListAsync();
var perlist = await db.Queryable<SysPermissionTenant>()
.Where(x => x.MenuType == 1 && x.IsHidden == false && permissions.Contains(x.PermissionId) &&
(x.PermissionType == 1 || x.PermissionType == 0))
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.PermissionId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
Redirect = a.Redirect,
SortCode = a.SortCode,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
})
.ToListAsync();
list.AddRange(perlist);
//去重
list.Distinct();
//排序
list = list.OrderBy(x => x.SortCode).ToList();
foreach (var item in list)
{
var childs = await db.Queryable<SysPermissionTenant>().Where(x =>
(x.MenuType == 1 || x.MenuType == 2) && x.ParentId == item.ParentId && x.IsHidden == false &&
permissions.Contains(x.PermissionId) &&
(x.PermissionType == 1 || x.PermissionType == 0) &&
x.PermissionId != 1744968217220222976) //排除企业用户维护
.OrderBy(x => x.SortCode)
.Select(a => new RouteItem
{
Id = a.Id,
ParentId = a.PermissionId,
Path = a.Url,
Name = a.PermissionName,
EnName = a.PermissionEnName,
Component = a.Component,
IsCache = a.IsCache,
Meta = new RouteMeta()
{
Title = a.Title,
Icon = a.Icon,
}
}).ToListAsync();
//去重
childs.Distinct();
//排序
childs = childs.OrderBy(x => x.SortCode).ToList();
item.Children = childs;
}
// list = list.OrderBy(x => x.Id).ToList();
return await Task.FromResult(DataResult<List<RouteItem>>.Success("获取数据成功!", list));
}
/// <summary>
/// 根据权限模块获取数据范围列表
/// </summary>
/// <param name="permissionId"></param>
/// <returns></returns>
public async Task<DataResult<List<DataRuleRes>>> GetDataRuleListByPermission(string permissionId)
{
var data = await db.Queryable<SysDataRule>()
.Where(x => x.PermissionId == long.Parse(permissionId) && x.Status == StatusEnum.Enable)
.Select<DataRuleRes>()
.ToListAsync();
return await Task.FromResult(DataResult<List<DataRuleRes>>.Success(data, MultiLanguageConst.DataQuerySuccess));
}
/// <summary>
/// 按Excel导入用户信息
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public async Task<DataResult<string>> ImportUserByExcel(IFormFile file)
{
//未上传文件
if (file == null || file.Length == 0)
{
return await Task.FromResult(DataResult<string>.Failed("请上传Excel!"));
}
var formFile = file;
//DataResult<string> api_Result = new Api_Result<string>();
//获取文件名
var fileName = formFile.FileName;
// 获取文件后缀
var fileExtension = Path.GetExtension(fileName);
// 判断后缀是否是xlsx或者xls
if (fileExtension != ".xlsx" && fileExtension != ".xls")
{
return DataResult<string>.Failed("文件格式错误");
}
var length = formFile.Length;
if (length > 1024 * 1024 * 10)
{
return DataResult<string>.Failed("文件大小不能超过10M");
}
// MemoryStream 内存流 在内存当中创建一个流(开辟空间)
using (var stream = new MemoryStream())
{
//将文件写入内存流
formFile.CopyTo(stream);
//将流的位置归零
stream.Position = 0;
//将内存流转成List集合
var list = await stream.QueryAsync<UserExcelImportReq>();
var users = new List<SysUser>();
foreach (var item in list)
{
var sysUser = new SysUser()
{
UserCode = item.UserCode,
UserName = item.UserName,
PinYinCode = item.UserName + "("+ PinYinUtil.GetFristLetter(item.UserName)+")",
4 months ago
UserNumber = item.UserNumber,
Password = "123456ABC",
MD5Password = MD5Helper.MD5Encrypt("123456ABC"),
UserEnName = item.UserEnName,
Sex = item.Sex == "女"? 2:1,
Duty = item.Duty,
OfficePhone = item.OfficePhone,
Email = item.Email,
Phone = item.Phone,
IsOperator = item.IsOperator == 1? true : false,
IsVouchingClerk = item.IsVouchingClerk == 1 ? true : false,
IsSale = item.IsSale == 1 ? true : false,
IsCustom = item.IsCustom == 1 ? true : false,
IsFinancialStaff = item.IsFinancialStaff == 1 ? true : false,
IsCustomerService = item.IsCustomerService == 1 ? true : false,
IsDriver = item.IsDriver == 1 ? true : false,
IsDispatcher = item.IsDispatcher == 1 ? true : false,
UserType = 2
};
users.Add(sysUser);
}
await db.Insertable(users).ExecuteCommandAsync();
return await Task.FromResult(DataResult<string>.Failed("导入成功!", MultiLanguageConst.DataImportSuccess));
}
}
12 months ago
}