using BaseOUDAL; using CsvHelper; using MathNet.Numerics.Providers.LinearAlgebra; using Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Word; using Newtonsoft.Json.Linq; using NPOI.SS.Formula.Functions; using Org.BouncyCastle.Ocsp; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic.Core; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using YLErp.BLL; using YLErp.Core.Helpers; using YLErp.DBModels; using YLErp.DBModels.Consts; using YLErp.Helpers; using YLErp.MailKit; using YLErp.Model; using YLErp.Models; using YLErp.Modules.EodModule.QueryModule; using YLErp.Modules.SwapModule.Margin; using YLErp.Office.Converters; using YLErp.Office.Helpers; using static YLErp.ConsGlobal; namespace YLErp.Modules.SwapModule { public class SwapEventEmailService : YLBaseService { private List eventTypes = new List() { (int)SwapFlowEventTypeEnum.开仓, (int)SwapFlowEventTypeEnum.平仓 }; private List marginTypes = MarginModes.All.ToList(); private decimal wan = 10000m; public SwapEventEmailService(OptUserInfo userInfo) : base(userInfo) { } /// /// 查询资金提示列表 /// public SearchListResult SearchList(SwapEventEmailRequest req) { if (!req.Valuedate.HasValue) { throw new Exception("缺少日期参数"); } var predicate = PredicateBuilder.Create(n => n.event_date == req.Valuedate); var flowEventPredicate = PredicateBuilder.Create(n => n.PositionType > 0 && eventTypes.Contains(n.EventType) && n.UnwindDate == req.Valuedate.Value && n.DataState == (int)SwapFlowDateStateEnum.完成); var clientSpanPredicate = PredicateBuilder.Create(x => x.ValueDate == req.Valuedate.Value && x.WorstCastClientPayable < 0 && x.SpanType == ClientSpan.SpanType_Eod); var valueDate = valuedateBLL.ValueDate; if (req.ClientIds != null && req.ClientIds.Any()) { flowEventPredicate = flowEventPredicate.And(d => req.ClientIds.Contains(d.ClientId ?? 0)); clientSpanPredicate = clientSpanPredicate.And(d => req.ClientIds.Contains(d.ClientId)); } var emailquery = DbContext.swap_event_email.Where(predicate); var dmaEmailQuery = emailquery.Where(x => x.event_id == 0); var flowQuery = DbContext.swap_flow_event.Where(flowEventPredicate); var clientSpanQuery = DbContext.client_span.Where(clientSpanPredicate); var noDmaquery = from f in flowQuery join t in DbContext.trade on f.SwapTradeId equals t.id join se in DbContext.swap_event.Where(x => !x.Invalid) on f.EventId equals se.id into setemp from se in setemp.DefaultIfEmpty() join em in emailquery on f.id equals em.event_id into emTmp from em in emTmp.DefaultIfEmpty() where t.ValidState == "Valid" && t.TradeType == "收益互换" select new SwapEventEmailResponse { event_id = f.id, client_name = t.ClientName, client_id = t.ClientId, event_type = f.EventType, send_email = em == null ? false : em.send_email, send_remark = em == null ? "" : em.send_remark, transpond = em == null ? 0 : em.transpond, trade_number = t.TradeNumber, single = em == null ? null : em.single, }; var dmaquery = from f in clientSpanQuery join em in dmaEmailQuery on f.ClientId equals em.client_id into emTmp from em in emTmp.DefaultIfEmpty() select new SwapEventEmailResponse { event_id = 0, client_id = f.ClientId, event_type = 3, send_email = em == null ? false : em.send_email, send_remark = em == null ? "" : em.send_remark, transpond = em == null ? 0 : em.transpond, trade_number = "" }; var noDmaResults = noDmaquery.ToList(); var dmaResults = dmaquery.ToList(); var allReulst = dmaResults.Concat(noDmaResults); foreach (var item in allReulst) { if (item.event_id > 0) { if (!item.single.HasValue) { var singleEvent = allReulst.Count(x => x.client_id == item.client_id && x.single == null) == 1; if (singleEvent) { item.single = true; } } } item.transpondStr = item.transpond == 0 ? "未转发" : "已转发"; } SearchListResult searchList = new SearchListResult(); var retListResult = allReulst.OrderBy(o => o.client_name).ThenBy(t => t.trade_number).AsQueryable().ToSearchList(req); foreach (var item in retListResult.rows) { var client = DataCacheProvider.GetClientDataSource().GetData(item.client_id); item.client_type = client?.SwapTradeTypeStr; item.client_name = client?.Name; item.event_date = req.Valuedate.Value; } return retListResult; } /// /// 发送邮件 /// /// /// public void SendEmail(SendSwapEventEmailRequest request) { if (request.EventEmailEmails == null || !request.EventEmailEmails.Any()) { throw new Exception($"没有需要发邮件的数据"); } var dmaEmailDatas = request.EventEmailEmails.Where(x => x.event_id == 0).ToList(); var noDmaEmailDatas = request.EventEmailEmails.Where(x => x.event_id > 0).ToList(); var clientDuitys = GetClientDuitys(); DealNoDmaEmail(noDmaEmailDatas, request.ValueDate, clientDuitys); DealDmaEmail(dmaEmailDatas, request.ValueDate, clientDuitys); } /// /// 处理非dma数据邮件 /// /// /// private void DealNoDmaEmail(List EventEmailEmails, DateTime valueDate, List clientDuitys) { if (!EventEmailEmails.Any()) { return; } var flowEventIds = EventEmailEmails.Select(s => s.event_id).ToList(); var flowEvents = DbContext.swap_flow_event.Where(x => flowEventIds.Contains(x.id)); var clientIds = flowEvents.Select(x => x.ClientId).ToList(); var flowQuery = from f in DbContext.swap_flow_event join t in DbContext.trade on f.SwapTradeId equals t.id join se in DbContext.swap_event.Where(x => !x.Invalid) on f.EventId equals se.id into setemp from se in setemp.DefaultIfEmpty() join em in DbContext.swap_event_email on f.id equals em.event_id into emTmp from em in emTmp.DefaultIfEmpty() where t.ValidState == "Valid" && t.TradeType=="收益互换" && (em == null || em.send_email == false) && clientIds.Contains(f.ClientId) && f.UnwindDate == valueDate && f.PayDirection > 0 && eventTypes.Contains(f.EventType) && f.DataState == (int)SwapFlowDateStateEnum.完成 select f; var flowEventList = flowQuery.ToList(); var docs = new List(); var openFlowEventList = flowEventList.Where(x => x.EventType == (int)SwapFlowEventTypeEnum.开仓).ToList(); var closeFlowEventList = flowEventList.Where(x => x.EventType == (int)SwapFlowEventTypeEnum.平仓).ToList(); docs.AddRange(CheckConfirmDoc(openFlowEventList)); docs.AddRange(CheckSettlementDoc(closeFlowEventList)); SendNoDmaEmail(docs, valueDate, clientDuitys); } /// /// 校验交易确认书是否存在 /// /// /// /// private List CheckConfirmDoc(List flowEvents) { var tradeIds = flowEvents.Select(s => s.SwapTradeId).ToList(); var query = from doc in DbContext.trade_contract_document join r in DbContext.trade_contract_r on doc.Code equals r.ContractCode where doc.Type == r.Type && r.IsValid && r.Type == ContractTypeEnum.Trade && tradeIds.Contains(r.TradeId) select new SwapTradeContractDto { Paths = doc.Paths, Type = r.Type, TradeId = r.TradeId, SwapFlowEventId = r.SwapFlowEventId, FileName = doc.FileName, TradeNumber = r.TradeNumber, }; var docLsit = query.ToList(); List list = new List(); List tradeNumbers = new List(); foreach (var item in flowEvents) { SwapTradeContractDto doc = docLsit.FirstOrDefault(f => f.TradeId == item.SwapTradeId); if (doc == null) { tradeNumbers.Add(item.SwapTradeNo); } else { doc.ClientId = item.ClientId ?? 0; doc.SwapFlowEventType = item.EventType; var client = DataCacheProvider.GetClientDataSource().GetData(doc.ClientId); doc.ClientName = client.Name; doc.SwapFlowEventId = item.id; list.Add(doc); } } if (tradeNumbers.Any()) { throw new Exception($"交易编号为{string.Join(",", tradeNumbers.Distinct())}找不到有效的交易确认书附件,请检查或生成后再发送邮件"); } return list; } /// /// 校验结算确认书 /// /// /// /// private List CheckSettlementDoc(List flowEvents) { var flowEventIds = flowEvents.Select(s => s.id).ToList(); var query = from doc in DbContext.trade_contract_document join r in DbContext.trade_contract_r on doc.Code equals r.ContractCode where doc.Type == r.Type && r.IsValid && r.Type == ContractTypeEnum.Clearing && flowEventIds.Contains(r.SwapFlowEventId ?? 0) select new SwapTradeContractDto { Paths = doc.Paths, Type = r.Type, TradeId = r.TradeId, SwapFlowEventId = r.SwapFlowEventId, FileName = doc.FileName, TradeNumber = r.TradeNumber, }; var docLsit = query.ToList(); List list = new List(); List tradeNumbers = new List(); foreach (var item in flowEvents) { SwapTradeContractDto doc = docLsit.FirstOrDefault(f => f.SwapFlowEventId == item.id); if (doc == null) { tradeNumbers.Add(item.SwapTradeNo); } else { doc.ClientId = item.ClientId ?? 0; doc.SwapFlowEventType = item.EventType; var client = DataCacheProvider.GetClientDataSource().GetData(doc.ClientId); doc.ClientName = client.Name; doc.SwapFlowEventId = item.id; list.Add(doc); } } if (tradeNumbers.Any()) { throw new Exception($"交易编号为{string.Join(",", tradeNumbers.Distinct())}找不到有效的结算确认书附件,请检查或生成后再发送邮件"); } return list; } /// /// 发送非dma数据邮件 /// /// /// private void SendNoDmaEmail(List swapTradeContracts, DateTime valueDate, List clientDuitys) { var flowEventContractGroup = swapTradeContracts.Where(x => x.SwapFlowEventId > 0).GroupBy(g => g.ClientId); foreach (var item in flowEventContractGroup) { var list = item.ToList(); if (list.Count == 1)//单开单平 { SendNodmaEmail(list, valueDate, clientDuitys); } else //轧差支付 { SendNodmaEmailComplex(list, valueDate, clientDuitys); } } } /// /// 发送单开邮件 /// /// /// /// /// private void SendNodmaEmail(List swapTradeContracts, DateTime valueDate, List clientDuitys) { SwapTradeContractDto swapTradeContract = swapTradeContracts.First(); var eventEmail = SaveEventEmail(swapTradeContract.SwapFlowEventId, swapTradeContract.ClientId, valueDate, true); var emails = GetEmailTo(clientDuitys, swapTradeContracts); List filePaths = new List(); string title = $"【{valueDate.ToString("yyyy.MM.dd")}结算说明】{swapTradeContract.ClientName}"; string content = ""; if (swapTradeContract.SwapFlowEventType == (int)SwapFlowEventTypeEnum.开仓) { content = GetSingleEventOpenContent(swapTradeContract, valueDate); } else { content = GetSingleEventCloseContent(swapTradeContract, valueDate); } var file = GetFileName(swapTradeContract.Paths, ".xlsx"); filePaths.Add(file); var emailMsgId = SendEmailApi(title, emails, content, true, filePaths); eventEmail.email_msg_id = emailMsgId; eventEmail.send_email = true; DbContext.SaveChanges(); } /// /// 发送轧差支付邮件 /// /// /// /// /// private void SendNodmaEmailComplex(List swapTradeContracts, DateTime valueDate, List clientDuitys) { List swapEventEmails = new List(); var emails = GetEmailTo(clientDuitys, swapTradeContracts); List filePaths = new List(); string title = $"【{valueDate.ToString("yyyy.MM.dd")}净额结算说明】{swapTradeContracts.First().ClientName}"; string content = ""; foreach (var item in swapTradeContracts) { var file = GetFileName(item.Paths, ".xlsx"); if (!filePaths.Contains(file)) { filePaths.Add(file); } var eventEmail = SaveEventEmail(item.SwapFlowEventId, item.ClientId, valueDate, false); swapEventEmails.Add(eventEmail); } Dictionary dic = new Dictionary(); var clientName = swapTradeContracts.First().ClientName; dic["clientName"] = clientName; dic["settlementDate"] = valueDate.ToString("yyyy.MM.dd"); var openEvents = swapTradeContracts.Where(x => x.SwapFlowEventType == (int)SwapFlowEventTypeEnum.开仓).ToList(); var closeEvents = swapTradeContracts.Where(x => x.SwapFlowEventType == (int)SwapFlowEventTypeEnum.平仓).ToList(); var openAmount = DealOpenEventData(openEvents, dic); var closeAmount = DealCloseEventData(closeEvents, dic); var totalAmount = openAmount + closeAmount; dic["payAmount"] = Math.Abs(totalAmount).ToString("0.######"); dic["payDirect"] = totalAmount >= 0 ? "我方" : "客户"; content = GetComplexEventContent(dic, valueDate, clientName); var swapEventEmailIds = swapEventEmails.Select(s => s.id).ToList(); var emailMsgId = SendEmailApi(title, emails, content, true, filePaths); swapEventEmails.ForEach(x => { x.send_email = true; x.email_msg_id = emailMsgId; }); DbContext.SaveChanges(); } /// /// 处理轧差支付 开仓数据 /// /// /// private decimal DealOpenEventData(List swapTradeContracts, Dictionary dic) { var tradeIds = swapTradeContracts.Select(s => s.TradeId).Distinct().ToList(); var trades = DbContext.trade.Where(x => tradeIds.Contains(x.id)).ToList(); var swapPositions = DbContext.swap_position.Where(x => tradeIds.Contains(x.SwapTradeId) && x.IsInitial && !x.Invalid).ToList(); var posiList = swapPositions.Where(x => x.PosiDirection > 0); var stockNotional = posiList.Sum(s => s.PosiNotionalValue) / wan; var notionalStock = stockNotional; if (stockNotional >= wan) { notionalStock /= wan; } dic["openTotal"] = trades.Count; dic["openNotionalStock"] = (notionalStock).ToString("0.######") + (stockNotional >= wan ? "亿" : "万"); string tradeNumbers = string.Empty; decimal marginAmountTotal = 0; foreach (var t in trades) { var marginAmount = swapPositions.Where(x => marginTypes.Contains(x.InterestMode) && x.PosiStartDate == t.StartDate && x.SwapTradeId == t.id).Sum(s => s.InterestPrincipalFix * (s.InterestDirection == 1 ? -1m : 1m)); marginAmountTotal += marginAmount; tradeNumbers += $"

合约编号 {t.TradeNumber}

"; } marginAmountTotal /= wan; dic["openTradeNumber"] = tradeNumbers; dic["openPaySide"] = marginAmountTotal > 0 ? "我方" : ""; dic["openMarginAmount"] = Math.Abs(marginAmountTotal).ToString("0.######"); return marginAmountTotal; } /// /// 处理轧差支付 平仓数据 /// /// /// private decimal DealCloseEventData(List swapTradeContracts, Dictionary dic) { var flowEventIds = swapTradeContracts.Select(s => s.SwapFlowEventId).ToList(); var swapFlowEvents = DbContext.swap_flow_event.Where(x => flowEventIds.Contains(x.id)).ToList(); var eventIds = swapFlowEvents.Select(s => s.EventId).Distinct().ToList(); var swapEvents = DbContext.swap_event.Where(x => eventIds.Contains(x.id)).ToList(); decimal stockNotionalTotal = 0; decimal swapCloseAmountTotal = 0; string tradeNumbers = string.Empty; foreach (var swapEvent in swapEvents) { var unwindData = JsonHelper.Deserialize(swapEvent.EventData); var flowEvent = swapFlowEvents.Where(x => x.EventId == swapEvent.id).First(); var stockNotional = unwindData.CloseNotionalValue / wan; var marginAmount = unwindData.SwapMarginAmount / wan; stockNotionalTotal += stockNotional; swapCloseAmountTotal += -(unwindData.SwapCloseAmount + unwindData.SwapMarginRebatePnl - unwindData.SwapMarginAmount) / wan; tradeNumbers += $"

合约编号 {flowEvent.SwapTradeNo}

"; } var notionalStock = stockNotionalTotal; if (stockNotionalTotal >= wan) { notionalStock /= wan; } dic["closeTradeNumber"] = tradeNumbers; dic["closeNotionalStock"] = (notionalStock).ToString("0.######") + (stockNotionalTotal >= wan ? "亿" : "万"); dic["closePaySide"] = swapCloseAmountTotal > 0 ? "我方" : ""; dic["closeMarginAmount"] = Math.Abs(swapCloseAmountTotal).ToString("0.######"); return swapCloseAmountTotal; } /// /// 获取轧差支付邮件内容 /// /// /// /// /// private string GetComplexEventContent(Dictionary dic, DateTime valueDate, string clientName) { var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string templatePath = Path.Combine(sourcePath, "资金提示-轧差支付模板.docx"); var tempFolder = OtcAppContext.MapPath("~/App_Docs/Temp/结算报告"); tempFolder = MosPathHelper.Combine(tempFolder, ""); var targetPath = Path.Combine(tempFolder, valueDate.ToString("yyyyMMdd")); if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } var fileName = $"资金提示-轧差支付{valueDate:yyyyMMdd}_{clientName}"; var targetFileName = Path.Combine(targetPath, $"{fileName}.docx"); return GetEmailContent(templatePath, dic, targetFileName); } /// /// 保存记录 /// /// /// /// /// /// private SwapEventEmail SaveEventEmail(long? eventId, int clientId, DateTime valueDate, bool single) { var swapEventEmail = DbContext.swap_event_email.FirstOrDefault(x => x.event_id == eventId && x.client_id == clientId && x.event_date == valueDate); if (swapEventEmail == null) { swapEventEmail = new SwapEventEmail() { event_date = valueDate, event_id = eventId, client_id = clientId, single = single, send_remark = single ? "结算提示-单开单平" : "结算提示-轧差支付" }; swapEventEmail.SetCreator(UserId, UserName); swapEventEmail.SetOpt(UserId, UserName); DbContext.swap_event_email.Add(swapEventEmail); DbContext.SaveChanges(); } return swapEventEmail; } /// /// 保存记录 /// /// /// /// /// private SwapEventEmail SaveEventEmail(long? eventId, int clientId, DateTime valueDate) { var swapEventEmail = DbContext.swap_event_email.FirstOrDefault(x => x.event_id == eventId && x.client_id == clientId && x.event_date == valueDate); if (swapEventEmail == null) { swapEventEmail = new SwapEventEmail() { event_date = valueDate, event_id = eventId, client_id = clientId, single = false, send_remark = "追缴预付金Email" }; swapEventEmail.SetCreator(UserId, UserName); swapEventEmail.SetOpt(UserId, UserName); DbContext.swap_event_email.Add(swapEventEmail); DbContext.SaveChanges(); } return swapEventEmail; } /// /// 处理dma数据邮件 /// /// /// private void DealDmaEmail(List EventEmailEmails, DateTime valueDate, List clientDuitys) { var clientIds = EventEmailEmails.Select(x => x.client_id).ToList(); var clientEmailDic = GetEmailTo(clientDuitys, clientIds); var clientSpans = DbContext.client_span.Where(x => clientIds.Contains(x.ClientId) && x.ValueDate == valueDate && x.WorstCastClientPayable < 0 && x.SpanType == ClientSpan.SpanType_Eod).ToList(); foreach (var clientSpan in clientSpans) { var client = DataCacheProvider.GetClientDataSource().GetData(clientSpan.ClientId); if (client == null) { continue; } var clientNumber = client.Name; var eventEmail = SaveEventEmail(0, client.id, valueDate); string title = $"【{valueDate.ToString("yyyy.MM.dd")}追缴预付金通知】{client.Name}"; var content = GetDmaContent(client.Name, valueDate, Math.Abs(clientSpan.WorstCastClientPayable ?? 0)); content += $"

{eventEmail.id}

"; var emailTo = clientEmailDic[client.id]; var emailMsgId = SendEmailApi(title, emailTo, content, true, new List()); eventEmail.send_email = true; eventEmail.email_msg_id = emailMsgId; DbContext.SaveChanges(); } } ///

/// 获取客户联系人邮箱 /// /// private List GetClientDuitys() { using var db = new ClientDBContext(); var clientContacts = db.clientduty.Where(x => x.ApprovalOrder < 1 && (x.DeadLine == null || x.DeadLine > DateTime.Now) && x.IsReceiveEmail == 1 && x.Email != null && x.ContactTypeId.Contains("4")) .ToList(); return clientContacts; } /// /// 获取收件人联系邮箱 /// /// /// /// /// private string GetEmailTo(List clientDuitys, List swapTradeContracts) { var clientIds = swapTradeContracts.Select(s => s.ClientId).Distinct().ToList(); var clientDuityQuery = clientDuitys.Where(x => clientIds.Contains(x.ClientId ?? 0)); List clientNumbers = new List(); foreach (var swapTradeContract in swapTradeContracts.GroupBy(g => g.ClientId)) { var clientNumber = swapTradeContract.ToList().First().ClientName; if (!clientDuityQuery.Any(x => x.ClientId == swapTradeContract.Key)) { clientNumbers.Add(clientNumber); } } if (clientNumbers.Any()) { throw new Exception($"客户{string.Join(",", clientNumbers)}未维护职责类型为联系人且接收相关邮件选项为是"); } var emails = clientDuityQuery.Select(s => s.Email).Distinct().ToList(); return string.Join(";", emails); } /// /// 获取收件人联系邮箱 /// /// /// /// /// private Dictionary GetEmailTo(List clientDuitys, List clientIds) { var clientDuityQuery = clientDuitys.Where(x => clientIds.Contains(x.ClientId ?? 0)); List clientNumbers = new List(); Dictionary dic = new Dictionary(); foreach (var t in clientIds) { var client = DataCacheProvider.GetClientDataSource().GetData(t); var clientNumber = client?.Name; if (!clientDuityQuery.Any(x => x.ClientId == t)) { clientNumbers.Add(clientNumber); } var emails = clientDuityQuery.Where(x => x.ClientId == t).Select(s => s.Email).Distinct().ToList(); dic.Add(t, string.Join(";", emails)); } if (clientNumbers.Any()) { throw new Exception($"客户{string.Join(",", clientNumbers)}未维护职责类型为联系人且接收相关邮件选项为是"); } return dic; } /// /// 获取单开邮件内容 /// /// /// /// private string GetSingleEventOpenContent(SwapTradeContractDto swapTradeContract, DateTime valueDate) { var trade = DbContext.trade.Find(swapTradeContract.TradeId); var swapPositions = DbContext.swap_position.Where(x => x.SwapTradeId == swapTradeContract.TradeId && x.IsInitial && !x.Invalid); var marginAmount = swapPositions.Where(x => marginTypes.Contains(x.InterestMode) && x.PosiStartDate == trade.StartDate).Sum(s => s.InterestPrincipalFix * (s.InterestDirection == 1 ? -1m : 1m)); var posi = swapPositions.FirstOrDefault(x => x.PosiDirection > 0); Dictionary dic = new Dictionary(); var stockNotional = posi.PosiNotionalValue / wan; marginAmount /= wan; var notionalStock = stockNotional; if (stockNotional >= wan) { notionalStock /= wan; } dic["clientName"] = swapTradeContract.ClientName; dic["settlementDate"] = valueDate.ToString("yyyy.MM.dd"); dic["tradeNumber"] = swapTradeContract.TradeNumber; dic["notionalStock"] = notionalStock.ToString("0.######") + (stockNotional >= wan ? "亿" : "万"); dic["paySide"] = marginAmount >= 0 ? "我方" : ""; dic["marginAmount"] = Math.Abs(marginAmount).ToString("0.######"); dic["payAmount"] = Math.Abs(marginAmount).ToString("0.######"); dic["payDirect"] = marginAmount >= 0 ? "我方" : "客户"; var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string templatePath = Path.Combine(sourcePath, "资金提示-单开模板.docx"); var tempFolder = OtcAppContext.MapPath("~/App_Docs/Temp/结算报告"); tempFolder = MosPathHelper.Combine(tempFolder, ""); var targetPath = Path.Combine(tempFolder, valueDate.ToString("yyyyMMdd")); if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } var clientName = swapTradeContract.ClientName; var fileName = $"资金提示-单开{valueDate:yyyyMMdd}_{clientName}"; var targetFileName = Path.Combine(targetPath, $"{fileName}.docx"); return GetEmailContent(templatePath, dic, targetFileName); } /// /// 获取单平邮件内容 /// /// /// /// private string GetSingleEventCloseContent(SwapTradeContractDto swapTradeContract, DateTime valueDate) { var swapFlowEvent = DbContext.swap_flow_event.Find(swapTradeContract.SwapFlowEventId); var swapEvent = DbContext.swap_event.Find(swapFlowEvent.EventId); var unwindData = JsonHelper.Deserialize(swapEvent.EventData); Dictionary dic = new Dictionary(); var stockNotional = unwindData.CloseNotionalValue / wan; var payAmount = -(unwindData.SwapCloseAmount + unwindData.SwapMarginRebatePnl - unwindData.SwapMarginAmount) / wan; var notionalStock = stockNotional; if (stockNotional >= wan) { notionalStock /= wan; } dic["clientName"] = swapTradeContract.ClientName; dic["settlementDate"] = valueDate.ToString("yyyy.MM.dd"); dic["tradeNumber"] = swapTradeContract.TradeNumber; dic["notionalStock"] = notionalStock.ToString("0.######") + (stockNotional >= wan ? "亿" : "万"); dic["paySide"] = payAmount > 0 ? "我方" : ""; dic["marginAmount"] = Math.Abs(payAmount).ToString("0.######"); ; dic["payAmount"] = Math.Abs(payAmount).ToString("0.######"); dic["payDirect"] = payAmount > 0 ? "我方" : "客户"; var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string templatePath = Path.Combine(sourcePath, "资金提示-单平模板.docx"); var tempFolder = OtcAppContext.MapPath("~/App_Docs/Temp/结算报告"); tempFolder = MosPathHelper.Combine(tempFolder, ""); var targetPath = Path.Combine(tempFolder, valueDate.ToString("yyyyMMdd")); if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } var clientName = swapTradeContract.ClientName; var fileName = $"资金提示-单平{valueDate:yyyyMMdd}_{clientName}"; var targetFileName = Path.Combine(targetPath, $"{fileName}.docx"); return GetEmailContent(templatePath, dic, targetFileName); } /// /// 获取dma邮件数据 /// /// /// /// /// private string GetDmaContent(string clientName, DateTime valueDate, double marginAmount) { Dictionary dic = new Dictionary(); dic["clientName"] = clientName; dic["settlementDate"] = valueDate.ToString("yyyy.MM.dd"); dic["marginAmount"] = marginAmount; var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string templatePath = Path.Combine(sourcePath, "资金提示-追加预付金模板.docx"); var tempFolder = OtcAppContext.MapPath("~/App_Docs/Temp/结算报告"); tempFolder = MosPathHelper.Combine(tempFolder, ""); var targetPath = Path.Combine(tempFolder, valueDate.ToString("yyyyMMdd")); if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } var fileName = $"资金提示-追加预付金{valueDate:yyyyMMdd}_{clientName}"; var targetFileName = Path.Combine(targetPath, $"{fileName}.docx"); return GetEmailContent(templatePath, dic, targetFileName); } private string GetEmailContent(string templatePath, Dictionary modelDic, string outputFilePath) { var varDic = new JsonVarDic(modelDic); OfficeFileConverter.ConvertByUsingDocTemplate(templatePath, outputFilePath, varDic, false); string content = DocHelper.GetContent(outputFilePath); File.Delete(outputFilePath); return content; } /// /// 发送单个邮件内容 /// /// /// /// /// /// private string SendEmailApi(string subject, string mailTo, string body, bool isBodyHtml, List filesToAttach) { return EmailHelper.SendMail(mailTo, subject, body, isBodyHtml, filesToAttach); } private string GetFileName(string baseName, string sufferFix) { var fName = baseName; if (fName.EndsWith(sufferFix)) { fName = Path.ChangeExtension(fName, sufferFix); } if (!string.IsNullOrWhiteSpace(fName) && (fName[0] != '/' || fName[0] != '\\')) { fName = fName.Insert(0, "/"); } fName = OtcAppContext.MapPath(fName); if (!System.IO.File.Exists(fName)) { fName = Path.ChangeExtension(fName, "docx"); }//解决数据库中存的后缀名是doc但实际文件是docx的问题; if (System.IO.File.Exists(fName)) { return fName; } else { return null; } } } }