using BaseOUDAL; using OfficeOpenXml; using OfficeOpenXml.Style; using Org.BouncyCastle.Ocsp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using YieldChain.Helpers; using YLErp.BLL; using YLErp.BLL.EodSettlement; using YLErp.Configuration; using YLErp.Core.Helpers; using YLErp.Enums; using YLErp.Helpers; using YLErp.Model; using YLErp.Modules.ClientModule; using YLErp.Modules.DataCacheModule; using YLErp.Modules.SwapModule; using YLErp.Office; using YLErp.QdpModule; namespace YLErp.Modules.ReportModule.SettlementReportModule { /// /// 山西固收结算报告 /// public class SettlementReportFotShanXiService : YLBaseService { public SettlementReportFotShanXiService(OptUserInfo userInfo) : base(userInfo) { } public ClientDingShiReport_ShanXi GetReportData(DingShiReportEmail emailData, IEnumerable userAssetUnits, string template = "") { var report = new ClientDingShiReport_ShanXi() { ReportFrom = emailData.From, ReportEnd = emailData.To }; report.client = DataCacheProvider.GetClientDataSource().GetData(emailData.ClientId); report.CurUserName = emailData.CurUserName; report.OptUserInfo = this.UserInfo; report.ClientBank = new ClientDBContext().bankcard.Where(x => x.ApprovalOrder < 1 && x.ClientId == emailData.ClientId && x.ValidState != "InValid").ToList(); var swapEodPositionService = new SwapEodPositionService(this); #region 账户状况 if (emailData.SendContent.Contains("账户状况")) { var IsGap = false; var IsOuter = false; if (emailData.ReportType == "ClientBalanceGap") { IsGap = true; } if (emailData.ReportType == "GetOuterMargin") { IsOuter = true; } report.FundReportModel = GetFundReport(emailData,IsGap,IsOuter); } #endregion if (emailData.SendContent.Contains("互换估值")) { var eodReq = new ClientSwapPositionRequest { ClientId = emailData.ClientId, ValueDate = emailData.To, ValueDateFrom = emailData.From,page=1, rows=10000,StructureType= "普通债券类收益互换" }; report.EodSwapPositions = swapEodPositionService.SearchEodPositionList(eodReq).rows.ToList(); } if (emailData.SendContent.Contains("互换持仓明细")) { var eodReq = new ClientSwapPositionRequest { ClientId = emailData.ClientId, ValueDate = emailData.To, ValueDateFrom = emailData.From, page = 1, rows = 10000 }; report.SwapPositions = swapEodPositionService.SearchPositionList(eodReq).rows.ToList(); } if (emailData.SendContent.Contains("互换交易流水")) { var eodReq = new ClientSwapPositionRequest { ClientId = emailData.ClientId, ValueDate = emailData.To, ValueDateFrom = emailData.From, page = 1, rows = 10000 }; report.clientSwapPositions = new SwapFlowEventService(UserInfo).SearchPositionFlowEvent(eodReq).rows.ToList(); } if (emailData.SendContent.Contains("资金明细")) { var eereq = new EntryExitReq() { ClientId = emailData.ClientId, HappenDateStart = emailData.From, HappenDateEnd = emailData.To, ParentFlag = emailData.ParentFlag }; report.ClientCashInCashOutExtendList = SearchListExtendOnly(eereq); } if (emailData.SendContent.Contains("质押记录")) { var productReq = new clientcashincashout_productReq() { ClientId = emailData.ClientId, ValueDate = emailData.To, ParentFlag = emailData.ParentFlag }; report.clientcashincashout_productLinq = SearchListOnlyForMarketReport(productReq); } //txt报告特殊处理用到 var desc = DBCacheManager.Single.GetStr(CacheTable.DingShiDesc, template: template); if (string.IsNullOrWhiteSpace(desc)) { desc = DBCacheManager.Single.GetStr(CacheTable.DingShiDesc); } var descList = Regex.Split(desc, "

", RegexOptions.IgnoreCase).Where(x => !string.IsNullOrWhiteSpace(x)).ToList(); var newDescList = new List(); descList.ForEach(x => { x = Regex.Replace(x, "<[^>]+>", ""); x = Regex.Replace(x, "&[^;]+;", ""); newDescList.Add(x); }); report.downloadFilePath = emailData.DownloadFilePath; report.descList = newDescList; report.desc = desc;//string.Join("\n", newDescList); if (string.IsNullOrWhiteSpace(emailData.Title)) { emailData.Title = DBCacheManager.Single.GetStr(CacheTable.ClientBalanceReportTiltle, template: template); } report.Title = ReplaceWildcard(emailData.Title, report); return report; } /// /// 发送邮件 /// /// /// /// /// /// /// /// /// public (EmailTradeConfirmResultType status, string message) SendSettlementReports(DingShiReportEmail emailData, ClientDingShiReport_ShanXi report, string template, bool IsSkipCheckMarginCall = false, List recevier = null) { LogFactory.GetLogger().Info("开始发邮件[info]SendSettlementReports"); string message = null; var attachFiles = new List(); List fileTypes=new List(); emailData.FileTypes.ForEach(type => { if (type.@checked) { fileTypes.Add(type.type.ToLower()); } }); if (fileTypes.Contains("pdf")) { var filepath = GenerateFileEntry(report, "pdf"); if (!string.IsNullOrEmpty(filepath)) { attachFiles.Add(filepath); } if (fileTypes.Contains("excel")) { filepath = filepath.Replace(".pdf",".xlsx"); attachFiles.Add(filepath); } } else { var filepath = GenerateFileEntry(report, "excel"); if (!string.IsNullOrEmpty(filepath)) { attachFiles.Add(filepath); } } // 要向该客户的所有订阅了邮件通知的人员发送邮件 var emails = ClientDataQueryService.GetClientEmails(report.client.id, false, recevier,true); var status = EmailTradeConfirmResultType.Succeed; if (emails.All(o => string.IsNullOrWhiteSpace(o))) { status = EmailTradeConfirmResultType.NoEmailSetting; } else { emails = emails.Where(o => !string.IsNullOrWhiteSpace(o)); var title = report.Title; var detail = emailData.Detail; detail = ReplaceWildcard(detail, report); var mailFrom = DBCacheManager.Single.GetStr(CacheTable.TradeMarketSendUser, template); if (string.IsNullOrWhiteSpace(mailFrom)) { mailFrom = DBCacheManager.Single.GetStr(CacheTable.TradeMarketSendUser); } LogFactory.GetLogger().Info("开始发邮件[info]SendSettlementReports_start"); message = EmailHelper.SendMail(string.Join(";", emails), title, detail, true, attachFiles, emailData.CCEmail, mailFrom); LogFactory.GetLogger().Info($"开始发邮件[info]SendSettlementReports_end {message}"); if (!string.IsNullOrEmpty(message)) { status = EmailTradeConfirmResultType.EmailSentFailed; } } return (status, message); } /// /// 生成附件 /// /// /// /// /// public string GenerateFileEntry(ClientDingShiReport_ShanXi report, string type) { var filepath = GenerateReportExcel(report, type.ToLower() == "pdf"); return filepath; } public string GenerateReportExcel(ClientDingShiReport_ShanXi report,bool needToPdf) { var tempFolder = OtcAppContext.MapPath("~/App_Docs/Temp/结算报告"); tempFolder = MosPathHelper.Combine(tempFolder, ""); var targetPath = string.IsNullOrEmpty(report.downloadFilePath) ? Path.Combine(tempFolder, report.ReportEnd.ToString("yyyyMMdd")) : report.downloadFilePath; if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } var clientName = report.client.Name; var fileName = report.ReportFrom == DateTime.MinValue ? $"证券_估值表_{report.ReportEnd:yyyyMMdd}_{clientName}" : $"证券_估值表_{report.ReportFrom:yyyyMMdd}_{report.ReportEnd:yyyyMMdd}_{clientName}"; var targetFileName = Path.Combine(targetPath, $"{fileName}.xlsx"); var excelDeclareModel = new ExcelDeclareModel() { Company = PS.Config.CompanyFullName,// PS.Config.Company.ToString() + "风险管理有限公司", CurDay = DateTime.Now.Date.ToString("yyyy年MM月dd日"), CurTime = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss"), CurUser = string.IsNullOrEmpty(report.CurUserName) ? OptUser.UserName : report.CurUserName, Name = report.client.Name, Number = report.client.Number, ReportEnd = report.ReportEnd.ToString("yyyy年MM月dd日"), ReportFrom = report.ReportFrom.ToString("yyyy年MM月dd日") == "0001年01月01日" ? "" : report.ReportFrom.ToString("yyyy年MM月dd日"), Title = report.Title, DescList=report.descList, Desc=report.desc }; var modelDict = new Dictionary(); if (report.FundReportModel != null) { report.FundReportModel.ExcelDeclareModel = excelDeclareModel; modelDict.Add("账户状况", report.FundReportModel); } if (report.EodSwapPositions != null) { modelDict.Add("互换估值", new { EodSwapPositions = report.EodSwapPositions, PosiNotionalValueSum= report.EodSwapPositions.Sum(x => x.position.PosiNotionalValue), PosiQuantitySum= report.EodSwapPositions.Sum(x => x.position.PosiQuantity), PeriodAmountSum= report.EodSwapPositions.Sum(x => x.PeriodAmount), InterestAmountSum= report.EodSwapPositions.Sum(x => x.InterestAmount), PosiFeePendingSum = report.EodSwapPositions.Sum(x => x.position.PosiFeePending), PosiProfitSum= report.EodSwapPositions.Sum(x => x.position.PosiProfitSum), NetSettmentAmountSum= report.EodSwapPositions.Sum(x => x.NetSettmentAmount), }); } if (report.SwapPositions != null) { modelDict.Add("互换持仓明细", report.SwapPositions); } if (report.clientSwapPositions != null) { modelDict.Add("互换交易流水", new { ClientSwapPositions = report.clientSwapPositions, TradeFeeSum= report.clientSwapPositions.Sum(x => x.TradeFee), TradingFeeSum= report.clientSwapPositions.Sum(x => x.TradingFee), PosiPnlSum = report.clientSwapPositions.Sum(x => x.PosiPnl), DividendInSum= report.clientSwapPositions.Sum(x => x.FlowEvent.DividendIn), InterestAmountSum= report.clientSwapPositions.Sum(x => x.FlowEvent.InterestClosePnL), InterestFeeSum= report.clientSwapPositions.Sum(x => x.FlowEvent.InterestFee), NetSettmentAmountSum = report.clientSwapPositions.Sum(x => x.NetSettmentAmount), }); } if (report.ClientCashInCashOutExtendList != null) { modelDict.Add("资金明细", new { ClientCashInCashOutList = report.ClientCashInCashOutExtendList, MoneyToShowSum = report.ClientCashInCashOutExtendList.Sum(x => x.MoneyToShow), MoneyInOutSum = report.ClientCashInCashOutExtendList.Sum(x => x.MoneyInOut), MoneyPriceSum = report.ClientCashInCashOutExtendList.Sum(x => x.MoneyPrice), MoneyUnwindExerSum = report.ClientCashInCashOutExtendList.Sum(x => x.MoneyUnwindExer), MoneyOtherSum = report.ClientCashInCashOutExtendList.Sum(x => x.MoneyOther) }); } if (report.clientcashincashout_productLinq != null) { modelDict.Add("质押记录", report.clientcashincashout_productLinq); } var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string sourceFileName = Path.Combine(sourcePath, $"结算报告模板.xlsx"); ExcelPackage.LicenseContext = LicenseContext.NonCommercial; var pdffile = ExcelTemplate.GeneratePDFFromExeclTemplate(sourcePath, sourceFileName, modelDict, targetPath, targetFileName , shouldDeleteSheet: true, needToPdf: false); if (needToPdf) { var targetPdfFileName = FileHelper.ReplaceExtension(targetFileName, ".pdf"); ConvertToPdfHelper.ConvertPDFByApi(HttpUtility.UrlEncode(targetFileName), HttpUtility.UrlEncode(targetPdfFileName)); return targetPdfFileName; } return Path.Combine(targetPath, targetFileName); } /// /// 财务状况 /// /// /// /// /// private FundReportModel GetFundReport(DingShiReportEmail emailData,bool IsGap,bool IsOuter) { var clientBalance = ClientBalanceUtility.GetClientBanlances(new List { emailData.ClientId }, emailData.From, emailData.To, IsClientBalanceGap: IsGap, IsGetOuterMarginGap: IsOuter, ParentFlag: emailData.ParentFlag).FirstOrDefault(); var FundReportModel = new FundReportModel() { LastDayRemainFund = clientBalance?.LastDayRemainFund ?? 0, LastDayRemainFundWithProduct = clientBalance?.LastDayRemainFundWithProduct ?? 0, CashInCashOutChange = clientBalance?.NetFundAll ?? 0, CashInChange = clientBalance?.InFund ?? 0, CashOutChange = clientBalance?.OutFund ?? 0, CashInCashOutOther = clientBalance?.OtherFund ?? 0, CashInCashOutProductChange = clientBalance?.CashInCashOutProductChange ?? 0, OptionPremium = clientBalance?.OptionPremium ?? 0, OptionPremiumSwap = clientBalance?.OptionPremiumSwap ?? 0, SettlementBalance = clientBalance?.SettlementBalance ?? 0, UnwindBalance = clientBalance?.UnwindBalance ?? 0, ExerciseBalance = clientBalance?.ExerciseBalance ?? 0, SwapBalance = clientBalance?.SwapBalance ?? 0, Coupon = clientBalance?.Coupon ?? 0, TodayRemianFund = clientBalance?.AmountFund ?? 0, TodayRemianFundProduct = clientBalance?.AmountFundWithProduct ?? 0, GuaranteesTotalAmount = clientBalance?.GuaranteesTotalAmount ?? 0, WorstCastClientPayable = clientBalance?.MinusPayableMarginTotal ?? 0, AvailableFund = clientBalance?.AvailableAmount ?? 0, TotalMargin = clientBalance?.TotalMarginTotal, Credit = clientBalance?.TotalCredit ?? 0, CreditRatio = clientBalance?.CreditUsed ?? 0, Margin = clientBalance?.MarginByPayableMarginTotal ?? 0, Amount = (PS.Config.IsPVRounded ? clientBalance?.RoundedTotalAmountTotal : clientBalance?.TotalAmountTotal) ?? 0, TotalPnl = (PS.Config.IsPVRounded ? (decimal)(clientBalance?.RoundedPositionPnl ?? 0) : (decimal)(clientBalance?.PositionPnl ?? 0)), PositionPremiumNetCash = clientBalance?.PositionPremiumNetCash ?? 0, SellTradePrice = clientBalance?.SellTradePrice, LastDayPositionPremiumNetCash = clientBalance?.LastDayPositionPremiumNetCash ?? 0, WinLoss =Math.Round( clientBalance?.WinLoss ?? 0,ConsGlobal.MoneyRound,MidpointRounding.AwayFromZero), ClosedTradeFundGap = clientBalance?.ClosedTradeFundGap ?? 0, ClosedTradePayableFund = clientBalance?.ClosedTradePayableFundTotal ?? 0, PositionTradePayableFund = clientBalance?.MarginByPayableMarginTotal ?? 0, DesirableFund = clientBalance?.DesirableFundTotal ?? 0, PayableFund = emailData.PayableFund >= 0 ? emailData.PayableFund : (clientBalance?.PayableFundTotal ?? 0), PositionPv = PS.Config.IsPVRounded ? (clientBalance?.RoundedPositionPv ?? 0) : (clientBalance?.PositionPv ?? 0), PrepaymentAmount = clientBalance?.PrepaymentAmount, PositionPnl = PS.Config.IsPVRounded ? (clientBalance?.RoundedPositionPnl ?? 0) : (clientBalance?.PositionPnl ?? 0), TotalNetSettlement = clientBalance?.TotalNetSettlementTotal ?? 0, ClientSellPositionPnl = clientBalance?.ClientSellPositionPnl, FreezePremium = clientBalance?.FreezePremium, EndDesirableFund = clientBalance?.EndDesirableFund ?? 0, MySideMargin= clientBalance?.MySideMargin, MarginBalance= clientBalance?.MarginBalance, NetFundAll = clientBalance?.NetFundAll, SwapMarketAmount= clientBalance?.SwapMarketAmount, VmFundSum= clientBalance?.VmFundSum, MaintenanceMargin=clientBalance?.MaintenanceMargin, }; return FundReportModel; } /// /// 资金明细 /// /// /// private List SearchListExtendOnly(EntryExitReq req) { req.State = "已确认,已结算"; req.Direction = $"入金,出金,其他收入,其他支出,应收"; req.TradeAction = $"{ClientCashInCashOut.系统操作_行权费},{ClientCashInCashOut.系统操作_平仓费},{ClientCashInCashOut.系统操作_期权费},{ClientCashInCashOut.系统操作_票息},{ClientCashInCashOut.系统操作_互换},{ClientCashInCashOut.系统操作_应付预付金},{ClientCashInCashOut.系统操作_预付金返息}"; req.IsMoneyNotEqualsZero = true; var sList = new EntryExitBLL().SearchListExtendOnly(req); return sList; } /// /// 质押记录 /// /// /// private List SearchListOnlyForMarketReport(clientcashincashout_productReq req) { var bll = new clientcashincashout_productBLL(); var sList = bll.SearchListOnlyForMarketReport(req); return sList; } private string ReplaceWildcard(string input, ClientDingShiReport_ShanXi report) { if (!string.IsNullOrEmpty(input)) { input = Regex.Replace(input, @"\{\{(.*?)\}\}", m => { switch (m.Groups[1].Value) { case "客户名称": return report.client.Name; case "客户编号": return report.client.Number; case "支付截止时间": if (PS.Config.Company == CompanyEnum.宏源) { return DateTime.Now.Hour >= 15 ? QdpCalendarHelper.GetNonHoliday(DateTime.Now.AddDays(1)).ToString("yyyy年MM月dd日") + "上午11时" : QdpCalendarHelper.GetNonHoliday(DateTime.Now).ToString("yyyy年MM月dd日") + "下午16:30"; } else if (PS.Config.Company == CompanyEnum.浙期) { return QdpCalendarHelper.GetNonHoliday(DateTime.Now < DateTime.Now.Date.AddHours(11).AddMinutes(30) ? DateTime.Now : DateTime.Now.AddDays(1)).ToString("yyyy年MM月dd日") + "上午11:30"; } else { return QdpCalendarHelper.GetNonHoliday(DateTime.Now < DateTime.Now.Date.AddHours(9).AddMinutes(30) ? DateTime.Now : DateTime.Now.AddDays(1)).ToString("yyyy年MM月dd日") + "上午9:30"; } case "追保金额": return report.FundReportModel.PositionTradePayableFundString; case "大写追保金额": return NumberHelper.CmycurD(report.FundReportModel.PositionTradePayableFund ?? 0); case "预付金余额": return report.FundReportModel.MarginBalanceString; case "初始保证金金额": return report.FundReportModel.MySideMarginString; case "发送日期": return DateTime.Now.ToString("yyyy-MM-dd"); case "可用资金": return report.FundReportModel.AvailableFundString; case "可取资金": return report.FundReportModel.DesirableFundString; case "起始日期": return report.ReportFrom.ToString("yyyy-MM-dd"); case "结束日期": return report.ReportEnd.ToString("yyyy-MM-dd"); case "开户行": if (report.ClientBank.Any()) { var Bank = new StringBuilder(); report.ClientBank.ForEach(x => { Bank.Append(x.Bank).Append(","); }); return Bank.ToString().Substring(0, Bank.ToString().Length - 1); } return string.Empty; case "户名": if (report.ClientBank.Any()) { var ClientName = new StringBuilder(); report.ClientBank.ForEach(x => { ClientName.Append(x.ClientName).Append(","); }); return ClientName.ToString().Substring(0, ClientName.ToString().Length - 1); } return string.Empty; case "账号": if (report.ClientBank.Any()) { var Card = new StringBuilder(); report.ClientBank.ForEach(x => { Card.Append(x.Card).Append(","); }); return Card.ToString().Substring(0, Card.ToString().Length - 1); } return string.Empty; case "期末结存": return report.FundReportModel.TodayRemianFundString; default: return string.Empty; } }); } return input; } } }