Files
zszq-trs/YLErpDAL/Modules/ClientModule/ClientSaveService.cs
T

1047 lines
44 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using BaseOUDAL;
using Confluent.Kafka;
using Org.BouncyCastle.Ocsp;
using Qdp.Pricing.Library.Base.Utilities;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using YieldChain.Helpers;
using YLErp.BLL;
using YLErp.CustomizedBizLogic;
using YLErp.DataBase;
using YLErp.DBModels;
using YLErp.DBModels.Attributes;
using YLErp.DBModels.Enums;
using YLErp.Helpers;
using YLErp.Model;
using YLErp.Model.Enum;
using YLErp.Models;
using YLErp.Modules.ClientModule.Constant;
using YLErp.Modules.EodModule.QueryModule;
using YLErp.Modules.SwapModule;
using YLErp.Modules.SystemModule;
namespace YLErp.Modules.ClientModule
{
/// <summary>
/// 客户信息保存服务
/// </summary>
public class ClientSaveService : ClientBaseService
{
public ClientSaveService(OptUserInfo userInfo) : base(userInfo)
{
}
public ClientSaveService(ClientBaseService baseService) : base(baseService)
{
}
/// <summary>
/// 保存客户信息
/// </summary>
/// <param name="req"></param>
/// <param name="updatedPropertyNameSet">被更新的属性名称集合</param>
/// <param name="blAudit">是否审批</param>
public Client SaveData(Client req, HashSet<string> updatedPropertyNameSet, out bool blAudit)
{
blAudit = false;
Client dbModel;
var oldName = string.Empty;
var isAddNew = req.id == 0;
var oldRiskServiceDegree = 0;
var changeList = new List<List<string>>();
//多选框未选择时未赋值nullTryUpdateModel无法更新,特殊处理
req.ProtocolSignVersion = req.ProtocolSignVersion;
req.DerivativesInvestmentVarieties = req.DerivativesInvestmentVarieties;
req.TransactionTarget = req.TransactionTarget;
if (req.EvaluateDate != null && req.EvaluateOfValidity != null)
{
req.EvaluateExpireDate = ClientLinqExtendService.GetEvaluateDate(req.EvaluateDate, req.EvaluateOfValidity);
}
else
{
req.EvaluateExpireDate = null;
}
if (PS.Config.Is格林大华)
{
req.CustomerManager = req.CustomerManager;
req.CustomerManagerId = "";
}
else
{
if (!string.IsNullOrEmpty(req.CustomerManagerId))
{
if (req.CustomerManagerId.Contains(','))
{
var managerNames = new List<string>();
var CustomerManagerIds = req.CustomerManagerId.Split(',').ToList();
CustomerManagerIds.ForEach(a =>
{
var manager = UserBLL.GetById(Convert.ToInt32(a));
if (manager != null)
{
managerNames.Add(manager.Name);
}
});
req.CustomerManager = managerNames.Any() ? string.Join(",", managerNames) : string.Empty;
}
else
{
var manager = UserBLL.GetById(Convert.ToInt32(req.CustomerManagerId));
req.CustomerManager = manager == null ? "" : manager.Name;
}
}
else
{
req.CustomerManager = null;
}
}
if ((PS.Config.Company == Configuration.CompanyEnum.浙期 && string.IsNullOrWhiteSpace(req.Number))
|| (PS.Config.Company == Configuration.CompanyEnum.国投))
{
BizLogicSingleton.Instance.GenerateClientCode(req, DbContext.client.AsNoTracking());
}
var clientCredit = yldb.credit.Where(x => x.ClientId == req.id).ToList();
var dbClient = new ClientDBContext();
if (clientCredit != null && clientCredit.Count > 0)
{
clientCredit.ForEach(x =>
{
x.ClientName = req.Name;
if (req.Number != null && string.IsNullOrWhiteSpace(req.Number)) { x.ClientNumber = req.Number; }
else
{
var clientModel = dbClient.client.First(c => c.id == req.id);
x.ClientNumber = clientModel.Number;
}
});
}
//当客户属性为自然人/产品时,客户性质为“不适用”
if (req.ClientType == ClientTypeEnum.自然人.ToString() || req.ClientType == ClientTypeEnum.产品.ToString())
{
req.InstitutionalAttributes = "不适用";
}
if (req.ClientType != ClientTypeEnum.产品.ToString())
{
req.ProductNumber = "";
req.AdminFullName = "";
}
if (!(req.ClientType == ClientTypeEnum.产品.ToString() || (req.ClientType == ClientTypeEnum.机构.ToString() && req.BusinessType == "私募管理人")))
{
req.AdminRegisteredNum = "";
}
if (req.ClientType == ClientTypeEnum.自然人.ToString())
{
req.RegisteredCapital = "";
req.RegisteredAddress = "";
}
if (PS.Config.ClientElement.IsCreditLimit)
{
req.IsTradeCredit = 1;
}
else
{
req.IsCreditOn = 1;
}
req.SwapTradeType = req.SwapTradeType ?? 0;
if (isAddNew)
{
req.ProcessStatus = "未提交";
req.ProcessOrderId = 0;
req.ProcessOptDate = DateTime.Now;
SetDBModelCreator(req);
CheckModel(req, req.Name, isAddNew);
DbContext.client.Add(dbModel = req);
}
else
{
dbModel = DbContext.client.Find(req.id);
if (dbModel == null)
{
throw new ServiceException("要更新的数据 已不存在");
}
changeList = DataChangeHelper.GetDataChanges(dbModel, req);
changeList = ClientDataChangeLogHandle.Handle(typeof(Client), changeList);
var changeRegisteredCapital = changeList.FirstOrDefault(n => n[0] == nameof(Client.RegisteredCapital));
if (changeRegisteredCapital != null && changeRegisteredCapital.Count > 0)
{
if (req.ClientType == "产品")
{
changeRegisteredCapital[1] = "产品规模(万元)";
}
else
{
changeRegisteredCapital[1] = "注册资本(万元)";
}
}
req.ProcessStatus = dbModel.ProcessStatus;
req.ProcessOrderId = dbModel.ProcessOrderId;
oldName = dbModel.Name;
CheckModel(req, oldName, isAddNew);
oldRiskServiceDegree = dbModel.RiskServiceDegree ?? 0;
//比较数据库数据和要更新的请求数据以确定是否重置为审批状态
if (CheckClientProcess(dbModel, req, updatedPropertyNameSet))
{
blAudit = true;
return dbModel;
}
ObjectHelper.MapValues(dbModel, req, updatedPropertyNameSet);
}
SetDBModelOpt(dbModel);
DbContext.SaveChanges();
//修改客户名时,需要同步修改该客户文件管理相关的文件夹名
//12/23 添加了FilePath,直接使用客户Id就能区分,当文件名仍然存在客户名称,就换成Id作文件名
if (!isAddNew && oldName != dbModel.Name)
{
var blackList = DbContext.client_black.Where(O => O.Name == oldName);
foreach (var item in blackList)
{
item.Name = dbModel.Name;
}
var oldClientPath = $"{dbModel.id}_{string.Join("", oldName.Where(O => !System.IO.Path.GetInvalidFileNameChars().Contains(O)))}";
var newClientPath = $"{dbModel.id}";
var oldFileSuitablyPath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/SuitablyFiles/{oldClientPath}");
var newFileSuitablyPath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/SuitablyFiles/{newClientPath}");
var oldFilePath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/{oldClientPath}");
var newFilePath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/{newClientPath}");
var oldHistoryFilePath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/{oldClientPath}/history");
var newHistoryFilePath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/{newClientPath}/history");
if (System.IO.Directory.Exists(oldFileSuitablyPath))
{
if (!System.IO.Directory.Exists(newFileSuitablyPath))
{
System.IO.Directory.Move(oldFileSuitablyPath, newFileSuitablyPath);
}
else
{
var paths = System.IO.Directory.GetFiles(oldFileSuitablyPath);
if (paths.Length > 0)
{
foreach (var path in paths)
{
var newPath = path.Replace(oldFileSuitablyPath, newFileSuitablyPath);
System.IO.File.Move(path, newPath);
}
}
}
}
if (System.IO.Directory.Exists(oldFilePath))
{
if (!System.IO.Directory.Exists(newFilePath))
{
System.IO.Directory.Move(oldFilePath, newFilePath);
}
else
{
var paths = System.IO.Directory.GetFiles(oldFilePath);
if (paths.Length > 0)
{
foreach (var path in paths)
{
var newPath = path.Replace(oldFilePath, newFilePath);
System.IO.File.Move(path, newPath);
}
}
}
}
if (System.IO.Directory.Exists(oldHistoryFilePath))
{
if (!System.IO.Directory.Exists(newHistoryFilePath))
{
System.IO.Directory.Move(oldHistoryFilePath, newHistoryFilePath);
}
else
{
var paths = System.IO.Directory.GetFiles(oldHistoryFilePath);
if (paths.Length > 0)
{
foreach (var path in paths)
{
var newPath = path.Replace(oldHistoryFilePath, newHistoryFilePath);
System.IO.File.Move(path, newPath);
}
}
}
}
}
//交易元数据
if (req.MetaDic.Any())
{
foreach (var kv in req.MetaDic)
{
if (isAddNew)
{
if (!string.IsNullOrEmpty(kv.Value))
{
AddMeta(false, dbModel.id, kv.Key, kv.Value);
}
}
else
{
var mete = AddOrUpdateMeta(false, dbModel.id, kv.Key, kv.Value);
if (mete != null && mete.Count > 0)
{
changeList.Add(mete);
}
}
}
}
DbContext.SaveChanges();
yldb.SaveChanges();
var changeStr = string.Empty;
if (req.id == 0)
{
AddClientOperationHistory(dbModel, "新增客户");
}
else if (req.id > 0)
{
changeStr = changeList.ToJson();
if (changeList != null && changeList.Count > 0)
{
AddClientOperationHistory(dbModel, "编辑客户", changeStr, true);
}
}
//增加评估日志
AddClientAssessmentLog(dbModel, changeStr, isAddNew);
SaveClientCustomerManage(dbModel.id,req.CustomerManagerId);
return dbModel;
}
/// <summary>
/// 保存客户与客户服务人对应关系
/// </summary>
/// <param name="clientId"></param>
/// <param name="customerManageIds"></param>
private void SaveClientCustomerManage(int clientId,string customerManageIds)
{
var clientManagers = DbContext.client_customer_manage.Where(x=>x.ClientId==clientId);
DbContext.client_customer_manage.RemoveRange(clientManagers);
if (!string.IsNullOrEmpty(customerManageIds))
{
if (customerManageIds.Contains(','))
{
var managerNames = new List<string>();
var CustomerManagerIds = customerManageIds.Split(',').ToList();
CustomerManagerIds.ForEach(a =>
{
var sysUserId=Convert.ToInt32(a);
ClientCustomerManage clientCustomer=new ClientCustomerManage();
clientCustomer.ClientId = clientId;
clientCustomer.SysuserId = sysUserId;
clientCustomer.create_time = DateTime.Now;
clientCustomer.create_user = UserId;
DbContext.client_customer_manage.Add(clientCustomer);
});
}
else
{
var sysUserId = Convert.ToInt32(customerManageIds);
ClientCustomerManage clientCustomer = new ClientCustomerManage();
clientCustomer.ClientId = clientId;
clientCustomer.SysuserId = sysUserId;
clientCustomer.create_time = DateTime.Now;
clientCustomer.create_user = UserId;
DbContext.client_customer_manage.Add(clientCustomer);
}
}
DbContext.SaveChanges();
}
/// <summary>
/// 保存客户信息变更数据
/// </summary>
/// <param name="req"></param>
/// <param name="updatedPropertyNameSet">被更新的属性名称集合</param>
/// <param name="blAudit">是否审批</param>
public Client SaveEditData(Client req)
{
Client dbModel;
var oldName = string.Empty;
var isAddNew = req.id == 0;
var oldRiskServiceDegree = 0;
var changeList = new List<List<string>>();
dbModel = DbContext.client.Find(req.id);
if (dbModel == null)
{
throw new ServiceException("要更新的数据 已不存在");
}
changeList = DataChangeHelper.GetDataChanges(dbModel, req);
changeList = ClientDataChangeLogHandle.Handle(typeof(Client), changeList);
oldName = dbModel.Name;
CheckModel(req, oldName, isAddNew);
oldRiskServiceDegree = dbModel.RiskServiceDegree ?? 0;
foreach (var kv in req.MetaDic)
{
var mete = AddOrUpdateMeta(false, dbModel.id, kv.Key, kv.Value);
if (mete != null && mete.Count > 0)
{
changeList.Add(mete);
}
}
ObjectHelper.MapValues(dbModel, req);
SetDBModelOpt(dbModel);
DbContext.SaveChanges();
//修改客户名时,需要同步修改该客户文件管理相关的文件夹名
//12/23 添加了FilePath,直接使用客户Id就能区分,当文件名仍然存在客户名称,就换成Id作文件名
if (oldName != dbModel.Name)
{
var blackList = DbContext.client_black.Where(O => O.Name == oldName);
foreach (var item in blackList)
{
item.Name = dbModel.Name;
}
var oldClientPath = $"{dbModel.id}_{string.Join("", oldName.Where(O => !System.IO.Path.GetInvalidFileNameChars().Contains(O)))}";
var newClientPath = $"{dbModel.id}";
var oldFileSuitablyPath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/SuitablyFiles/{oldClientPath}");
var newFileSuitablyPath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/SuitablyFiles/{newClientPath}");
var oldFilePath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/{oldClientPath}");
var newFilePath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/{newClientPath}");
var oldHistoryFilePath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/{oldClientPath}/history");
var newHistoryFilePath = OtcAppContext.MapPath($"~/App_Docs/ClientFiles/{newClientPath}/history");
if (System.IO.Directory.Exists(oldFileSuitablyPath))
{
if (!System.IO.Directory.Exists(newFileSuitablyPath))
{
System.IO.Directory.Move(oldFileSuitablyPath, newFileSuitablyPath);
}
else
{
var paths = System.IO.Directory.GetFiles(oldFileSuitablyPath);
if (paths.Length > 0)
{
foreach (var path in paths)
{
var newPath = path.Replace(oldFileSuitablyPath, newFileSuitablyPath);
System.IO.File.Move(path, newPath);
}
}
}
}
if (System.IO.Directory.Exists(oldFilePath))
{
if (!System.IO.Directory.Exists(newFilePath))
{
System.IO.Directory.Move(oldFilePath, newFilePath);
}
else
{
var paths = System.IO.Directory.GetFiles(oldFilePath);
if (paths.Length > 0)
{
foreach (var path in paths)
{
var newPath = path.Replace(oldFilePath, newFilePath);
System.IO.File.Move(path, newPath);
}
}
}
}
if (System.IO.Directory.Exists(oldHistoryFilePath))
{
if (!System.IO.Directory.Exists(newHistoryFilePath))
{
System.IO.Directory.Move(oldHistoryFilePath, newHistoryFilePath);
}
else
{
var paths = System.IO.Directory.GetFiles(oldHistoryFilePath);
if (paths.Length > 0)
{
foreach (var path in paths)
{
var newPath = path.Replace(oldHistoryFilePath, newHistoryFilePath);
System.IO.File.Move(path, newPath);
}
}
}
}
}
DbContext.SaveChanges();
yldb.SaveChanges();
var changeStr = string.Empty;
changeStr = changeList.ToJson();
if (changeList != null && changeList.Count > 0)
{
AddClientOperationHistory(dbModel, "编辑客户", changeStr, true);
}
//增加评估日志
AddClientAssessmentLog(dbModel, changeStr, isAddNew);
return dbModel;
}
private void AddClientOperationHistory(Client req, string optType, string Comments = null, bool isJson = false)
{
DbContext.ClientAuditLog.Add(new ClientAuditLog
{
ClientId = req.id,
OptType = optType,
Changes = Comments ?? string.Empty,
DataType = isJson ? "C02" : "00",
OptId = UserId,
OptName = UserName,
OptDate = OptDate
});
DbContext.SaveChanges();
}
private void AddClientAssessmentLog(Client newClient, string changeStr, bool isNew)
{
//新增与变更评估日期以及评估有效期时增加日志
if ((isNew && newClient.EvaluateDate != null && newClient.EvaluateOfValidity != null)
|| changeStr.Contains("EvaluateDate") || changeStr.Contains("EvaluateOfValidity"))
{
DbContext.ClientAuditLog.Add(new ClientAuditLog
{
ClientId = newClient.id,
OptType = "评估记录",
Changes = JsonHelper.ToJson(new ClientAssessmentLogModel
{
EvaluateDate = newClient.EvaluateDate == null ? string.Empty : newClient.EvaluateDate.Value.ToString("yyyy-MM-dd"),
EvaluateOfValidity = newClient.EvaluateOfValidity,
OptId = UserId,
OptName = UserName,
OptDate = OptDate.ToString("yyyy-MM-dd HH:mm:ss")
}),
DataType = "C02",
OptId = UserId,
OptName = UserName,
OptDate = OptDate
});
DbContext.SaveChanges();
}
}
private bool CheckClientProcess(Client dbModel, Client req, HashSet<string> updatedPropertyNameSet)
{
var clientProcess = yldb.approvalprocess.Where(s => s.processType == "ClientProcess").ToList();
if (clientProcess.Count == 0)
{
return false;
}
var blAudit = dbModel.ProcessStatus == "已开户" || dbModel.ApprovalStatus == "审批中"
|| dbModel.ProcessStatus == "已休眠" || dbModel.ProcessStatus == "已销户";
if (!blAudit)
{
return false;
}
blAudit = true;
if (DbContext.bankcard.Where(b => b.ClientId == dbModel.id && b.ApprovalOrder != (int)ApprovalOrderEnum.无需审批 && b.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).Any()
|| DbContext.clientduty.Where(b => b.ClientId == dbModel.id && b.ApprovalOrder != (int)ApprovalOrderEnum.无需审批 && b.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).Any()
|| DbContext.client_file.Where(b => b.ClientId == dbModel.id && b.ApprovalOrder != (int)ApprovalOrderEnum.无需审批 && b.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).Any())
{
blAudit = true;
}
//浙期每个字段更改都要审批
if (!blAudit && (PS.Config.Is浙期 || PS.Config.Company == Configuration.CompanyEnum.招证))
{
var update = updatedPropertyNameSet.Where(x => !x.Contains("][") && !x.Contains("meta_") && x != "HadPass");
foreach (var up in update)
{
if (!blAudit)
{
var notmapped = dbModel.GetType().GetProperty(up).GetCustomAttributes(typeof(NotMappedAttribute), false);
if (notmapped != null && notmapped.Length > 0)
{
continue;
}
var oldvalue = dbModel.GetType().GetProperty(up).GetValue(dbModel, null);
var newvalue = req.GetType().GetProperty(up).GetValue(req, null);
if ((oldvalue != null && newvalue != null && !oldvalue.Equals(newvalue)) || ((oldvalue == null || newvalue == null) && oldvalue != newvalue))
{
blAudit = true;
}
}
else
{
break;
}
}
foreach (var kv in req.MetaDic)
{
if (!blAudit)
{
var mete = AddOrUpdateMeta(false, dbModel.id, kv.Key, kv.Value);
if (mete != null && mete.Count > 0)
{
blAudit = true;
}
}
else
{
break;
}
}
}
if (blAudit)
{
if ("已休眠".Equals(dbModel.ProcessStatus))
{
var preAuditStatus = DbContext.ClientMeta.FirstOrDefault(p => p.ClientId == dbModel.id && p.MetaKey == ClientMetaKey.AuditPreStatus);
if (preAuditStatus == null)
{
preAuditStatus = new ClientMeta
{
ClientId = dbModel.id,
MetaKey = ClientMetaKey.AuditPreStatus,
MetaValue = dbModel.ProcessStatus,
OptId = UserId,
OptName = UserName,
OptDate = DateTime.Now
};
DbContext.ClientMeta.Add(preAuditStatus);
}
}
bool approvalBranch = clientProcess.Any(x => x.approvalGroupId != 0);//审批流程有分支情况
req.ProcessOrderBranch = 0;
req.ApprovalOrderId = ProcessTradeLog.审批中;
req.ApprovalOptDate = DateTime.Now;
req.ApprovalStatus = "审批中";
var groupId = UserBLL.GetApprovalProcessGroup(UserId);
if (approvalBranch)//审批流程有分支情况
{
//该审批组属于流程的审批组或该审批组不属于流程审批组
var tradeProessBranchQuery = clientProcess.FirstOrDefault(x => (x.approvalGroupId == groupId && x.approvalCondition == 1) || (x.approvalGroupId != groupId && x.approvalCondition == 2));
if (tradeProessBranchQuery == null)//都没有情况
{
throw new ServiceException("当前存在分支开户审批流程,检测到申请人不满足任意一个分支进入条件,无法提交审批,请更换申请人或调整审批组");
}
req.ApprovalOrderId = tradeProessBranchQuery.order > 1 ? 1 : tradeProessBranchQuery.order + 1;//第一个节点是分支需要跳过审批组那一级
req.ProcessOrderBranch = tradeProessBranchQuery.node ?? 1;//审批组分支
}
dbModel = DbContext.client.Find(req.id);
dbModel.ApprovalStatus = req.ApprovalStatus;
dbModel.ApprovalOrderId = req.ApprovalOrderId;
dbModel.ApprovalOptDate = req.ApprovalOptDate;
dbModel.ProcessOrderBranch = req.ProcessOrderBranch;
var clientAuditlog = new ClientAuditLog
{
ClientId = dbModel.id,
OptType = "提交信息变更审批",
DataType = "00",
OptId = UserId,
OptName = UserName,
OptDate = DateTime.Now
};
///日志记录
DbContext.ClientAuditLog.Add(clientAuditlog);
DbContext.SaveChanges();
dbModel.ApprovalLogId = clientAuditlog.id;
clientAuditlog.Changes = ClientHelper.Serialize(req);
var range = DbContext.client_file_audit.Where(x => x.ClientId == dbModel.id).ToList();
DbContext.client_file_audit.RemoveRange(range);
DbContext.SaveChanges();
}
return blAudit;
}
public void CheckModel(Client req, string blackNameForCheck, bool isAddNew)
{
if (string.IsNullOrWhiteSpace(req.Name))
{
throw new ServiceException("客户名称 必须填写");
}
if (string.IsNullOrWhiteSpace(req.SettleFileNumber)&&req.SwapTradeType==1)
{
throw new ServiceException("定义文件编号 必须填写");
}
//if (string.IsNullOrWhiteSpace(req.))
//{
// throw new ServiceException("自定义必须填写");
//}
//新增时,新的客户名如果在黑名单里,不允许新增
//修改时,旧的客户名如果在黑名单里,不允许修改
if (!isAddNew && !req.Name.Equals(blackNameForCheck) && DbContext.client_black.Any(x => x.Name == blackNameForCheck))
{
throw new ServiceException("该客户为黑名单客户," + (req.id > 0 ? "不允许修改客户名称" : "不允许新增"));
}
//字段唯一性验证(客户名称,客户代码,默认登录名)
if (DbContext.client.Any(x => x.id != req.id && x.Name == req.Name && x.ProcessStatus != "已销户"))
{
throw new ServiceException("客户名称不能重复");
}
if (DbContext.client.Any(x => x.id != req.id && x.Number == req.Number && !string.IsNullOrEmpty(req.Number)))
{
throw new ServiceException("客户编号不能重复");
}
if (!PS.Config.Is国泰君安 && PS.Config.ComponentVersion == Configuration.ComponentVersion.Broker)
{
if (DbContext.client.Any(x => x.id != req.id && x.Code == req.Code && !string.IsNullOrEmpty(req.Code)))
{
throw new ServiceException("客户代码不能重复");
}
}
if (DbContext.client.Any(x => x.id != req.id && x.DefaultLoginName == req.DefaultLoginName && !string.IsNullOrEmpty(req.DefaultLoginName)))
{
throw new ServiceException("默认登录名不能重复");
}
HashSet<string> yldicSet;
using (var db = new ErpBaseContext())
{
yldicSet = db.Dictionaries.Where(n => db.DictionaryItems.Any(m => m.DictId == n.Id)).Select(n => n.Name).ToHashSet();
}
if (!yldicSet.Contains("行业"))
{
throw new ServiceException("请配置数据字典 行业");
}
if (!yldicSet.Contains("投资经验"))
{
throw new ServiceException("请配置数据字典 投资经验");
}
if (!yldicSet.Contains(PS.Config.Is中财 ? "投资知识" : "风险偏好"))
{
throw new ServiceException("请配置数据字典 " + (PS.Config.Is中财 ? "投资知识" : "风险偏好"));
}
if (!yldicSet.Contains("期望收益"))
{
throw new ServiceException("请配置数据字典 期望收益");
}
if (!yldicSet.Contains("适当性客户分类"))
{
throw new ServiceException("请配置数据字典 适当性客户分类");
}
if (!yldicSet.Contains("协议签署版本"))
{
throw new ServiceException("请配置数据字典 协议签署版本");
}
if (req.ParentId > 0 && req.id > 0 && Treeleveldata(req.id).Any(c => c.id == req.ParentId))
{
throw new ServiceException("所属机构不能选择下一层");
}
//存在已审批或审批中的资质评级
if (PS.Config.ClientElement.IsCreditLimit && req.IsCreditOn != 1 && DbContext.Client_Rating.Where(t => !t.IsDeleted && t.ClientId == req.id
&& (t.ProcessStatus == "已审批" || t.ProcessStatus == "审批中")
&& (!t.RatingDeadLine.HasValue || t.RatingDeadLine >= valuedateBLL.ValueDate)).Any())
{
throw new ServiceException("存在已审批或审批中的资质评级, 请先处理相关资质评级记录");
}
//存在已审批或审批中的授信
if (PS.Config.ClientElement.IsCreditLimit && req.IsCreditOn != 1 && yldb.credit.Where(t => t.ClientId == req.id && (t.ProcessStatus == "已审批" || t.ProcessStatus == "审批中") && (!t.CreditDeadLine.HasValue || t.CreditDeadLine >= valuedateBLL.ValueDate)).Any())
{
throw new ServiceException("存在已审批或审批中的授信, 客户期权费授信不能为否,请先处理相关授信记录");
}
////存在已审批或审批中的互换授信
//if (yldb.credit.Where(t => (t.DerivativesInvestmentVarieties != null && t.DerivativesInvestmentVarieties.Contains(((int)DerivativesInvestmentVarietiesEnum.场外期权).ToString())) && t.ClientId == req.id && (t.ProcessStatus == "已审批" || t.ProcessStatus == "审批中") && (!t.CreditDeadLine.HasValue || t.CreditDeadLine >= valuedateBLL.ValueDate)).Any())
//{
// if (req.BusinessType == null || !((req.BusinessType.Contains("银行") && "AAA".Equals(req.BankCreditRating)) || (req.BusinessType.Contains("证券") && req.SamePeer == 0)))
// {
// throw new ServiceException("存在已审批或审批中的互换授信, 客户不允许修改为非AAA银行或非同业交易商,请先处理相关授信记录!");
// }
//}
//产品用户投资者,如果存在收益互换权限 只有专业投资者权益百分比可以大于20%
if (req.ClientType == ClientTypeEnum.产品.ToString() && req.DerivativesInvestmentVarieties.Contains((int)DerivativesInvestmentVarietiesEnum.场外互换 + ""))
{
//获取产品投资人
var hasClientInvestors = DbContext.ClientInvestor.Where(t => t.ClientId == req.id && !t.EligibilityType.Equals("专业投资者") && t.ShareRate > 0.2);
if (hasClientInvestors != null && hasClientInvestors.Any())
{
throw new ServiceException("本产品客户,存在非专业投资人权益比例大于20%情况,无法进行场外互换交易!");
}
}
//if (req.ClientRight=="5")//行情及交易
//{
// if (string.IsNullOrEmpty(req.ProxyEmail))
// {
// throw new ServiceException("代理委托邮箱必填!");
// }
// if (string.IsNullOrEmpty(req.ProxyEmailPwd))
// {
// throw new ServiceException("邮箱授权码必填!");
// }
//}
var clientFields = isAddNew ? ClientEditConfigService.GetAllFormEditFieldByTableId("basic") : ClientEditConfigService.GetAllFormEditField();
clientFields = clientFields.Where(a => !string.IsNullOrEmpty(a.label) && !a.@readonly);
foreach (var field in clientFields)
{
if (field.name.Contains("meta_"))
{
var metaKey = field.name.Split('_')[1];
if (field.required && ((req.MetaDic.TryGetValue(metaKey, out var metaValue) && string.IsNullOrWhiteSpace(metaValue)) || !req.MetaDic.TryGetValue(metaKey, out metaValue)) && isAddNew)
{
throw new ServiceException($"{field.label} 必须填写");
}
}
else
{
var propertys = req.GetType().GetProperties();
var prop = propertys.Where(a => a.Name == field.name).FirstOrDefault();
if (prop != null && field.required)
{
if (prop.PropertyType == typeof(string))
{
if (string.IsNullOrWhiteSpace(prop.GetValue(req, null)?.ToString()))
{
throw new ServiceException($"{field.label} 必须填写");
}
}
else if (field.name== "TradingInstType"&& (TradingInstTypeEnum)prop.GetValue(req, null) == TradingInstTypeEnum.None)
{
throw new ServiceException($"{field.label} 必须填写");
}
else if (prop.GetValue(req, null) == null)
{
throw new ServiceException($"{field.label} 必须填写");
}
}
}
}
}
private List<Client> Treeleveldata(int clientid)
{
var resultList = new List<Client>();
var clientQuery = DataCacheProvider.GetClientDataSource().AsQueryable();
FoundChildNode(clientQuery, clientid, resultList, null);
return resultList;
}
private void FoundChildNode(IQueryable<Client> clientQuery, int parentId, List<Client> resultList, HashSet<int> checkSet)
{
checkSet ??= new HashSet<int>();
if (!checkSet.Add(parentId))
{
checkSet.Clear();
var pid = parentId;
var list = new List<string>();
for (var i = 0; i < 100; i++)
{
if (pid <= 0 || !checkSet.Add(pid)) break;
var client = clientQuery.FirstOrDefault(n => n.id == pid);
if (client == null)
{
break;
}
else
{
list.Add(client.Name);
pid = client.ParentId;
}
}
if (list.Count > 0)
{
list.Add(list[0]);
}
throw new ServiceFaultException("客户父子关系产生了循环依赖:" + string.Join("->", list));
}
var childItems = clientQuery.Where(c => c.ParentId == parentId && c.id != parentId).ToList();
foreach (var child in childItems)
{
resultList.Add(child);
FoundChildNode(clientQuery, child.id, resultList, checkSet);
}
}
/// <summary>
/// API
/// </summary>
public Client SaveClientAPI(Client req)
{
if (req == null)
{
throw new ServiceException("参数错误");
}
if (string.IsNullOrWhiteSpace(req.Number))
{
req.id = 0;
}
else
{
var client = DbContext.client.FirstOrDefault(p => req.Number.Equals(p.Number));
req.id = client != null ? client.id : 0;
}
return new ClientSaveService(OptUser).SaveData(req, null, out bool blAudit);
}
/// <summary>
/// API
/// </summary>
/// <param name="req"></param>
public void CreateClient(CreateClientReq req)
{
if (req?.Client == null)
{
throw new ServiceException("参数错误:" + nameof(req.Client));
}
req.Client.id = 0;
req.Client.LevelId = DbContext.clientlevel.Where(c => c.LevelName == req.Client.Level).FirstOrDefault().id;
if (req.Client.SalesDepartmentId != null && req.Client.SalesDepartmentId > 0)
{
req.Client.SalesDepartmentId = GetAllSaleDepartment(req.Client.SalesDepartment);
}
if (!string.IsNullOrEmpty(req.Client.CustomerManager))
{
var managerNames = new List<string> { req.Client.CustomerManager };
if (req.Client.CustomerManager.Contains(','))
{
managerNames = req.Client.CustomerManager.Split(',').ToList();
}
using var db = new ErpBaseContext();
var ids = db.SystemUsers.Where(n => managerNames.Contains(n.LoginName) || managerNames.Contains(n.Name)).Select(n => n.Id).ToArray();
req.Client.CustomerManagerId = string.Join(",", ids);
}
var client = new ClientSaveService(OptUser).SaveData(req.Client, null, out bool blAudit);
if (req.Bankcards != null && req.Bankcards.Any())
{
foreach (var item in req.Bankcards)
{
item.id = 0;
item.ClientId = client.id;
new ClientBankCardService(OptUser).SaveBankCard(item, out _);
}
}
if (req.ClientDutys != null && req.ClientDutys.Any())
{
foreach (var item in req.ClientDutys)
{
item.id = 0;
item.ClientId = client.id;
new ClientDutyService(OptUser).SaveClientDuty(item);
}
}
}
/// <summary>
/// 获取归属营业部
/// </summary>
/// <param name="SalesDepartment"></param>
/// <returns></returns>
public static int GetAllSaleDepartment(string SalesDepartment)
{
var SalesDepartmentId = 0;
using (var condb = new ErpBaseContext())
{
var list = condb.Departments.Where(x => x.DepartmentType == SalesDepartment).FirstOrDefault();
SalesDepartmentId = list.Id;
}
return SalesDepartmentId;
}
/// <summary>
/// 修改外部编号
/// </summary>
/// <param name="clientNumber"></param>
/// <param name="outNumer"></param>
public void UpdateClientOutNumber(string clientNumber,string outNumer)
{
var client= DbContext.client.FirstOrDefault(x=>x.Number==clientNumber);
if (client!=null)
{
client.OutNumber= outNumer;
DbContext.SaveChanges();
}
}
/// <summary>
/// 添加元数据
/// </summary>
protected void AddMeta(bool saveChanges, int clientId, string metaKey, string metaValue)
{
DbContext.ClientMeta.Add(new ClientMeta
{
ClientId = clientId,
MetaKey = metaKey,
MetaValue = metaValue
});
if (saveChanges)
{
DbContext.SaveChanges();
}
}
/// <summary>
/// 添加或更新元数据
/// </summary>
protected List<string> AddOrUpdateMeta(bool saveChanges, int clientId, string metaKey, string metaValue)
{
return new ClientMetaService(this).AddMeta(clientId, metaKey, metaValue, saveChanges);
}
}
public class CreateClientReq
{
public Client Client { get; set; }
public IEnumerable<ClientBankCard> Bankcards { get; set; }
public IEnumerable<ClientDuty> ClientDutys { get; set; }
}
}