using BaseOUDAL; using NPOI.SS.Formula.Functions; using OfficeOpenXml; using OfficeOpenXml.Style; using System.Drawing; using System.Linq.Extend; using System.Text; using System.Text.RegularExpressions; using YLErp.BLL; using YLErp.BLL.EodSettlement; using YLErp.Commons; 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.EodModule; using YLErp.Modules.ReportModule.SettlementReportModule; using YLErp.Modules.TradeModule.SwapModule; using YLErp.Office; using YLErp.QdpModule; namespace YLErp.Modules.ReportModule { /// /// 结算报告服务 /// public class SettlementReportService : YLBaseService { public SettlementReportService(OptUserInfo userInfo) : base(userInfo) { } /// /// from:trade_spancontroller.GetReportData /// public ClientDingShiReport GetReportData(DingShiReportEmail emailData, IEnumerable userAssetUnits, string template = "") { if (PS.Config.Is申万) { emailData.FileTypes = new List() { new DingShiReportEmail.CheckType() { @checked = true, type = "PDF" } }; emailData.PayableFund = -1; emailData.PayableMargin = -1; emailData.TargetFileType = "PDF"; emailData.SendContent = new List() { "账户状况", "持仓明细", "历史交易", "资金明细" }; } var report = new ClientDingShiReport() { ReportFrom = emailData.From, ReportEnd = emailData.To }; report.client = DataCacheProvider.GetClientDataSource().GetData(emailData.ClientId); report.OptUserInfo = this.UserInfo; report.ClientBank = new ClientDBContext().bankcard.Where(x => x.ApprovalOrder < 1 && x.ClientId == emailData.ClientId && x.ValidState != "InValid").ToList(); if (PS.Config.Is申万) { emailData.Title = "场外衍生品-" + report.client.Name + "对账单-" + emailData.To.ToString("yyyyMMdd"); report.Title = emailData.Title; emailData.Detail = "

" + report.client.Name + ":

" + "

附件为" + emailData.To.ToString("yyyy年M月d日") + "场外衍生品对账单,请查收。

" + "-----------------------------------
" + "swzfotc@sywgqh.com.cn"; } report.CurUserName = emailData.CurUserName; //账户状况一定要发送 if (emailData.SendContent.Contains("账户状况")) { #region 账户状况 var IsGap = false; var IsOuter = false; if (emailData.ReportType == "ClientBalanceGap") { IsGap = true; } if (emailData.ReportType == "GetOuterMargin") { IsOuter = true; } var clientBalance = ClientBalanceUtility.GetClientBanlances(new List { emailData.ClientId }, emailData.From, emailData.To, IsClientBalanceGap: IsGap, IsGetOuterMarginGap: IsOuter, ParentFlag: emailData.ParentFlag).FirstOrDefault(); report.FundReportModel = new FundReportModel() { LastDayRemainFund = clientBalance?.LastDayRemainFund ?? 0, LastDayRemainFundWithProduct = clientBalance?.LastDayRemainFundWithProduct ?? 0, CashInCashOutChange = clientBalance?.NetFund ?? 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 = clientBalance?.WinLoss ?? 0, ClosedTradeFundGap = clientBalance?.ClosedTradeFundGap ?? 0, ClosedTradePayableFund = clientBalance?.ClosedTradePayableFundTotal ?? 0, PositionTradePayableFund = clientBalance?.PositionTradePayableFundTotal ?? 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 }; if (PS.Config.Is申万 && report.FundReportModel.Margin > 0) { emailData.Title = emailData.To.ToString("yyyyMMdd") + report.client.Name + "追保通知"; report.Title = emailData.Title; emailData.Detail = "

" + report.client.Name + ":

" + "

截至" + emailData.To.ToString("yyyy年M月d日") + "收盘,贵公司当前预付金总额为" + report.FundReportModel.TotalMargin?.ToString("0.00") + "元,盘后应缴纳预付金金额为" + report.FundReportModel.WorstCastClientPayableString + "元,应追加预付金" + report.FundReportModel.MarginString + "元,请及时补足预付金。

" + "

贵公司应不迟于通知后的下一交易日北京时间【14时30分】前(含该时点)追加预付金。如果贵公司未能按照我公司的要求追加预付金,我公司有权对贵公司的交易实施部分提前终止,以使得贵公司的预付金总额不低于当日需缴纳预付金或者我公司要求的其它价值。如贵公司未按照以上规定补足追加预付金的,我公司有权对其持有头寸强行平仓,并且追究贵公司违约责任。

" + "

感谢配合!

" + "-----------------------------------
" + "swzfotc@sywgqh.com.cn"; } if (PS.Config.Company == CompanyEnum.润和) { report.FundReportModel.SettlementBalance += report.FundReportModel.SwapBalance; report.FundReportModel.CreditOccupy = Math.Min(report.FundReportModel.Credit ?? 0, Math.Max((report.FundReportModel.WorstCastClientPayable - report.FundReportModel.TodayRemianFund) ?? 0, 0)); report.FundReportModel.DesirableFund = Math.Max(report.FundReportModel.AvailableFund ?? 0, 0); report.FundReportModel.AvailableFund = report.FundReportModel.AvailableFund + report.FundReportModel.Credit; } #endregion } if (emailData.SendContent.Contains("持仓明细")) { var spanReq = new TradeSpanReq { ClientId = emailData.ClientId, ValueDate = emailData.To, ParentFlag = emailData.ParentFlag }; if (PS.Config.Is宏源) { spanReq.sord = "asc"; spanReq.sidx = "UserGroup"; } report.eod_positionList = clientTradePositionQueryList(spanReq, userAssetUnits); var tradeTypes = report.eod_positionList.Select(x => x.TradeType).ToHashSet(); report.eod_positionList_default = report.eod_positionList.Where(n => n.TradeType == "香草期权").ToList(); tradeTypes.Remove("香草期权"); report.eod_positionList_assin = report.eod_positionList.Where(n => n.TradeType == "亚式期权").ToList(); tradeTypes.Remove("亚式期权"); report.eod_positionList_binary = report.eod_positionList.Where(n => n.TradeType == "二元期权").ToList(); tradeTypes.Remove("二元期权"); report.eod_positionList_barriar = report.eod_positionList.Where(n => n.TradeType == "障碍期权").ToList(); tradeTypes.Remove("障碍期权"); report.eod_positionList_sharkfin = report.eod_positionList.Where(n => n.TradeType == "双鲨期权").ToList(); tradeTypes.Remove("双鲨期权"); report.eod_positionList_rainbow = report.eod_positionList.Where(n => n.TradeType == "彩虹期权").ToList(); tradeTypes.Remove("彩虹期权"); report.eod_positionList_autocall = report.eod_positionList.Where(n => n.TradeType == "凤凰期权").ToList(); tradeTypes.Remove("凤凰期权"); report.eod_positionList_snowball = report.eod_positionList.Where(n => n.TradeType == "雪球期权").ToList(); tradeTypes.Remove("雪球期权"); report.eod_positionList_rangeaccrual = report.eod_positionList.Where(n => n.TradeType == "区间累积期权").ToList(); tradeTypes.Remove("区间累积期权"); report.eod_positionList_airbag = report.eod_positionList.Where(n => n.TradeType == "气囊结构").ToList(); tradeTypes.Remove("气囊结构"); report.eod_positionList_forward = report.eod_positionList.Where(n => n.TradeType == "远期").ToList(); tradeTypes.Remove("远期"); report.eod_positionList_compositespread = report.eod_positionList.Where(n => n.TradeType == "合成价差期权").ToList(); tradeTypes.Remove("合成价差期权"); report.eod_positionList_manual = report.eod_positionList.Where(n => n.TradeType == "自定义交易").ToList(); tradeTypes.Remove("自定义交易"); report.eod_positionList_enhance = report.eod_positionList.Where(n => n.TradeType == "收益增强结构").ToList(); tradeTypes.Remove("收益增强结构"); report.eod_positionList_cashflow = report.eod_positionList.Where(n => n.TradeType == "现金流交易").ToList(); tradeTypes.Remove("现金流交易"); var accumulatorOptionIds = DbContext.trade_accumulator_option.Where(l => l.AccumulatorStructureType == AccumulatorStructureTypeEnum.Segmented).Select(l => l.TradeId).ToList(); report.eod_positionList_accumulator = report.eod_positionList.Where(n => n.TradeType == "累计期权" && !accumulatorOptionIds.Contains(n.TradeId)).ToList(); report.eod_positionList_accumulatorSegmented = report.eod_positionList.Where(n => n.TradeType == "累计期权" && accumulatorOptionIds.Contains(n.TradeId)).ToList(); tradeTypes.Remove("累计期权"); report.eod_positionList_risky = report.eod_positionList.Where(c => c.TradeType == "Risky期权").ToList(); tradeTypes.Remove("Risky期权"); //if (PS.Config.IsGuoJun) //{ // var sList = new EodSwapPositionMannualService(UserInfo).SearchPositionListAll(spanReq); // report.eod_positionList_swapflow = sList.ToList(); // report.eod_positionList_swap = new List(); //} //else //{ // report.eod_positionList_swap = report.eod_positionList.Where(n => n.TradeType == "收益互换").ToList(); //} report.eod_positionList_swap = report.eod_positionList.Where(n => n.TradeType == "收益互换").ToList(); tradeTypes.Remove("收益互换"); report.eod_positionList_others = report.eod_positionList.Where(n => tradeTypes.Contains(n.TradeType)).ToList(); if (PS.Config.Is宏源) { report.eod_positionList_default = report.eod_positionList_default.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_assin = report.eod_positionList_assin.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_binary = report.eod_positionList_binary.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_barriar = report.eod_positionList_barriar.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_sharkfin = report.eod_positionList_sharkfin.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_rainbow = report.eod_positionList_rainbow.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_autocall = report.eod_positionList_autocall.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_snowball = report.eod_positionList_snowball.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_rangeaccrual = report.eod_positionList_rangeaccrual.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_airbag = report.eod_positionList_airbag.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_forward = report.eod_positionList_forward.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_compositespread = report.eod_positionList_compositespread.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_manual = report.eod_positionList_manual.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_enhance = report.eod_positionList_enhance.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_cashflow = report.eod_positionList_cashflow.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_accumulator = report.eod_positionList_accumulator.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_accumulatorSegmented = report.eod_positionList_accumulatorSegmented.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_risky = report.eod_positionList_risky.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_swap = report.eod_positionList_swap.OrderBy(x => x.UserGroup).ToList(); report.eod_positionList_others = report.eod_positionList_others.OrderBy(x => x.UserGroup).ToList(); } } //新增互换持仓明细 if (emailData.SendContent.Contains("互换持仓明细")) { } if (emailData.SendContent.Contains("历史交易")) { #region 历史交易 var treq = new TradeReq() { ClientId = emailData.ClientId, ValueDateStart = emailData.From, ValueDateEnd = emailData.To, ParentFlag = emailData.ParentFlag }; if (PS.Config.Is宏源) { treq.sord = "asc"; treq.sidx = "UserGroup"; } report.trade_contract_groupList = ClientAssetDataService.SearchHistoryListOnly(treq, true); var tradeTypes = report.trade_contract_groupList.Select(x => x.TradeType).ToHashSet(); report.trade_contract_groupList_default = report.trade_contract_groupList.Where(n => n.TradeType == "香草期权").ToList(); tradeTypes.Remove("香草期权"); report.trade_contract_groupList_assin = report.trade_contract_groupList.Where(n => n.TradeType == "亚式期权").ToList(); tradeTypes.Remove("亚式期权"); report.trade_contract_groupList_binary = report.trade_contract_groupList.Where(n => n.TradeType == "二元期权").ToList(); tradeTypes.Remove("二元期权"); report.trade_contract_groupList_barriar = report.trade_contract_groupList.Where(n => n.TradeType == "障碍期权").ToList(); tradeTypes.Remove("障碍期权"); report.trade_contract_groupList_sharkfin = report.trade_contract_groupList.Where(n => n.TradeType == "双鲨期权").ToList(); tradeTypes.Remove("双鲨期权"); report.trade_contract_groupList_rainbow = report.trade_contract_groupList.Where(n => n.TradeType == "彩虹期权").ToList(); tradeTypes.Remove("彩虹期权"); report.trade_contract_groupList_autocall = report.trade_contract_groupList.Where(n => n.TradeType == "凤凰期权").ToList(); tradeTypes.Remove("凤凰期权"); report.trade_contract_groupList_snowball = report.trade_contract_groupList.Where(n => n.TradeType == "雪球期权").ToList(); tradeTypes.Remove("雪球期权"); report.trade_contract_groupList_rangeaccrual = report.trade_contract_groupList.Where(n => n.TradeType == "区间累积期权").ToList(); tradeTypes.Remove("区间累积期权"); report.trade_contract_groupList_airbag = report.trade_contract_groupList.Where(n => n.TradeType == "气囊结构").ToList(); tradeTypes.Remove("气囊结构"); report.trade_contract_groupList_forward = report.trade_contract_groupList.Where(n => n.TradeType == "远期").ToList(); tradeTypes.Remove("远期"); report.trade_contract_groupList_compositespread = report.trade_contract_groupList.Where(n => n.TradeType == "合成价差期权").ToList(); tradeTypes.Remove("合成价差期权"); report.trade_contract_groupList_manual = report.trade_contract_groupList.Where(n => n.TradeType == "自定义交易").ToList(); tradeTypes.Remove("自定义交易"); report.trade_contract_groupList_enhance = report.trade_contract_groupList.Where(n => n.TradeType == "收益增强结构").ToList(); tradeTypes.Remove("收益增强结构"); report.trade_contract_groupList_cashflow = report.trade_contract_groupList.Where(n => n.TradeType == "现金流交易").ToList(); tradeTypes.Remove("现金流交易"); var accumulatorOptionIds = DbContext.trade_accumulator_option.Where(l => l.AccumulatorStructureType == AccumulatorStructureTypeEnum.Segmented).Select(l => l.TradeId).ToList(); report.trade_contract_groupList_accumulator = report.trade_contract_groupList.Where(n => n.TradeType == "累计期权" && !accumulatorOptionIds.Contains(n.trade.id)).ToList(); report.trade_contract_groupList_accumulatorSegmented = report.trade_contract_groupList.Where(n => n.TradeType == "累计期权" && accumulatorOptionIds.Contains(n.trade.id)).ToList(); tradeTypes.Remove("累计期权"); report.trade_contract_groupList_risky = report.trade_contract_groupList.Where(c => c.TradeType == "Risky期权").ToList(); tradeTypes.Remove("Risky期权"); //if (PS.Config.IsGuoJun) //{ // var sList = new TradeSwapService(UserInfo).SearchFlowMoreHistoryList(treq); // report.trade_contract_groupList_swapFlow = sList.ToList(); // report.trade_contract_groupList_swap = new List(); //} //else //{ // report.trade_contract_groupList_swap = report.trade_contract_groupList.Where(n => n.TradeType == "收益互换").ToList(); //} report.trade_contract_groupList_swap = report.trade_contract_groupList.Where(n => n.TradeType == "收益互换").ToList(); tradeTypes.Remove("收益互换"); report.trade_contract_groupList_others = report.trade_contract_groupList.Where(n => tradeTypes.Contains(n.TradeType)).ToList(); if (PS.Config.Is宏源) { report.trade_contract_groupList_default = report.trade_contract_groupList_default.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_assin = report.trade_contract_groupList_assin.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_binary = report.trade_contract_groupList_binary.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_barriar = report.trade_contract_groupList_barriar.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_sharkfin = report.trade_contract_groupList_sharkfin.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_rainbow = report.trade_contract_groupList_rainbow.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_autocall = report.trade_contract_groupList_autocall.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_snowball = report.trade_contract_groupList_snowball.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_rangeaccrual = report.trade_contract_groupList_rangeaccrual.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_airbag = report.trade_contract_groupList_airbag.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_forward = report.trade_contract_groupList_forward.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_compositespread = report.trade_contract_groupList_compositespread.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_manual = report.trade_contract_groupList_manual.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_enhance = report.trade_contract_groupList_enhance.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_cashflow = report.trade_contract_groupList_cashflow.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_accumulator = report.trade_contract_groupList_accumulator.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_accumulatorSegmented = report.trade_contract_groupList_accumulatorSegmented.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_risky = report.trade_contract_groupList_risky.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_swap = report.trade_contract_groupList_swap.OrderBy(x => x.UserGroup).ToList(); report.trade_contract_groupList_others = report.trade_contract_groupList_others.OrderBy(x => x.UserGroup).ToList(); } #endregion } //新增互换历史交易 if (emailData.SendContent.Contains("互换历史交易")) { } 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.descList = newDescList; report.desc = desc;//string.Join("\n", newDescList); report.downloadFilePath = emailData.DownloadFilePath; if (string.IsNullOrWhiteSpace(emailData.Title)) { emailData.Title = DBCacheManager.Single.GetStr(CacheTable.ClientBalanceReportTiltle, template: template); } report.Title = ReplaceWildcard(emailData.Title, report); return report; } public string ReplaceWildcard(string input, ClientDingShiReport 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.MarginString; case "大写追保金额": return NumberHelper.CmycurD(report.FundReportModel.Margin ?? 0); case "应付资金总额": return report.FundReportModel.PayableFundString; case "大写应付资金总额": return NumberHelper.CmycurD(report.FundReportModel.PayableFund ?? 0); case "发送日期": return DateTime.Now.ToString("yyyy-MM-dd"); case "预付金占用": return report.FundReportModel.WorstCastClientPayableString; case "可用资金": return report.FundReportModel.AvailableFundString; case "授信额度": return report.FundReportModel.CreditString; case "应付了结交易款": return report.FundReportModel.ClosedTradePayableFundString; case "应付存续交易款": return report.FundReportModel.PositionTradePayableFundString; case "存续交易期权费净额": return report.FundReportModel.PositionPremiumNetCashString; 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; } public (EmailTradeConfirmResultType status, string message) SendSettlementReports(DingShiReportEmail emailData, ClientDingShiReport report, string template, string pdfHtml = "", string txtHtml = "", bool IsSkipCheckMarginCall = false, List recevier = null) { string message = null; var attachFiles = new List(); var IsNeedMarginCall = false; if (!IsSkipCheckMarginCall) { IsNeedMarginCall = CheckIsNeedMarginCall(report.client, emailData.PayableFund > 0 ? emailData.PayableFund : report.FundReportModel.PayableFund ?? 0, report.FundReportModel.Margin ?? 0); } emailData.FileTypes.ForEach(type => { if (type.@checked) { var html = ""; if (type.type.ToLower() == "pdf") { html = pdfHtml; } if (type.type.ToLower() == "txt") { html = txtHtml; } var filepath = GenerateFileEntry(report, type.type, html); if (!string.IsNullOrEmpty(filepath)) { attachFiles.Add(filepath); } } }); //刘总认为追保无需检查用户银行卡 //var bankcard = ClientDataProvider.GetBankCard(report.client.id); //if (bankcard == null && report.FundReportModel.PayableFund > 0) //{ // throw new Exception(report.client.Name + "未配置银行卡信息!"); //} // 要向该客户的所有订阅了邮件通知的人员发送邮件 var emails = ClientDataQueryService.GetClientEmails(report.client.id, false, recevier); var status = EmailTradeConfirmResultType.Succeed; if (emails.All(o => string.IsNullOrWhiteSpace(o))) { status = EmailTradeConfirmResultType.NoEmailSetting; } else { emails = emails.Where(o => !string.IsNullOrWhiteSpace(o)); var title = string.Empty; var detail = string.Empty; if (IsNeedMarginCall) { title = $"【追保通知】{report.Title}"; detail = emailData.MarginDetail; detail = ReplaceWildcard(detail, report); } else { title = report.Title; 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); } message = EmailHelper.SendMail(string.Join(";", emails), title, detail, true, attachFiles, emailData.CCEmail, mailFrom); if (!string.IsNullOrEmpty(message)) { status = EmailTradeConfirmResultType.EmailSentFailed; } } return (status, message); } public bool CheckIsNeedMarginCall(int ClientId, DateTime start, DateTime end, double payableFund = -1, bool IsGap = false, bool IsOuter = false, bool ParentFlag = false) { var client = DataCacheProvider.GetClientDataSource().GetData(ClientId); var clientBalance = ClientBalanceUtility.GetClientBanlances(new List { ClientId }, start, end, IsGap, IsOuter, ParentFlag).FirstOrDefault(); return CheckIsNeedMarginCall(client, payableFund >= 0 ? payableFund : clientBalance.PayableFundTotal, clientBalance.MarginByPayableMargin); } private bool CheckIsNeedMarginCall(Client client, double payableFund, double margin) { var isNeedMarginCall = CheckIsNeedMarginCall(client, payableFund); if (PS.Config.Is东吴) { isNeedMarginCall = margin > (client.MinimumTransferAmount ?? 0); } if (PS.Config.Is湘财) { isNeedMarginCall = margin > 0; } return isNeedMarginCall; } private bool CheckIsNeedMarginCall(Client client, double payableFund) { var SamePeerMarginCallStarting = valuedateBLL.SystemDate.SamePeerMarginCallPoint; payableFund = Math.Round(payableFund, 2);//OTC-5978 应付资金精度问题 if (client.SamePeer == 0 && payableFund > SamePeerMarginCallStarting) { return true; } if (client.SamePeer == 1 && payableFund > 1) { return true; } return false; } public string GenerateFileEntry(ClientDingShiReport report, string type, string html = "") { var filepath = ""; switch (type.ToLower()) { case "pdf": filepath = GenerateReportPDF(report, html); break; case "excel": filepath = GenerateReportExcel(report); break; case "txt": filepath = GenerateReportTxt(report, html); break; } return filepath; } public string GenerateReportPDF(ClientDingShiReport report, string html) { var pdfHelper = new PdfHelper(); var sourcePath = OtcAppContext.MapPath("~/App_Docs/TradeMarket"); sourcePath = MosPathHelper.Combine(sourcePath,""); if (!Directory.Exists(sourcePath)) { Directory.CreateDirectory(sourcePath); } var clientName = report.client.Name; var fileName = report.ReportFrom == DateTime.MinValue ? $"持仓报告_{report.ReportEnd:yyyyMMdd}_{clientName}" : $"持仓报告_{report.ReportFrom:yyyyMMdd}_{report.ReportEnd:yyyyMMdd}_{clientName}"; if (PS.Config.Is申万) { fileName = "场外衍生品-对账单-" + report.client.Name + report.ReportEnd.ToString("yyyyMMdd"); } if (PS.Config.Is海通) { fileName = $"结算报告_{clientName}_{report.ReportEnd:yyyy-MM-dd}"; } var sourceFileName = Path.Combine(sourcePath, $"{fileName}.pdf"); pdfHelper.ToPDFFile(html, sourceFileName, true); return sourceFileName; } public string GenerateReportExcel(ClientDingShiReport report) { 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}"; if (PS.Config.Is海通) { fileName = $"结算报告_{clientName}_{report.ReportEnd:yyyy-MM-dd}"; } var targetFileName = Path.Combine(targetPath, $"{fileName}.xlsx"); //Excel Model index为0那一行没输出,添加一个空行 report.descList.Insert(0, ""); 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); } var positionCount = 0; var positionSheetModels = new PositionSheetModels(); if (report.eod_positionList != null) { positionSheetModels.PositionSheetModel_airbag = GetPositionSheetModel(report.eod_positionList_airbag); positionCount += positionSheetModels.PositionSheetModel_airbag.EodPositionList.Count; positionSheetModels.PositionSheetModel_assin = GetPositionSheetModel(report.eod_positionList_assin); positionCount += positionSheetModels.PositionSheetModel_assin.EodPositionList.Count; positionSheetModels.PositionSheetModel_autocall = GetPositionSheetModel(report.eod_positionList_autocall); positionCount += positionSheetModels.PositionSheetModel_autocall.EodPositionList.Count; positionSheetModels.PositionSheetModel_barriar = GetPositionSheetModel(report.eod_positionList_barriar); positionCount += positionSheetModels.PositionSheetModel_barriar.EodPositionList.Count; positionSheetModels.PositionSheetModel_binary = GetPositionSheetModel(report.eod_positionList_binary); positionCount += positionSheetModels.PositionSheetModel_binary.EodPositionList.Count; positionSheetModels.PositionSheetModel_default = GetPositionSheetModel(report.eod_positionList_default); positionCount += positionSheetModels.PositionSheetModel_default.EodPositionList.Count; positionSheetModels.PositionSheetModel_rainbow = GetPositionSheetModel(report.eod_positionList_rainbow); positionCount += positionSheetModels.PositionSheetModel_rainbow.EodPositionList.Count; positionSheetModels.PositionSheetModel_rangeaccrual = GetPositionSheetModel(report.eod_positionList_rangeaccrual); positionCount += positionSheetModels.PositionSheetModel_rangeaccrual.EodPositionList.Count; positionSheetModels.PositionSheetModel_sharkfin = GetPositionSheetModel(report.eod_positionList_sharkfin); positionCount += positionSheetModels.PositionSheetModel_sharkfin.EodPositionList.Count; positionSheetModels.PositionSheetModel_snowball = GetPositionSheetModel(report.eod_positionList_snowball); positionCount += positionSheetModels.PositionSheetModel_snowball.EodPositionList.Count; positionSheetModels.PositionSheetModel_forward = GetPositionSheetModel(report.eod_positionList_forward); positionCount += positionSheetModels.PositionSheetModel_forward.EodPositionList.Count; positionSheetModels.PositionSheetModel_swap = GetPositionSheetModel(report.eod_positionList_swap); positionCount += positionSheetModels.PositionSheetModel_swap.EodPositionList.Count; positionSheetModels.PositionSheetModel_compositespread = GetPositionSheetModel(report.eod_positionList_compositespread); positionCount += positionSheetModels.PositionSheetModel_compositespread.EodPositionList.Count; positionSheetModels.PositionSheetModel_manual = GetPositionSheetModel(report.eod_positionList_manual); positionCount += positionSheetModels.PositionSheetModel_manual.EodPositionList.Count; positionSheetModels.PositionSheetModel_enhance = GetPositionSheetModel(report.eod_positionList_enhance); positionCount += positionSheetModels.PositionSheetModel_enhance.EodPositionList.Count; positionSheetModels.PositionSheetModel_cashflow = GetPositionSheetModel(report.eod_positionList_cashflow); positionCount += positionSheetModels.PositionSheetModel_cashflow.EodPositionList.Count; positionSheetModels.PositionSheetModel_accumulator = GetPositionSheetModel(report.eod_positionList_accumulator); positionCount += positionSheetModels.PositionSheetModel_accumulator.EodPositionList.Count; positionSheetModels.PositionSheetModel_risky = GetPositionSheetModel(report.eod_positionList_risky); positionCount += positionSheetModels.PositionSheetModel_risky.EodPositionList.Count; positionSheetModels.PositionSheetModel_accumulatorSegmented = GetPositionSheetModel(report.eod_positionList_accumulatorSegmented); positionCount += positionSheetModels.PositionSheetModel_accumulatorSegmented.EodPositionList.Count; modelDict.Add("持仓明细", positionSheetModels); } //新增互换持仓明细Tab if (report.eod_positionList != null && !PS.Config.IsGuoJun) { modelDict.Add("互换持仓明细", positionSheetModels); } var positionSwapFlowSheetModel = new PositionSwapFlowSheetModel(); if (report.eod_positionList_swapflow != null) { positionSwapFlowSheetModel = GetPositionSwapFlowSheetModel(report.eod_positionList_swapflow); modelDict.Add("互换持仓明细", positionSwapFlowSheetModel); } var historyCount = 0; var historySheetModels = new HistorySheetModels(); if (report.trade_contract_groupList != null) { historySheetModels.HistorySheetModel_airbag = GetHistorySheetModel(report.trade_contract_groupList_airbag); historyCount += historySheetModels.HistorySheetModel_airbag.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_assin = GetHistorySheetModel(report.trade_contract_groupList_assin); historyCount += historySheetModels.HistorySheetModel_assin.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_autocall = GetHistorySheetModel(report.trade_contract_groupList_autocall); historyCount += historySheetModels.HistorySheetModel_autocall.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_barriar = GetHistorySheetModel(report.trade_contract_groupList_barriar); historyCount += historySheetModels.HistorySheetModel_barriar.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_binary = GetHistorySheetModel(report.trade_contract_groupList_binary); historyCount += historySheetModels.HistorySheetModel_binary.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_default = GetHistorySheetModel(report.trade_contract_groupList_default); historyCount += historySheetModels.HistorySheetModel_default.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_rainbow = GetHistorySheetModel(report.trade_contract_groupList_rainbow); historyCount += historySheetModels.HistorySheetModel_rainbow.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_rangeaccrual = GetHistorySheetModel(report.trade_contract_groupList_rangeaccrual); historyCount += historySheetModels.HistorySheetModel_rangeaccrual.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_sharkfin = GetHistorySheetModel(report.trade_contract_groupList_sharkfin); historyCount += historySheetModels.HistorySheetModel_sharkfin.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_snowball = GetHistorySheetModel(report.trade_contract_groupList_snowball); historyCount += historySheetModels.HistorySheetModel_snowball.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_forward = GetHistorySheetModel(report.trade_contract_groupList_forward); historyCount += historySheetModels.HistorySheetModel_forward.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_swap = GetHistorySheetModel(report.trade_contract_groupList_swap); historyCount += historySheetModels.HistorySheetModel_swap.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_compositespread = GetHistorySheetModel(report.trade_contract_groupList_compositespread); historyCount += historySheetModels.HistorySheetModel_compositespread.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_manual = GetHistorySheetModel(report.trade_contract_groupList_manual); historyCount += historySheetModels.HistorySheetModel_manual.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_enhance = GetHistorySheetModel(report.trade_contract_groupList_enhance); historyCount += historySheetModels.HistorySheetModel_enhance.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_cashflow = GetHistorySheetModel(report.trade_contract_groupList_cashflow); historyCount += historySheetModels.HistorySheetModel_cashflow.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_accumulator = GetHistorySheetModel(report.trade_contract_groupList_accumulator); historyCount += historySheetModels.HistorySheetModel_accumulator.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_risky = GetHistorySheetModel(report.trade_contract_groupList_risky); historyCount += historySheetModels.HistorySheetModel_risky.TradeContractGroupList.Count; historySheetModels.HistorySheetModel_accumulatorSegmented = GetHistorySheetModel(report.trade_contract_groupList_accumulatorSegmented); historyCount += historySheetModels.HistorySheetModel_accumulatorSegmented.TradeContractGroupList.Count; modelDict.Add("历史交易", historySheetModels); } //新增互换历史交易Tab if (report.trade_contract_groupList != null) { modelDict.Add("互换历史交易", historySheetModels); } var historySwapFlowSheetModel = new HistorySwapFlowSheetModel(); if (report.trade_contract_groupList_swapFlow != null) { historySwapFlowSheetModel = GetHistorySwapFlowSheetModel(report.trade_contract_groupList_swapFlow); modelDict.Add("互换交易流水", historySwapFlowSheetModel); } 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); } if (PS.Config.Company == CompanyEnum.弘业) { var model = GetHongYeSheetModel(report); modelDict.Add("弘业结算单", model); } bool isShowMargin = false; var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string sourceFileName; switch (PS.Config.Company) { case CompanyEnum.国泰君安: //isShowMargin = new TradeMarketReportConfigureService(UserInfo).IsShowMarginByTradeMarketReportConfigure(report.client.id); sourceFileName = Path.Combine(sourcePath, isShowMargin ? "结算报告模板_国君_含预付金.xlsx" : "结算报告模板_国君.xlsx"); break; case CompanyEnum.弘业: sourceFileName = Path.Combine(sourcePath, "结算报告模板_弘业.xlsx"); break; case CompanyEnum.润和: sourceFileName = Path.Combine(sourcePath, "结算报告模板_东证.xlsx"); break; default: sourceFileName = Path.Combine(sourcePath, $"结算报告模板_{PS.Config.Company}.xlsx"); if (!File.Exists(sourceFileName)) { sourceFileName = Path.Combine(sourcePath, "结算报告模板.xlsx"); } break; } if (PS.Config.ErpElement.ForwardTradePriceModel == Configuration.Enums.ForwardTradePriceModel.STANDARD) { sourceFileName = sourceFileName.Replace("结算报告模板", "结算报告标准模板"); } ExcelPackage.LicenseContext = LicenseContext.NonCommercial; var pdffile = ExcelTemplate.GeneratePDFFromExeclTemplate(sourcePath, sourceFileName, modelDict, targetPath, targetFileName , shouldDeleteSheet: true, needToPdf: false, callback: new GenerateExcelCallback(this) { positionCount = positionCount, historyCount = historyCount, historySheetModels = historySheetModels, positionSheetModels = positionSheetModels, report = report, isShowMargin = isShowMargin, }.Callback); return Path.Combine(targetPath, targetFileName); } class GenerateExcelCallback : YLBaseService { public int positionCount; public PositionSheetModels positionSheetModels; public int historyCount; public HistorySheetModels historySheetModels; public ClientDingShiReport report; public bool isShowMargin; public GenerateExcelCallback(YLBaseService baseService) : base(baseService) { } public void Callback(ExcelWorksheets sheets) { if (!PS.Config.ClientElement.TradeMarketShowTotalNetSettlement) { var fundReportSheet = sheets["账户状况"]; if (fundReportSheet != null) { fundReportSheet.DeleteRow(22); } } //if (!PS.Config.IsPVRounded) //{ // var positionReportSheet = sheets["持仓明细"]; // if (positionReportSheet != null) // { // positionReportSheet.Column(15).Style.Numberformat.Format = "0.0000"; // } //} foreach (var sheet in sheets) { //删除空列表 if (sheet.Name == "持仓明细") { var columnManualDefault = 0; if (report.eod_positionList_others.Any()) { var tradeTypes = report.eod_positionList_others.Select(x => x.TradeType).Distinct().ToList(); var startRowIndex = positionCount + 77; foreach (var tradeType in tradeTypes) { var eod_positionList_others = report.eod_positionList_others.Where(x => x.TradeType == tradeType).ToList(); setPositionCell(sheet, startRowIndex, eod_positionList_others, isShowMargin); startRowIndex += eod_positionList_others.Count + 4; } } for (var i = positionCount + 94; i > 0; i--) { if (sheet.GetValue(i, 1)?.ToString() == "累计期权三段式" && !positionSheetModels.PositionSheetModel_accumulatorSegmented.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "累计期权" && !positionSheetModels.PositionSheetModel_accumulator.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "Risky期权" && !positionSheetModels.PositionSheetModel_risky.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "气囊结构" && !positionSheetModels.PositionSheetModel_airbag.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "亚式期权" && !positionSheetModels.PositionSheetModel_assin.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "凤凰期权" && !positionSheetModels.PositionSheetModel_autocall.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "障碍期权" && !positionSheetModels.PositionSheetModel_barriar.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "二元期权" && !positionSheetModels.PositionSheetModel_binary.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "香草期权" && !positionSheetModels.PositionSheetModel_default.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "彩虹期权" && !positionSheetModels.PositionSheetModel_rainbow.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "区间累积期权" && !positionSheetModels.PositionSheetModel_rangeaccrual.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "双鲨期权" && !positionSheetModels.PositionSheetModel_sharkfin.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "雪球期权" && !positionSheetModels.PositionSheetModel_snowball.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "远期" && !positionSheetModels.PositionSheetModel_forward.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "收益互换" && !positionSheetModels.PositionSheetModel_swap.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "合成价差期权" && !positionSheetModels.PositionSheetModel_compositespread.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "自定义交易") { if (!positionSheetModels.PositionSheetModel_manual.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } else { var titleColumnDic = new Dictionary(); var n = 1; var count = positionSheetModels.PositionSheetModel_manual.EodPositionList.Count(); foreach (var item in positionSheetModels.PositionSheetModel_manual.EodPositionList) { n++; if (item.trade.Propertys != null && !string.IsNullOrEmpty(item.trade.TradeNumber) && !(item.trade.TradeNumber.Contains("S") && PS.Config.Is国泰君安)) { for (var column = 0; column <= 30; column++) { if (sheet.GetValue(i + 1, column)?.ToString() == null) { if (columnManualDefault == 0) { columnManualDefault = column; } } } foreach (var property in item.trade.Propertys) { if (titleColumnDic.ContainsKey(property.name)) { sheet.Cells[i + n, titleColumnDic[property.name]].Value = property.value; } else { sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Font.Bold = true; sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Font.Name = "微软雅黑"; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Value = property.name; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Font.Bold = true; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Font.Name = "微软雅黑"; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.VerticalAlignment = ExcelVerticalAlignment.Center; for (var k = 2; k <= count + 1; k++) { sheet.Cells[i + k, titleColumnDic.Count() + columnManualDefault].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[i + k, titleColumnDic.Count() + columnManualDefault].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[i + k, titleColumnDic.Count() + columnManualDefault].Style.VerticalAlignment = ExcelVerticalAlignment.Center; } sheet.Cells[i + n, titleColumnDic.Count() + columnManualDefault].Value = property.value; titleColumnDic.Add(property.name, titleColumnDic.Count() + columnManualDefault); } } } } } } if (sheet.GetValue(i, 1)?.ToString() == "收益增强结构" && !positionSheetModels.PositionSheetModel_enhance.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "现金流交易" && !positionSheetModels.PositionSheetModel_cashflow.EodPositionList.Any()) { sheet.DeleteRow(i, 4); } } } else if (sheet.Name == "历史交易") { var columnManualDefault = 0; if (report.trade_contract_groupList_others.Any()) { var tradeTypes = report.trade_contract_groupList_others.Select(x => x.TradeType).Distinct().ToList(); var startRowIndex = historyCount + 77; foreach (var tradeType in tradeTypes) { var trade_contract_groupList_others = report.trade_contract_groupList_others.Where(x => x.TradeType == tradeType).ToList(); setHistoryCell(sheet, startRowIndex, trade_contract_groupList_others); startRowIndex += trade_contract_groupList_others.Count + 4; } } for (var i = historyCount + 94; i > 0; i--) { if (sheet.GetValue(i, 1)?.ToString() == "累计期权三段式" && !historySheetModels.HistorySheetModel_accumulatorSegmented.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "累计期权" && !historySheetModels.HistorySheetModel_accumulator.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "Risky期权" && !historySheetModels.HistorySheetModel_risky.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "雪球期权" && !historySheetModels.HistorySheetModel_snowball.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "气囊结构" && !historySheetModels.HistorySheetModel_airbag.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "亚式期权" && !historySheetModels.HistorySheetModel_assin.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "凤凰期权" && !historySheetModels.HistorySheetModel_autocall.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "障碍期权" && !historySheetModels.HistorySheetModel_barriar.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "二元期权" && !historySheetModels.HistorySheetModel_binary.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "香草期权" && !historySheetModels.HistorySheetModel_default.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "彩虹期权" && !historySheetModels.HistorySheetModel_rainbow.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "区间累积期权" && !historySheetModels.HistorySheetModel_rangeaccrual.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "双鲨期权" && !historySheetModels.HistorySheetModel_sharkfin.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "雪球期权" && !historySheetModels.HistorySheetModel_snowball.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "远期" && !historySheetModels.HistorySheetModel_forward.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "收益互换" && !historySheetModels.HistorySheetModel_swap.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "合成价差期权" && !historySheetModels.HistorySheetModel_compositespread.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "自定义交易") { for (var column = 0; column <= 30; column++) { if (sheet.GetValue(i + 1, column)?.ToString() == null) { if (columnManualDefault == 0) { columnManualDefault = column; } } } if (!historySheetModels.HistorySheetModel_manual.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } else { var titleColumnDic = new Dictionary(); var n = 1; var count = historySheetModels.HistorySheetModel_manual.TradeContractGroupList.Count(); foreach (var item in historySheetModels.HistorySheetModel_manual.TradeContractGroupList) { n++; if (item.trade.Propertys != null && !(item.trade.TradeNumber.Contains("S") && PS.Config.Is国泰君安)) { foreach (var property in item.trade.Propertys) { if (titleColumnDic.ContainsKey(property.name)) { sheet.Cells[i + n, titleColumnDic[property.name]].Value = property.value; } else { //sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Font.Bold = true; sheet.Cells[i, titleColumnDic.Count() + columnManualDefault].Style.Font.Name = "微软雅黑"; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Value = property.name; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Font.Bold = true; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.Font.Name = "微软雅黑"; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[i + 1, titleColumnDic.Count() + columnManualDefault].Style.VerticalAlignment = ExcelVerticalAlignment.Center; for (var k = 2; k <= count + 1; k++) { sheet.Cells[i + k, titleColumnDic.Count() + columnManualDefault].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[i + k, titleColumnDic.Count() + columnManualDefault].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[i + k, titleColumnDic.Count() + columnManualDefault].Style.VerticalAlignment = ExcelVerticalAlignment.Center; } sheet.Cells[i + n, titleColumnDic.Count() + columnManualDefault].Value = property.value; titleColumnDic.Add(property.name, titleColumnDic.Count() + columnManualDefault); } } } } } } if (sheet.GetValue(i, 1)?.ToString() == "收益增强结构" && !historySheetModels.HistorySheetModel_enhance.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } if (sheet.GetValue(i, 1)?.ToString() == "现金流交易" && !historySheetModels.HistorySheetModel_cashflow.TradeContractGroupList.Any()) { sheet.DeleteRow(i, 4); } } } } } private void setPositionCell(ExcelWorksheet sheet, int startRowIndex, List eod_positionList_others, bool isShowMargin) { var tradeIds = eod_positionList_others.Select(x => x.TradeId).ToList(); var trades = DbContext.trade.Where(y => tradeIds.Contains(y.id)); var defaultTrade = trades.FirstOrDefault(); sheet.Cells[startRowIndex, 1].Value = defaultTrade.StructureType; sheet.Cells[startRowIndex, 1].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[startRowIndex, 1].Style.Font.Bold = true; sheet.Cells[startRowIndex, 1].Style.Font.Size = 14; sheet.Cells[startRowIndex, 1].Style.Font.Name = "微软雅黑"; sheet.Cells[startRowIndex + 1, 1].Value = "交易编号"; sheet.Cells[startRowIndex + 1, 2].Value = "交易方向"; sheet.Cells[startRowIndex + 1, 3].Value = "交易日期"; sheet.Cells[startRowIndex + 1, 4].Value = "到期日期"; sheet.Cells[startRowIndex + 1, 5].Value = "交易总额"; sheet.Cells[startRowIndex + 1, 6].Value = "名义本金"; sheet.Cells[startRowIndex + 1, 7].Value = "持仓名义本金"; sheet.Cells[startRowIndex + 1, 8].Value = "标的代码"; sheet.Cells[startRowIndex + 1, 9].Value = "标的名称"; sheet.Cells[startRowIndex + 1, 10].Value = "期初价格"; sheet.Cells[startRowIndex + 1, 11].Value = "期权现价(单价)"; sheet.Cells[startRowIndex + 1, 12].Value = "持仓数量"; sheet.Cells[startRowIndex + 1, 13].Value = "持仓市值"; sheet.Cells[startRowIndex + 1, 14].Value = "持仓盈亏"; int row = 14; if (isShowMargin) { row++; sheet.Cells[startRowIndex + 1, row].Value = "持仓预付金"; } for (var col = 1; col <= row; col++) { sheet.Cells[startRowIndex, col].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[startRowIndex, col].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[startRowIndex + 1, col].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[startRowIndex + 1, col].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[startRowIndex + 1, col].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[startRowIndex + 1, col].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[startRowIndex + 1, col].Style.Font.Bold = true; sheet.Cells[startRowIndex + 1, col].Style.Font.Name = "微软雅黑"; sheet.Cells[startRowIndex + 1, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[startRowIndex + 1, col].Style.VerticalAlignment = ExcelVerticalAlignment.Center; } var i = 0; //东莞,持仓记录,黑箱交易不导出自定义字段 if (!PS.Config.Is东莞) { if (defaultTrade.Propertys != null) { defaultTrade.Propertys.ForEach(x => { i++; sheet.Cells[startRowIndex, row + i].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[startRowIndex, row + i].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[startRowIndex + 1, row + i].Value = x.name; sheet.Cells[startRowIndex + 1, row + i].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[startRowIndex + 1, row + i].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[startRowIndex + 1, row + i].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[startRowIndex + 1, row + i].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[startRowIndex + 1, row + i].Style.Font.Bold = true; sheet.Cells[startRowIndex + 1, row + i].Style.Font.Name = "微软雅黑"; sheet.Cells[startRowIndex + 1, row + i].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[startRowIndex + 1, row + i].Style.VerticalAlignment = ExcelVerticalAlignment.Center; }); } } var j = 0; foreach (var item in eod_positionList_others) { var trade = trades.FirstOrDefault(x => x.id == item.TradeId); j++; sheet.Cells[startRowIndex + 1 + j, 1].Value = item.TradeNumber; sheet.Cells[startRowIndex + 1 + j, 2].Value = item.BuySell; sheet.Cells[startRowIndex + 1 + j, 3].Value = item.TradeDate; sheet.Cells[startRowIndex + 1 + j, 4].Value = item.ExerciseDate; sheet.Cells[startRowIndex + 1 + j, 5].Value = item.TradePrice; sheet.Cells[startRowIndex + 1 + j, 6].Value = item.OriginalStockEqvNotional; sheet.Cells[startRowIndex + 1 + j, 7].Value = item.StockEqvNotional; sheet.Cells[startRowIndex + 1 + j, 8].Value = item.UnderlyingCode; sheet.Cells[startRowIndex + 1 + j, 9].Value = item.UnderlyingAssetName; sheet.Cells[startRowIndex + 1 + j, 10].Value = item.InitialSpotPrice; sheet.Cells[startRowIndex + 1 + j, 11].Value = item.CurrentPriceString; sheet.Cells[startRowIndex + 1 + j, 12].Value = item.TradeAmount; sheet.Cells[startRowIndex + 1 + j, 13].Value = item.Pv; sheet.Cells[startRowIndex + 1 + j, 14].Value = item.Pnl; if (isShowMargin) { sheet.Cells[startRowIndex + 1 + j, row].Value = item.Margin; } for (var col = 1; col <= row; col++) { sheet.Cells[startRowIndex + 1 + j, col].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[startRowIndex + 1 + j, col].Style.VerticalAlignment = ExcelVerticalAlignment.Center; if (col == 1) { sheet.Cells[startRowIndex + 1 + j, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left; } else if (new int[] { 5, 6, 7, 10, 11, 12, 13, 14 }.Contains(col) || (row == 15 && col == 15)) { sheet.Cells[startRowIndex + 1 + j, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right; } else { sheet.Cells[startRowIndex + 1 + j, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; } } //东莞,持仓记录,黑箱交易不导出自定义字段 if (!PS.Config.Is东莞) { for (var col = 1; col <= i; col++) { var PropertysName = sheet.Cells[startRowIndex + 1, row + col].Value.ToString(); var PropertysValue = trade.Propertys?.FirstOrDefault(p => p.name == PropertysName)?.value; if (PropertysName == "参与率二" && PS.Config.IsGuoJun) { if (string.IsNullOrWhiteSpace(PropertysValue)) { sheet.Cells[startRowIndex + 1 + j, row + col].Value = ""; } else if (PropertysValue.Contains("%")) { var _rate2 = (1 - Convert.ToDouble(PropertysValue.Substring(0, PropertysValue.Length - 1)) / 100).OtcFormatPercent(); sheet.Cells[startRowIndex + 1 + j, row + col].Value = $"{_rate2}"; } else { var _rate2 = (1 - Convert.ToDouble(PropertysValue)).OtcFormatPercent(); sheet.Cells[startRowIndex + 1 + j, row + col].Value = $"{_rate2}"; } } else { sheet.Cells[startRowIndex + 1 + j, row + col].Value = PropertysValue; } sheet.Cells[startRowIndex + 1 + j, row + col].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[startRowIndex + 1 + j, row + col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[startRowIndex + 1 + j, row + col].Style.VerticalAlignment = ExcelVerticalAlignment.Center; } } } } private void setHistoryCell(ExcelWorksheet sheet, int startRowIndex, List trade_contract_groupList_others) { var tradeIds = trade_contract_groupList_others.Select(x => x.trade.id).ToList(); var trades = DbContext.trade.Where(y => tradeIds.Contains(y.id)); var defaultTrade = trades.FirstOrDefault(); sheet.Cells[startRowIndex, 1].Value = defaultTrade.StructureType; sheet.Cells[startRowIndex, 1].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[startRowIndex, 1].Style.Font.Bold = true; sheet.Cells[startRowIndex, 1].Style.Font.Size = 14; sheet.Cells[startRowIndex, 1].Style.Font.Name = "微软雅黑"; sheet.Cells[startRowIndex + 1, 1].Value = "交易编号"; sheet.Cells[startRowIndex + 1, 2].Value = "交易方向"; sheet.Cells[startRowIndex + 1, 3].Value = "交易日期"; sheet.Cells[startRowIndex + 1, 4].Value = "到期日期"; sheet.Cells[startRowIndex + 1, 5].Value = "交易总额"; sheet.Cells[startRowIndex + 1, 6].Value = "名义本金"; sheet.Cells[startRowIndex + 1, 7].Value = "标的代码"; sheet.Cells[startRowIndex + 1, 8].Value = "标的名称"; sheet.Cells[startRowIndex + 1, 9].Value = "期初价格"; sheet.Cells[startRowIndex + 1, 10].Value = "交易状态"; sheet.Cells[startRowIndex + 1, 11].Value = "了结日期"; sheet.Cells[startRowIndex + 1, 12].Value = "了结总额"; sheet.Cells[startRowIndex + 1, 13].Value = "实现盈亏"; for (var col = 1; col <= 13; col++) { sheet.Cells[startRowIndex, col].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[startRowIndex, col].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[startRowIndex + 1, col].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[startRowIndex + 1, col].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[startRowIndex + 1, col].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[startRowIndex + 1, col].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[startRowIndex + 1, col].Style.Font.Bold = true; sheet.Cells[startRowIndex + 1, col].Style.Font.Name = "微软雅黑"; sheet.Cells[startRowIndex + 1, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[startRowIndex + 1, col].Style.VerticalAlignment = ExcelVerticalAlignment.Center; } var i = 0; if (defaultTrade.Propertys != null) { defaultTrade.Propertys.ForEach(x => { i++; sheet.Cells[startRowIndex, 13 + i].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[startRowIndex, 13 + i].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[startRowIndex + 1, 13 + i].Value = x.name; sheet.Cells[startRowIndex + 1, 13 + i].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[startRowIndex + 1, 13 + i].Style.Fill.PatternType = ExcelFillStyle.Solid; sheet.Cells[startRowIndex + 1, 13 + i].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(174, 170, 170)); sheet.Cells[startRowIndex + 1, 13 + i].Style.Font.Color.SetColor(Color.FromArgb(68, 84, 106)); sheet.Cells[startRowIndex + 1, 13 + i].Style.Font.Bold = true; sheet.Cells[startRowIndex + 1, 13 + i].Style.Font.Name = "微软雅黑"; sheet.Cells[startRowIndex + 1, 13 + i].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[startRowIndex + 1, 13 + i].Style.VerticalAlignment = ExcelVerticalAlignment.Center; }); } var j = 0; foreach (var item in trade_contract_groupList_others) { var trade = trades.FirstOrDefault(x => x.id == item.trade.id); j++; sheet.Cells[startRowIndex + 1 + j, 1].Value = item.trade.TradeNumber; sheet.Cells[startRowIndex + 1 + j, 2].Value = item.BuySell; sheet.Cells[startRowIndex + 1 + j, 3].Value = item.trade.TradeDate?.ToString("yyyy-MM-dd"); sheet.Cells[startRowIndex + 1 + j, 4].Value = item.trade.ExerciseDate?.ToString("yyyy-MM-dd"); sheet.Cells[startRowIndex + 1 + j, 5].Value = item.trade.TradePrice; sheet.Cells[startRowIndex + 1 + j, 6].Value = item.trade.OriginalStockEqvNotionalV2; sheet.Cells[startRowIndex + 1 + j, 7].Value = item.trade.UnderlyingCode; sheet.Cells[startRowIndex + 1 + j, 8].Value = item.trade.UnderlyingAssetName; sheet.Cells[startRowIndex + 1 + j, 9].Value = item.trade.InitialSpotPrice; sheet.Cells[startRowIndex + 1 + j, 10].Value = item.TradeStatusShow; sheet.Cells[startRowIndex + 1 + j, 11].Value = item.trade_cash.ValueDate.ToString("yyyy-MM-dd"); sheet.Cells[startRowIndex + 1 + j, 12].Value = item.trade_cash.MinusAmount; sheet.Cells[startRowIndex + 1 + j, 13].Value = item.trade_cash.WinLossDouble; for (var col = 1; col <= 13; col++) { sheet.Cells[startRowIndex + 1 + j, col].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[startRowIndex + 1 + j, col].Style.VerticalAlignment = ExcelVerticalAlignment.Center; if (col == 1) { sheet.Cells[startRowIndex + 1 + j, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left; } else if (new int[] { 5, 6, 9, 12, 13 }.Contains(col)) { sheet.Cells[startRowIndex + 1 + j, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Right; } else { sheet.Cells[startRowIndex + 1 + j, col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; } } for (var col = 1; col <= i; col++) { sheet.Cells[startRowIndex + 1 + j, 13 + col].Value = trade.Propertys?.FirstOrDefault(p => p.name == sheet.Cells[startRowIndex + 1, 13 + col].Value.ToString())?.value; sheet.Cells[startRowIndex + 1 + j, 13 + col].Style.Border.BorderAround(ExcelBorderStyle.Thin); sheet.Cells[startRowIndex + 1 + j, 13 + col].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; sheet.Cells[startRowIndex + 1 + j, 13 + col].Style.VerticalAlignment = ExcelVerticalAlignment.Center; } } } } /// /// 获取弘业自定义sheet页数据 /// private HongYeSheetModel GetHongYeSheetModel(ClientDingShiReport report) { var fundModel = report.FundReportModel; var SettlementCoupon = fundModel?.Coupon ?? 0;//当日凤凰、雪球票息 var SettlementOptionPremiumSwap = fundModel?.OptionPremiumSwap ?? 0;//当日互换成交 var SettlementSwapBalance = fundModel?.SwapBalance ?? 0;//当日互换了结 var addMoeny = (SettlementCoupon + SettlementOptionPremiumSwap + SettlementSwapBalance);//结算加总 var LastDayRemainFund = fundModel?.LastDayRemainFund ?? 0; //上日账户余额 var CashInCashOutChange = fundModel?.CashInCashOutChange ?? 0; //当日净出入金 var OptionPremium = fundModel?.OptionPremium ?? 0; //当日开仓收支 var SettlementBalance = fundModel?.SettlementBalance ?? 0; SettlementBalance = SettlementBalance + addMoeny; //当日了结收支 //当前账户余额=上日账户余额+当日净出入金+当日开仓收支+当日了结收支 var CurBalance = LastDayRemainFund + CashInCashOutChange + OptionPremium + SettlementBalance; //履约预付金 var WorstCastClientPayable = Math.Max(fundModel?.WorstCastClientPayable ?? 0, 0); //授信额度 var Credit = fundModel?.Credit ?? 0; //可用资金=当前账户余额+授信额度-履约预付金 var Available = CurBalance + Credit - WorstCastClientPayable; //可取资金=max(可用资金-授信额度,0) or max(当前账户余额-履约预付金,0) var WithdrawQuota = Math.Max(CurBalance - WorstCastClientPayable, 0); //追加资金=max(-可用资金,0) var ExtraMoney = Math.Max(-Available, 0); var hyModel = new HongYeSheetModel { CompanyName = PS.Config.CompanyFullName, ClientName = report.client.Name, SettleDate = $"{(report.ReportFrom == DateTime.MinValue ? "" : report.ReportFrom.ToString("yyyy-MM-dd_"))}{report.ReportEnd.ToString("yyyy-MM-dd")}", LastDayRemainFund = LastDayRemainFund.ToString("F2"), CashInCashOutChange = CashInCashOutChange.ToString("F2"), OptionPremium = OptionPremium.ToString("F2"), SettlementBalance = (SettlementBalance).ToString("F2"), CurBalance = CurBalance.ToString("F2"), WorstCastClientPayable = WorstCastClientPayable.ToString("F2"), PositionPv = fundModel?.PositionPv?.ToString("F2"), PositionPnl = fundModel?.PositionPnl?.ToString("F2"), Amount = fundModel?.Amount?.ToString("F2"), Credit = Credit.ToString("F2"), Available = Available.ToString("F2"), WithdrawQuota = WithdrawQuota.ToString("F2"), ExtraMoney = ExtraMoney.ToString("F2"), PositionList = report.eod_positionList ?? new List(), HistoryList = report.trade_contract_groupList ?? new List(), WinLossTotal = report.trade_contract_groupList?.SumDouble(t => t.WinLoss).ToString("F2") }; return hyModel; } private HistorySheetModel GetHistorySheetModel(List trade_contract_groupList) { var model = new HistorySheetModel { TradeContractGroupList = trade_contract_groupList, WinLossSum = trade_contract_groupList.Sum(x => Math.Round(x.WinLoss * 1000) / 1000), TradePriceSum = trade_contract_groupList.Select(x => new { x.trade.id, x.TradePrice }).Distinct().Sum(x => Math.Round((x.TradePrice ?? 0) * 1000) / 1000), MinusAmountSum = trade_contract_groupList.Sum(x => Math.Round(x.trade_cash.MinusAmount * 1000) / 1000), StockEqvNotionalSum = trade_contract_groupList.Select(x => new { x.trade.id, x.trade.OriginalStockEqvNotional }).Distinct().Sum(x => Math.Round((x.OriginalStockEqvNotional ?? 0) * 100) / 100) }; return model; } private HistorySwapFlowSheetModel GetHistorySwapFlowSheetModel(List eod_positionList) { var model = new HistorySwapFlowSheetModel { TradeContractGroupList = eod_positionList, AmountSum = eod_positionList.Where(x => x.BuySell != "开仓").Sum(x => x.Amount.OtcFormatValue(OtcFormatFlag.tradePrice) ?? 0), QuoteAmountSum = eod_positionList.Where(x => x.BuySell != "开仓").Sum(x => x.QuoteAmount.OtcFormatValue(OtcFormatFlag.tradePrice) ?? 0) }; return model; } private PositionSheetModel GetPositionSheetModel(List eod_positionList) { var model = new PositionSheetModel { EodPositionList = eod_positionList, PvSum = eod_positionList.Sum(x => x.PvDouble) == null ? 0 : eod_positionList.Sum(x => x.PvDouble).Value, PnlSum = eod_positionList.Sum(x => x.PnlDouble) == null ? 0 : eod_positionList.Sum(x => x.PnlDouble).Value, TradePriceSum = eod_positionList.Sum(x => x.TradePrice), OriginalStockEqvNotionalSum = eod_positionList.Sum(x => x.OriginalStockEqvNotional), StockEqvNotionalSum = eod_positionList.Sum(x => x.StockEqvNotional), MarginSum = eod_positionList.Sum(x => x.Margin ?? 0) }; return model; } private PositionSwapFlowSheetModel GetPositionSwapFlowSheetModel(List eod_positionList) { var model = new PositionSwapFlowSheetModel { EodPositionList = eod_positionList, TotalFeeSum = eod_positionList.Sum(x => x.TotalFee), MarginSum = eod_positionList.Sum(x => x.Margin), PositionPnlSum = eod_positionList.Sum(x => x.PositionPnl), QuotePositionPnlSum = eod_positionList.Sum(x => x.QuotePositionPnl), }; return model; } public string GenerateReportTxt(ClientDingShiReport report, string html) { var sourcePath = OtcAppContext.MapPath("~/App_Docs/TradeMarket"); sourcePath = MosPathHelper.Combine(sourcePath, ""); if (!Directory.Exists(sourcePath)) { Directory.CreateDirectory(sourcePath); } var clientName = report.client.Name; var fileName = report.ReportFrom == DateTime.MinValue ? $"结算报告_{report.ReportEnd.ToString("MMdd")}_{clientName}" : $"结算报告_{report.ReportFrom:MMdd}_{report.ReportEnd:MMdd}_{clientName}"; var sourceFileName = Path.Combine(sourcePath, $"{fileName}.txt"); System.IO.File.WriteAllText(sourceFileName, html, Encoding.UTF8); return sourceFileName; } //from:trade_spancontroller.clientTradePositionQueryList private List clientTradePositionQueryList(TradeSpanReq req, IEnumerable userAssetUnits) { if (req.ClientId == null || req.ValueDate == null) { return new List(0); } var positionList = new ClientPositionQueryService(this).SearchPositionListAll(req, userAssetUnits); var result = positionList.Select(x => { var model = new EodPositionReportModel() { TradeId = x.TradeId, ClientId = x.ClientId, TradeNumber = x.TradeNumber, TradeType = x.TradeType, TradeContractCode = x.TradeContractCode, UnderlyingCode = x.trade.TradeType == "合成价差期权" ? x.SyntheticUnderlyingTipsInfo : x.UnderlyingCode, UnderlyingPrice = x.UnderlyingPrice, Pv = PS.Config.IsPVRounded ? (x.RoundedPv == null ? "0.00" : x.RoundedPv.Value.ToString("0.00")) : (x.Pv == null ? "0.00" : x.Pv.Value.ToString("0.00")), Pnl = PS.Config.IsPVRounded ? (x.RoundedPnl == null ? "0.00" : x.RoundedPnl.Value.ToString("0.00")) : (x.Pnl == null ? "0.00" : x.Pnl.Value.ToString("0.00")), ValueDate = x.ValueDate, TradeJson = x.TradeJson, tradeOrigin = x.tradeOrigin, PvDouble = (PS.Config.IsPVRounded ? x.RoundedPv : x.Pv) ?? 0, PnlDouble = (PS.Config.IsPVRounded ? x.RoundedPnl : x.Pnl) ?? 0, TradeOpenVolatilityValue = x.TradeOpenVolatility ?? 0, TradeOpenVolatility = x.TradeOpenVolatility == null ? "0.00%" : ((x.TradeOpenVolatility.Value * 100).ToString("0.00") + "%"), VolValue = x.Vol ?? 0, Vol = x.Vol == null ? "0.00%" : ((x.Vol.Value * 100).ToString("0.00") + "%"), DeltaOriginal = x.Delta == null ? "0.00" : (-x.Delta.Value).ToString("0.00"), Delta = x.Delta == null ? "0.00" : (x.ContractSize > 0 ? (-x.Delta.Value / x.ContractSize) : -x.Delta.Value).ToString("0.00"), GammaOriginal = x.Gamma == null ? "0.00" : (-x.Gamma.Value).ToString("0.00"), Gamma = x.Gamma == null ? "0.00" : (x.ContractSize > 0 ? (-x.Gamma.Value / x.ContractSize) : -x.Gamma.Value).ToString("0.00"), Rho = x.Rho == null ? "0.00" : (-x.Rho.Value * 100).ToString("0.00"), Theta = x.Theta == null ? "0.00" : (-x.Theta.Value).ToString("0.00"), Vega = x.Vega == null ? "0.00" : (-x.Vega.Value).ToString("0.00"), Margin = x.Margin ?? 0, PositionRelizedAmount = x.PositionRelizedAmount ?? 0, dic = x.dic, AnnualizeFactor = x.AnnualizeFactor.OtcFormatMoney(), ParticipationRate = x.ParticipationRate.OtcFormatPercent(), PrincipalRate = x.PrincipalRate.OtcFormatPercent(), NoRiskRate = x.NoRiskRate.OtcFormatPercent(), BasisUnderlyingCode = x.BasisUnderlyingCode, BasisUnderlyingName = x.BasisUnderlyingName, BasisGap = x.BasisGap, Lots = x.Lots, QuoteUnitSingle = x.QuoteUnitSingle, MarketCode = x.MarketCode, DeltaCashOriginal = (-x.Delta.Value * x.UnderlyingPrice ?? 0).ToString("0.00"), GammaCashOriginal = (-x.Gamma.Value * x.UnderlyingPrice * x.UnderlyingPrice / 100 ?? 0).ToString("0.00"), SettlementFlag = x.SettlementFlag, UserGroup = x.UserGroup }; if (!model.BasisUnderlyingCode.IsNullOrWhiteSpace() && model.BasisUnderlyingName.IsNullOrWhiteSpace()) { model.BasisUnderlyingName = DataCacheProvider.GetUnderlyingDataSource().GetData(model.BasisUnderlyingCode)?.UnderlyingName; } if (x.InstrumentType == "Stock") { model.Delta = (-x.Delta.Value / 100).ToString("0.00"); model.Gamma = (-x.Gamma.Value / 100).ToString("0.00"); } return model; }).ToList(); result.ForEach(O => { O.trade.TradeSinglePrice = O.trade.TradeSinglePrice.IsNormalize() ? (double?)Math.Abs(O.trade.TradeSinglePrice.Value) : O.trade.TradeSinglePrice; }); return result; } //from:trade_spancontroller.SearchListExtendOnly private List SearchListExtendOnly(EntryExitReq req) { req.State = "已确认,已结算"; req.Direction = $"入金,出金,其他收入,其他支出"; req.TradeAction = $"{ClientCashInCashOut.系统操作_行权费},{ClientCashInCashOut.系统操作_平仓费},{ClientCashInCashOut.系统操作_期权费},{ClientCashInCashOut.系统操作_票息},{ClientCashInCashOut.系统操作_互换}"; req.IsMoneyNotEqualsZero = true; var sList = new EntryExitBLL().SearchListExtendOnly(req); return sList; } //from:trade_spancontroller.SearchListOnlyForMarketReport private List SearchListOnlyForMarketReport(clientcashincashout_productReq req) { var bll = new clientcashincashout_productBLL(); var sList = bll.SearchListOnlyForMarketReport(req); return sList; } } internal class HongYeSheetModel { /// /// 公司名称 /// public string CompanyName { get; set; } /// /// 客户名称 /// public string ClientName { get; set; } /// /// 结算日 /// public string SettleDate { get; set; } /// /// 上日账户余额 /// public string LastDayRemainFund { get; set; } /// /// 当日净出入金 /// public string CashInCashOutChange { get; set; } /// /// 当日开仓收支 /// public string OptionPremium { get; set; } /// /// 当日了结收支 /// public string SettlementBalance { get; set; } /// /// 当日账户余额 /// public string CurBalance { get; set; } /// /// 履约预付金 /// public string WorstCastClientPayable { get; set; } /// /// 持仓市值汇总 /// public string PositionPv { get; set; } /// /// 持仓浮动盈亏 /// public string PositionPnl { get; set; } /// /// 账户总权益 /// public string Amount { get; set; } /// /// 授信额度 /// public string Credit { get; set; } /// /// 可用资金 /// public string Available { get; set; } /// /// 可取资金 /// public string WithdrawQuota { get; set; } /// /// 追加资金 /// public string ExtraMoney { get; set; } public List PositionList { get; set; } public List HistoryList { get; set; } //历史交易 public string WinLossTotal { get; set; } } }