3397 lines
152 KiB
C#
3397 lines
152 KiB
C#
using Dapper;
|
|
using DocumentFormat.OpenXml.Drawing.Charts;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using OfficeOpenXml;
|
|
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
|
|
using Org.BouncyCastle.Crypto.Tls;
|
|
using Org.BouncyCastle.Ocsp;
|
|
using YLErp.Abstract;
|
|
using YLErp.BLL.Eod;
|
|
using YLErp.BLL.EodSettlement;
|
|
using YLErp.Commons;
|
|
using YLErp.DataBase;
|
|
using YLErp.DBModels;
|
|
using YLErp.DBModels.Consts;
|
|
using YLErp.Enums;
|
|
using YLErp.Model.Enum;
|
|
using YLErp.Models.Tag;
|
|
using YLErp.Modules.ClientModule;
|
|
using YLErp.Modules.ClientModule.Dto;
|
|
using YLErp.Modules.EodModule.QueryModule;
|
|
using YLErp.Modules.ReportModule;
|
|
using YLErp.Modules.SalesModule;
|
|
using YLErp.Modules.SubAppModule.ClientApp;
|
|
using YLErp.Modules.SuperviseReportModule.SAC.Model;
|
|
using YLErp.Modules.SystemModule;
|
|
using YLErp.Modules.TagModule;
|
|
using YLErp.Modules.TradeDalModule;
|
|
using YLErp.Modules.TradeModule;
|
|
using YLErp.Modules.TradeModule.QueryModule;
|
|
using YLErp.Office;
|
|
using YLErp.Office.iTextModule;
|
|
using YLErp.QdpModule;
|
|
|
|
namespace YLErp.Web.Controllers
|
|
{
|
|
/// <summary>
|
|
/// 客户信息控制器
|
|
/// </summary>
|
|
public class ClientController : BaseController
|
|
{
|
|
readonly IViewRenderService _viewRenderer;
|
|
private IKafkaProduce _kafkaProduce;
|
|
|
|
public ClientController(IViewRenderService viewRenderer, IKafkaProduce kafkaProduce)
|
|
{
|
|
_viewRenderer = viewRenderer;
|
|
_kafkaProduce = kafkaProduce;
|
|
}
|
|
|
|
readonly ErpBaseContext basedb = new();
|
|
public JsonResult GetValidBankCard(int ClientId, string Direction)
|
|
{
|
|
var cards = clientDB.bankcard.Where(b => b.ApprovalOrder < 1 && b.ClientId == ClientId && b.ValidState == "Valid").ToList();
|
|
//if (CurUser.结算管理_出入金是否进行资金账户类型用途的校验)
|
|
//{
|
|
// var dictionaryName = new ClientCashImportService(CurUser).CheckCashAccountTypePermission(Direction);
|
|
// cards = cards.Where(b => dictionaryName.Contains(b.Use)).ToList();
|
|
//}
|
|
return JsonSuccessData(cards);
|
|
}
|
|
|
|
[MyAuthorize("风险控制-资金监控")]
|
|
public ActionResult clientRiskMonitor()
|
|
{
|
|
ViewBag.valueDate = valuedateBLL.ValueDate.ToString("yyyy-MM-dd");
|
|
//获取根据系统时间
|
|
ViewBag.lastSettledDate = EodOperationBase.GetLastSettlementDate(DateTime.Now.Date).ToString("yyyy-MM-dd");
|
|
return View();
|
|
}
|
|
|
|
[MyAuthorize("风险控制-资金监控")]
|
|
public ActionResult clientRiskMonitorBatchSend(string clientids, DateTime valuedate, string showntype)
|
|
{
|
|
ViewBag.ClientIds = clientids;
|
|
ViewBag.ValueDate = valuedate;
|
|
ViewBag.LuoKuanDesc = DBCacheManager.Single.GetStr(CacheTable.LuoKuanDesc);
|
|
ViewBag.MarginLuoKuanDesc = DBCacheManager.Single.GetStr(CacheTable.MarginLuoKuanDesc);
|
|
ViewBag.ShownType = showntype;
|
|
return View();
|
|
}
|
|
|
|
/*---------------------- client------------------------------*/
|
|
[MyAuthorize("客户管理-客户查看")]
|
|
public ActionResult ClientList()
|
|
{
|
|
var isCanle = CurUser.客户管理.客户销户;
|
|
ViewBag.isCanle = isCanle;
|
|
return View("ClientListV2");
|
|
}
|
|
|
|
[MyAuthorize("客户管理-客户查看")]
|
|
public ActionResult ClientListV2()
|
|
{
|
|
var isCanle = CurUser.客户管理.客户销户;
|
|
ViewBag.isCanle = isCanle;
|
|
return View();
|
|
}
|
|
|
|
[MyAuthorize("客户管理-客户查看")]
|
|
public ActionResult ClientExpireWarningList()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
[MyAuthorize("客户管理-客户查看")]
|
|
public JsonResult ClientExpireWarningListJson(ExpireWarningReq req)
|
|
{
|
|
var sList = new ClientWarningService(CurUser).GetExpiresWarning(req);
|
|
return Json(sList);
|
|
}
|
|
|
|
[MyAuthorize("客户管理-客户查看")]
|
|
public JsonResult CheckedClientWarning()
|
|
{
|
|
var expireWarningStatus = new ClientWarningService(CurUser).CheckedClient();
|
|
return Json(expireWarningStatus);
|
|
}
|
|
|
|
[MyAuthorize("客户管理-客户查看")]
|
|
public JsonResult ClientExpireWarningUpdate(string enid)
|
|
{
|
|
var intid = DataProtectHelper.DecryptInt(enid);
|
|
new ClientWarningService(CurUser).UpdateWarning(intid);
|
|
return JsonSuccess("");
|
|
}
|
|
|
|
[MyAuthorize("客户管理-客户查看")]
|
|
public JsonResult ClientExpireWarningStatusJson(string enid)
|
|
{
|
|
var expireWarningStatus = new ClientWarningService(CurUser).GetExpireStatus();
|
|
return Json(expireWarningStatus);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 导出客户人员信息
|
|
/// </summary>
|
|
public object ExportClientDuty(ClientReq req)
|
|
{
|
|
req.CurUserClientIds = CurUser.GetClientIdsByCustomerManager();
|
|
var sList = new ClientQueryService(CurUser).SearchList(req);
|
|
var bytes = new ClientDutyService(CurUser).ExportClientDutyToExcel(sList.rows.Select(o => o.id));
|
|
return File(bytes, xlsxMimeType, $"客户人员信息-{DateTime.Now:yyyy-MM-dd}.xlsx");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 导出客户银行卡信息
|
|
/// </summary>
|
|
public object ExportClientBankCard(ClientReq req)
|
|
{
|
|
req.CurUserClientIds = CurUser.GetClientIdsByCustomerManager();
|
|
var sList = new ClientQueryService(CurUser).SearchList(req);
|
|
var bytes = new ClientBankCardService(CurUser).ExportBankCardsToExcel(sList.rows.Select(o => o.id));
|
|
return File(bytes, xlsxMimeType, $"客户银行卡信息-{DateTime.Now:yyyy-MM-dd}.xlsx");
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 浙期-导出客户基本信息、人员信息、银行信息到一个xlsx中
|
|
/// </summary>
|
|
/// <param name="req"></param>
|
|
/// <returns></returns>
|
|
public object ExportClientAll(ClientReq req)
|
|
{
|
|
req.ValueDate = valuedateBLL.ValueDate;
|
|
|
|
req.CheckContactExpired = true;
|
|
req.CurUserClientIds = CurUser.GetClientIdsByCustomerManager();
|
|
var service = new ClientQueryService(CurUser);
|
|
var sList = service.SearchList(req);
|
|
var appropriatenessAssessors = RoleRight.GetSystemUserByFunction("担任适当性评估人");
|
|
var salesDic = new Lazy<Dictionary<int, string>>(() =>
|
|
{
|
|
return yldb.salesmen.Select(n => new { n.id, n.Name }).ToDictionary(n => n.id, m => m.Name);
|
|
});
|
|
foreach (var x in sList.rows)
|
|
{
|
|
if (AppHelper.UseFutureVersion("销售提成", "V2"))
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(x.Seller))
|
|
{
|
|
var tempArray = x.Seller.Split(',');
|
|
var SalesmenNames = new List<string>();
|
|
foreach (var item in tempArray)
|
|
{
|
|
if (int.TryParse(item, out var id) && id > 0
|
|
&& salesDic.Value.TryGetValue(id, out var name) && !string.IsNullOrWhiteSpace(name))
|
|
{
|
|
SalesmenNames.Add(name);
|
|
}
|
|
}
|
|
if (SalesmenNames != null && SalesmenNames.Any())
|
|
{
|
|
x.Seller = string.Join(",", SalesmenNames);
|
|
}
|
|
}
|
|
}
|
|
else if (!string.IsNullOrEmpty(x.Seller))
|
|
{
|
|
var tempArray = new List<int>();
|
|
if (x.Seller.Contains(","))
|
|
{
|
|
tempArray = x.Seller.Split(',').Select(a => Convert.ToInt32(a)).ToList();
|
|
}
|
|
else
|
|
{
|
|
if (int.TryParse(x.Seller, out var a))
|
|
{
|
|
tempArray.Add(Convert.ToInt32(x.Seller));
|
|
|
|
}
|
|
}
|
|
if (tempArray.Any())
|
|
{
|
|
var salesmanNames = new SalesmenDataService(CurUser).GetSalesNamesByIds(tempArray).Select(o => o.Name);
|
|
if (salesmanNames.Any())
|
|
{
|
|
x.Seller = string.Join(",", salesmanNames);
|
|
}
|
|
}
|
|
|
|
}
|
|
if (x.SalesDepartmentId == null)
|
|
{
|
|
x.SalesDepartment = "";
|
|
}
|
|
else
|
|
{
|
|
var department = DepartmentsController.GetDepartmentById(x.SalesDepartmentId.Value);
|
|
x.SalesDepartment = department == null ? "" : department.Name;
|
|
}
|
|
|
|
x.AppropriatenessAssessorName = appropriatenessAssessors.Where(y => y.Id == x.AppropriatenessAssessor).FirstOrDefault() == null ? "" : appropriatenessAssessors.Where(y => y.Id == x.AppropriatenessAssessor).FirstOrDefault().Name;
|
|
if (!string.IsNullOrEmpty(x.CustomerManagerId))
|
|
{
|
|
if (x.CustomerManagerId.Contains(","))
|
|
{
|
|
var managerNames = new List<string>();
|
|
var CustomerManagerIds = x.CustomerManagerId.Split(',').ToList();
|
|
CustomerManagerIds.ForEach(a =>
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(a));
|
|
if (manager != null)
|
|
{
|
|
managerNames.Add(manager.Name);
|
|
}
|
|
});
|
|
x.CustomerManager = managerNames.Any() ? string.Join(",", managerNames) : string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(x.CustomerManagerId));
|
|
x.CustomerManager = manager == null ? "" : manager.Name;
|
|
}
|
|
}
|
|
|
|
|
|
var deadLine = ClientLinqExtendService.GetEvaluateDate(x.EvaluateDate, x.EvaluateOfValidity);
|
|
x.AssessmentExpired = deadLine.Date <= DateTime.Now.Date;
|
|
x.AssessmentExpiredWithinThreeDays = deadLine > DateTime.Now.Date && deadLine.Date <= DateTime.Now.Date.AddDays(30).Date;
|
|
x.AssessmentExpiredDate = deadLine.ToString("yyyy-MM-dd");
|
|
x.HasDocuments = new ClientFileService(CurUser).hasDocments(x.id);
|
|
}
|
|
|
|
|
|
var colList = ClientEditConfigService.GetClientList();
|
|
var bytes = new ClientDataService(CurUser).exprotClientAllExcel(sList.rows.ToList(), colList);
|
|
return File(bytes, xlsxMimeType, $"客户信息合并表_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
|
|
}
|
|
|
|
public JsonResult GetClientById(int? clientId)
|
|
{
|
|
var client = DataCacheProvider.GetClientDataSource().GetData(clientId ?? 0);
|
|
if (client == null)
|
|
{
|
|
return JsonError("没有客户信息");
|
|
}
|
|
return JsonSuccessData(client);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取客户状态
|
|
/// </summary>
|
|
[HttpPost]
|
|
public JsonResult GetClientStatus(int? clientId)
|
|
{
|
|
var client = DataCacheProvider.GetClientDataSource().GetData(clientId ?? 0);
|
|
if (client == null)
|
|
{
|
|
return JsonSuccess("");
|
|
}
|
|
return JsonSuccessData(client?.ProcessStatus);
|
|
}
|
|
|
|
[MyAuthorize("结算管理-追加预付金报告")]
|
|
public ActionResult ClientPaymentList()
|
|
{
|
|
ViewBag.valueDate = EodOperationBase.GetLastSettlementDate(valuedateBLL.ValueDate).ToString("yyyy-MM-dd"); // valuedateBLL.ValueDate.ToString("yyyy-MM-dd");
|
|
return View();
|
|
}
|
|
|
|
/// <summary>
|
|
///客户操作历史记录
|
|
/// </summary>
|
|
public ActionResult ClientOperationHistory(int id)
|
|
{
|
|
var dates = clientDB.ClientAuditLog.Where(c => c.ClientId == id)
|
|
.Select(n => new ClientAuditLogDto
|
|
{
|
|
id = n.id,
|
|
OptType = n.OptType,
|
|
Changes = n.Changes,
|
|
DataType = n.DataType,
|
|
OptName = n.OptName,
|
|
OptDate = n.OptDate
|
|
})
|
|
.OrderByDescending(d => d.id).ToArray();
|
|
|
|
foreach (var a in dates)
|
|
{
|
|
if (!string.IsNullOrEmpty(a.Changes) && (a.OptType == "编辑客户" || a.OptType == "编辑客户人员" || a.OptType == "编辑银行卡"))
|
|
{
|
|
var changeList = JsonHelper.Deserialize<List<List<string>>>(a.Changes);
|
|
if (changeList != null && changeList.Count > 0)
|
|
{
|
|
changeList = ClientDataChangeLogHandle.Handle(a.OptType, changeList);
|
|
a.Changes = changeList.ToJson();
|
|
}
|
|
}
|
|
a.Changes = (a.OptType == "编辑银行卡" || a.OptType == "编辑客户" || a.OptType == "编辑产品投资人" || a.OptType == "编辑客户人员" || a.OptType == "上传文件" || a.OptType == "修改上传文件" || a.OptType == "删除人员信息" || a.OptType == "销户" || a.OptType == "删除文件") ?
|
|
new DatatraceQueryService(CurUser).ReplaceDataChanges(new Client(), a.Changes) : "";
|
|
}
|
|
return View(dates);
|
|
}
|
|
|
|
/// <summary>
|
|
///客户操作历史记录--历史评估记录
|
|
/// </summary>
|
|
public ActionResult ClientAssessmentHistoryLog(int id)
|
|
{
|
|
var dates = clientDB.ClientAuditLog.Where(c => c.ClientId == id && c.OptType == "评估记录").OrderByDescending(d => d.id).ToList();
|
|
var list = new List<ClientAssessmentLogModel>();
|
|
if (dates != null && dates.Count > 0)
|
|
{
|
|
dates.ForEach(t =>
|
|
{
|
|
list.Add(JsonHelper.ToObject<ClientAssessmentLogModel>(t.Changes));
|
|
});
|
|
}
|
|
return View(list);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询客户信息
|
|
/// </summary>
|
|
[HttpPost]
|
|
[MyAuthorize("客户管理-客户查看")]
|
|
public JsonResult ClientQuery(ClientReq req)
|
|
{
|
|
req.ValueDate = valuedateBLL.ValueDate;
|
|
req.CheckContactExpired = true;
|
|
req.CurUserClientIds = CurUser.GetClientIdsByCustomerManager();
|
|
var service = new ClientQueryService(CurUser);
|
|
var sList = service.SearchList(req);
|
|
var appropriatenessAssessors = RoleRight.GetSystemUserByFunction("担任适当性评估人");
|
|
var salesDic = new Lazy<Dictionary<int, string>>(() =>
|
|
{
|
|
return yldb.salesmen.Select(n => new { n.id, n.Name }).ToDictionary(n => n.id, m => m.Name);
|
|
});
|
|
Dictionary<int, List<TagDto>> clientTagList = null;
|
|
if (sList != null && sList.rows != null && sList.rows.Any())
|
|
{
|
|
using var tagService = new TagService(CurUser);
|
|
clientTagList = tagService.GetTagByClientIds(sList.rows.Select(p => p.id).Distinct().ToList());
|
|
}
|
|
clientTagList ??= new Dictionary<int, List<TagDto>>();
|
|
foreach (var x in sList.rows)
|
|
{
|
|
if (AppHelper.UseFutureVersion("销售提成", "V2"))
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(x.Seller))
|
|
{
|
|
var tempArray = x.Seller.Split(',');
|
|
var SalesmenNames = new List<string>();
|
|
foreach (var item in tempArray)
|
|
{
|
|
if (int.TryParse(item, out var id) && id > 0
|
|
&& salesDic.Value.TryGetValue(id, out var name) && !string.IsNullOrWhiteSpace(name))
|
|
{
|
|
SalesmenNames.Add(name);
|
|
}
|
|
}
|
|
if (SalesmenNames != null && SalesmenNames.Any())
|
|
{
|
|
x.Seller = string.Join(",", SalesmenNames);
|
|
}
|
|
}
|
|
}
|
|
else if (!string.IsNullOrEmpty(x.Seller))
|
|
{
|
|
var tempArray = new List<int>();
|
|
if (x.Seller.Contains(","))
|
|
{
|
|
tempArray = x.Seller.Split(',').Select(a => Convert.ToInt32(a)).ToList();
|
|
}
|
|
else
|
|
{
|
|
if (int.TryParse(x.Seller, out var a))
|
|
{
|
|
tempArray.Add(Convert.ToInt32(x.Seller));
|
|
|
|
}
|
|
}
|
|
if (tempArray.Any())
|
|
{
|
|
var salesmanNames = new SalesmenDataService(CurUser).GetSalesNamesByIds(tempArray).Select(o => o.Name);
|
|
if (salesmanNames.Any())
|
|
{
|
|
x.Seller = string.Join(",", salesmanNames);
|
|
}
|
|
}
|
|
|
|
}
|
|
if (x.SalesDepartmentId == null)
|
|
{
|
|
x.SalesDepartment = "";
|
|
}
|
|
else
|
|
{
|
|
var department = DepartmentsController.GetDepartmentById(x.SalesDepartmentId.Value);
|
|
x.SalesDepartment = department == null ? "" : department.Name;
|
|
}
|
|
|
|
x.AppropriatenessAssessorName = appropriatenessAssessors.Where(y => y.Id == x.AppropriatenessAssessor).FirstOrDefault() == null ? "" : appropriatenessAssessors.Where(y => y.Id == x.AppropriatenessAssessor).FirstOrDefault().Name;
|
|
|
|
if (!PS.Config.Is格林大华)
|
|
{
|
|
if (!string.IsNullOrEmpty(x.CustomerManagerId))
|
|
{
|
|
if (x.CustomerManagerId.Contains(","))
|
|
{
|
|
var managerNames = new List<string>();
|
|
var CustomerManagerIds = x.CustomerManagerId.Split(',').ToList();
|
|
CustomerManagerIds.ForEach(a =>
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(a));
|
|
if (manager != null)
|
|
{
|
|
managerNames.Add(manager.Name);
|
|
}
|
|
});
|
|
x.CustomerManager = managerNames.Any() ? string.Join(",", managerNames) : string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(x.CustomerManagerId));
|
|
x.CustomerManager = manager == null ? "" : manager.Name;
|
|
}
|
|
}
|
|
}
|
|
|
|
var deadLine = ClientLinqExtendService.GetEvaluateDate(x.EvaluateDate, x.EvaluateOfValidity);
|
|
x.AssessmentExpired = deadLine.Date <= DateTime.Now.Date;
|
|
x.AssessmentExpiredWithinThreeDays = deadLine > DateTime.Now.Date && deadLine.Date <= DateTime.Now.Date.AddDays(30).Date;
|
|
x.AssessmentExpiredDate = deadLine.ToString("yyyy-MM-dd");
|
|
|
|
|
|
//var clientPath = $"{x.id}_{x.Name}";
|
|
//var filePath = Server.MapPath($"~/App_Docs/ClientFiles/{clientPath}");
|
|
//var fileSuitablyFilesPath = Server.MapPath($"~/App_Docs/ClientFiles/SuitablyFiles/{clientPath}");
|
|
//var fileNames = new List<string>();
|
|
//if (Directory.Exists(filePath))
|
|
//{
|
|
// fileNames.AddRange(Directory.EnumerateFiles(filePath).Select(y => Path.GetFileName(y)).ToList());
|
|
//}
|
|
|
|
//if (Directory.Exists(fileSuitablyFilesPath))
|
|
//{
|
|
// fileNames.AddRange(Directory.EnumerateFiles(fileSuitablyFilesPath).Select(y => Path.GetFileName(y)).ToList());
|
|
//}
|
|
//暂时解决东吴生产问题(适当性评级需优化)
|
|
// if (PS.Config.Is东吴)
|
|
// {
|
|
// x.AppropriatenessDegree = x.AppropriatenessDegree + 1;
|
|
// }
|
|
x.HasDocuments = new ClientFileService(CurUser).hasDocments(x.id);
|
|
|
|
//拼装标签值
|
|
if (clientTagList.ContainsKey(x.id))
|
|
{
|
|
x.Tags = clientTagList[x.id];
|
|
x.OutputTags = TagService.GetOutputTagsStr(x.Tags);
|
|
}
|
|
}
|
|
|
|
return Json(sList);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 导出客户列表
|
|
/// </summary>
|
|
[ResponseCache(NoStore = true)]
|
|
public ActionResult ClientListExport(ClientReq req)
|
|
{
|
|
var list = ((SearchListResult<ClientLinq>)ClientQuery(req).Value).rows;
|
|
var templateFilePath = Server.MapPath("~/App_Docs/导出模板/客户信息列表.xlsx");
|
|
var dicList = list.Select(n => ExpandoDictionary.ConvertObject(n, (pname, pvalue) =>
|
|
{
|
|
switch (pname)
|
|
{
|
|
case nameof(ClientLinq.IsIndustryConnectVariety): //行业标的相关
|
|
case nameof(ClientLinq.IsRealControl): //实际控制关系
|
|
case nameof(ClientLinq.IsEvaluate): //是否评估
|
|
case nameof(ClientLinq.IsRequireConversionTypes): //转化类型
|
|
case nameof(ClientLinq.IsAssessmentResultChange): //评估结果变动
|
|
case nameof(ClientLinq.IsTradeCredit): //期权费授信
|
|
case nameof(ClientLinq.PendingMarginCallPayment): //是否需要追保
|
|
return pvalue?.ToString() == "1" ? "是" : "否";
|
|
}
|
|
return pvalue?.ToString() ?? string.Empty;
|
|
}));
|
|
using var generator = Office.ExcelModule.ExcelGenerator.UseTemplateGenerator(templateFilePath).
|
|
AddVariable(new { list = dicList });
|
|
return File(generator.GenerateBytes(), "application/vnd.ms-excel", "客户信息列表_" + DateTime.Today.ToString("yyyy-MM-dd") + ".xlsx");
|
|
}
|
|
|
|
[HttpPost]
|
|
public JsonResult ClientBanlanceQuery(ClientReq req)
|
|
{
|
|
if (req.sidx != "Number")
|
|
{
|
|
req.sidx = null;
|
|
}
|
|
if (!req.ValueDate.HasValue)
|
|
{
|
|
req.ValueDate = valuedateBLL.ValueDate;
|
|
}
|
|
req.rows = 100000;
|
|
|
|
var curUser = CurUser;
|
|
req.CurUserClientIds = CurUser.GetClientIdsByCurUser(true);
|
|
var clientService = new ClientQueryService(curUser);
|
|
var predicate = clientService.CreatePredicate(req);
|
|
var clientList = clientService.GetClientListByWhere(predicate);
|
|
var task1 = Task.Run(() => clientService.SearchList(req, predicate));
|
|
var task2 = Task.Run(() =>
|
|
{
|
|
var clientIds = clientList.Select(O => O.id).ToList();
|
|
return ClientBalanceUtility.GetClientRiskMonitorForShanXiGuShou(clientIds, req.ValueDate.Value, req.MarginShownType);
|
|
});
|
|
Task.WaitAll(task1, task2);
|
|
|
|
var sList = task1.Result;
|
|
var banlanceList = task2.Result ?? Array.Empty<ClientSettleBalance>();
|
|
|
|
//var sList = new ClientQueryService(curUser).SearchList(req, predicate);
|
|
//var clientIds = clientList.Select(O => O.id).ToList();
|
|
//var banlanceList = ClientBalanceUtility.GetClientRiskMonitor(clientIds, req.ValueDate.Value, req.MarginShownType) ?? Array.Empty<ClientSettleBalance>();
|
|
//var creditExposureDict = new Dictionary<string, double?>();
|
|
//var ratioDict = new Dictionary<int, double?>();
|
|
|
|
|
|
|
|
|
|
var set = sList.rows.Select(n => n.id).ToHashSet();
|
|
var allList = banlanceList.Where(n => set.Add(n.ClientId)).Select(n => new ClientLinq { id = n.ClientId }).Concat(sList.rows).ToArray();
|
|
var banlanceDic = banlanceList.ToDictionary(n => n.ClientId);
|
|
var salesDic = new Lazy<Dictionary<int, string>>(() =>
|
|
{
|
|
return yldb.salesmen.Select(n => new { n.id, n.Name }).ToDictionary(n => n.id, m => m.Name);
|
|
});
|
|
var RegisteredCapitalDict = new ClientMetaService(CurUser).GetMeta(req.CurUserClientIds, "RegisteredCapital");
|
|
//上市
|
|
var listedCorpDict = new ClientMetaService(CurUser).GetMeta(req.CurUserClientIds, "listedCorp");
|
|
//小微
|
|
var microCorpDict = new ClientMetaService(CurUser).GetMeta(req.CurUserClientIds, "microCorp");
|
|
Dictionary<int, List<TagDto>> clientTagList = null;
|
|
if (allList != null && allList.Any())
|
|
{
|
|
using var tagService = new TagService(CurUser);
|
|
clientTagList = tagService.GetTagByClientIds(allList.Select(p => p.id).Distinct().ToList());
|
|
}
|
|
clientTagList ??= new Dictionary<int, List<TagDto>>();
|
|
|
|
foreach (var x in allList)
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(x.Seller))
|
|
{
|
|
var tempArray = x.Seller.Split(',');
|
|
var SalesmenNames = new List<string>();
|
|
foreach (var item in tempArray)
|
|
{
|
|
if (int.TryParse(item, out var id) && id > 0
|
|
&& salesDic.Value.TryGetValue(id, out var name) && !string.IsNullOrWhiteSpace(name))
|
|
{
|
|
SalesmenNames.Add(name);
|
|
}
|
|
}
|
|
if (SalesmenNames != null && SalesmenNames.Any())
|
|
{
|
|
x.Seller = string.Join(",", SalesmenNames);
|
|
}
|
|
}
|
|
if (x.CustomerNature > 0)
|
|
{
|
|
x.CustomerNatureName = ((CustomerNatureEnum)x.CustomerNature.Value).ToString();
|
|
}
|
|
if (x.SalesDepartmentId == null)
|
|
{
|
|
x.SalesDepartment = string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var department = DepartmentsController.GetDepartmentById(x.SalesDepartmentId.Value);
|
|
x.SalesDepartment = department?.Name ?? string.Empty;
|
|
}
|
|
|
|
banlanceDic.TryGetValue(x.id, out var clientBalance);
|
|
var client = DataCacheProvider.GetClientDataSource().GetData(x.id);
|
|
clientBalance ??= new ClientSettleBalance { ClientId = x.id };
|
|
x.TransactionPenNumber = clientBalance.TradeCount;
|
|
x.SellNominalPrincipalOfTransaction = clientBalance.SellNotionalPrincipal;
|
|
x.BuyNominalPrincipalOfTransaction = clientBalance.BuyNotionalPrincipal;
|
|
x.CurrentHoldingPenNumber = clientBalance.PositionCount;
|
|
x.HoldingDeposit = -clientBalance.PayableMargin;
|
|
x.HoldingDepositA = -clientBalance.PayableMarginA;
|
|
x.HoldingDepositB = -clientBalance.PayableMarginB;
|
|
x.SwapPayableMargin = -clientBalance.SwapPayableMargin;
|
|
x.AvailableAmount = clientBalance.AvailableAmount;
|
|
x.InsuredAmount = clientBalance.MarginByPayableMarginTotal;
|
|
x.MarginMonitoringTime = clientBalance.UpdateDate ?? DateTime.Now;
|
|
x.FreezePremium = clientBalance.FreezePremium;
|
|
x.ReceivablesPremium = clientBalance.ReceivablesPremium;
|
|
x.AdvisableMargin = clientBalance.AdvisableMargin;
|
|
x.MarginBalance = clientBalance.MarginBalance;
|
|
x.PotentialSurpluses = clientBalance.PotentialSurpluses;
|
|
x.TotalCredit = clientBalance.TotalCredit;
|
|
x.CreditUsed = clientBalance.CreditUsed;
|
|
x.OptionPremium = clientBalance.OptionPremium;
|
|
x.OptionPremiumSwap = clientBalance.OptionPremiumSwap;
|
|
x.SettlementBalance = clientBalance.SettlementBalance;
|
|
x.TodayNewMargin = clientBalance.TodayNewMargin;
|
|
x.GuaranteesTotalAmount = clientBalance.GuaranteesTotalAmount;
|
|
x.FreezingGuaranteesTotalAmount =
|
|
Math.Min(Math.Abs(Math.Min((x.AvailableAmount ?? 0) - (x.GuaranteesTotalAmount ?? 0), 0)), x.GuaranteesTotalAmount ?? 0);
|
|
x.AmountFund = clientBalance.AmountFund;
|
|
x.AmountFundWithProduct = clientBalance.AmountFundWithProduct;
|
|
x.TotalAmount = clientBalance.SwapMarketAmount;
|
|
x.RoundedTotalAmount = clientBalance.RoundedTotalAmount;
|
|
x.TotalTradeCount = clientBalance.TotalTradeCount;
|
|
x.BuyCount = clientBalance.BuyCount;
|
|
x.SellCount = clientBalance.SellCount;
|
|
x.TotalNotionalPrincipal = clientBalance.TotalNotionalPrincipal;
|
|
x.TodayNotionalPrincipal = clientBalance.TodayNotionalPrincipal;
|
|
x.PositionNotionalPrincipal = clientBalance.PositionNotionalPrincipal;
|
|
x.DaliyPnl = clientBalance.DaliyPnl;
|
|
x.RoundedDaliyPnl = clientBalance.RoundedDaliyPnl;
|
|
x.PositionPnl = clientBalance.PositionPnl;
|
|
x.RoundedPositionPnl = clientBalance.RoundedPositionPnl;
|
|
x.WinLoss = clientBalance.WinLoss;
|
|
x.PositionPremiumNetCash = clientBalance.PositionPremiumNetCash;
|
|
x.PositionPv = clientBalance.PositionPv;
|
|
x.RoundedPositionPv = clientBalance.RoundedPositionPv;
|
|
x.PrepaymentAmount = clientBalance.PrepaymentAmount;
|
|
x.FrozenMarginMoney = clientBalance.FrozenMarginMoney;
|
|
x.NetFund = clientBalance.NetFund;
|
|
x.NetFundAll = clientBalance.NetFundAll;
|
|
x.VmFundSum = clientBalance.VmFundSum;
|
|
x.OtherFund = clientBalance.OtherFund;
|
|
x.Coupon = clientBalance.Coupon;
|
|
x.SwapBalance = clientBalance.SwapBalance;
|
|
x.PayableMargin = clientBalance.PayableMargin;
|
|
x.TwoSideMargin = clientBalance.TwoSideMargin;
|
|
x.OtherSideMargin = -clientBalance.OtherSideMargin;
|
|
x.MySideMargin = clientBalance.MySideMargin;
|
|
x.DeltaMargin = -clientBalance.DeltaMargin;
|
|
x.IsPayableMarginManual = clientBalance?.IsPayableMarginManual;
|
|
x.AvailableAmount = clientBalance.AvailableAmount;
|
|
x.MarginByPayableMargin = clientBalance.MarginByPayableMargin;
|
|
x.ClosedTradePayableFund = clientBalance.ClosedTradePayableFund;
|
|
x.PositionTradePayableFund = clientBalance.PositionTradePayableFund;
|
|
x.PayableFund = clientBalance.PayableFund;
|
|
x.DesirableFund = clientBalance.DesirableFund;
|
|
x.CreditUsedValue = clientBalance.CreditUsed * clientBalance.TotalCredit;
|
|
x.BuyerPositionMargin = clientBalance.BuyerPositionMargin;
|
|
x.SellerPositionPremium = clientBalance.SellerPositionPremium;
|
|
x.ShouldCharged = x.BuyerPositionMargin + x.SellerPositionPremium;
|
|
x.AvailableStockEqvNotional = clientBalance.AvailableStockEqvNotional.Normalize();
|
|
x.PFE = clientBalance.PFE;
|
|
x.EndDesirableFund = x.NetFund + x.SettlementBalance + clientBalance.EndPremiumSum;
|
|
x.SwapMarketAmount= clientBalance.SwapMarketAmount;
|
|
x.SwapMarketAmountPercent=clientBalance.SwapMarketAmountPercent;
|
|
x.MaintenanceMargin=clientBalance.MaintenanceMargin;
|
|
x.NeedAddMargin=clientBalance.NeedAddMargin;
|
|
x.LastDayRemainFund=clientBalance.LastDayRemainFund;
|
|
if (clientBalance.MarginOccupation == 0)
|
|
{
|
|
x.WorstCastClientPayableRatio = 10000;
|
|
}
|
|
else
|
|
{
|
|
x.WorstCastClientPayableRatio = (x.MarginBalance / clientBalance.MarginOccupation) ?? 0;
|
|
}
|
|
x.clientEquity = (x.AmountFund + x.PositionPv) ?? 0;
|
|
x.licenseCodes = client.LicenseCode;
|
|
//是否小微
|
|
if (microCorpDict.ContainsKey(client.id))
|
|
{
|
|
x.IsSmallAndMicroEnterpriseas = microCorpDict.TryGetValue(client.id, out var microCorp) ? microCorp : "";
|
|
}
|
|
//是否上市
|
|
if (listedCorpDict.ContainsKey(client.id))
|
|
{
|
|
x.IsmicroCorp = listedCorpDict.TryGetValue(client.id, out var listedCorp) ? listedCorp : "";
|
|
}
|
|
|
|
|
|
|
|
x.LastDayPositionPremiumNetCashs = -(clientBalance.PositionPremiumNetCash); //GetMeta
|
|
if (RegisteredCapitalDict.ContainsKey(client.id))
|
|
{
|
|
x.NetFundSum = double.TryParse(RegisteredCapitalDict[client.id], out var registeredCapital) ? registeredCapital : registeredCapital;
|
|
}
|
|
x.availableNetFundSums = (clientBalance.PositionNotionalPrincipal / x.NetFundSum);
|
|
x.EAD = clientBalance.EAD;
|
|
var clientName = client?.Name ?? "";
|
|
x.MinimumTransferAmount = client?.MinimumTransferAmount;
|
|
|
|
x.LastHTSettlemetTime = clientBalance.LastHTSettlemetTime;
|
|
x.LastSettlemetTime = clientBalance.LastSettlemetTime;
|
|
x.InterestPnl = clientBalance.InterestPnl;
|
|
x.TradeFee = clientBalance.TradeFee;
|
|
|
|
//拼装标签值
|
|
if (clientTagList.ContainsKey(x.id))
|
|
{
|
|
x.Tags = clientTagList[x.id];
|
|
x.OutputTags = TagService.GetOutputTagsStr(x.Tags);
|
|
}
|
|
}
|
|
|
|
|
|
var sList2 = new SearchListResult<ClientLinq>();
|
|
|
|
//获取根据系统时间
|
|
var lastBalanceDate = EodOperationBase.GetLastSettlementDate(DateTime.Now.Date);
|
|
//系统交易日
|
|
var valuedate = valuedateBLL.ValueDate;
|
|
//获取根据系统时间
|
|
if (valuedate <= lastBalanceDate || yldb.eodStatus.FirstOrDefault(n => n.ValueDate == req.ValueDate)?.Status != "已收盘")
|
|
{
|
|
var clientIdsList = new List<int>();
|
|
|
|
if (req.HaveMarginAmount || req.HavePayableFund || req.HavePosition || req.HaveClosedPayableFund || req.HaveTotalAsset)
|
|
{
|
|
if (req.HaveMarginAmount)
|
|
{
|
|
clientIdsList.AddRange(allList.Where(n => Math.Abs(n.InsuredAmount ?? 0) > 1e-4).Select(n => n.id).ToList());
|
|
}
|
|
|
|
if (req.HavePayableFund)
|
|
{
|
|
clientIdsList.AddRange(allList.Where(n => Math.Abs(n.PayableFund) > 1e-4).Select(n => n.id).ToList());
|
|
}
|
|
|
|
if (req.HavePosition)
|
|
{
|
|
clientIdsList.AddRange(yldb.intraday_trade_position.Where(n => n.ValueDate == req.ValueDate && n.TradeStatus == "确认成交").Distinct().Select(n => n.ClientId).ToList());
|
|
}
|
|
|
|
if (req.HaveClosedPayableFund)
|
|
{
|
|
clientIdsList.AddRange(allList.Where(n => Math.Abs(n.ClosedTradePayableFund) > 1e-4).Select(n => n.id).ToList());
|
|
}
|
|
|
|
if (req.HaveTotalAsset)
|
|
{
|
|
clientIdsList.AddRange(allList.Where(n => n.RoundedTotalAmount > 1).Select(n => n.id).ToList());
|
|
}
|
|
|
|
var allList2 = allList.Where(n => clientIdsList.Contains(n.id)).ToArray();
|
|
|
|
sList2.rows = sList.rows.Where(n => clientIdsList.Contains(n.id)).ToArray();
|
|
sList2.total = 1;
|
|
sList2.page = 1;
|
|
sList2.records = sList2.rows.Count();
|
|
sList2.Sum = SumHelper.CalculateSums(allList2);
|
|
return Json(sList2);
|
|
}
|
|
}
|
|
sList.Sum = SumHelper.CalculateSums(allList);
|
|
|
|
|
|
return Json(sList);
|
|
}
|
|
|
|
private Dictionary<int, List<ClientBalanceDaily>> GetClientBanlance(ClientReq req)
|
|
{
|
|
Dictionary<int, List<ClientBalanceDaily>> dict = null;
|
|
using (var dbContext = new YLContext())
|
|
{
|
|
var query = dbContext.ClientBalanceDaily.AsNoTracking().Where(daily => daily.BalanceDate >= req.StartDate && daily.BalanceDate <= req.ValueDate);
|
|
if (req.ClientIds != null && req.ClientIds.Any(n => n > 0))
|
|
{
|
|
query = query.Where(O => req.ClientIds.Contains(O.ClientId));
|
|
}
|
|
dict = query.AsEnumerable().GroupBy(O => O.ClientId).ToDictionary(K => K.Key, V => V.ToList());
|
|
}
|
|
return dict;
|
|
}
|
|
|
|
public ActionResult ClientBanlanceExport(ClientReq req)
|
|
{
|
|
object obj = null;
|
|
string targetFileName = null;
|
|
var sourceFileName = OtcAppContext.MapPath("~/App_Docs/导出模板/");
|
|
if (req.StartDate == null || req.StartDate == req.ValueDate)
|
|
{
|
|
var temp = Path.Combine(sourceFileName, $"资金监控模板1.xlsx");
|
|
sourceFileName = temp;
|
|
var searchList = ClientBanlanceQuery(req).Value as SearchListResult<ClientLinq>;
|
|
//模板绑定值,处理四舍五入配置
|
|
foreach (var c in searchList.rows)
|
|
{
|
|
if (PS.Config.IsPVRounded)
|
|
{
|
|
c.PositionPv = c.RoundedPositionPv;
|
|
c.PositionPnl = c.RoundedPositionPnl;
|
|
c.TotalAmount = c.RoundedTotalAmount;
|
|
c.DaliyPnl = c.RoundedDaliyPnl;
|
|
}
|
|
}
|
|
|
|
var pairs = searchList.Sum as Dictionary<string, object>;
|
|
obj = new
|
|
{
|
|
TotalTradeCountSum = pairs["TotalTradeCountSum"],
|
|
TotalNotionalPrincipalSum = pairs["TotalNotionalPrincipalSum"],
|
|
TransactionPenNumberSum = pairs["TransactionPenNumberSum"],
|
|
TodayNotionalPrincipalSum = pairs["TodayNotionalPrincipalSum"],
|
|
PositionNotionalPrincipalSum = pairs["PositionNotionalPrincipalSum"],
|
|
CurrentHoldingPenNumberSum = pairs["CurrentHoldingPenNumberSum"],
|
|
WinLossSum = pairs["WinLossSum"],
|
|
PositionPvSum = PS.Config.IsPVRounded ? pairs["RoundedPositionPvSum"] : pairs["PositionPvSum"],
|
|
PositionPnlSum = PS.Config.IsPVRounded ? pairs["RoundedPositionPnlSum"] : pairs["PositionPnlSum"],
|
|
LastDayRemainFundSum = pairs["LastDayRemainFundSum"],
|
|
NetFundSum = pairs["NetFundSum"],
|
|
NetFundAllSum = pairs["NetFundAllSum"],
|
|
OtherFundSum = pairs["OtherFundSum"],
|
|
AmountFundSum = pairs["AmountFundSum"],
|
|
AvailableAmountSum = pairs["AvailableAmountSum"],
|
|
InsuredAmountSum = pairs["InsuredAmountSum"],
|
|
DesirableFundSum = pairs["DesirableFundSum"],
|
|
MySideMarginSum = pairs["MySideMarginSum"],
|
|
VmFundSumSum = pairs["VmFundSumSum"],
|
|
MaintenanceMarginSum = pairs["MaintenanceMarginSum"],
|
|
SwapMarketAmountSum = pairs["SwapMarketAmountSum"],
|
|
InterestPnlSum=pairs["InterestPnlSum"],
|
|
TradeFeeSum=pairs["TradeFeeSum"],
|
|
InfoList = searchList.rows
|
|
};
|
|
|
|
targetFileName = $"资金监控_{req.ValueDate:yyyyMMdd}.xlsx";
|
|
}
|
|
else
|
|
{
|
|
sourceFileName = Path.Combine(sourceFileName, "资金监控模板2.xlsx");
|
|
var startDate = req.StartDate;
|
|
req.StartDate = valuedateBLL.GetNonHolidayDefore(req.StartDate.Value.AddDays(-1));
|
|
req.CurUserClientIds = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易);
|
|
var sList = new ClientQueryService(CurUser).SearchList(req);
|
|
req.ClientIds = sList.rows.Select(O => O.id).ToList();
|
|
var dict = GetClientBanlance(req);
|
|
var objs = new List<object>();
|
|
foreach (var item in dict)
|
|
{
|
|
var maxDate = item.Value.Max(B => B.BalanceDate.Value);
|
|
var daily = item.Value.FirstOrDefault(O => O.BalanceDate.Value == req.StartDate);
|
|
var endObj = item.Value.First(O => O.BalanceDate.Value == maxDate);
|
|
var list = item.Value.Where(O => O.BalanceDate.Value != req.StartDate).ToList();
|
|
var toDayRemainFund = (daily?.ToDayRemainFund) ?? 0;
|
|
var startClientBalanceGap = new ClientBalanceGap();
|
|
var endClientBalanceGap = new ClientBalanceGap();
|
|
switch (req.MarginShownType)
|
|
{
|
|
case "default":
|
|
startClientBalanceGap = null;
|
|
endClientBalanceGap = null;
|
|
break;
|
|
case "ClientBalanceGap":
|
|
startClientBalanceGap = yldb.ClientBalanceGap.Where(o => o.ClientId == item.Key && o.ValueDate == req.StartDate && !o.IsImportOuterMargin).FirstOrDefault();
|
|
endClientBalanceGap = yldb.ClientBalanceGap.Where(o => o.ClientId == item.Key && o.ValueDate == maxDate && !o.IsImportOuterMargin).FirstOrDefault();
|
|
break;
|
|
case "GetOuterMargin":
|
|
startClientBalanceGap = yldb.ClientBalanceGap.Where(o => o.ClientId == item.Key && o.ValueDate == req.StartDate && o.IsImportOuterMargin).FirstOrDefault();
|
|
endClientBalanceGap = yldb.ClientBalanceGap.Where(o => o.ClientId == item.Key && o.ValueDate == maxDate && o.IsImportOuterMargin).FirstOrDefault();
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
objs.Add(new
|
|
{
|
|
Name = endObj.ClientName,
|
|
endObj.ClientNumber,
|
|
ToDayRemainFund = toDayRemainFund + (startClientBalanceGap == null ? 0 : startClientBalanceGap.ToDayRemainFund ?? 0),
|
|
InFund = list.Sum(O => O.InFund),
|
|
OutFund = list.Sum(O => O.OutFund),
|
|
OptionPremium = list.Sum(O => O.OptionPremium) + (endClientBalanceGap == null ? 0 : endClientBalanceGap.OptionPremium ?? 0),
|
|
OptionPremiumSwap = list.Sum(O => O.OptionPremiumSwap) + (endClientBalanceGap == null ? 0 : endClientBalanceGap.OptionPremiumSwap ?? 0),
|
|
SettlementBalance = list.Sum(O => O.SettlementBalance) + (endClientBalanceGap == null ? 0 : endClientBalanceGap.SettlementBalance ?? 0),
|
|
OtherFund = list.Sum(O => O.OtherFund) + (endClientBalanceGap == null ? 0 : endClientBalanceGap.OtherFund ?? 0),
|
|
Coupon = list.Sum(O => O.Coupon) + (endClientBalanceGap == null ? 0 : endClientBalanceGap.Coupon ?? 0),
|
|
SwapBalance = list.Sum(O => O.SwapBalance) + (endClientBalanceGap == null ? 0 : endClientBalanceGap.SwapBalance ?? 0),
|
|
EndDayRemainFund = endObj.ToDayRemainFund + (endClientBalanceGap == null ? 0 : endClientBalanceGap.ToDayRemainFund ?? 0),
|
|
pnl = endObj.ToDayRemainFund + (endClientBalanceGap == null ? 0 : endClientBalanceGap.ToDayRemainFund ?? 0) -
|
|
(toDayRemainFund + (startClientBalanceGap == null ? 0 : startClientBalanceGap.ToDayRemainFund ?? 0))
|
|
});
|
|
}
|
|
obj = new { InfoList = objs };
|
|
targetFileName = $"资金监控_{startDate:yyyyMMdd}-{req.ValueDate:yyyyMMdd}.xlsx";
|
|
}
|
|
if (obj == null) { throw new Exception("查询出错!"); }
|
|
var fileDownloadName = $"资金监控_{DateTime.Now:yyyyMMdd}.xlsx";
|
|
var modleDict = new Dictionary<string, object>
|
|
{
|
|
["Sheet1"] = obj
|
|
};
|
|
|
|
var result = OtcAppContext.GetExportFileOutputPath(targetFileName);
|
|
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
|
|
new ExcelTemplateGenerator().SetTemplateFile(sourceFileName).SetTemplateData(modleDict).OutputToFile(result.PhysicalPath);
|
|
|
|
// 读取字节流
|
|
byte[] fileBytes = System.IO.File.ReadAllBytes(result.PhysicalPath);
|
|
|
|
// 删除临时文件
|
|
System.IO.File.Delete(result.PhysicalPath);
|
|
|
|
// 返回文件流
|
|
return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", targetFileName);
|
|
}
|
|
|
|
[HttpPost]
|
|
public JsonResult ClientOpeningProcessQuery(ClientReq req)
|
|
{
|
|
req.CurUserClientIds = CurUser.GetClientIdsByCustomerManager();
|
|
|
|
var sList = new ClientQueryService(CurUser).SearchOpeningProcessList(req);
|
|
var salesDic = new Lazy<Dictionary<int, string>>(() =>
|
|
{
|
|
return yldb.salesmen.Select(n => new { n.id, n.Name }).ToDictionary(n => n.id, m => m.Name);
|
|
});
|
|
var DerivativesInvestmentVarietiesDic = new Lazy<Dictionary<int, string>>(() =>
|
|
{
|
|
return ClientDataModel.GetAllDerivativesInvestmentVarieties().Select(n => new { n.Value, n.Text }).ToDictionary(n => int.Parse(n.Value), m => m.Text);
|
|
});
|
|
Dictionary<int, List<TagDto>> clientTagList = null;
|
|
if (sList != null && sList.rows != null && sList.rows.Any())
|
|
{
|
|
using var tagService = new TagService(CurUser);
|
|
clientTagList = tagService.GetTagByClientIds(sList.rows.Select(p => p.id).Distinct().ToList());
|
|
}
|
|
clientTagList ??= new Dictionary<int, List<TagDto>>();
|
|
foreach (var x in sList.rows)
|
|
{
|
|
x.TradingInstTypeName = DBModels.Enums.TradingInstTypeUtil.GetDesc(x.TradingInstType);
|
|
if (!string.IsNullOrWhiteSpace(x.DerivativesInvestmentVarieties))
|
|
{
|
|
var tempArray = x.DerivativesInvestmentVarieties.Split(',');
|
|
var DerivativesInvestmentVarietiesNames = new List<string>();
|
|
foreach (var item in tempArray)
|
|
{
|
|
if (int.TryParse(item, out var id) && id > 0
|
|
&& DerivativesInvestmentVarietiesDic.Value.TryGetValue(id, out var name) && !string.IsNullOrWhiteSpace(name))
|
|
{
|
|
DerivativesInvestmentVarietiesNames.Add(name);
|
|
}
|
|
}
|
|
if (DerivativesInvestmentVarietiesNames != null && DerivativesInvestmentVarietiesNames.Any())
|
|
{
|
|
x.DerivativesInvestmentVarieties = string.Join(",", DerivativesInvestmentVarietiesNames);
|
|
}
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(x.Seller))
|
|
{
|
|
var tempArray = x.Seller.Split(',');
|
|
var SalesmenNames = new List<string>();
|
|
foreach (var item in tempArray)
|
|
{
|
|
if (int.TryParse(item, out var id) && id > 0
|
|
&& salesDic.Value.TryGetValue(id, out var name) && !string.IsNullOrWhiteSpace(name))
|
|
{
|
|
SalesmenNames.Add(name);
|
|
}
|
|
}
|
|
if (SalesmenNames != null && SalesmenNames.Any())
|
|
{
|
|
x.Seller = string.Join(",", SalesmenNames);
|
|
}
|
|
}
|
|
x.CustomerNatureName = x.CustomerNature == null ? "" : Enum.Parse(typeof(CustomerNatureEnum), x.CustomerNature.Value.ToString()).ToString();
|
|
if (x.SalesDepartmentId == null)
|
|
{
|
|
x.SalesDepartment = "";
|
|
}
|
|
else
|
|
{
|
|
var department = DepartmentsController.GetDepartmentById(x.SalesDepartmentId.Value);
|
|
x.SalesDepartment = department == null ? "" : department.Name;
|
|
}
|
|
|
|
if (!PS.Config.Is格林大华)
|
|
{
|
|
if (!string.IsNullOrEmpty(x.CustomerManagerId))
|
|
{
|
|
if (x.CustomerManagerId.Contains(","))
|
|
{
|
|
var managerNames = new List<string>();
|
|
var CustomerManagerIds = x.CustomerManagerId.Split(',').ToList();
|
|
CustomerManagerIds.ForEach(a =>
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(a));
|
|
if (manager != null)
|
|
{
|
|
managerNames.Add(manager.Name);
|
|
}
|
|
});
|
|
x.CustomerManager = managerNames.Any() ? string.Join(",", managerNames) : string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(x.CustomerManagerId));
|
|
x.CustomerManager = manager == null ? "" : manager.Name;
|
|
}
|
|
}
|
|
}
|
|
|
|
//var clientPath = $"{x.id}_{x.Name}";
|
|
//var filePath = Server.MapPath($"~/App_Docs/ClientFiles/{clientPath}");
|
|
//var fileSuitablyFilesPath = Server.MapPath($"~/App_Docs/ClientFiles/SuitablyFiles/{clientPath}");
|
|
//var fileNames = new List<string>();
|
|
//if (Directory.Exists(filePath))
|
|
//{
|
|
// fileNames.AddRange(Directory.EnumerateFiles(filePath).Select(y => Path.GetFileName(y)).ToList());
|
|
//}
|
|
|
|
//if (Directory.Exists(fileSuitablyFilesPath))
|
|
//{
|
|
// fileNames.AddRange(Directory.EnumerateFiles(fileSuitablyFilesPath).Select(y => Path.GetFileName(y)).ToList());
|
|
//}
|
|
|
|
x.HasDocuments = new ClientFileService(CurUser).hasDocments(x.id);
|
|
//拼装标签值
|
|
if (clientTagList.ContainsKey(x.id))
|
|
{
|
|
x.Tags = clientTagList[x.id];
|
|
x.OutputTags = TagService.GetOutputTagsStr(x.Tags);
|
|
}
|
|
}
|
|
return Json(sList);
|
|
}
|
|
|
|
[HttpPost]
|
|
public JsonResult ClientPaymentListQuery(ClientReq req)
|
|
{
|
|
req.CurUserClientIds = CurUser.GetClientIdsByCurUser(true);
|
|
var sList = new ClientPaymentService(CurUser).SearchPaymentList(req);
|
|
var contractCodeList =
|
|
sList.rows.Select(p => $"{p.Number}_{p.ValueDate.Value:yyyyMMdd}").ToList();
|
|
var contractDocDic = yldb.trade_contract_document.Where(contract =>
|
|
contract.Type == ContractTypeEnum.Margin && contractCodeList.Contains(contract.Code)).ToDictionary(c => c.Code, c => c.RelativePath);
|
|
foreach (var p in sList.rows)
|
|
{
|
|
var key = $"{p.Number}_{p.ValueDate.Value:yyyyMMdd}";
|
|
if (contractDocDic.ContainsKey(key))
|
|
{
|
|
p.ContractUrl = contractDocDic[key];
|
|
}
|
|
}
|
|
return Json(sList);
|
|
}
|
|
|
|
public JsonResult GeneratePaymentDoc(DateTime? valueDate)
|
|
{
|
|
if (valueDate == null)
|
|
{
|
|
valueDate = valuedateBLL.ValueDate;
|
|
}
|
|
//追保确通知书模板路径
|
|
var docPath = PS.Config.ErpElement.DocPath;
|
|
if (docPath.IsNullOrWhiteSpace())
|
|
{
|
|
//docPath = "SYWG";
|
|
docPath = "导出模板";
|
|
}
|
|
var basePath = OtcAppContext.MapPath($"/App_Docs/contractdoc/output");
|
|
var sourcePath = OtcAppContext.MapPath($"/App_Docs/{docPath}");
|
|
var sourceFileName = Path.Combine(sourcePath, "商品期权追保通知书.xlsx");
|
|
var targetPath = Path.Combine(basePath, valueDate.Value.ToString("yyyyMMdd"));
|
|
if (!Directory.Exists(targetPath))
|
|
{
|
|
Directory.CreateDirectory(targetPath);
|
|
}
|
|
|
|
//只取追保状态为冻结
|
|
var clientDic = clientDB.client.Where(t => t.PendingMarginCallPayment == 1)
|
|
.Select(n => new { n.id, n.Name, n.Number }).ToDictionary(n => n.id);
|
|
|
|
var query = from clientbalance in yldb.ClientBalanceDaily.AsNoTracking()
|
|
where clientbalance.BalanceDate == valueDate && clientDic.Keys.Contains(clientbalance.ClientId)
|
|
select clientbalance;
|
|
|
|
//只取追保状态为冻结
|
|
var clientBalances = query.ToList();
|
|
|
|
if (PS.Config.ErpElement.NeedAdditionalMargin)
|
|
{
|
|
clientBalances.ForEach(item =>
|
|
{
|
|
item.PayableMargin = -item.PayableMargin + Math.Abs(item.AdditionalMargin ?? 0);
|
|
item.Margin = Math.Abs(item.Margin ?? 0) + Math.Abs(item.AdditionalMargin ?? 0);
|
|
});
|
|
}
|
|
|
|
if (clientBalances.Count <= 0)
|
|
{
|
|
return JsonError("当前没有需要追保用户!");
|
|
}
|
|
|
|
//追保金额进一处理
|
|
clientBalances.ForEach(item =>
|
|
{
|
|
item.Margin = (double)(Math.Ceiling((decimal)item.Margin * 100) / 100);
|
|
});
|
|
|
|
var tcdList = new List<trade_contract_document>();
|
|
clientBalances.ForEach(t =>
|
|
{
|
|
clientDic.TryGetValue(t.ClientId, out var client);
|
|
|
|
var code = $"{client.Number}_{valueDate.Value:yyyyMMdd}";
|
|
var targetFileName = $"商品期权追保通知书_{code}.xlsx";
|
|
ExcelTemplate.GeneratePDFFromExeclTemplate(sourcePath, sourceFileName,
|
|
new Dictionary<string, object> { { "Sheet1", t } }, targetPath, targetFileName);
|
|
|
|
tcdList.Add(new trade_contract_document
|
|
{
|
|
Code = code,
|
|
ValueDate = valueDate,
|
|
BuyerId = client.id,
|
|
BuyerName = client.Name,
|
|
FileType = FileTypeEnum.Pdf,
|
|
Status = ContractStatusEnum.Draft,
|
|
Paths = targetPath,
|
|
FileName = targetFileName.Replace(".xlsx", ".pdf"),
|
|
OptDate = DateTime.Now,
|
|
OptId = CurUser.UserId,
|
|
OptName = CurUser.UserName,
|
|
Type = ContractTypeEnum.Margin
|
|
});
|
|
});
|
|
//保存追保通知书
|
|
if (tcdList.Count > 0)
|
|
{
|
|
var codeList = tcdList.Select(t => t.Code).ToList();
|
|
var oldTcds = yldb.trade_contract_document.Where(t => codeList.Contains(t.Code) && ContractTypeEnum.Margin.Equals(t.Type) && t.ValueDate == valueDate);
|
|
yldb.trade_contract_document.RemoveRange(oldTcds);
|
|
yldb.trade_contract_document.AddRange(tcdList);
|
|
yldb.SaveChanges();
|
|
}
|
|
|
|
return JsonSuccess("生成追保通知书!");
|
|
}
|
|
public JsonResult SendMailPaymentDoc(DateTime? valueDate)
|
|
{
|
|
if (valueDate == null)
|
|
{
|
|
valueDate = valuedateBLL.ValueDate;
|
|
}
|
|
//追保确通知书模板路径
|
|
var basePath = Server.MapPath($"/App_Docs/contractdoc/output");
|
|
var sourcePath = Server.MapPath("~/App_Docs/导出模板");
|
|
var sourceFileName = Path.Combine(sourcePath, "申万追保通知书模板.xlsx");
|
|
var targetPath = Path.Combine(basePath, valueDate.Value.ToString("yyyyMMdd"));
|
|
if (!Directory.Exists(targetPath))
|
|
{
|
|
Directory.CreateDirectory(targetPath);
|
|
}
|
|
var clientTcdList = (//from source in clientDB.client
|
|
from tcd in yldb.trade_contract_document
|
|
//on source.id equals tcd.BuyerId
|
|
where tcd.Type == ContractTypeEnum.Margin && tcd.ValueDate == valueDate
|
|
select new
|
|
{
|
|
//client = source,
|
|
id = tcd.BuyerId,
|
|
trade_contract_document = tcd
|
|
}).ToList();
|
|
|
|
|
|
if (clientTcdList.Count > 0)
|
|
{
|
|
var errorClientList = new List<Client>();
|
|
var errorMsg = new List<string>();
|
|
clientTcdList.ForEach(t =>
|
|
{
|
|
|
|
var fileList = new List<string>
|
|
{
|
|
Path.Combine(t.trade_contract_document.Paths, t.trade_contract_document.FileName)
|
|
};
|
|
var client = clientDB.client.Where(o => o.id == t.id).FirstOrDefault();
|
|
// 要向该客户的所有订阅了邮件通知的人员发送邮件
|
|
var clientContactMails = clientDB.clientduty.Where(x => x.ApprovalOrder < 1 && x.ClientId == client.id && x.IsReceiveEmail.HasValue && x.IsReceiveEmail == 1).Select(x => x.Email).ToList();
|
|
var emails = DataConvert.EmailsSplitByComma(clientContactMails);
|
|
if (emails == null || !emails.Any())
|
|
{
|
|
errorClientList.Add(client);
|
|
errorMsg.Add(client.Name + "用户没未设置可接受邮件人员信息");
|
|
}
|
|
var sendMail = EmailHelper.SendMail(string.Join(";", emails), $"追加预付金通知书-{valueDate.Value:yyyy-MM-dd}", "", true, fileList.ToArray());
|
|
if (!string.IsNullOrEmpty(sendMail))
|
|
{
|
|
errorClientList.Add(client);
|
|
if (!errorMsg.Contains(sendMail))
|
|
{
|
|
errorMsg.Add(sendMail);
|
|
}
|
|
}
|
|
});
|
|
|
|
//判断是否有发送失败的客户
|
|
if (errorClientList.Count > 0)
|
|
{
|
|
return JsonError($"错误:{string.Join(",", errorClientList.Select(t => t.Name).ToArray())}发送报告时出错<br/>{string.Join("<br/>", errorMsg)}。");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
return JsonError($"{valueDate.Value:yyyy-MM-dd}日追保通知书列表为空!");
|
|
}
|
|
return JsonSuccess("发送追保通知书!");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 根据主键获取
|
|
/// </summary>
|
|
[HttpGet]
|
|
public JsonResult ClientGetById(int id)
|
|
{
|
|
var data = clientDB.client.Find(id);
|
|
return Json(data);
|
|
}
|
|
|
|
public ActionResult ClientView(string enid, int tabId = 1)
|
|
{
|
|
ViewBag.TabViewId = tabId;
|
|
var intid = DataProtectHelper.DecryptInt(enid);
|
|
var r = clientDB.client.Find(intid);
|
|
if (AppHelper.UseFutureVersion("销售提成", "V2"))
|
|
{
|
|
if (!string.IsNullOrWhiteSpace(r.Seller))
|
|
{
|
|
var tempArray = r.Seller.Split(',');
|
|
var SalesmenNames = new List<string>();
|
|
foreach (var item in tempArray)
|
|
{
|
|
int.TryParse(item, out var id);
|
|
var name = new SalesmenDataService(CurUser).GetSalesman(id)?.Name;
|
|
if (!string.IsNullOrWhiteSpace(name))
|
|
{
|
|
SalesmenNames.Add(name);
|
|
}
|
|
}
|
|
if (SalesmenNames != null && SalesmenNames.Any())
|
|
{
|
|
r.Seller = string.Join(",", SalesmenNames);
|
|
}
|
|
}
|
|
}
|
|
if (r.SalesDepartmentId == null)
|
|
{
|
|
r.SalesDepartment = "";
|
|
}
|
|
else
|
|
{
|
|
var sd = DepartmentsController.GetDepartmentById(r.SalesDepartmentId.Value);
|
|
if (sd != null && r != null)
|
|
{
|
|
r.SalesDepartment = sd.Name;
|
|
}
|
|
}
|
|
if (!PS.Config.Is格林大华)
|
|
{
|
|
if (!string.IsNullOrEmpty(r.CustomerManagerId))
|
|
{
|
|
if (r.CustomerManagerId.Contains(","))
|
|
{
|
|
var managerNames = new List<string>();
|
|
var CustomerManagerIds = r.CustomerManagerId.Split(',').ToList();
|
|
CustomerManagerIds.ForEach(a =>
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(a));
|
|
if (manager != null)
|
|
{
|
|
managerNames.Add(manager.Name);
|
|
}
|
|
});
|
|
r.CustomerManager = managerNames.Any() ? string.Join(",", managerNames) : string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(r.CustomerManagerId));
|
|
r.CustomerManager = manager == null ? "" : manager.Name;
|
|
}
|
|
}
|
|
}
|
|
if (PS.Config.Company == Configuration.CompanyEnum.中金)
|
|
{
|
|
r.ProductName = new ClientQueryService(CurUser).GetProductName(r.id);
|
|
}
|
|
|
|
r.MetaDic = new ClientMetaService(CurUser).GetMetaDic(r.id);
|
|
ViewBag.ViewType = "clientView";
|
|
return View(r);
|
|
}
|
|
|
|
// [MyAuthorize("客户信息-客户信息编辑")]
|
|
public ActionResult ClientEdit(string enid, int? tabId)
|
|
{
|
|
return ClientEditV2(enid);
|
|
|
|
//var clientCount = yldb.approvalprocess.Where(x => x.processType == "OpenProcess").Count();
|
|
//ViewBag.ClientApprovalProcessCount = clientCount;
|
|
//var baseDb = DbContextFactory.GetErpBaseContext();
|
|
//ViewBag.ActualSubject = (from type in baseDb.Dictionaries
|
|
// join item in baseDb.DictionaryItems
|
|
// on type.Id equals item.DictId
|
|
// where type.Name == "同一主体"
|
|
// orderby item.IndexNum
|
|
// select item.Name).ToArray();
|
|
|
|
//var r = new Client();
|
|
//if (tabId == 0)
|
|
//{
|
|
// tabId = 1;
|
|
//}
|
|
//ViewBag.TabEditId = tabId;
|
|
//var isAdd = string.IsNullOrEmpty(enid) || enid == "0";
|
|
//if (isAdd)
|
|
//{
|
|
// if (UserInfo.客户管理.客户新增)
|
|
// {
|
|
// r.BookTime = DateTime.Now;
|
|
// r.TradingInstType = DBModels.Enums.TradingInstTypeEnum.All;
|
|
// r.DerivativesInvestmentVarieties = string.Join(",", ClientDataModel.GetAllDerivativesInvestmentVarieties().Select(n => n.Value).ToArray());
|
|
// if (PS.Config.Company == Configuration.CompanyEnum.海通)
|
|
// {
|
|
// r.TradingInstType = DBModels.Enums.TradingInstTypeEnum.Commodity;
|
|
// }
|
|
// r.MetaDic["同一主体"] = "";
|
|
// return View(r);
|
|
// }
|
|
// return ShowError("抱歉,您没有'客户新增'的权限!");
|
|
//}
|
|
|
|
//var intid = DataProtectHelper.DecryptInt(enid);
|
|
//r = clientDB.client.Find(intid);
|
|
//if (r == null)
|
|
//{
|
|
// r = new Client();
|
|
//}
|
|
//r.BookTime = DateTime.Now;
|
|
//if (PS.Config.Company == Configuration.CompanyEnum.中金)
|
|
//{
|
|
// //产品名称
|
|
// r.ProductName = new ClientQueryService(CurUser).GetProductName(r.id);
|
|
//}
|
|
//r.MetaDic = new ClientMetaService(CurUser).GetMetaDic(r.id);
|
|
|
|
//return View(r);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 保存客户信息
|
|
/// </summary>
|
|
[HttpPost]
|
|
public JsonResult ClientEditJson(string enid, ClientSaveDto req)
|
|
{
|
|
req.ClientReq.HadPass = 0;
|
|
req.ClientReq.id = string.IsNullOrEmpty(enid) ? 0 : DataProtectHelper.DecryptInt(enid);
|
|
|
|
var clientKeys = new List<string>();
|
|
var keys = Request.Form.Keys.Cast<string>().ToList();
|
|
if (keys != null && keys.Any())
|
|
{
|
|
keys.ForEach(p =>
|
|
{
|
|
if (p.StartsWith("ClientReq"))
|
|
{
|
|
var index1 = p.IndexOf("[");
|
|
clientKeys.Add(p.Substring(index1 + 1, p.Length - index1 - 2));
|
|
}
|
|
});
|
|
}
|
|
if (!string.IsNullOrEmpty(req.ClientReq.ProxyEmailPwd))
|
|
{
|
|
req.ClientReq.ProxyEmailPwd = DataProtectHelper.Encrypt(req.ClientReq.ProxyEmailPwd);
|
|
}
|
|
var oldClient = clientDB.client.FirstOrDefault(s => s.id == req.ClientReq.id);
|
|
var r = new ClientSaveService(CurUser).SaveData(req.ClientReq, clientKeys.ToHashSet(StringComparer.OrdinalIgnoreCase), out bool blAudit);
|
|
if (r.id > 0)
|
|
{
|
|
//保存标签信息
|
|
using var tagService = new TagService(CurUser);
|
|
tagService.SetClientTagForClientEdit(new Modules.TagModule.Dto.SetClientTagForClientEditRequest
|
|
{
|
|
ClientId = r.id,
|
|
Tags = req.Tags
|
|
});
|
|
if (!blAudit)
|
|
{
|
|
new ClientKafkaService(_kafkaProduce).Send(r, oldClient);
|
|
}
|
|
}
|
|
return JsonSuccess(blAudit ? "提交信息变更审批成功" : "更新成功", r);
|
|
}
|
|
|
|
#region 客户文件操作
|
|
[MyAuthorize("客户管理-客户修改")]
|
|
[HttpPost, Obsolete("等待机会删除这个方法")]
|
|
public JsonResult UploadFiles(string clientId)
|
|
{
|
|
var fileDesc = HttpContext.Request.Form["fileDesc"];
|
|
var isSuitably = HttpContext.Request.Form["isSuitably"];
|
|
var isBookRadio = HttpContext.Request.Form["isBookRadio"];
|
|
var bookTime = HttpContext.Request.Form["bookTime"];
|
|
var FileType = HttpContext.Request.Form["fileType"];
|
|
var ProtocolNumber = HttpContext.Request.Form["protocolNumber"].ToString()?.ToUpper();
|
|
var MainProtocolNumber = HttpContext.Request.Form["mainProtocolNumber"].ToString()?.ToUpper();
|
|
var SideProtocolNumber = HttpContext.Request.Form["sideProtocolNumber"].ToString()?.ToUpper();
|
|
var SignDate = HttpContext.Request.Form["signDate"];
|
|
if (string.IsNullOrWhiteSpace(SignDate))
|
|
{
|
|
SignDate = HttpContext.Request.Form["DatesignDate"];
|
|
}
|
|
var SignType = HttpContext.Request.Form["signType"];
|
|
var ReportRole = HttpContext.Request.Form["reportorRole"];
|
|
DateTime.TryParse(HttpContext.Request.Form["OptDateTime"], out var optDateTime);
|
|
|
|
try
|
|
{
|
|
var intid = DataProtectHelper.DecryptInt(clientId);
|
|
var client = clientDB.client.Find(intid);
|
|
if (client == null)
|
|
{
|
|
return JsonError("未找到客户信息,请先保存客户后在上传文件");
|
|
}
|
|
var clientPath = $"{client.id}";
|
|
CheckFiles(Request.Form.Files, FileType, fileDesc, intid);
|
|
var result = new List<string>();
|
|
var successCount = 0;
|
|
var failCount = 0;
|
|
for (var i = 0; i < Request.Form.Files.Count; i++)
|
|
{
|
|
var file = Request.Form.Files[i];
|
|
var protocolTypes = new List<string>() { "主协议附件(PDF)", "补充协议附件(PDF)", "履约协议附件(PDF)", "代签产品附件(PDF)" };
|
|
var filePath = isSuitably == "true" ? $"~/App_Docs/ClientFiles/SuitablyFiles/{clientPath}" : $"~/App_Docs/ClientFiles/{clientPath}";
|
|
if (!Directory.Exists(filePath))
|
|
{
|
|
Directory.CreateDirectory(Server.MapPath(filePath));
|
|
}
|
|
|
|
var oldName = $"{fileDesc}-{file.FileName}";
|
|
|
|
//check fileName protocol
|
|
if (!string.IsNullOrWhiteSpace(ProtocolNumber))
|
|
{
|
|
var OtherClientFilesName = clientDB.client_file.Where(o => o.ApprovalOrder < 1 && o.ClientId != client.id && o.ProtocolNumber != null && o.ProtocolNumber != "" && o.IsValid).Select(o => new { o.FileName, o.FileDesc }).ToList();
|
|
if (OtherClientFilesName.Where(o => o.FileName.ToUpper() == oldName.ToUpper() || o.FileName.ToUpper() == file.FileName.ToUpper()).Any())
|
|
{
|
|
return JsonError("其他客户有协议使用的文件与该文件重名,请修改文件名后上传。");
|
|
}
|
|
var OtherClientProtocolNumber = clientDB.client_file.Where(o => o.ApprovalOrder < 1 && o.ClientId != client.id && o.IsValid).Select(o => o.ProtocolNumber).ToList();
|
|
if (OtherClientProtocolNumber.Contains(ProtocolNumber))
|
|
{
|
|
return JsonError("其他客户存在的文件存在相同的协议编号,请修改协议编号后上传。");
|
|
}
|
|
OtherClientProtocolNumber = clientDB.client_file.Where(o => o.ApprovalOrder < 1 && !o.IsValid && o.OptState == ConsReport.OptFlagsEnum.D).Select(o => o.ProtocolNumber).ToList();
|
|
if (OtherClientProtocolNumber.Contains(ProtocolNumber))
|
|
{
|
|
return JsonError("该协议编号已存在,且已废弃删除,请修改协议编号后上传。");
|
|
}
|
|
if (clientDB.client_file.Where(O => O.ApprovalOrder < 1 && (O.FileName == file.FileName || O.FileName == oldName) && O.ProtocolNumber != null && O.ProtocolNumber != "" && O.ProtocolNumber != ProtocolNumber && O.IsValid).Any())
|
|
{
|
|
return JsonError("该文件已属于其他协议,请上传未使用的文件。");
|
|
}
|
|
if (FileType == "代签产品附件(PDF)" && clientDB.client_file.Where(o => o.ApprovalOrder < 1 && o.ClientId == client.id && o.MainProtocolNumber == MainProtocolNumber && o.ProtocolNumber != ProtocolNumber && o.FileTypeName == "代签产品附件(PDF)" && o.IsValid).Any())
|
|
{
|
|
return JsonError("该主协议在该产品下已存在代签产品附件,请先删除或废弃。");
|
|
}
|
|
}
|
|
|
|
var clientFile = new client_file();
|
|
|
|
if (DateTime.TryParse(bookTime, out var time) && isBookRadio == "true")
|
|
{
|
|
clientFile.BookTime = time;
|
|
}
|
|
if (DateTime.TryParse(SignDate, out var date))
|
|
{
|
|
clientFile.SignDate = date;
|
|
}
|
|
clientFile.FileTypeName = FileType;
|
|
if (protocolTypes.Contains(FileType))
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ProtocolNumber))
|
|
{
|
|
return JsonError("协议编号未填写");
|
|
}
|
|
if (string.IsNullOrWhiteSpace(SignDate))
|
|
{
|
|
return JsonError("签署日期未填写");
|
|
}
|
|
}
|
|
if (clientFile.FileTypeName == "主协议附件(PDF)")
|
|
{
|
|
if (string.IsNullOrWhiteSpace(SignType))
|
|
{
|
|
return JsonError("主协议附件签署版本未填写");
|
|
}
|
|
if (string.IsNullOrWhiteSpace(ReportRole))
|
|
{
|
|
return JsonError("主协议附件填报方角色未填写");
|
|
}
|
|
clientFile.SignType = SignType;
|
|
clientFile.ReportorRole = ReportRole;
|
|
}
|
|
if (clientFile.FileTypeName == "履约协议附件(PDF)")
|
|
{
|
|
if (string.IsNullOrWhiteSpace(SideProtocolNumber))
|
|
{
|
|
return JsonError("履约协议附件补充协议编号未填写");
|
|
}
|
|
clientFile.MainProtocolNumber = SideProtocolNumber;
|
|
}
|
|
if (clientFile.FileTypeName == "补充协议附件(PDF)"
|
|
|| clientFile.FileTypeName == "代签产品附件(PDF)")
|
|
{
|
|
if (string.IsNullOrWhiteSpace(MainProtocolNumber))
|
|
{
|
|
return JsonError("主协议编号未填写");
|
|
}
|
|
clientFile.MainProtocolNumber = MainProtocolNumber;
|
|
}
|
|
|
|
clientFile.FileName = file.FileName;
|
|
clientFile.FileDesc = fileDesc;
|
|
clientFile.ClientId = client.id;
|
|
clientFile.FileDesc = fileDesc;
|
|
clientFile.OptId = CurUser.UserId;
|
|
clientFile.OptName = CurUser.UserName;
|
|
clientFile.OptDate = optDateTime; // DateTime.Now
|
|
clientFile.ProtocolNumber = ProtocolNumber;
|
|
clientFile.HasSent = false;
|
|
clientFile.FilePath = Path.Combine(filePath.TrimStart('~'), file.FileName);
|
|
clientFile.IsValid = true;
|
|
|
|
var ret = new ClientFileService(CurUser).UploadFile(clientFile);
|
|
if (string.IsNullOrWhiteSpace(ret) || ret == "修改成功")
|
|
{
|
|
file.SaveAs(Path.Combine(Server.MapPath(filePath), file.FileName));
|
|
LogFactory.GetLogger<ClientController>().Info($"客户{client.Name}(id:{client.id})上传文件({file.FileName}),真实上传时间:{DateTime.Now},客户选择的日期:{optDateTime}");
|
|
if (ret == "修改成功")
|
|
{
|
|
result.Add($"{clientFile.ProtocolNumber}文件已修改,文件{clientFile.FileName}已覆盖上传");
|
|
}
|
|
else
|
|
{
|
|
result.Add($"文件{clientFile.FileName}上传成功: {ret}");
|
|
}
|
|
successCount++;
|
|
}
|
|
else
|
|
{
|
|
result.Add($"文件{clientFile.FileName}上传失败: {ret}");
|
|
failCount++;
|
|
}
|
|
}
|
|
if (failCount > 0)
|
|
{
|
|
return JsonError(string.Join(";", result));
|
|
}
|
|
return JsonSuccess("上传成功 " + string.Join(";", result));
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger("客户文件上传").Error(ex);
|
|
return JsonError("上传文件出错," + ex.Message);
|
|
}
|
|
}
|
|
|
|
public JsonResult RecoverFile(string clientId, string fileName, string protocolNumber, bool isDirectSubApp = false)
|
|
{
|
|
var intid = DataProtectHelper.DecryptInt(clientId);
|
|
fileName = Uri.UnescapeDataString(fileName);
|
|
var ret = new ClientFileService(CurUser).RecoverFile(intid, fileName, protocolNumber, isDirectSubApp);
|
|
if (ret == "还原成功" || ret == "废弃解除")
|
|
{
|
|
return JsonSuccess(ret);
|
|
}
|
|
else
|
|
{
|
|
return JsonError(ret);
|
|
}
|
|
}
|
|
|
|
private void CheckFiles(IFormFileCollection files, string fileType, string fileTypeName, int clientId)
|
|
{
|
|
if (fileTypeName.Contains('-'))
|
|
{
|
|
throw new ServiceException("文件说明中请不要使用字符‘-’");
|
|
}
|
|
|
|
var list = new List<string>() { "主协议附件(PDF)", "补充协议附件(PDF)", "履约协议附件(PDF)", "代签产品附件(PDF)" };
|
|
if (list.Contains(fileType))
|
|
{
|
|
if (files.Count > 1)
|
|
{
|
|
throw new ServiceException("主协议附件,补充协议附件,履约预付金附件,代签产品附件 只能上传单个文件");
|
|
}
|
|
if (files[0].Length > ReportStatusModel.MaxAnnexLength)
|
|
{
|
|
throw new ServiceException("主协议附件,补充协议附件,履约预付金附件,代签产品附件 单个附件大小不可以超过30M");
|
|
}
|
|
if (PS.Config.ErpElement.SecuritiesEnvironment && files[0].ContentType != "application/pdf")
|
|
{
|
|
throw new ServiceException("主协议附件,补充协议附件,履约预付金附件,代签产品附件 只能上传pdf文档");
|
|
}
|
|
}
|
|
|
|
for (var i = 0; i < files.Count; i++)
|
|
{
|
|
var oldname = $"{fileTypeName}-{files[i].FileName}";
|
|
var name = files[i].FileName;
|
|
|
|
|
|
var clientFileCount = clientDB.client_file.Where(o => o.ApprovalOrder < 1 && o.ClientId == clientId && (o.FileName == oldname || o.FileName == name) && o.FileTypeName != fileType).Count();
|
|
if (clientFileCount > 0)
|
|
{
|
|
throw new ServiceException("在该客户上传的文件中" + files[i].FileName + "属于其他文件类型,请确认!");
|
|
}
|
|
}
|
|
}
|
|
|
|
private bool HasSideprotocols(int clientId, string protocolNumber)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(protocolNumber))
|
|
{
|
|
return false;
|
|
}
|
|
var clientFiles = clientDB.client_file.Where(o => o.ApprovalOrder < 1 && o.ClientId == clientId
|
|
&& o.MainProtocolNumber == protocolNumber
|
|
&& o.IsValid && o.OptState != ConsReport.OptFlagsEnum.D);
|
|
//如果有没废弃的
|
|
return clientFiles.Count() > 0;
|
|
}
|
|
|
|
public JsonResult getMainProtocolCodes(int clientId = 0)
|
|
{
|
|
var result = ClientDataModel.getMainProtocols(clientId);
|
|
return Json(result);
|
|
}
|
|
|
|
public JsonResult getSideProtocols(string mainProtocol)
|
|
{
|
|
var result = ClientDataModel.getSideProtocols(mainProtocol);
|
|
return Json(result);
|
|
}
|
|
|
|
[HttpPost]
|
|
public JsonResult DeleteFile(string clientId, string fileName, string protocolNumber, bool isDirectSubApp = false)
|
|
{
|
|
var intid = DataProtectHelper.DecryptInt(clientId);
|
|
fileName = Uri.UnescapeDataString(fileName);
|
|
var ret = new ClientFileService(CurUser).DeleteFile(intid, fileName, protocolNumber, isDirectSubApp: isDirectSubApp);
|
|
return ret.IsSuccess ? JsonSuccess(ret.Message) : JsonError(ret.Message);
|
|
}
|
|
|
|
[HttpPost]
|
|
public JsonResult AbandonFile(string clientId, string protocolNumber)
|
|
{
|
|
var intid = DataProtectHelper.DecryptInt(clientId);
|
|
var ret = new ClientFileService(CurUser).AbandonFile(intid, protocolNumber);
|
|
if (ret == "文件已废弃")
|
|
{
|
|
return JsonSuccess(ret);
|
|
}
|
|
else
|
|
{
|
|
return JsonError(ret);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 某一客户的已上传文件审核列表页面
|
|
/// </summary>
|
|
public ActionResult ClientFilesAudit(int clientId, bool isApproval = true)
|
|
{
|
|
var data = GetAuditPages(clientId);
|
|
ViewBag.IsApproval = isApproval;
|
|
return View(data);
|
|
}
|
|
|
|
public ClientfileauditPage GetAuditPages(int clientId)
|
|
{
|
|
var client = clientDB.client.Find(clientId);
|
|
if (client == null)
|
|
{
|
|
throw new ServiceException("客户信息未找到");
|
|
}
|
|
var pageResult = new ClientfileauditPage();
|
|
var rawRows = JsonHelper.Parse<List<ClientfileauditPageRow>>(PS.Config.ClientFileAuditItems);
|
|
var aviliableRoleid = yldb.approvalprocess.Where(x => x.processType == "OpenProcess"/* && x.order < client.ProcessOrderId*/).OrderBy(x => x.order).Select(x => x.roleId).ToList();
|
|
var pendingRoleid = yldb.approvalprocess.FirstOrDefault(x => x.processType == "OpenProcess" && x.order == client.ProcessOrderId)?.roleId ?? 0;
|
|
|
|
//当前客户之后的无权查看
|
|
//var currentRoleid = CurUser.Roles.Select(x => x.Id).ToList();
|
|
//if (currentRoleid.Contains(pendingRoleid))
|
|
//{
|
|
if (pendingRoleid > 0 && !aviliableRoleid.Contains(pendingRoleid))
|
|
{
|
|
aviliableRoleid.Add(pendingRoleid);
|
|
}
|
|
//}
|
|
|
|
pageResult.RoleColumns = new List<RoleColumnsInner>
|
|
{
|
|
//添加 提交人 一栏
|
|
new RoleColumnsInner { Id = 0, Name = "提交人", OptName = "提交人" }
|
|
};
|
|
foreach (var rid in aviliableRoleid)
|
|
{
|
|
var rc = DbContextFactory.GetErpBaseContext().Roles.Find(rid);
|
|
pageResult.RoleColumns.Add(new RoleColumnsInner { Id = rc.Id, Name = rc.Name, OptName = rc.Name });
|
|
}
|
|
|
|
|
|
pageResult.ItemRows = rawRows;
|
|
pageResult.ClientId = clientId;
|
|
pageResult.ClientName = client?.Name;
|
|
|
|
return pageResult;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 执行客户已上传文件的检查确认操作
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public ActionResult ClientFileAuditExec(ClientfileAuditExecRequest reqs)
|
|
{
|
|
try
|
|
{
|
|
if (reqs.Items != null && reqs.Items.Any())
|
|
{
|
|
foreach (var req in reqs.Items)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(req.Group) || string.IsNullOrWhiteSpace(req.Title))
|
|
{
|
|
continue;
|
|
}
|
|
//支持批量检查
|
|
var cfa = clientDB.client_file_audit.FirstOrDefault(x => x.ClientId == reqs.ClientId && x.OptRoleName == req.RoleName && x.Title == req.Title && x.Group == req.Group);
|
|
if (cfa == null)
|
|
{
|
|
cfa = new client_file_audit() { ClientId = reqs.ClientId };
|
|
clientDB.client_file_audit.Add(cfa);
|
|
}
|
|
|
|
cfa.IsPass = req.Checked;
|
|
cfa.Group = req.Group;
|
|
cfa.Title = req.Title;
|
|
cfa.OptDate = DateTime.Now; cfa.OptName = CurUser.UserName; cfa.OptId = CurUser.UserId; cfa.OptRoleName = req.RoleName;
|
|
}
|
|
clientDB.SaveChanges();
|
|
}
|
|
|
|
return JsonSuccess("");
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
return JsonError($"发生错误!{e.Message}");
|
|
}
|
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
/// 某一客户的已上传文件审核列表页面数据
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public ActionResult ClientFilesAuditQuery(int clientId)
|
|
{
|
|
try
|
|
{
|
|
var data = clientDB.client_file_audit.Where(x => x.ClientId == clientId).OrderByDescending(x => x.OptDate).ToList();
|
|
return Json(data);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger().Error("获取客户文件审核列表数据失败", ex);
|
|
return JsonError("获取客户文件审核列表数据失败");
|
|
}
|
|
}
|
|
|
|
public async Task<ActionResult> ClientFilesAuditDownload(int clientId)
|
|
{
|
|
var model = GetAuditPages(clientId);
|
|
var html = await _viewRenderer.RenderToStringAsync("client/ClientFilesAudit", model);
|
|
var fileBytes2 = new HtmlToPdfHelper().ConvertHtmlTextToPDF(html, new HtmlToPdfOptions
|
|
{
|
|
IsHorizental = true,
|
|
UseFontSong = true
|
|
});
|
|
return File(fileBytes2, "application/pdf", DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 查询某一客户的已上传文件列表
|
|
/// </summary>
|
|
/// <param name="clientId">客户id</param>
|
|
/// <param name="clientType">视图类型: clientEdit/clientView</param>
|
|
/// <returns>查询结果</returns>
|
|
[HttpPost]
|
|
public ActionResult ClientFilesEditPopInner(string clientId, string clientType, string[] fileType = null, string fileName = "", string fileDate = "")
|
|
{
|
|
try
|
|
{
|
|
var intid = DataProtectHelper.DecryptInt(clientId);
|
|
var client = clientDB.client.Find(intid);
|
|
if (client == null)
|
|
{ //新增客户的时候,client就是null
|
|
return View(new ClientFileResult());
|
|
}
|
|
|
|
ViewBag.ClientType = clientType;
|
|
var clientFileResult = new ClientFileResult()
|
|
{
|
|
ClientId = intid,
|
|
EncryptId = clientId,
|
|
ClientName = client.Name
|
|
};
|
|
var query = clientDB.client_file.Where(x => x.ApprovalOrder < 1 && x.ClientId == client.id && x.IsValid).ToList();
|
|
|
|
var FilesDic = SortClientFiles(query);
|
|
|
|
foreach (var Dic in FilesDic)
|
|
{
|
|
var fileList = Dic.Value;
|
|
|
|
if (fileType != null && fileType.Length > 0)
|
|
{
|
|
fileList = fileList.Where(o => fileType.Contains(o.file.FileTypeName)).ToList();
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(fileName))
|
|
{
|
|
|
|
fileList = fileList.Where(o => o.file.FileName.Substring(o.file.FileName.IndexOf('-') + 1, o.file.FileName.IndexOf('.') - o.file.FileName.IndexOf('-') - 1).Contains(fileName)).ToList();
|
|
}
|
|
|
|
if (DateTime.TryParse(fileDate, out var date))
|
|
{
|
|
var dateEnd = date.AddDays(1);
|
|
fileList = fileList.Where(o => o.file.OptDate >= date && o.file.OptDate <= dateEnd).ToList();
|
|
}
|
|
|
|
if (fileList.Count() > 0)
|
|
{
|
|
clientFileResult.FilesDic.Add(Dic.Key, fileList);
|
|
}
|
|
}
|
|
|
|
return View(clientFileResult);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger().Error("获取文件列表出错", ex);
|
|
return JsonError("获取文件列表出错");
|
|
}
|
|
}
|
|
|
|
private Dictionary<string, List<clientFileRet>> SortClientFiles(List<client_file> clientFiles)
|
|
{
|
|
var dics = new Dictionary<string, List<clientFileRet>>();
|
|
clientFiles.Sort((x, y) => x.CompareTo(y));
|
|
foreach (var file in clientFiles)
|
|
{
|
|
var ret = new clientFileRet
|
|
{
|
|
file = file,
|
|
CanDelete = string.IsNullOrWhiteSpace(file.ProtocolNumber) || (!file.HasSent && file.OptState == ConsReport.OptFlagsEnum.A),
|
|
CanDrop = !string.IsNullOrWhiteSpace(file.ProtocolNumber) && file.HasSent && file.OptState != ConsReport.OptFlagsEnum.D,
|
|
CanBack = new ClientFileService(CurUser).getBackRecordV2(file.ClientId, file.ProtocolNumber) != null && (!file.HasSent)
|
|
};
|
|
if (string.IsNullOrWhiteSpace(file.MainProtocolNumber))
|
|
{
|
|
if (file.FileTypeName == "主协议附件(PDF)")
|
|
{
|
|
if (dics.ContainsKey(file.ProtocolNumber))
|
|
{
|
|
dics[file.ProtocolNumber].Add(ret);
|
|
}
|
|
else
|
|
{
|
|
dics.Add(file.ProtocolNumber, new List<clientFileRet>() { ret });
|
|
}
|
|
|
|
}
|
|
else
|
|
{
|
|
dics.Add(file.FileName, new List<clientFileRet>() { ret });
|
|
}
|
|
}
|
|
else
|
|
{
|
|
if (file.FileTypeName != "履约协议附件(PDF)")
|
|
{
|
|
if (dics.ContainsKey(file.MainProtocolNumber))
|
|
{
|
|
dics[file.MainProtocolNumber].Add(ret);
|
|
}
|
|
else
|
|
{
|
|
dics.Add(file.MainProtocolNumber, new List<clientFileRet>() { ret });
|
|
}
|
|
}
|
|
else
|
|
{
|
|
var enhanceProtocol = clientFiles.Where(o => o.ProtocolNumber == file.MainProtocolNumber).FirstOrDefault();
|
|
if (dics.ContainsKey(enhanceProtocol.MainProtocolNumber))
|
|
{
|
|
dics[enhanceProtocol.MainProtocolNumber].Add(ret);
|
|
}
|
|
else
|
|
{
|
|
dics.Add(enhanceProtocol.MainProtocolNumber, new List<clientFileRet>() { ret });
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return dics;
|
|
}
|
|
|
|
public ActionResult DownloadClientFile(string clientId, string fileName, string fileid)
|
|
{
|
|
try
|
|
{
|
|
fileName = Uri.UnescapeDataString(fileName);
|
|
var intid = DataProtectHelper.DecryptInt(clientId);
|
|
var filetid = DataProtectHelper.DecryptInt(fileid);
|
|
if (!clientDB.client.Any(n => n.id == intid))
|
|
{
|
|
return ShowError("没有找到客户信息");
|
|
}
|
|
|
|
var clientFile = clientDB.client_file.Where(o => o.ClientId == intid && o.FileName == fileName).FirstOrDefault();
|
|
if (!string.IsNullOrWhiteSpace(fileid))
|
|
{
|
|
clientFile = clientDB.client_file.Find(filetid);
|
|
}
|
|
if (clientFile == null)
|
|
{
|
|
return ShowError("没有找到文件信息");
|
|
}
|
|
var path = clientFile.FilePath;
|
|
var fullPath = Server.MapPath(path);
|
|
|
|
if (string.IsNullOrWhiteSpace(path) || !System.IO.File.Exists(fullPath))
|
|
{
|
|
//如果不存在,可能是客户名变了,看重新组的路径有没有文件
|
|
path = new ClientFileService(CurUser).GetPathFromElderWay(clientFile.ClientId, clientFile.FileName);
|
|
fullPath = Server.MapPath(path);
|
|
if (!System.IO.File.Exists(fullPath))
|
|
{
|
|
return ShowError("文件不存在");
|
|
}
|
|
clientFile.FilePath = path;
|
|
clientDB.SaveChanges();
|
|
}
|
|
|
|
LogFactory.GetLogger("下载客户文件").Info(path);
|
|
return PhysicalFile(fullPath, "application/pdf", clientFile.FileName);
|
|
}
|
|
catch (ServiceException ex)
|
|
{
|
|
return ShowError("下载出错:" + ex.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger("下载客户文件").Error(ex);
|
|
return ShowError("下载出错:" + ex.Message);
|
|
}
|
|
}
|
|
|
|
public JsonResult ShowClientFile(string clientId, string fileName)
|
|
{
|
|
try
|
|
{
|
|
fileName = Uri.UnescapeDataString(fileName);
|
|
var intid = DataProtectHelper.DecryptInt(clientId);
|
|
if (!clientDB.client.Any(n => n.id == intid))
|
|
{
|
|
return JsonError("没有找到客户信息");
|
|
}
|
|
|
|
var clientFile = clientDB.client_file.Where(o => o.ClientId == intid && o.FileName == fileName).FirstOrDefault();
|
|
if (clientFile == null)
|
|
{
|
|
return JsonError("没有找到文件信息");
|
|
}
|
|
var path = clientFile.FilePath;
|
|
var fullPath = Server.MapPath(path);
|
|
|
|
if (string.IsNullOrWhiteSpace(path) || !System.IO.File.Exists(fullPath))
|
|
{
|
|
//如果不存在,可能是客户名变了,看重新组的路径有没有文件
|
|
path = new ClientFileService(CurUser).GetPathFromElderWay(clientFile.ClientId, clientFile.FileName);
|
|
fullPath = Server.MapPath(path);
|
|
if (!System.IO.File.Exists(fullPath))
|
|
{
|
|
return JsonError("文件不存在");
|
|
}
|
|
clientFile.FilePath = path;
|
|
clientDB.SaveChanges();
|
|
}
|
|
|
|
return JsonSuccess("", path);
|
|
}
|
|
catch (ServiceException ex)
|
|
{
|
|
LogFactory.GetLogger("预览客户文件").Error(ex);
|
|
return JsonError("预览出错:" + ex.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger("预览客户文件").Error(ex);
|
|
return JsonError("预览出错:" + ex.Message);
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
/// <summary>
|
|
/// 销户
|
|
/// </summary>
|
|
/// <param name="id">客户id</param>
|
|
/// <param name="collection"></param>
|
|
/// <returns></returns>
|
|
[HttpPost]
|
|
public JsonResult Deleteclient(string id)
|
|
{
|
|
var intid = DataProtectHelper.DecryptInt(id);
|
|
var r = clientDB.client.Find(intid);
|
|
|
|
if (r == null)
|
|
{
|
|
return JsonError("删除失败,找不到客户信息");
|
|
}
|
|
var checkResult = new ClientFileService(CurUser).checkFiles(r.id);
|
|
if (!string.IsNullOrWhiteSpace(checkResult))
|
|
{
|
|
return JsonError("删除失败", checkResult);
|
|
}
|
|
if (r.HadPass > 0)
|
|
{
|
|
return JsonError("删除失败", "该用户存在客户编号,不能删除");
|
|
}
|
|
|
|
if (clientDB.client.Any(c => c.ParentId == intid))
|
|
{
|
|
return JsonError("删除失败", "该用户存在子级用户,请先解除关系");
|
|
}
|
|
|
|
clientDB.client.Remove(r);
|
|
clientDB.SaveChanges();
|
|
return JsonSuccess("删除成功", "删除成功");
|
|
}
|
|
|
|
public ActionResult UploadClientMain(string MasterType)
|
|
{
|
|
if (!CurUser.客户管理.客户新增)
|
|
{
|
|
return JsonError("Invaild Option!");
|
|
}
|
|
|
|
var files = Request.Form.Files;
|
|
|
|
if (files.Count == 0)
|
|
{
|
|
return JsonError("缺少上传文件");
|
|
}
|
|
|
|
var file = files[0];
|
|
var fileExt = Path.GetExtension(file.FileName)?.ToLowerInvariant();
|
|
|
|
if (fileExt == ".csv")
|
|
{
|
|
return UploadClient(file, MasterType);
|
|
}
|
|
else if (fileExt == ".xlsx")
|
|
{
|
|
return UploadClientExcel(file);
|
|
}
|
|
else
|
|
{
|
|
return JsonError("请上传xlsx或csv格式文件");
|
|
}
|
|
}
|
|
|
|
public ActionResult UploadClientMainV2()
|
|
{
|
|
if (!CurUser.客户管理.客户新增)
|
|
{
|
|
return JsonError("Invaild Option!");
|
|
}
|
|
|
|
var files = Request.Form.Files;
|
|
|
|
if (files.Count == 0)
|
|
{
|
|
return JsonError("缺少上传文件");
|
|
}
|
|
|
|
var file = files[0];
|
|
var fileExt = Path.GetExtension(file.FileName)?.ToLowerInvariant();
|
|
|
|
if (fileExt == ".xlsx")
|
|
{
|
|
return UploadClientExcel(file);
|
|
}
|
|
else
|
|
{
|
|
return JsonError("请上传xlsx");
|
|
}
|
|
}
|
|
|
|
|
|
public ActionResult UploadClient(IFormFile file, string MasterType)
|
|
{
|
|
if (!CurUser.客户管理.客户新增)
|
|
{
|
|
return JsonError("Invaild Option!");
|
|
}
|
|
var fileName = "";
|
|
|
|
//上传交易存储目录
|
|
var MainUploadPath = "/App_Upload/Client";
|
|
|
|
var filePathName = string.Empty;
|
|
|
|
var files = Request.Form.Files;
|
|
|
|
if (files.Count == 0)
|
|
{
|
|
return JsonError("保存失败");
|
|
}
|
|
try
|
|
{
|
|
//上传同名文件会覆盖
|
|
fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + file.FileName;
|
|
var directoryName = string.Format("{1}{0}/", MasterType, MainUploadPath);
|
|
filePathName = directoryName + fileName; //自行处理保存
|
|
var pafile = Server.MapPath(directoryName);
|
|
if (!Directory.Exists(pafile))
|
|
{
|
|
Directory.CreateDirectory(pafile);
|
|
}
|
|
//files[0].FileName
|
|
var pa = Server.MapPath(filePathName);
|
|
|
|
file.SaveAs(pa); //把文件上传到服务器的绝对路径上
|
|
|
|
var result = new ClientImportService(CurUser).UploadClientCsv(pa);
|
|
if (result.IsSuccess)
|
|
{
|
|
return JsonSuccess("导入成功");
|
|
}
|
|
return JsonError(result.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
|
|
LogFactory.GetLogger(nameof(ClientController)).Error("UploadClientCsv", ex);
|
|
return JsonError(ex.Message);
|
|
}
|
|
}
|
|
|
|
public ActionResult UploadClientExcel(IFormFile file)
|
|
{
|
|
if (!CurUser.客户管理.客户新增)
|
|
{
|
|
return JsonError("Invaild Option!");
|
|
}
|
|
try
|
|
{
|
|
var isSellerV2 = AppHelper.UseFutureVersion("销售提成", "V2");
|
|
using var inputStream = file.OpenReadStream();
|
|
var result = new ClientImportService(CurUser).UploadClientExcel(inputStream, isSellerV2);
|
|
if (result.IsSuccess)
|
|
{
|
|
return JsonSuccess("导入成功");
|
|
}
|
|
return JsonError(result.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger(nameof(ClientController)).Error("UploadClientExcel", ex);
|
|
return JsonError(ex.Message);
|
|
}
|
|
}
|
|
|
|
public ActionResult UploadClientExcelV2()
|
|
{
|
|
var files = Request.Form.Files;
|
|
|
|
if (files.Count == 0)
|
|
{
|
|
return JsonError("上传文件不存在");
|
|
}
|
|
|
|
var file = files[0];
|
|
|
|
if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return JsonError("请上传Excel(.xlsx)格式文件");
|
|
}
|
|
|
|
using var inputStream = file.OpenReadStream();
|
|
new ClientTemplateImportService(CurUser).ImportFromExcel(inputStream, out var TotalNum, out var SuccessNum);
|
|
|
|
return Json(new
|
|
{
|
|
success = true,
|
|
totalNum = TotalNum,
|
|
successNum = SuccessNum,
|
|
});
|
|
}
|
|
|
|
/// <summary>
|
|
/// 批量导入修改客户信息
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public ActionResult UploadClientExcelForBatchUpdate()
|
|
{
|
|
if (Request.Form.Files.Count == 0)
|
|
{
|
|
return JsonError("上传文件不存在");
|
|
}
|
|
|
|
var file = Request.Form.Files[0];
|
|
|
|
if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return JsonError("请上传Excel(.xlsx)格式文件");
|
|
}
|
|
|
|
using var inputStream = file.OpenReadStream();
|
|
var res = new ClientTemplateImportService(CurUser).ImportFromExcelForBatchUpdate(inputStream);
|
|
|
|
return Json(res);
|
|
}
|
|
|
|
|
|
public ActionResult ImportKYCExcelToClientInfo()
|
|
{
|
|
if (Request.Form.Files.Count == 0)
|
|
{
|
|
return JsonError("上传文件不存在");
|
|
}
|
|
|
|
var file = Request.Form.Files[0];
|
|
|
|
if (!Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return JsonError("请上传Excel(.xlsx)格式文件");
|
|
}
|
|
using (var inputStream = file.OpenReadStream())
|
|
{
|
|
new ClientTemplateImportService(CurUser).ImportKYCExcelToClientInfo(inputStream);
|
|
}
|
|
|
|
return Json(new
|
|
{
|
|
success = true
|
|
});
|
|
}
|
|
|
|
|
|
public ActionResult UploadClientDutyExcel(IFormFile file)
|
|
{
|
|
if (!CurUser.客户管理.客户新增)
|
|
{
|
|
return JsonError("Invaild Option!");
|
|
}
|
|
try
|
|
{
|
|
using var inputStream = file.OpenReadStream();
|
|
var result = new ClientImportService(CurUser).UploadClientDutyExcel(inputStream);
|
|
if (result.IsSuccess)
|
|
{
|
|
return JsonSuccess("导入客户人员信息成功");
|
|
}
|
|
return JsonError(result.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger(nameof(ClientController)).Error("UploadClientDutyExcel", ex);
|
|
return JsonError(ex.Message);
|
|
}
|
|
}
|
|
|
|
public ActionResult UploadClientBankcardExcel(IFormFile file)
|
|
{
|
|
if (!CurUser.客户管理.客户新增)
|
|
{
|
|
return JsonError("Invaild Option!");
|
|
}
|
|
try
|
|
{
|
|
using var inputStream = file.OpenReadStream();
|
|
var result = new ClientImportService(CurUser).UploadClientBankcardExcel(inputStream, CurUser.UserId, CurUser.UserName);
|
|
if (result.IsSuccess)
|
|
{
|
|
return JsonSuccess("导入客户银行卡成功");
|
|
}
|
|
return JsonError(result.Message);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger(nameof(ClientController)).Error("UploadClientBankcardExcel", ex);
|
|
return JsonError(ex.Message);
|
|
}
|
|
}
|
|
|
|
public ActionResult ClientUpload()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
public ActionResult ClientUploadV2(int flag = 0)
|
|
{
|
|
ViewBag.Flag = flag;
|
|
return View();
|
|
}
|
|
|
|
|
|
[HttpPost]
|
|
public ActionResult ClientQueryForDown(ClientReq req)
|
|
{
|
|
req.ValueDate = valuedateBLL.ValueDate;
|
|
var sList = new ClientQueryService(CurUser).SearchListClient(req);
|
|
var appropriatenessAssessors = RoleRight.GetSystemUserByFunction("担任适当性评估人");
|
|
|
|
sList.ForEach(x =>
|
|
{
|
|
x.AppropriatenessAssessorName = appropriatenessAssessors.Where(y => y.Id == x.AppropriatenessAssessor).FirstOrDefault() == null ? "" : appropriatenessAssessors.Where(y => y.Id == x.AppropriatenessAssessor).FirstOrDefault().Name;
|
|
|
|
if (!PS.Config.Is格林大华)
|
|
{
|
|
if (!string.IsNullOrEmpty(x.CustomerManagerId))
|
|
{
|
|
if (x.CustomerManagerId.Contains(","))
|
|
{
|
|
var managerNames = new List<string>();
|
|
var CustomerManagerIds = x.CustomerManagerId.Split(',').ToList();
|
|
CustomerManagerIds.ForEach(a =>
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(a));
|
|
if (manager != null)
|
|
{
|
|
managerNames.Add(manager.Name);
|
|
}
|
|
});
|
|
x.CustomerManager = managerNames.Any() ? string.Join(",", managerNames) : string.Empty;
|
|
}
|
|
else
|
|
{
|
|
var manager = UserBLL.GetById(Convert.ToInt32(x.CustomerManagerId));
|
|
x.CustomerManager = manager == null ? "" : manager.Name;
|
|
}
|
|
}
|
|
}
|
|
|
|
x.CustomerNatureName = x.CustomerNature == null ? "" : Enum.Parse(typeof(CustomerNatureEnum), x.CustomerNature.Value.ToString()).ToString();
|
|
if (x.SalesDepartmentId == null)
|
|
{
|
|
x.SalesDepartment = "";
|
|
}
|
|
else
|
|
{
|
|
var department = DepartmentsController.GetDepartmentById(x.SalesDepartmentId.Value);
|
|
x.SalesDepartment = department == null ? "" : department.Name;
|
|
}
|
|
|
|
x.Phone = x.Phone != null ? x.Phone.Replace(",", "/") : "";
|
|
});
|
|
|
|
return Json(sList);
|
|
}
|
|
|
|
[HttpPost]
|
|
public ActionResult CancelClient(int? clientId)
|
|
{
|
|
var error = "提交失败";
|
|
var success = "提交成功";
|
|
if (clientId == null)
|
|
{
|
|
return JsonError(error);
|
|
}
|
|
|
|
var client = clientDB.client.FirstOrDefault(s => s.id == clientId);
|
|
if (client == null)
|
|
{
|
|
return JsonError(error);
|
|
}
|
|
var oldClient = client.Clone();
|
|
var hasPendingTrades = yldb.trade.Any(x => x.ClientId == clientId && ConsTrade.NeedMarginTradeStatusList.Contains(x.TradeStatus) && x.ValidState != "InValid");
|
|
if (hasPendingTrades)
|
|
{
|
|
return JsonError("该用户存在交易尚未了结,不能销户");
|
|
}
|
|
|
|
var hasClientCashInCashOutProduct = yldb.clientcashincashout_product.Any(d => d.ClientId == clientId
|
|
&& ((d.Status == Clientcashincashout_productStatusEnum.抵押.ToString() && d.OptStatus == ClientCashInCashOut.已确认)
|
|
|| (d.Status == Clientcashincashout_productStatusEnum.赎回.ToString() && d.OptStatus != ClientCashInCashOut.已确认)));
|
|
if (hasClientCashInCashOutProduct)
|
|
{
|
|
return JsonError("该用户存在处于抵押状态的抵押品,不能销户");
|
|
}
|
|
|
|
var dt = DateTime.Now;
|
|
|
|
client.ProcessOrderId = -3;
|
|
client.ProcessStatus = "已销户";
|
|
client.ProcessOptDate = dt;
|
|
client.OptId = CurUser.UserId;
|
|
client.OptName = CurUser.UserName;
|
|
client.OptDate = dt;
|
|
var bankcardService = new ClientBankCardService(CurUser);
|
|
clientDB.ClientAuditLog.Add(new ClientAuditLog
|
|
{
|
|
ClientId = clientId ?? 0,
|
|
OptType = "销户",
|
|
Changes = string.Empty,
|
|
DataType = "00",
|
|
OptId = CurUser.UserId,
|
|
OptName = CurUser.UserName,
|
|
OptDate = dt
|
|
});
|
|
if (clientId != null)
|
|
{
|
|
bankcardService.SetBankCardValidStateWhenClientDisable((int)clientId, clientDB);
|
|
}
|
|
|
|
clientDB.SaveChanges();
|
|
new ClientKafkaService(_kafkaProduce).Send(client, oldClient);
|
|
return JsonSuccess(success);
|
|
}
|
|
|
|
[HttpPost]
|
|
public ActionResult SuspendClient(int? clientId)
|
|
{
|
|
var error = "提交失败";
|
|
var success = "提交成功";
|
|
if (clientId == null)
|
|
{
|
|
return JsonError(error);
|
|
}
|
|
|
|
var client = clientDB.client.FirstOrDefault(s => s.id == clientId);
|
|
if (client == null)
|
|
{
|
|
return JsonError(error);
|
|
}
|
|
var oldClient = client.Clone();
|
|
var bankCardService = new ClientBankCardService(CurUser);
|
|
var dt = DateTime.Now;
|
|
client.ProcessOrderId = -4;
|
|
client.ProcessStatus = "已休眠";
|
|
client.OptId = CurUser.UserId;
|
|
client.OptName = CurUser.UserName;
|
|
client.OptDate = dt;
|
|
|
|
clientDB.ClientAuditLog.Add(new ClientAuditLog
|
|
{
|
|
ClientId = clientId ?? 0,
|
|
OptType = "休眠",
|
|
Changes = string.Empty,
|
|
DataType = "00",
|
|
OptId = CurUser.UserId,
|
|
OptName = CurUser.UserName,
|
|
OptDate = dt
|
|
});
|
|
if (clientId != null)
|
|
{
|
|
bankCardService.SetBankCardValidStateWhenClientDisable((int)clientId, clientDB);
|
|
}
|
|
clientDB.SaveChanges();
|
|
new ClientKafkaService(_kafkaProduce).Send(client, oldClient);
|
|
return JsonSuccess(success);
|
|
}
|
|
|
|
[HttpPost]
|
|
public ActionResult ResumeClient(int? clientId)
|
|
{
|
|
var error = "提交失败";
|
|
var success = "提交成功";
|
|
if (clientId == null)
|
|
{
|
|
return JsonError(error);
|
|
}
|
|
|
|
var client = clientDB.client.FirstOrDefault(s => s.id == clientId);
|
|
if (client == null)
|
|
{
|
|
return JsonError(error);
|
|
}
|
|
var clientblack = clientDB.client_black.FirstOrDefault(c => c.Name == client.Name);
|
|
if (clientblack != null)
|
|
{
|
|
return JsonError("该客户为黑名单客户,禁止取消休眠");
|
|
}
|
|
var bankcardService = new ClientBankCardService(CurUser);
|
|
var dt = DateTime.Now;
|
|
client.ProcessOrderId = -2;
|
|
client.ProcessStatus = "已开户";
|
|
client.OptId = CurUser.UserId;
|
|
client.OptName = CurUser.UserName;
|
|
client.OptDate = dt;
|
|
|
|
clientDB.ClientAuditLog.Add(new ClientAuditLog
|
|
{
|
|
ClientId = clientId ?? 0,
|
|
OptType = "取消休眠",
|
|
Changes = string.Empty,
|
|
DataType = "00",
|
|
OptId = CurUser.UserId,
|
|
OptName = CurUser.UserName,
|
|
OptDate = dt
|
|
});
|
|
if (clientId != null)
|
|
{
|
|
bankcardService.SetBankCardValidStateWhenClientReEnable((int)clientId, clientDB);
|
|
}
|
|
clientDB.SaveChanges();
|
|
return JsonSuccess(success);
|
|
}
|
|
|
|
[HttpPost]
|
|
public ActionResult ResetPassword(int clientId)
|
|
{
|
|
var message = new ClientUserPasswordService(CurUser).ResetPassword(clientId);
|
|
return JsonSuccess(message);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 批量向客户发送报告
|
|
/// </summary>
|
|
//[ValidateInput(false)]
|
|
[HttpPost]
|
|
public JsonResult BatchSendClientRiskMonitor(BatchSendClientRiskMonitorModel input, string detailTemplate, string balanceTemplate, List<string> detailReceiver = null, List<string> balanceReceiver = null)
|
|
{
|
|
input.Detail = Uri.UnescapeDataString(input.Detail ?? string.Empty);
|
|
input.MarginDetail = Uri.UnescapeDataString(input.MarginDetail ?? string.Empty);
|
|
var clientIds = DataConvert.ConvertCommaValuesToInt32Array(input.ClientIds);
|
|
var clients = clientDB.client.Where(x => clientIds.Contains(x.id))
|
|
.Select(n => new { n.id, n.Name }).ToArray()
|
|
.Select(n => new KeyValuePair<int, string>(n.id, n.Name)).ToArray();
|
|
IEnumerable<int> userAssetUnits = null;
|
|
if (ConsUserGroup.HasGroup && !ShowAllTrades)
|
|
{
|
|
userAssetUnits = GetUserAssetunitIds();
|
|
}
|
|
var port = Request.Host.Port;
|
|
var tradeListHtmlViewPath = Server.MapPath("~/Statics/views/TradeDetailsListMail.cshtml");
|
|
var extendParams = (input, CurUser, detailTemplate, balanceTemplate, userAssetUnits, tradeListHtmlViewPath, detailReceiver, balanceReceiver);
|
|
if (!ProgressHelper<KeyValuePair<int, string>>.Start(clients, "ClientBalanceReport", SendMailByClient, extendParams))
|
|
{
|
|
return JsonError("线程正在被占用");
|
|
}
|
|
return JsonSuccess("开始发送邮件");
|
|
}
|
|
|
|
private string SendMailByClient(KeyValuePair<int, string> client, object extends)
|
|
{
|
|
var exParam = ((BatchSendClientRiskMonitorModel model, UserInfo CurUser, string detailTemplateName,
|
|
string balanceTemplateName, IEnumerable<int> userAssetUnits, string tradeListHtmlViewPath, List<string> detailReceiver, List<string> balanceReceiver))extends;
|
|
var clientName = client.Value;
|
|
var message = string.Empty;
|
|
var reqModel = exParam.model;
|
|
if (string.IsNullOrWhiteSpace(reqModel.Detail))
|
|
{
|
|
reqModel.Detail = DBCacheManager.Single.GetStr(CacheTable.LuoKuanDesc, exParam.balanceTemplateName);
|
|
reqModel.MarginDetail = DBCacheManager.Single.GetStr(CacheTable.MarginLuoKuanDesc, exParam.balanceTemplateName);
|
|
}
|
|
if (reqModel.HasTradeMarketReport)
|
|
{
|
|
try
|
|
{
|
|
var sheets = DBCacheManager.Single.GetStr(CacheTable.TradeMarketSheets, exParam.balanceTemplateName);
|
|
var ccEmail = DBCacheManager.Single.GetStr(CacheTable.MarketCCEmail, exParam.balanceTemplateName);
|
|
var emailData = new DingShiReportEmail()
|
|
{
|
|
ClientId = client.Key,
|
|
Detail = reqModel.Detail,
|
|
MarginDetail = reqModel.MarginDetail,
|
|
FileTypes = new List<DingShiReportEmail.CheckType>()
|
|
{
|
|
new DingShiReportEmail.CheckType()
|
|
{
|
|
type = "excel",
|
|
@checked = true
|
|
}
|
|
},
|
|
TargetFileType = "excel",
|
|
Title = reqModel.Title,
|
|
From = reqModel.TradeMarketReportDateType == "当日" ? reqModel.ValueDate : (reqModel.TradeMarketReportDateType == "当月区间" ? QdpCalendarHelper.GetNonHoliday(reqModel.ValueDate.Date.AddDays(1 - reqModel.ValueDate.Day)) : DateTime.MinValue),
|
|
To = reqModel.ValueDate,
|
|
CurUserName = exParam.CurUser.UserName,
|
|
SendContent = string.IsNullOrEmpty(sheets) ? new List<string>() { "账户状况", "互换估值", "互换交易流水", "资金明细"} : sheets.Split(',').ToList(),
|
|
PayableFund = -1,//表示从后台获取
|
|
PayableMargin = -1,//表示从后台获取
|
|
ReportType = reqModel.ClientBalanceDataType,
|
|
CCEmail = ccEmail
|
|
};
|
|
try
|
|
{
|
|
var skipCheckMarginCall = DataCacheProvider.GetClientDataSource().AsQueryable().FirstOrDefault(x => x.id == client.Key)?.IsSendRecovery == 0;
|
|
var controller = new clientbalanceController(_viewRenderer)
|
|
{
|
|
reportUser = exParam.CurUser
|
|
};
|
|
var tradeMarketResult = controller.SendReportMails(emailData,
|
|
exParam.userAssetUnits, exParam.CurUser, exParam.balanceTemplateName, true, skipCheckMarginCall: skipCheckMarginCall, recevier: exParam.balanceReceiver).Result;
|
|
|
|
var data = tradeMarketResult.Value as Result;
|
|
if (!data.success)
|
|
{
|
|
message += "[客户" + clientName + "发送结算报告失败," + data.msg + "]; ";
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
LogFactory.GetLogger<clientbalanceController>().Error(e, "GenerateTradeMarketBill2");
|
|
message += "[客户" + clientName + "发送结算报告失败," + e.Message == "The number of columns in PdfPTable constructor must be greater than zero." ? "生成的pdf列表的列数必须大于零,请检查配置列不可为空" : e.Message + "]";
|
|
}
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
LogFactory.GetLogger<ClientController>().Error(e, "发送结算报告失败");
|
|
message += "[客户" + clientName + "发送结算报告失败," + e.Message + "]; ";
|
|
}
|
|
}
|
|
return message;
|
|
}
|
|
|
|
public JsonResult BatchDownloadClientRiskMonitorInProcess(BatchSendClientRiskMonitorModel input, string balanceTemplate = "默认", string detailTemplate = "默认")
|
|
{
|
|
var clientIds = input.ClientIds.Split(',');
|
|
var clients = clientDB.client.Where(x => clientIds.Contains(x.id.ToString())).ToList();
|
|
var extendParams = (input, detailTemplate, balanceTemplate);
|
|
if (!ProgressHelper<Client>.Start(clients, "ClientRiskMonitor", GenerateClientRiskFiles, ZipFiles, extendParams))
|
|
{
|
|
return JsonError("线程正在被占用");
|
|
}
|
|
return JsonSuccess("开始生成文件");
|
|
}
|
|
|
|
private string GenerateClientRiskFiles(Client client, object extends)
|
|
{
|
|
var message = "";
|
|
var exParam = ((BatchSendClientRiskMonitorModel input, string balanceTemplate, string detailTemplate))extends;
|
|
var curUserName = CurUser.UserName;
|
|
var input = exParam.input;
|
|
var tempFolder = Server.MapPath("~/App_Docs/Temp");
|
|
var marketFolder = Path.Combine(tempFolder, "结算报告" + DateTime.Now.ToString("yyyyMMdd"));
|
|
var detailsFolder = Path.Combine(tempFolder, "交易明细" + DateTime.Now.ToString("yyyyMMdd"));
|
|
if (client != null)
|
|
{
|
|
Directory.CreateDirectory(marketFolder);
|
|
Directory.CreateDirectory(detailsFolder);
|
|
var clientName = client.Name;
|
|
|
|
if (input.HasTradeMarketReport)
|
|
{
|
|
try
|
|
{
|
|
var sheets = DBCacheManager.Single.GetStr(CacheTable.TradeMarketSheets, exParam.balanceTemplate);
|
|
var emailData = new DingShiReportEmail()
|
|
{
|
|
ClientId = client.id,
|
|
Detail = input.Detail,
|
|
FileTypes = new List<DingShiReportEmail.CheckType>()
|
|
{
|
|
new DingShiReportEmail.CheckType()
|
|
{
|
|
type = "excel",
|
|
@checked = true
|
|
}
|
|
},
|
|
TargetFileType = "excel",
|
|
Title = "结算报告",
|
|
From = input.TradeMarketReportDateType == "当日" ? input.ValueDate : (input.TradeMarketReportDateType == "当月区间" ? QdpCalendarHelper.GetNonHoliday(input.ValueDate.Date.AddDays(1 - input.ValueDate.Day)) : DateTime.MinValue),
|
|
To = input.ValueDate,
|
|
CurUserName = curUserName,
|
|
SendContent = string.IsNullOrEmpty(sheets) ? new List<string>() { "账户状况", "持仓明细", "历史交易", "资金明细", "质押记录" } : sheets.Split(',').ToList(),
|
|
PayableFund = -1,//表示从后台获取
|
|
PayableMargin = -1,//表示从后台获取
|
|
DownloadFilePath = marketFolder,
|
|
ReportType = input.ClientBalanceDataType
|
|
};
|
|
var controller = new clientbalanceController(_viewRenderer)
|
|
{
|
|
reportUser = CurUser
|
|
};
|
|
controller.GenerateDownloadTradeMarketBill2(emailData, exParam.balanceTemplate);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
message += "[客户" + clientName + "生成结算报告失败," + e.Message + "]; ";
|
|
}
|
|
}
|
|
|
|
if (input.HasTradeDetails)
|
|
{
|
|
try
|
|
{
|
|
var req = new TradeDetailsReq()
|
|
{
|
|
ClientId = client.id,
|
|
StartDate = input.TradeDetailsDateType == "当日" ? input.ValueDate : (input.TradeDetailsDateType == "当月区间" ? QdpCalendarHelper.GetNonHoliday(input.ValueDate.Date.AddDays(1 - input.ValueDate.Day)) : DateTime.MinValue),
|
|
EndDate = input.ValueDate,
|
|
DetailStatuses = "成交,提前终止,到期",
|
|
OutputFolder = detailsFolder
|
|
};
|
|
var biaoTou = DBCacheManager.Single.GetStr(CacheTable.TradeDetailsBiaoTou, exParam.detailTemplate);
|
|
var biaoWei = DBCacheManager.Single.GetStr(CacheTable.TradeDetailsBiaoWei, exParam.detailTemplate);
|
|
var tradeDetailsService = new TradeDetailsQueryService(CurUser);
|
|
tradeDetailsService.ExportReport(req, biaoTou, biaoWei);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
message += "[客户" + clientName + "生成交易明细失败," + e.Message + "]; ";
|
|
}
|
|
}
|
|
}
|
|
return message;
|
|
}
|
|
|
|
private string ZipFiles(object extends)
|
|
{
|
|
var exParam = ((BatchSendClientRiskMonitorModel input, string balanceTemplate, string detailTemplate))extends;
|
|
var tempFolder = Server.MapPath("~/App_Docs/Temp");
|
|
var input = exParam.input;
|
|
var marketFolder = Path.Combine(tempFolder, "结算报告" + DateTime.Now.ToString("yyyyMMdd"));
|
|
var detailsFolder = Path.Combine(tempFolder, "交易明细" + DateTime.Now.ToString("yyyyMMdd"));
|
|
var marketZipFileName = "结算报告"
|
|
+ input.ValueDate.ToString("yyyyMMdd")
|
|
+ ".zip";
|
|
var detailsZipFileName = "交易明细"
|
|
+ input.ValueDate.ToString("yyyyMMdd")
|
|
+ ".zip";
|
|
|
|
var zipWebPath = $"/App_Docs/Temp/";
|
|
var zipLocalFolder = Server.MapPath(zipWebPath);
|
|
Directory.CreateDirectory(zipLocalFolder);
|
|
|
|
var marketZipFile = Path.Combine(zipLocalFolder, marketZipFileName);
|
|
var detailsZipFile = Path.Combine(zipLocalFolder, detailsZipFileName);
|
|
ZipHelper.ZipDirectory(marketFolder, marketZipFile);
|
|
ZipHelper.ZipDirectory(detailsFolder, detailsZipFile);
|
|
|
|
Directory.Delete(marketFolder, true);
|
|
Directory.Delete(detailsFolder, true);
|
|
|
|
return "";
|
|
}
|
|
/// <summary>
|
|
/// 批量下载报告
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
//[ValidateInput(false)]
|
|
[HttpPost]
|
|
public JsonResult BatchDownloadClientRiskMonitor(BatchSendClientRiskMonitorModel input, string balanceTemplate = "默认", string detailTemplate = "默认")
|
|
{
|
|
input.Detail = Uri.UnescapeDataString(input.Detail ?? string.Empty);
|
|
var clientIds = input.ClientIds.Split(',');
|
|
var clients = clientDB.client.Where(x => clientIds.Contains(x.id.ToString()));
|
|
var curUserName = CurUser.UserName;
|
|
var message = "";
|
|
var tempFolder = Server.MapPath("~/App_Docs/Temp");
|
|
var marketFolder = Path.Combine(tempFolder, "结算报告" + DateTime.Now.ToString("yyyyMMddHHmmss"));
|
|
|
|
//如果没有相关数据,会创建一个空文件夹
|
|
Directory.CreateDirectory(marketFolder);
|
|
|
|
foreach (var clientId in clientIds)
|
|
{
|
|
var client = clients.FirstOrDefault(x => x.id.ToString() == clientId);
|
|
if (client != null)
|
|
{
|
|
var clientName = client.Name;
|
|
|
|
if (input.HasTradeMarketReport)
|
|
{
|
|
try
|
|
{
|
|
var sheets = DBCacheManager.Single.GetStr(CacheTable.TradeMarketSheets, balanceTemplate);
|
|
var emailData = new DingShiReportEmail()
|
|
{
|
|
ClientId = int.Parse(clientId),
|
|
Detail = input.Detail,
|
|
FileTypes = new List<DingShiReportEmail.CheckType>()
|
|
{
|
|
new DingShiReportEmail.CheckType()
|
|
{
|
|
type = "excel",
|
|
@checked = true
|
|
}
|
|
},
|
|
TargetFileType = "excel",
|
|
Title = "结算报告",
|
|
From = input.TradeMarketReportDateType == "当日" ? input.ValueDate : (input.TradeMarketReportDateType == "当月区间" ? QdpCalendarHelper.GetNonHoliday(input.ValueDate.Date.AddDays(1 - input.ValueDate.Day)) : DateTime.MinValue),
|
|
To = input.ValueDate,
|
|
CurUserName = curUserName,
|
|
SendContent = string.IsNullOrEmpty(sheets) ? new List<string>() { "账户状况", "持仓明细", "历史交易", "资金明细", "质押记录" } : sheets.Split(',').ToList(),
|
|
PayableFund = -1,//表示从后台获取
|
|
PayableMargin = -1,//表示从后台获取
|
|
DownloadFilePath = marketFolder,
|
|
ReportType = input.ClientBalanceDataType
|
|
};
|
|
var controller = new clientbalanceController(_viewRenderer)
|
|
{
|
|
reportUser = CurUser
|
|
};
|
|
controller.GenerateDownloadTradeMarketBill2(emailData, balanceTemplate);
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
message += "[客户" + clientName + "生成结算报告失败," + e.Message + "]; ";
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
var marketZipFileName = "结算报告"
|
|
+ (input.TradeMarketReportDateType == "当日" ? (input.ValueDate.ToString("yyyyMMdd") + "-") : (input.TradeMarketReportDateType == "当月区间" ? (QdpCalendarHelper.GetNonHoliday(input.ValueDate.Date.AddDays(1 - input.ValueDate.Day)).ToString("yyyyMMdd") + "-") : ""))
|
|
+ input.ValueDate.ToString("yyyyMMdd")
|
|
+ ".zip";
|
|
|
|
var zipWebPath = $"/App_Docs/Temp/";
|
|
var zipLocalFolder = Server.MapPath(zipWebPath);
|
|
Directory.CreateDirectory(zipLocalFolder);
|
|
|
|
var marketZipFile = Path.Combine(zipLocalFolder, marketZipFileName);
|
|
ZipHelper.ZipDirectory(marketFolder, marketZipFile);
|
|
|
|
Directory.Delete(marketFolder, true);
|
|
|
|
if (!string.IsNullOrEmpty(message))
|
|
{
|
|
LogFactory.GetLogger("批量下载客户文件").Error(message);
|
|
}
|
|
|
|
return JsonSuccess("批量下载成功", new
|
|
{
|
|
marketZipFile = zipWebPath + marketZipFileName
|
|
});
|
|
}
|
|
|
|
public ActionResult GetCustomerNaturesByBusinessType(string name)
|
|
{
|
|
var item = DictionaryBLL.GetDictionaryItemByName(name);
|
|
var customerNatures = item == null ? "" : item.ShortName;
|
|
return Json(customerNatures);
|
|
}
|
|
|
|
public ActionResult Clientlevel(int clientid)
|
|
{
|
|
ViewBag.clientid = clientid;
|
|
return View();
|
|
}
|
|
|
|
public ActionResult GetClientParents(int clientid)
|
|
{
|
|
var res = new ClientHierarchyService(CurUser).Treeleveldata(clientid);
|
|
return Json(res);
|
|
}
|
|
|
|
public ActionResult GetMarginType(int clientid)
|
|
{
|
|
var client = clientDB.client.FirstOrDefault(s => s.id == clientid).MarginOptionType;
|
|
return Json(client);
|
|
}
|
|
|
|
#region----可定制编辑页面----
|
|
|
|
public ActionResult ClientEditV2(string enid, bool isView = false, bool isApproval = false)
|
|
{
|
|
var model = new ClientEditViewModel(CurUser)
|
|
{
|
|
editConfig = ClientEditConfigService.GetConfig(true, isView),
|
|
maxAnnexLength = ReportStatusModel.MaxAnnexLength,
|
|
maxRequestLength = PS.Config.UploadFileSizeLimit,
|
|
clientApprovalProcessCount = yldb.approvalprocess.Where(x => x.processType == "OpenProcess").Count()
|
|
};
|
|
|
|
if (string.IsNullOrEmpty(enid) || enid == "0")
|
|
{
|
|
if (!CurUser.客户管理.客户新增)
|
|
{
|
|
return ShowError("抱歉,您没有'客户新增'的权限!");
|
|
}
|
|
model.client = new Client();
|
|
}
|
|
else
|
|
{
|
|
var intid = DataProtectHelper.DecryptInt(enid);
|
|
model.client = clientDB.client.AsNoTracking().FirstOrDefault(n => n.id == intid);
|
|
if (model.client == null)
|
|
{
|
|
return ShowError("找不到客户数据");
|
|
}
|
|
model.client.MetaDic = new ClientMetaService(CurUser).GetMetaDic(intid);
|
|
model.client.ProxyEmailPwd = DataProtectHelper.Decrypt(model.client.ProxyEmailPwd);
|
|
if (isApproval)
|
|
{
|
|
var ca = clientDB.ClientAuditLog.Where(x => x.id == model.client.ApprovalLogId && x.OptType == "提交信息变更审批").FirstOrDefault();
|
|
if (ca != null && ca.Changes != null)
|
|
{
|
|
model.client = ClientHelper.Deserialize(ca.Changes);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (PS.Config.IsGuoJun)
|
|
{
|
|
model.client.ConfirmBookMode = model.client.SupProtocolDate != null ? "单章版" : "双章版";
|
|
}
|
|
|
|
//银行卡
|
|
if (model.editConfig.sections.Any(n => n.tabId == "bankcards"))
|
|
{
|
|
model.editConfig.lists["bankcardList"] = GetBankcards(model.client.id, isApproval);
|
|
}
|
|
|
|
//客户人员信息管理
|
|
if (model.editConfig.sections.Any(n => n.tabId == "dutys"))
|
|
{
|
|
var dutys = GetDutys(model.client.id, isApproval);
|
|
var dic = clientDB.contactype.Where(a => !a.ContactType.Equals("产品投资经理")).ToDictionary(n => n.id, m => m.ContactType);
|
|
if (model.client.ClientType == ClientTypeEnum.产品.ToString())
|
|
{
|
|
dic = clientDB.contactype.ToDictionary(n => n.id, m => m.ContactType);
|
|
}
|
|
if (dutys.Any())
|
|
{
|
|
foreach (var bc in dutys)
|
|
{
|
|
var types = (bc.ContactTypeId ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
|
|
.Select(n => int.TryParse(n, out var id) && dic.TryGetValue(id, out var type) ? type : string.Empty)
|
|
.Where(n => !string.IsNullOrWhiteSpace(n)).ToArray();
|
|
bc.ContactType = string.Join(",", types);
|
|
}
|
|
}
|
|
model.editConfig.lists["dutyList"] = dutys;
|
|
model.editConfig.selects[nameof(contactype.ContactType)] = dic.Select(kv => new SelectItem { Text = kv.Value, Value = kv.Key.ToString() }).ToArray();
|
|
}
|
|
|
|
//客户董事会人员信息管理
|
|
if (model.editConfig.sections.Any(n => n.tabId == "dutysdirector"))
|
|
{
|
|
var dutys = GetDutys(model.client.id, isApproval);
|
|
|
|
var dic = clientDB.contactype.Where(a => !a.ContactType.Equals("产品投资经理")).ToDictionary(n => n.id, m => m.ContactType);
|
|
if (model.client.ClientType == ClientTypeEnum.产品.ToString())
|
|
{
|
|
dic = clientDB.contactype.ToDictionary(n => n.id, m => m.ContactType);
|
|
}
|
|
if (dutys.Any())
|
|
{
|
|
foreach (var bc in dutys)
|
|
{
|
|
var types = (bc.ContactTypeId ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
|
|
.Select(n => int.TryParse(n, out var id) && dic.TryGetValue(id, out var type) ? type : string.Empty)
|
|
.Where(n => !string.IsNullOrWhiteSpace(n)).ToArray();
|
|
bc.ContactType = string.Join(",", types);
|
|
}
|
|
var listDirector = dic.Where(l => l.Value == "控股股东" || l.Value == "董事会成员" || l.Value == "普通股东").Select(n => n.Key.ToString());
|
|
dutys = dutys.Where(l => l.ContactTypeId.Split(',').ToList().Intersect(listDirector).Any()).ToArray();
|
|
}
|
|
model.editConfig.lists["dutydirectorList"] = dutys;
|
|
model.editConfig.selects[nameof(contactype.ContactType)] = dic.Select(kv => new SelectItem { Text = kv.Value, Value = kv.Key.ToString() }).ToArray();
|
|
}
|
|
|
|
//产品投资人
|
|
if (model.editConfig.sections.Any(n => n.tabId == "investors"))
|
|
{
|
|
var investors = model.client.id == 0
|
|
? new ClientInvestor[0]
|
|
: clientDB.ClientInvestor.Where(b => b.ClientId == model.client.id).ToArray();
|
|
model.editConfig.lists["investorList"] = investors;
|
|
}
|
|
|
|
//客户文件管理
|
|
if (model.editConfig.sections.Any(n => n.tabId == "files"))
|
|
{
|
|
model.editConfig.lists["fileList"] = GetClientFiles(model.client.id, isApproval);
|
|
model.editConfig.lists["parentFileList"] = GetClientFiles(model.client.ParentId, isApproval);
|
|
}
|
|
|
|
if (!isView)
|
|
{
|
|
model.client.BookTime = DateTime.Now;
|
|
//string Meg = "";
|
|
//var allFields = model.editConfig.sections.SelectMany(n => n.fields ?? Enumerable.Empty<FormEditField>()).ToArray();
|
|
//var selectFields = allFields.Where(a => (a.type == "select" || a.type == "select-m") && !string.IsNullOrEmpty(a.label) && !a.@readonly).ToList();
|
|
//if (selectFields != null && selectFields.Any())
|
|
//{
|
|
// selectFields.ForEach(a => {
|
|
// var selectItems = Enumerable.Empty<SelectItem>();
|
|
// var dicValue = "";
|
|
// if (!model.editConfig.selects.TryGetValue(a.name, out selectItems) || !(selectItems != null && selectItems.Any()))
|
|
// {
|
|
// Meg = $"请给【{a.label}】字段的下拉框设置选项";
|
|
// }
|
|
// if (a.required && !model.editConfig.defaults.TryGetValue(a.name, out dicValue))
|
|
// {
|
|
// Meg = $"【{a.label}】为必填字段,请给字段的下拉框设置默认值";
|
|
// }
|
|
// });
|
|
//}
|
|
//ViewBag.Meg = Meg;
|
|
}
|
|
ViewBag.LicenseValidTimeStr = model.client.LicenseValidTimeStr == "30001231" ? "长期有效" : model.client.LicenseValidTime?.ToString("yyyy-MM-dd");
|
|
using (var tagService = new TagService(CurUser))
|
|
{
|
|
ViewBag.TagList = tagService.GetTagListByType(TagTypeEnum.Customer);
|
|
if (model.client != null && model.client.id > 0)
|
|
{
|
|
model.Tags = tagService.GetTagByClientId(model.client.id);
|
|
}
|
|
}
|
|
ViewBag.isApproval = isApproval;
|
|
return View(isView ? "clientViewV2" : "clientEditV2", model);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 客户查看页面
|
|
/// </summary>
|
|
public ActionResult ClientViewV2(string enid, bool isApproval = false)
|
|
{
|
|
return ClientEditV2(enid, true, isApproval);
|
|
}
|
|
|
|
public JsonResult UploadFilesV2(string clientEnId, client_file req, string sideProtocolNumber, bool isDirectSubApp = false)
|
|
{
|
|
try
|
|
{
|
|
var files = Request.Form.Files;
|
|
if (files == null || files.Count < 1)
|
|
{
|
|
return JsonError("没有上传文件");
|
|
}
|
|
|
|
req.ClientId = req.ClientId == 0 ? DataProtectHelper.DecryptInt(clientEnId) : req.ClientId;
|
|
|
|
var count = files.Count;
|
|
var uploadFiles = files.ToUploadFileModelList();
|
|
|
|
var ret = new ClientFileService(CurUser).SaveClientFiles(req, sideProtocolNumber, uploadFiles, isDirectSubApp);
|
|
var fileList = GetClientFiles(req.ClientId, true);
|
|
|
|
return JsonSuccessData(new { ret, fileList });
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger("客户文件上传").Error(ex);
|
|
return JsonError("上传文件出错," + ex.Message);
|
|
}
|
|
}
|
|
|
|
public JsonResult AjaxGetClientFilesV2(string clientEnId, bool isApproval = false)
|
|
{
|
|
var clientId = DataProtectHelper.DecryptInt(clientEnId);
|
|
|
|
return JsonSuccessData(GetClientFiles(clientId, isApproval));
|
|
}
|
|
[HttpPost]
|
|
public JsonResult AjaxGetClientFilesV3(int clientId, bool IsEdit)
|
|
{
|
|
if (!IsEdit)
|
|
{
|
|
var clientPrentFile = clientDB.client.First(x => x.id == clientId);
|
|
return JsonSuccessData(GetClientFiles(clientPrentFile.ParentId));
|
|
}
|
|
return JsonSuccessData(GetClientFiles(clientId));
|
|
}
|
|
|
|
private IEnumerable<ClientBankCard> GetBankcards(int clientId, bool isApproval = false)
|
|
{
|
|
var bankcards = clientId == 0 ? new ClientBankCard[0] : clientDB.bankcard.Where(b => b.ClientId == clientId && b.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).ToArray();
|
|
|
|
if (isApproval)
|
|
{
|
|
var notbankcards = bankcards.Where(x => x.SourceId > 0).Select(x => x.SourceId ?? 0).ToList();
|
|
notbankcards.AddRange(bankcards.Where(x => x.ApprovalOrder == (int)ApprovalOrderEnum.删除).Select(x => x.id).ToList());
|
|
bankcards = bankcards.Where(x => !notbankcards.Contains(x.id)).ToArray();
|
|
foreach (var item in bankcards)
|
|
{
|
|
if (item.ApprovalOrder == (int?)ApprovalOrderEnum.失效)
|
|
{
|
|
item.ValidState = "InValid";
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
bankcards = bankcards.Where(x => x.ApprovalOrder < 1).ToArray();
|
|
}
|
|
|
|
return bankcards;
|
|
}
|
|
|
|
private IEnumerable<ClientDuty> GetDutys(int clientId, bool isApproval = false)
|
|
{
|
|
var dutys = clientId == 0 ? new ClientDuty[0] : clientDB.clientduty.Where(b => b.ClientId == clientId && b.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).ToArray();
|
|
|
|
if (isApproval)
|
|
{
|
|
var notdutys = dutys.Where(x => x.SourceId > 0).Select(x => x.SourceId ?? 0).ToList();
|
|
notdutys.AddRange(dutys.Where(x => x.ApprovalOrder == (int?)ApprovalOrderEnum.删除).Select(x => x.id).ToList());
|
|
dutys = dutys.Where(x => !notdutys.Contains(x.id)).ToArray();
|
|
}
|
|
else
|
|
{
|
|
dutys = dutys.Where(x => x.ApprovalOrder < 1).ToArray();
|
|
}
|
|
|
|
return dutys;
|
|
}
|
|
|
|
|
|
private IEnumerable<client_file> GetClientFiles(int clientId, bool isApproval = false)
|
|
{
|
|
var clientFiles = clientDB.client_file.Where(x => x.ClientId == clientId && x.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).ToList();
|
|
|
|
if (isApproval)
|
|
{
|
|
var notclientFiles = clientFiles.Where(x => x.SourceId > 0 && x.SourceId != x.id).Select(x => x.SourceId ?? 0).ToList();
|
|
notclientFiles.AddRange(clientFiles.Where(x => x.ApprovalOrder == (int)ApprovalOrderEnum.删除).Select(x => x.id).ToList());
|
|
clientFiles = clientFiles.Where(x => !notclientFiles.Contains(x.id)).ToList();
|
|
}
|
|
else
|
|
{
|
|
clientFiles = clientFiles.Where(x => x.ApprovalOrder < 1).ToList();
|
|
}
|
|
|
|
foreach (var file in clientFiles)
|
|
{
|
|
if (file.SignDate.HasValue && file.SignDate.Value == DateTime.MinValue)
|
|
{
|
|
file.SignDate = null;
|
|
}
|
|
if (file.BookTime.HasValue && file.BookTime.Value == DateTime.MinValue)
|
|
{
|
|
file.BookTime = null;
|
|
}
|
|
if (file.BookTime == null)
|
|
{
|
|
file.BookTime = file.OptDate;
|
|
}
|
|
if (new ClientFileService(CurUser).getBackRecordV2(file.ClientId, file.ProtocolNumber) != null && (!file.HasSent))
|
|
{
|
|
file.FlagStr = "#CB#";//可以回退
|
|
}
|
|
|
|
if (isApproval)
|
|
{
|
|
if (file.ApprovalOrder == (int?)ApprovalOrderEnum.文件解除废弃 || file.ApprovalOrder == (int)ApprovalOrderEnum.文件还原)
|
|
{
|
|
file.IsValid = true;
|
|
}
|
|
else if (file.ApprovalOrder == (int?)ApprovalOrderEnum.失效 || file.ApprovalOrder == (int?)ApprovalOrderEnum.文件中转失效 || file.ApprovalOrder == (int)ApprovalOrderEnum.删除 || file.ApprovalOrder == (int)ApprovalOrderEnum.文件中转删除 || file.ApprovalOrder == (int)ApprovalOrderEnum.文件废弃)
|
|
{
|
|
file.IsValid = false;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
clientFiles = clientFiles.Where(x => x.IsValid).ToList();
|
|
return clientFiles;
|
|
}
|
|
|
|
#endregion
|
|
|
|
/// <summary>
|
|
/// 保存客户信息
|
|
/// </summary>
|
|
public JsonResult UpdateClientFundThresholdJson(ClientReq req)
|
|
{
|
|
var client = new Client();
|
|
client = clientDB.client.Where(n => n.id == req.id).FirstOrDefault();
|
|
if (client != null)
|
|
{
|
|
if (!clientDB.client_Axis_Fundthresholds.Where(x => x.ClientId == client.id).Any() && client.FundThreshold > 0)
|
|
{
|
|
var client_Axis_F = new Client_Axis_Fundthreshold()
|
|
{
|
|
ClientId = client.id,
|
|
ValueDate = DateTime.MinValue,
|
|
FundThreshold = client.FundThreshold ?? 0,
|
|
OptId = 0,
|
|
OptName = "历史阈值",
|
|
OptDate = DateTime.Now,
|
|
};
|
|
clientDB.client_Axis_Fundthresholds.Add(client_Axis_F);
|
|
}
|
|
|
|
if (clientDB.client_Axis_Fundthresholds.Where(x => x.ClientId == client.id && x.ValueDate == valuedateBLL.ValueDate).Any())
|
|
{
|
|
var client_Axis_Fundthresholds = clientDB.client_Axis_Fundthresholds.Where(x => x.ClientId == client.id && x.ValueDate == valuedateBLL.ValueDate).FirstOrDefault();
|
|
client_Axis_Fundthresholds.FundThreshold = req.FundThreshold ?? 0;
|
|
client_Axis_Fundthresholds.OptId = CurUser.UserId;
|
|
client_Axis_Fundthresholds.OptName = CurUser.UserName;
|
|
client_Axis_Fundthresholds.OptDate = DateTime.Now;
|
|
}
|
|
else
|
|
{
|
|
var client_Axis_Fundthresholds = new Client_Axis_Fundthreshold()
|
|
{
|
|
ClientId = client.id,
|
|
ValueDate = valuedateBLL.ValueDate,
|
|
FundThreshold = req.FundThreshold ?? 0,
|
|
OptId = CurUser.UserId,
|
|
OptName = CurUser.UserName,
|
|
OptDate = DateTime.Now,
|
|
};
|
|
clientDB.client_Axis_Fundthresholds.Add(client_Axis_Fundthresholds);
|
|
}
|
|
|
|
client.FundThreshold = req.FundThreshold;
|
|
clientDB.SaveChanges();
|
|
return JsonSuccess("更新成功", client);
|
|
}
|
|
else
|
|
{
|
|
return JsonError("更新失败");
|
|
}
|
|
}
|
|
|
|
public ActionResult ClientTemplateChoose()
|
|
{
|
|
var model = new ClientConfirmTemplateService(CurUser).GetClientTemplates();
|
|
return View(model);
|
|
}
|
|
|
|
public JsonResult UploadComfirmsTemplate()
|
|
{
|
|
var files = Request.Form.Files;
|
|
if (files == null || !files.Any())
|
|
{
|
|
return JsonError("缺少上传文件");
|
|
}
|
|
var dir = Path.Combine(GlobalConfig.PluginFolder, $"App_Docs\\OtherTemplate\\");
|
|
using (var stream = files[0].OpenReadStream())
|
|
using (var fstream = System.IO.File.OpenWrite(Path.Combine(dir, files[0].FileName)))
|
|
{
|
|
stream.CopyTo(fstream);
|
|
}
|
|
return JsonSuccess("上传成功!");
|
|
}
|
|
|
|
public ActionResult ClientConfirmTemplateEdit(int id = 0)
|
|
{
|
|
var r = DbContextFactory.GetClientDbContext(CurUser).ClientMeta.Find(id);
|
|
if (r != null)
|
|
{
|
|
return View(new ConfirmsTemplate()
|
|
{
|
|
meta_id = r.id,
|
|
Clients = new List<int> { r.ClientId },
|
|
ClientId = r.ClientId,
|
|
ClientName = DataCacheProvider.GetClientDataSource().GetData(r.ClientId).Name,
|
|
fileType = r.MetaKey,
|
|
fileName = r.MetaValue
|
|
});
|
|
}
|
|
return View(new ConfirmsTemplate());
|
|
}
|
|
|
|
public JsonResult ClientConfirmTemplateDelete(int id)
|
|
{
|
|
new ClientConfirmTemplateService(CurUser).DeleteTemplate(id);
|
|
return JsonSuccess("删除成功!");
|
|
}
|
|
|
|
public JsonResult ClientConfirmTemplateEditJson(ConfirmsTemplate setting)
|
|
{
|
|
new ClientConfirmTemplateService(CurUser).SaveConfirmTemplates(setting);
|
|
return JsonSuccess("设置成功!");
|
|
}
|
|
|
|
public static List<SelectListItem> GetConfirmTemplates()
|
|
{
|
|
var ret = new List<SelectListItem>();
|
|
var dir = Path.Combine(GlobalConfig.PluginFolder, $"App_Docs\\OtherTemplate\\");
|
|
var templates = Directory.GetFiles(dir);
|
|
foreach (var item in templates)
|
|
{
|
|
ret.Add(new SelectListItem()
|
|
{
|
|
Text = item.Split('\\').LastOrDefault(),
|
|
Value = item.Split('\\').LastOrDefault(),
|
|
});
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 导入预付金参数
|
|
/// </summary>
|
|
public ActionResult ImportDongGuanClient(IFormFile file)
|
|
{
|
|
DongGuanClientImportResult result = null;
|
|
if (Path.GetExtension(file?.FileName)?.ToLowerInvariant() != ".xlsx")
|
|
{
|
|
ViewData["ERROR"] = "请上传xlsx格式文件";
|
|
}
|
|
else
|
|
{
|
|
try
|
|
{
|
|
using var openStream = file.OpenReadStream();
|
|
result = new ClientImportService(CurUser).ImportDongGuanClient(openStream);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LogFactory.GetLogger("ImportDongGuanClient").Error(ex);
|
|
ViewData["ERROR"] = "导入出错:" + ex.Message;
|
|
}
|
|
}
|
|
return View("ImportDongGuanClientView", result);
|
|
}
|
|
|
|
public ActionResult ImportDongGuanClientView()
|
|
{
|
|
return View();
|
|
}
|
|
|
|
public JsonResult GetIsApprove(string enid)
|
|
{
|
|
var clientId = DataProtectHelper.DecryptInt(enid);
|
|
if (clientId > 0 && clientDB.client.Find(clientId).ApprovalStatus == "审批中")
|
|
{
|
|
return JsonSuccessData(false);
|
|
}
|
|
bool IsApprove = clientDB.bankcard.Where(b => b.ClientId == clientId && b.ApprovalOrder != (int)ApprovalOrderEnum.无需审批 && b.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).Any();
|
|
IsApprove |= clientDB.clientduty.Where(b => b.ClientId == clientId && b.ApprovalOrder != (int)ApprovalOrderEnum.无需审批 && b.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).Any();
|
|
IsApprove |= clientDB.client_file.Where(b => b.ClientId == clientId && b.ApprovalOrder != (int)ApprovalOrderEnum.无需审批 && b.ApprovalOrder != (int)ApprovalOrderEnum.审批作废).Any();
|
|
return JsonSuccessData(IsApprove);
|
|
}
|
|
|
|
public JsonResult CancelApprove(string enid)
|
|
{
|
|
var clientId = DataProtectHelper.DecryptInt(enid);
|
|
new ClientProcessLogService(CurUser).revertBankDutyFile(clientId);
|
|
return JsonSuccess();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 填充客户收盘的历史交易费用、利息金额
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
[AllowAnonymous]
|
|
public JsonResult FillClientBalanceHisData()
|
|
{
|
|
Task.Run(() =>
|
|
{
|
|
ClientBalanceUtility.FillClientBalanceHisTradeFee();
|
|
});
|
|
return JsonSuccess();
|
|
}
|
|
}
|
|
} |