using DS.Module.Core;
using DS.Module.Core.Data;
using DS.Module.Core.Extensions;
using DS.Module.Core.Helpers;
using DS.Module.SqlSugar;
using DS.Module.UserModule;
using DS.WMS.Core.Code.Entity;
using DS.WMS.Core.Invoice.Dtos;
using DS.WMS.Core.Sys.Dtos;
using DS.WMS.Core.Sys.Entity;
using DS.WMS.Core.Sys.Interface;
using Mapster;
using Masuit.Tools.Systems;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SqlSugar.IOC;
using SysTenantLink = DS.Module.SqlSugar.SysTenantLink;
namespace DS.WMS.Core.Sys.Method;
public class TenantApplyService : ITenantApplyService
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
private readonly ISaasDbService saasService;
///
///
///
///
public TenantApplyService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService();
saasService = _serviceProvider.GetRequiredService();
user = _serviceProvider.GetRequiredService();
}
#region 企业用户审批
///
/// 企业注册用户列表
///
///
///
public DataResult> GetListByPage(PageRequest request)
{
// var query = _commonService.GetDataRuleFilter();
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var data = db.Queryable().ClearFilter()
.Select()
.Where(x => x.AuditStatus != AuditStatusEnum.NoAudit)
.Where(whereList).ToQueryPage(request.PageCondition);
return data;
}
///
/// 获取注册企业审批信息
///
///
public DataResult GetTenantAuditInfo(string id)
{
var data = db.Queryable()
.Where(a => a.Id == long.Parse(id))
.Select()
.First();
return DataResult.Success(data);
}
///
/// 企业用户审批 - 驳回
///
///
///
public DataResult RejectTenantApply(CommonAuditInput req)
{
var userId = user.UserId;
var apply = db.Queryable().Where(x => x.Id == req.Id).First();
if (apply.IsNull())
{
return DataResult.Failed("企业用户信息不存在!");
}
if (apply.AuditStatus == AuditStatusEnum.Approve)
{
return DataResult.Failed("已审批通过!");
}
if (req.Status == 1)
{
return DataResult.Failed("非法状态!");
}
else
{
apply.AuditStatus = (AuditStatusEnum)(int)req.Status;
apply.AuditNote = req.AuditNote;
db.Updateable(req).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
return DataResult.Successed("驳回成功!");
}
}
///
/// 企业用户审批 - 通过
///
///
///
public async Task TenantApplyAudit(TenantApplyAuditReq req)
{
var dbScope = (SqlSugarScope)db;
var masterDb = saasService.GetMasterDb();
var apply = await masterDb.Queryable().Where(x => x.Id == req.AuditInfo.Id).FirstAsync();
if (apply.IsNull())
{
return await Task.FromResult(DataResult.Failed("企业用户信息不存在!"));
}
if (apply.AuditStatus == AuditStatusEnum.Approve)
{
return await Task.FromResult(DataResult.Failed("已审批通过!"));
}
if (req.PermissionIds.Count == 0)
{
return await Task.FromResult(DataResult.Failed("请勾选权限模块!"));
}
if (req.AuditInfo.Status == 1)
{
try
{
//开启事务
await dbScope.Ado.BeginTranAsync();
#region 租户相关
//初始化新租户
var entity = apply.Adapt();
entity.PinYinCode = PinYinUtil.GetFristLetter(entity.Name);
var secret = MD5Helper.Encrypt(DateTime.Now.Ticks.ToString(), false, true);
entity.AppSecret = secret;
var tenant = await masterDb.Insertable(entity).ExecuteReturnEntityAsync();
//初始化租户数据库链接
var link = req.DbInfo.Adapt();
link.TenantId = tenant.Id;
await masterDb.Insertable(link).ExecuteReturnEntityAsync();
//初始化租户权限模块
var permissions = await masterDb.Queryable().Where(x => req.PermissionIds.Contains(x.Id)).ToListAsync();
var tenantPerList = new List();
foreach (var item in permissions)
{
var tenantPer = item.Adapt();
tenantPer.Id = 0;
tenantPer.TenantId = tenant.Id;
tenantPer.PermissionId = item.Id;
tenantPerList.Add(tenantPer);
}
await masterDb.Insertable(tenantPerList).ExecuteCommandAsync();
//初始化租户合同
var contract = new SysTenantContract()
{
ContractName = "新签约租户",
BeginDate = apply.ContractBeginDate,
EndDate = apply.ContractEndDate,
TenantId = tenant.Id,
AuditStatus = AuditStatusEnum.Approve,
};
await masterDb.Insertable(contract).ExecuteCommandAsync();
#region 加密授权信息
//租户用户授权数
var userAuth = new SysTenantUserAuth()
{
TenantId = tenant.Id,
AuthNum = EncrypteHelper.EncryptData(req.AuthUserNum.ToString(), secret)
};
await masterDb.Insertable(userAuth).ExecuteCommandAsync();
//租户模块授权数
#endregion
var perAuthList = new List();
foreach (var item in req.PermissionAuthList)
{
var perAuth = new SysTenantPermissionAuth()
{
TenantId = tenant.Id,
PermissionId = item.PermissionId,
AuthNum = EncrypteHelper.EncryptData(item.AuthNum.ToString(), secret)
};
perAuthList.Add(perAuth);
}
await masterDb.Insertable(perAuthList).ExecuteCommandAsync();
#endregion
#region 租户用户相关数据
var adminUser =await masterDb.Queryable().Where(x=>x.UserCode == apply.AdminUserCode && x.UserType == UserTypeEnum.ApplyUser.ToEnumInt()).FirstAsync();
//删除租户申请
var delUserRoles = await masterDb.Queryable().Where(x => x.UserId == adminUser.Id).ToListAsync();
await masterDb.Deleteable(delUserRoles).ExecuteCommandAsync();
//初始化租户角色
var roleEntity = new SysRole()
{
RoleCode = "tenantAdmin",
RoleName = "租户管理员",
TenantId = tenant.Id
};
var role = await masterDb.Insertable(roleEntity).ExecuteReturnEntityAsync();
//初始化租户用户角色关系
var roleUserEntity = new SysRoleUser()
{
UserId = adminUser.Id,
RoleId = role.Id,
// TenantId = tenant.Id
};
await masterDb.Insertable(roleUserEntity).ExecuteCommandAsync();
//写入租户管理员权限
var rolePerList = new List();
foreach (var item in permissions)
{
var rolePer = item.Adapt();
rolePer.RoleId = role.Id;
rolePer.PermissionId = item.Id;
rolePer.IsPermission = 1;
rolePerList.Add(rolePer);
}
await masterDb.Insertable(rolePerList).ExecuteCommandAsync();
//初始化租户机构信息
var orgEntity = new SysOrg()
{
OrgName = apply.Name,
ParentId = 0,
Leader = apply.Chief,
Tel = apply.Tel,
OrderNo = 1,
IsDepartment = false,
TenantId = tenant.Id,
Status = StatusEnum.Enable
};
var org = await masterDb.Insertable(orgEntity).ExecuteReturnEntityAsync();
//初始化租户用户机构
var orgUserEntity = new SysOrgUser()
{
UserId = adminUser.Id,
OrgId = org.Id,
};
await masterDb.Insertable(orgUserEntity).ExecuteCommandAsync();
//更新租户管理员信息 机构Id
adminUser.UserType = UserTypeEnum.Admin.ToEnumInt();
adminUser.TenantId = tenant.Id;
adminUser.TenantName = tenant.Name;
adminUser.DefaultOrgId = org.Id;
await masterDb.Updateable(adminUser).ExecuteCommandAsync();
#endregion
//#region 创建租户数据库及基础数初始化
//if (!dbScope.IsAnyConnection(tenant.Id))
//{
// dbScope.AddConnection(new ConnectionConfig() {
// ConfigId = tenant.Id,
// ConnectionString = link.Connection,
// DbType = link.DbType,
// IsAutoCloseConnection = true });
//}
//var tenantDb = saasService.GetBizDbScopeById(tenant.Id);
//StaticConfig.CodeFirst_MySqlCollate="utf8mb4_0900_ai_ci";//较高版本支持
////初始化数库
//tenantDb.DbMaintenance.CreateDatabase();
////tenantDb.CodeFirst.InitTables(typeof(CodeCountry));
//#endregion
//更新租户申请
apply.AuditStatus = (AuditStatusEnum)(int)req.AuditInfo.Status;
apply.AuditTime = DateTime.Now;
apply.AuditNote = req.AuditInfo.AuditNote;
await masterDb.Updateable(apply).IgnoreColumns(ignoreAllNullColumns: true).EnableDiffLogEvent().ExecuteCommandAsync();
await dbScope.Ado.CommitTranAsync();
return await Task.FromResult(DataResult.Successed("审批成功!"));
}
catch (Exception ex)
{
await dbScope.Ado.RollbackTranAsync();
await ex.LogAsync(db);
return await Task.FromResult(DataResult.Failed("审批失败!" + ",请联系管理员!"));
}
}
else
{
return await Task.FromResult(DataResult.Failed("非法状态!"));
}
}
#endregion
#region 企业用户维护信息
///
/// 获取注册企业申请信息
///
///
public DataResult GetTenantApplyInfo()
{
var userInfo = db.Queryable().First(x => x.Id == long.Parse(user.UserId));
var data = db.Queryable()
.Where(a => a.AdminUserCode == userInfo.UserCode)
.Select()
.First();
return DataResult.Success(data);
}
///
/// 维护企业用户信息
///
///
///
public DataResult EditTenantApplyInfo(TenantApplyReq req)
{
var existApply = db.Queryable().First(x => x.Id == req.Id);
if (existApply.AuditStatus == AuditStatusEnum.Approve || existApply.AuditStatus == AuditStatusEnum.Auditing)
{
return DataResult.Failed("审核通过或待审批状态不能提交!");
}
try
{
//开启事务
db.Ado.BeginTran();
var apply = req.Adapt();
db.Updateable(apply).IgnoreColumns(x =>
new
{
x.AdminUserPassword, x.AuditStatus, x.AuditNote
}).ExecuteCommand();
//TO DO 处理附件
// var gid = model.GID; //写入
// #region 处理文件
//
// #region 处理法人身份证
// //先删除 法人身份证
// var existCards = db.Queryable().Where(x => x.PID == gid && x.FILETYPE == "法人身份证").Select(n=>n.IMGPATH).ToArray();
// var cardFiles = model.cardfiles.Select(x => x.FilePath).ToArray();
// IEnumerable delCards = existCards.AsQueryable().Except(cardFiles);
// if (delCards.Count()>0)
// {
// foreach (var item in delCards)
// {
// var existInfo = db.Queryable()
// .Where(x => x.PID == gid && x.IMGPATH == item).First();
// db.Deleteable(existInfo).ExecuteCommand();
// }
// }
// //2.添加新的法人身份证
// IEnumerable addCards = cardFiles.AsQueryable().Except(existCards);
// if (addCards.Count()>0)
// {
// foreach (var item in addCards)
// {
// var infoFile = new INFO_FILES
// {
// GID = Guid.NewGuid(),
// PID = gid,
// FILENAME = model.cardfiles.Where(x=>x.FilePath ==item).Select(x=>x.FileName).First(),
// IMGPATH = item,
// FILETYPE = "法人身份证",
// CORPID = gid.ToString(),
// CreateDate = DateTime.Now,
// ModifyDate = DateTime.Now,
// UPLOADEMPLY = ""
// };
// db.Insertable(infoFile).ExecuteCommand();
// }
// }
// #endregion
// #region 处理营业执照
// //先删除 营业执照
// var existLicenses = db.Queryable().Where(x => x.PID == gid && x.FILETYPE == "营业执照").Select(n=>n.IMGPATH).ToArray();
// var licenseFiles = model.licensefiles.Select(x => x.FilePath).ToArray();
// IEnumerable delLicenses = existLicenses.AsQueryable().Except(licenseFiles);
// if (delLicenses.Count()>0)
// {
// foreach (var item in delLicenses)
// {
// var existInfo = db.Queryable()
// .Where(x => x.PID == gid && x.IMGPATH == item).First();
// db.Deleteable(existInfo).ExecuteCommand();
// }
// }
// //2.添加新的营业执照
// IEnumerable addLicenses = licenseFiles.AsQueryable().Except(existLicenses);
// if (addLicenses.Count()>0)
// {
// foreach (var item in addLicenses)
// {
// var infoFile = new INFO_FILES
// {
// GID = Guid.NewGuid(),
// PID = gid,
// FILENAME = model.licensefiles.Where(x=>x.FilePath ==item).Select(x=>x.FileName).First(),
// IMGPATH = item,
// FILETYPE = "营业执照",
// CORPID = gid.ToString(),
// CreateDate = DateTime.Now,
// ModifyDate = DateTime.Now,
// UPLOADEMPLY = ""
// };
// db.Insertable(infoFile).ExecuteCommand();
// }
// }
// #endregion
// #endregion
db.Ado.CommitTran();
return DataResult.Successed("更新成功!");
}
catch (Exception ex)
{
db.Ado.RollbackTran();
ex.LogAsync(db).GetAwaiter().GetResult();
return DataResult.Failed("更新失败!");
}
}
///
/// 提交审核
///
///
///
public DataResult SubmitTenantApply(string id)
{
var existApply = db.Queryable().First(x => x.Id == long.Parse(id));
if (existApply == null)
{
return DataResult.Failed("企业信息不存在,请先保存再提交!");
}
if (existApply.AuditStatus == AuditStatusEnum.Approve || existApply.AuditStatus == AuditStatusEnum.Auditing)
{
return DataResult.Failed("审核通过或待审批状态不能提交!");
}
// var licensefiles = db.Queryable().Where(x => x.PID == gid && x.FILETYPE =="营业执照").ToList();
// if (licensefiles.Count() == 0)
// {
// return DataResult.Failed("营业执照认证资料未上传不能提交!");
// }
// var cardfiles = db.Queryable().Where(x => x.PID == gid && x.FILETYPE =="法人身份证").ToList();
// if (cardfiles.Count() == 0)
// {
// return DataResult.Failed("营业执照认证资料未上传不能提交!");
// }
//更新状态为待审批
existApply.AuditStatus = AuditStatusEnum.Auditing;
db.Updateable(existApply).ExecuteCommand();
return DataResult.Successed("提交成功");
}
#endregion
}