diff --git a/Framework/YLErp.Core/DBModels/trade_contract_r.cs b/Framework/YLErp.Core/DBModels/trade_contract_r.cs index 705fb66e..8745dd6e 100644 --- a/Framework/YLErp.Core/DBModels/trade_contract_r.cs +++ b/Framework/YLErp.Core/DBModels/trade_contract_r.cs @@ -40,5 +40,9 @@ namespace YLErp.DBModels /// 是否发送邮件 /// public bool? send_email { get; set; } + /// + /// 邮件发送结果 + /// + public string send_email_result { get; set; } } } diff --git a/YLErpDAL/BLL/EodSettlement/RealtimePnlCalc.cs b/YLErpDAL/BLL/EodSettlement/RealtimePnlCalc.cs index 14ec59f5..9c2679e2 100644 --- a/YLErpDAL/BLL/EodSettlement/RealtimePnlCalc.cs +++ b/YLErpDAL/BLL/EodSettlement/RealtimePnlCalc.cs @@ -1378,9 +1378,17 @@ namespace YLErp.BLL.Eod var pvShift = tradeObj.TradeType == "雪球期权" && tradeObj.trade_snowball.PrepaymentUsed ? -tradeObj.Notional * (tradeObj.SpotPrice ?? 0) * (tradeObj.trade_snowball.PrepaymentRatio ?? 0) * (tradeObj.BuySell == "卖出" ? -1 : 1) : 0; - result.PositionPnl = EodOperationBase.GetPositionPnl((result.Pv ?? 0.0) + pvShift, tradeObj.TradePrice ?? 0.0, tradeObj.Notional, tradeObj.OriginalNotional ?? 0, tradeObj.BuySell); - result.RoundedPositionPnl = EodOperationBase.GetPositionPnl((result.RoundedPv ?? 0.0) + pvShift, tradeObj.TradePrice ?? 0.0, tradeObj.Notional, tradeObj.OriginalNotional ?? 0, tradeObj.BuySell); - result.RealizedPnl = 0; + if (tradeObj.TradeType == "收益互换") + { + result.PositionPnl = optionValueResult.Pv; + result.RoundedPositionPnl = optionValueResult.RoundedPv; + } + else + { + result.PositionPnl = EodOperationBase.GetPositionPnl((result.Pv ?? 0.0) + pvShift, tradeObj.TradePrice ?? 0.0, tradeObj.Notional, tradeObj.OriginalNotional ?? 0, tradeObj.BuySell); + result.RoundedPositionPnl = EodOperationBase.GetPositionPnl((result.RoundedPv ?? 0.0) + pvShift, tradeObj.TradePrice ?? 0.0, tradeObj.Notional, tradeObj.OriginalNotional ?? 0, tradeObj.BuySell); + } + result.RealizedPnl = optionValueResult.ExtendInfo.RealPnl; if (tradeObj.TradeType == "远期") diff --git a/YLErpDAL/BLL/ValuedateBLL.cs b/YLErpDAL/BLL/ValuedateBLL.cs index c239510f..969935f4 100644 --- a/YLErpDAL/BLL/ValuedateBLL.cs +++ b/YLErpDAL/BLL/ValuedateBLL.cs @@ -302,7 +302,7 @@ namespace YLErp.BLL var tradingDay = now.Date; - if (now.TimeOfDay > new TimeSpan(20, 30, 0)) + if (now.TimeOfDay > new TimeSpan(23, 59, 00)) { tradingDay = tradingDay.AddDays(1); } diff --git a/YLErpDAL/Helpers/EmailHelper.cs b/YLErpDAL/Helpers/EmailHelper.cs index 0f6c40d2..19dbceb4 100644 --- a/YLErpDAL/Helpers/EmailHelper.cs +++ b/YLErpDAL/Helpers/EmailHelper.cs @@ -44,10 +44,25 @@ namespace YLErp.Helpers { throw new ArgumentException("不能为空", nameof(mailTo)); } + if (PS.Config.ErpElement.MailMessageRateLimit > 0) + { + var milliSeconds = 60d * 1000 / PS.Config.ErpElement.MailMessageRateLimit; + lock (_dic) + { + if (_dic.TryGetValue("sendEmail", out var dt)) + { + while (dt < DateTime.Now && dt.AddMilliseconds(milliSeconds) > DateTime.Now) + { + Thread.Sleep(500); + } + } + _dic["sendEmail"] = DateTime.Now; + } + } return doSendMail(mailTo, subject, body, isBodyHtml, filesToAttach, ccEmail); } - private static string doSendMail( string mailTo, string subject, string body, bool isBodyHtml, IEnumerable filesToAttach, string ccEmail) + private static string doSendMail(string mailTo, string subject, string body, bool isBodyHtml, IEnumerable filesToAttach, string ccEmail) { try { @@ -57,7 +72,7 @@ namespace YLErp.Helpers var mailToArr = toSet.ToArray(); - MailSender.SendApi(new MailSendingOption + string result = MailSender.SendApi(new MailSendingOption { MailTo = mailToArr, Subject = subject, @@ -67,13 +82,13 @@ namespace YLErp.Helpers CC = ccEmail }); - return string.Empty; + return result; } catch (Exception ex) { LogFactory.GetLogger("邮件发送").Error("邮件发送失败:" + subject, ex); - return ex.Message; + throw ex; } } } diff --git a/YLErpDAL/Model/SendEmailResult.cs b/YLErpDAL/Model/SendEmailResult.cs new file mode 100644 index 00000000..9d50b9e3 --- /dev/null +++ b/YLErpDAL/Model/SendEmailResult.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using YLErp.Models; + +namespace YLErp.Model +{ + public class SendEmailResult:ApiResponse + { + public string data; + } +} diff --git a/YLErpDAL/Model/SwapTradeSendEmailReq.cs b/YLErpDAL/Model/SwapTradeSendEmailReq.cs new file mode 100644 index 00000000..8879f232 --- /dev/null +++ b/YLErpDAL/Model/SwapTradeSendEmailReq.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace YLErp.Model +{ + public class SwapTradeSendEmailReq + { + public SwapTradeSendEmailReq() { + tradeIds = new List(); + } + public List tradeIds; + } +} diff --git a/YLErpDAL/Model/SwapTradeSendEmailResp.cs b/YLErpDAL/Model/SwapTradeSendEmailResp.cs new file mode 100644 index 00000000..26542925 --- /dev/null +++ b/YLErpDAL/Model/SwapTradeSendEmailResp.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace YLErp.Model +{ + public class SwapTradeSendEmailResp + { + public int tradeId { get; set; } + public string send_email_result { get; set; } + } +} diff --git a/YLErpDAL/Modules/CalculationModule/Models/TradeValueResult.cs b/YLErpDAL/Modules/CalculationModule/Models/TradeValueResult.cs index 99993f4c..70afbbd5 100644 --- a/YLErpDAL/Modules/CalculationModule/Models/TradeValueResult.cs +++ b/YLErpDAL/Modules/CalculationModule/Models/TradeValueResult.cs @@ -525,6 +525,8 @@ namespace YLErp.Modules.CalculationModule public double PFE { get; set; } public double QuotePFE { get; set; } + + public double RealPnl { get;set; } } diff --git a/YLErpDAL/Modules/CalculationModule/PayoffSwapCalcService.cs b/YLErpDAL/Modules/CalculationModule/PayoffSwapCalcService.cs index a0ef134d..920730f5 100644 --- a/YLErpDAL/Modules/CalculationModule/PayoffSwapCalcService.cs +++ b/YLErpDAL/Modules/CalculationModule/PayoffSwapCalcService.cs @@ -116,6 +116,7 @@ namespace YLErp.Modules.CalculationModule { QuoteFloatingWinLoss =Convert.ToDouble(lastEodSwap.FloatingPnL), FloatingWinLoss = Convert.ToDouble(lastEodSwap.FloatingPnL) * rate, + RealPnl = Convert.ToDouble(lastEodSwap.RealizedPnL) * rate, QuoteCommission = clientCashOut?.Money??0, Commission = (clientCashOut?.Money ?? 0) * rate, QuoteAnnualFee = 0, @@ -151,33 +152,35 @@ namespace YLErp.Modules.CalculationModule /// private static eod_swap GetEodSwapData(OtcTradeBase trade, YLContext db) { - var eodSwap=new eod_swap(); - var positions = db.swap_position.Where(x=>x.PosiQuantity>0&&!x.IsInitial&&x.SwapTradeId== trade.id).ToList(); + var eodSwap = new eod_swap(); + var positions = db.swap_position.Where(x => x.PosiQuantity > 0 && !x.IsInitial && x.SwapTradeId == trade.id).ToList(); eodSwap.SwapTradeId = trade.id; eodSwap.NotionalValueLong = positions.Where(x => x.PositionType == (int)PositionTypeFlag.Long).Sum(s => s.PosiNotionalValue); eodSwap.NotionalValueShort = positions.Where(x => x.PositionType == (int)PositionTypeFlag.Short).Sum(s => s.PosiNotionalValue); eodSwap.NotionalValue = eodSwap.NotionalValueLong + eodSwap.NotionalValueShort; eodSwap.DV01 = 0; + var lastEod = db.eod_swap.Where(x => x.SwapTradeId == trade.id).OrderByDescending(o => o.ValueDate).FirstOrDefault(); + eodSwap.RealizedPnL = lastEod?.RealizedPnL ?? 0; + eodSwap.InterestPnL = lastEod?.InterestPnL ?? 0; foreach (var item in positions) { decimal shortRatio = item.PositionType == (int)PositionTypeFlag.Long ? 1 : -1;//多空方向 int directionRatio = item.PosiDirection == (int)SwapDirectionEnum.收取 ? 1 : -1; - var pv= item.PosiQuantity * shortRatio * item.ContractSize; - var pvNoPrice = item.PosiQuantity * item.ContractSize; + var pv = item.PosiQuantity * shortRatio * item.ContractSize; + var pvNoPrice = item.PosiQuantity * item.ContractSize; decimal vobp = 0; var data = DataCacheProvider.GetUnderlyingDataSource().GetData(item.UnderlyingCode); if (data != null) { if (data.IsBond()) { - var dealDate = QdpCalendarHelper.GetNonHolidayDefore(valuedateBLL.ValueDate.AddDays(-1)); - var bondPrice = EodPriceQueryService.GetBondPrice(dealDate, data.UnderlyingCode); + var bondPrice = EodPriceQueryService.GetBondPrice(valuedateBLL.ValueDate, data.UnderlyingCode); vobp = bondPrice.Vobp ?? 0; var price = Convert.ToDecimal(bondPrice.ClosePrice); - eodSwap.FloatingPnL = (price - item.PosiNetPrice) * item.PosiQuantity * item.ContractSize * shortRatio * directionRatio; + eodSwap.FloatingPnL = (price - item.PosiGrossPrice) * item.PosiQuantity * item.ContractSize * shortRatio * directionRatio; } } - if (shortRatio>0) + if (shortRatio > 0) { eodSwap.MarketValueLong += pv; } @@ -185,10 +188,10 @@ namespace YLErp.Modules.CalculationModule { eodSwap.MarketValueShort += pv; } - eodSwap.PostionValue += pv; - eodSwap.DV01+= pvNoPrice * vobp * shortRatio* directionRatio * 0.01m; + eodSwap.NotionalValue += pvNoPrice; + eodSwap.DV01 += pvNoPrice * vobp * shortRatio * directionRatio * 0.01m; } - + eodSwap.PostionValue = eodSwap.InterestPnL + eodSwap.FloatingPnL; return eodSwap; } diff --git a/YLErpDAL/Modules/DataCacheModule/DataSource/UnderlyingDbDataSource.cs b/YLErpDAL/Modules/DataCacheModule/DataSource/UnderlyingDbDataSource.cs index b850e1fe..6f5da96a 100644 --- a/YLErpDAL/Modules/DataCacheModule/DataSource/UnderlyingDbDataSource.cs +++ b/YLErpDAL/Modules/DataCacheModule/DataSource/UnderlyingDbDataSource.cs @@ -21,7 +21,7 @@ namespace YLErp.Modules.DataCacheModule { class UnderlyingDbDataSource : IUnderlyingDataSource, IBasketPriceProvider, IDataUpdater, IDataSource, IDataSource, IDataSourceEvent, IJsonSerializable { - private readonly YLContext _context=new YLContext(); + private readonly YLContext _context = new YLContext(); /// /// 查询过滤条件 /// @@ -151,9 +151,8 @@ namespace YLErp.Modules.DataCacheModule else if (un.IsBond()) { var valueDate = valuedateBLL.ValueDate; - valueDate=QdpCalendarHelper.GetNonHolidayDefore(valueDate.AddDays(-1)); - var bondPrice = EodPriceQueryService.GetBondPrice(valueDate,un.UnderlyingCode); - price = bondPrice!=null? bondPrice.ClosePrice:un.Price??0; + var bondPrice = EodPriceQueryService.GetBondPrice(valueDate, un.UnderlyingCode); + price = bondPrice != null ? bondPrice.ClosePrice : un.Price ?? 0; } else { diff --git a/YLErpDAL/Modules/DataProviderModule/EodPriceProvider.cs b/YLErpDAL/Modules/DataProviderModule/EodPriceProvider.cs index fd2501dd..9ed78cef 100644 --- a/YLErpDAL/Modules/DataProviderModule/EodPriceProvider.cs +++ b/YLErpDAL/Modules/DataProviderModule/EodPriceProvider.cs @@ -55,14 +55,10 @@ namespace YLErp.Modules.DataProviderModule /// public EodPriceProvider Initialize(IEnumerable underlyingCodes = null) { - if (!PreValueDate.HasValue) - { - PreValueDate = QdpCalendarHelper.GetNonHoliday(ValueDate.AddDays(-1)); - } using var db = DbContextFactory.GetYLDbContext(); var predicate1 = PredicateBuilder.Create(eodprice => eodprice.ValueDate == ValueDate); var predicate2 = PredicateBuilder.Create(eodprice => eodprice.ValueDate == ValueDate); - var predicate3 = PredicateBuilder.Create(eodprice => eodprice.valuation_date == PreValueDate); + var predicate3 = PredicateBuilder.Create(eodprice => eodprice.valuation_date == ValueDate); if (underlyingCodes != null && underlyingCodes.Any(n => !string.IsNullOrEmpty(n))) { var set = underlyingCodes.Where(n => n != null && !_priceDic.ContainsKey(n)).ToHashSet(); @@ -114,24 +110,24 @@ namespace YLErp.Modules.DataProviderModule DeciReferencePrice = 0, }; var eodBondQuery = from eodprice in db.china_bond_valuation.Where(predicate3) - join um in db.underlying_manager on eodprice.bond_id equals um.UnderlyingCode - select new EodPrice - { - IsStock = false, - ValueDate = ValueDate, - UnderlyingId = um.id, - UnderlyingCode = um.UnderlyingCode, - ClosePrice = 0, - SettlePrice = 0, - HighPrice = 0, - LowPrice = 0, - UnderlyingStatus = "正常运行", - UnderlyingInstrumentType = "Bonds", - ReferencePrice =0, - DeciSettlePrice = eodprice.dirty_price_close, - DeciClosePrice = eodprice.net_price, - DeciReferencePrice = eodprice.yield, - }; + join um in db.underlying_manager on eodprice.bond_id equals um.UnderlyingCode + select new EodPrice + { + IsStock = false, + ValueDate = ValueDate, + UnderlyingId = um.id, + UnderlyingCode = um.UnderlyingCode, + ClosePrice = 0, + SettlePrice = 0, + HighPrice = 0, + LowPrice = 0, + UnderlyingStatus = "正常运行", + UnderlyingInstrumentType = "Bonds", + ReferencePrice = 0, + DeciSettlePrice = eodprice.dirty_price_close, + DeciClosePrice = eodprice.net_price, + DeciReferencePrice = eodprice.yield, + }; //数据加载到字典中 var list = eodFutureQuery.Concat(eodStockQuery).Concat(eodBondQuery).ToArray(); @@ -143,7 +139,7 @@ namespace YLErp.Modules.DataProviderModule { if (item.UnderlyingInstrumentType == "Bonds") { - item.SettlePrice = Convert.ToDouble(item.DeciSettlePrice*ConsGlobal.bondPriceMultiple); + item.SettlePrice = Convert.ToDouble(item.DeciSettlePrice * ConsGlobal.bondPriceMultiple); item.ClosePrice = Convert.ToDouble(item.DeciClosePrice * ConsGlobal.bondPriceMultiple); item.ReferencePrice = Convert.ToDouble(item.DeciReferencePrice * ConsGlobal.bondPriceMultiple); } diff --git a/YLErpDAL/Modules/DataProviderModule/EodPriceQueryService.cs b/YLErpDAL/Modules/DataProviderModule/EodPriceQueryService.cs index 3a261e30..f06a51bc 100644 --- a/YLErpDAL/Modules/DataProviderModule/EodPriceQueryService.cs +++ b/YLErpDAL/Modules/DataProviderModule/EodPriceQueryService.cs @@ -13,12 +13,12 @@ namespace YLErp.Modules.DataProviderModule /// /// 检查数据库是否有数据 /// - public static bool CheckDbExists(DateTime valueDate,DateTime preSettleDate) + public static bool CheckDbExists(DateTime valueDate) { using var db = DbContextFactory.GetYLDbContext(); return db.eod_commodity_future_price.Any(n => n.ValueDate == valueDate) || db.eod_stock_price.Any(n => n.ValueDate == valueDate) - || db.china_bond_valuation.Any(n=>n.valuation_date== preSettleDate && n.dirty_price_close>0); + || db.china_bond_valuation.Any(n => n.valuation_date == valueDate && n.dirty_price_close > 0); } /// @@ -41,7 +41,7 @@ namespace YLErp.Modules.DataProviderModule //日终估值全价必须有值才算 var query = from e in db.china_bond_valuation where e.bond_id == underlyingCode - && e.valuation_date >= startDate && e.valuation_date <= valueDate &&e.dirty_price_close>0 + && e.valuation_date >= startDate && e.valuation_date <= valueDate && e.dirty_price_close > 0 select e; return query.Any(); @@ -110,7 +110,30 @@ namespace YLErp.Modules.DataProviderModule { return (eodPrice = GetEodPrice(valueDate, underlyingId)) != null; } + /// + /// 获取某日之前最新价格 + /// + /// + /// + /// + /// + public static bool TryGetPrice(DateTime valueDate, string underlyingCode, out double price) + { + price = 0; + valueDate = valueDate.Date; + using var db = DbContextFactory.GetYLDbContext(); + var data = db.eod_commodity_future_price.Where(x => x.ValueDate <= valueDate && x.UnderlyingCode == underlyingCode).OrderByDescending(o => o.ValueDate).FirstOrDefault(); + + if (data != null) + { + price = data.ReferencePrice ?? 0; + + return true; + } + + return false; + } /// /// 尝试获取标的某日的日终价 /// @@ -147,14 +170,14 @@ namespace YLErp.Modules.DataProviderModule { rp1 = epCommodity.ReferencePrice, rp2 = epStock.ReferencePrice, - rp3= epBond.dirty_price_close + rp3 = epBond.dirty_price_close }; var data = eodQuery.FirstOrDefault(); - if (data != null && (data.rp1 != null || data.rp2 != null||data.rp3 != null)) + if (data != null && (data.rp1 != null || data.rp2 != null || data.rp3 != null)) { - price = data.rp1 ?? data.rp2 ?? Convert.ToDouble((data.rp3??0)*ConsGlobal.bondPriceMultiple); + price = data.rp1 ?? data.rp2 ?? Convert.ToDouble((data.rp3 ?? 0) * ConsGlobal.bondPriceMultiple); return true; } @@ -186,17 +209,17 @@ namespace YLErp.Modules.DataProviderModule public static EodPrice GetBondPrice(DateTime valueDate, string underlyingCode) { using var db = DbContextFactory.GetYLDbContext(); - var bondPrice = db.china_bond_valuation.Where(x=>x.bond_id== underlyingCode&&x.valuation_date<=valueDate).OrderByDescending(o=>o.credibility).ThenByDescending(o=>o.valuation_date).FirstOrDefault(); - if (bondPrice==null) + var bondPrice = db.china_bond_valuation.Where(x => x.bond_id == underlyingCode && x.valuation_date <= valueDate).OrderByDescending(o => o.credibility).ThenByDescending(o => o.valuation_date).FirstOrDefault(); + if (bondPrice == null) { return null; } return new EodPrice { - Vobp= bondPrice.vobp, + Vobp = bondPrice.vobp, ValueDate = valueDate, UnderlyingCode = underlyingCode, - ClosePrice = Convert.ToDouble(bondPrice.dirty_price_close*ConsGlobal.bondPriceMultiple), + ClosePrice = Convert.ToDouble(bondPrice.dirty_price_close * ConsGlobal.bondPriceMultiple), SettlePrice = Convert.ToDouble(bondPrice.net_price * ConsGlobal.bondPriceMultiple), ReferencePrice = Convert.ToDouble(bondPrice.yield * ConsGlobal.bondPriceMultiple) }; @@ -216,9 +239,8 @@ namespace YLErp.Modules.DataProviderModule } if (data.IsBond()) { - var valuedate = QdpCalendarHelper.GetNonHolidayDefore(settleDate.AddDays(-1)); - var eodBondPrice = GetBondPrice(valuedate, code); - return eodBondPrice?.ClosePrice??0; + var eodBondPrice = GetBondPrice(settleDate, code); + return eodBondPrice?.ClosePrice ?? 0; } var price = data.Price ?? 0; if (TryGetEodPrice(settleDate, code, out var eodPrice)) diff --git a/YLErpDAL/Modules/EodModule/SettlementModule/EodCheckReferencePrice.cs b/YLErpDAL/Modules/EodModule/SettlementModule/EodCheckReferencePrice.cs index d71cf299..1a4518b3 100644 --- a/YLErpDAL/Modules/EodModule/SettlementModule/EodCheckReferencePrice.cs +++ b/YLErpDAL/Modules/EodModule/SettlementModule/EodCheckReferencePrice.cs @@ -33,7 +33,7 @@ namespace YLErp.Modules.EodModule.SettlementModule var eodPriceProvider = _context.GetEodPriceProvider(); //判断当日结算价是否已经入库 - if (!EodPriceQueryService.CheckDbExists(_context.SettleDate, _context.PreSettleDate)) + if (!EodPriceQueryService.CheckDbExists(_context.SettleDate)) { _context.RaiseError(Step, "结算价格未入库"); } diff --git a/YLErpDAL/Modules/EodModule/SettlementModule/EodCheckSettlePrice.cs b/YLErpDAL/Modules/EodModule/SettlementModule/EodCheckSettlePrice.cs index b81cd726..7c970b49 100644 --- a/YLErpDAL/Modules/EodModule/SettlementModule/EodCheckSettlePrice.cs +++ b/YLErpDAL/Modules/EodModule/SettlementModule/EodCheckSettlePrice.cs @@ -22,7 +22,7 @@ namespace YLErp.Modules.EodModule.SettlementModule /// public void Execute() { - if (!_context.OtcTrades.Any()&& !hasSwaptrade()) + if (!_context.OtcTrades.Any() && !hasSwaptrade()) { return; } @@ -34,7 +34,7 @@ namespace YLErp.Modules.EodModule.SettlementModule IQueryable allQuery = null; //判断当日结算价是否已经入库 - if (!EodPriceQueryService.CheckDbExists(_context.SettleDate,_context.PreSettleDate)) + if (!EodPriceQueryService.CheckDbExists(_context.SettleDate)) { _context.RaiseError(Step, "结算价格未入库"); } @@ -45,24 +45,24 @@ namespace YLErp.Modules.EodModule.SettlementModule if (request.IsSettleOtcTrades) { var tradePredicate = _context.PredicateBuilder.GetOtcTradePredicate() - .And(t => t.TradeType != "自定义交易"&&t.TradeType!="收益互换" && t.UnderlyingCode != null); - + .And(t => t.TradeType != "自定义交易" && t.TradeType != "收益互换" && t.UnderlyingCode != null); + //新增客户筛选 tw if (clienIds != null) { tradePredicate = tradePredicate.And(l => clienIds.Contains(l.ClientId)); } - + allQuery = DbContext.trade.Where(tradePredicate).Select(n => n.UnderlyingCode).Distinct(); var clientProductPredicate = _context.PredicateBuilder.GetClientProductPredicate(); - + //新增客户筛选 tw if (clienIds != null) { clientProductPredicate = clientProductPredicate.And(l => clienIds.Contains(l.ClientId)); } - + var clientProductQuery = from t in DbContext.clientcashincashout_product.Where(clientProductPredicate) join um in DbContext.underlying_manager on t.UnderlyingId equals um.id select um.UnderlyingCode; @@ -101,11 +101,11 @@ namespace YLErp.Modules.EodModule.SettlementModule var umCodeArr = allQuery.ToArray(); var swapUmCodeArr = GetSwapUnderlyingCodes(); - var eodPriceProvider = _context.GetEodPriceProvider().Initialize(umCodeArr); - var preEodPriceProvidaer = _context.GetPreEodPriceProvider().Initialize(swapUmCodeArr); - var umCodes = umCodeArr.Where(n => !string.IsNullOrEmpty(n) && !eodPriceProvider.HasValue(n)).ToHashSet(StringComparer.OrdinalIgnoreCase); - var swapUmCodes= swapUmCodeArr.Where(n => !string.IsNullOrEmpty(n) && !preEodPriceProvidaer.HasValue(n)).ToHashSet(StringComparer.OrdinalIgnoreCase); - umCodes= umCodes.Concat(swapUmCodes).ToHashSet(); + var codeArr = umCodeArr.Union(swapUmCodeArr); + var eodPriceProvider = _context.GetEodPriceProvider().Initialize(codeArr); + // var preEodPriceProvidaer = _context.GetPreEodPriceProvider().Initialize(swapUmCodeArr); + var umCodes = codeArr.Where(n => !string.IsNullOrEmpty(n) && !eodPriceProvider.HasValue(n)).ToHashSet(StringComparer.OrdinalIgnoreCase); + //var swapUmCodes= swapUmCodeArr.Where(n => !string.IsNullOrEmpty(n) && !preEodPriceProvidaer.HasValue(n)).ToHashSet(StringComparer.OrdinalIgnoreCase); //排除掉节假日不需要结算的交易 foreach (var t in _context.HolidayTrades) { @@ -131,7 +131,7 @@ namespace YLErp.Modules.EodModule.SettlementModule var tradePredicate = _context.PredicateBuilder.GetOtcSwapTradePredicate(); var query = from t in DbContext.trade.Where(tradePredicate) join p in DbContext.swap_position on t.id equals p.SwapTradeId - where p.IsInitial && !string.IsNullOrEmpty(p.UnderlyingCode)&& !p.Invalid + where p.IsInitial && !string.IsNullOrEmpty(p.UnderlyingCode) && !p.Invalid select p.UnderlyingCode; return query.Distinct().ToArray(); } diff --git a/YLErpDAL/Modules/EodModule/SettlementModule/EodClientBalanceCalc.cs b/YLErpDAL/Modules/EodModule/SettlementModule/EodClientBalanceCalc.cs index 7b655cf4..1522fe4c 100644 --- a/YLErpDAL/Modules/EodModule/SettlementModule/EodClientBalanceCalc.cs +++ b/YLErpDAL/Modules/EodModule/SettlementModule/EodClientBalanceCalc.cs @@ -153,7 +153,7 @@ namespace YLErp.Modules.EodModule.SettlementModule { ClientId = t.ClientId, StructureType = t.StructureType, - marin = s.InterestPrincipalFix * (s.InterestDirection == 1 ? -1 : 1) + marin = s.InterestPrincipalFix * (s.InterestDirection == 1 ? -1m : 1m) }; var eodSwaps = eodSwapQuery.ToList(); diff --git a/YLErpDAL/Modules/ExchangeTradeModule/ExchangeTradeImportService.cs b/YLErpDAL/Modules/ExchangeTradeModule/ExchangeTradeImportService.cs index f168c14e..034d4035 100644 --- a/YLErpDAL/Modules/ExchangeTradeModule/ExchangeTradeImportService.cs +++ b/YLErpDAL/Modules/ExchangeTradeModule/ExchangeTradeImportService.cs @@ -149,6 +149,7 @@ namespace YLErp.Modules.ExchangeTradeModule { throw new ServiceException(dto.TradeType+"交易类型必须填写债券标的"); } + dto.TradeSinglePrice /= 100; break; } diff --git a/YLErpDAL/Modules/RiskModule/QuotaMonitorService.cs b/YLErpDAL/Modules/RiskModule/QuotaMonitorService.cs index b2a0651b..65152d31 100644 --- a/YLErpDAL/Modules/RiskModule/QuotaMonitorService.cs +++ b/YLErpDAL/Modules/RiskModule/QuotaMonitorService.cs @@ -1065,11 +1065,12 @@ namespace YLErp.Modules.RiskModule setValue(swap, swapSetting); var positionList = new List>(); - var gloabDv01 = GetTradePositionDv01(); + double underPnl = 0; + var gloabDv01 = GetTradePositionDv01(ref underPnl); if (dict.ContainsKey("互换")) { var swapPositionList = dict["互换"].Select(O => new KeyValuePair(O.t, O.risk)); - swap.TotalPnL = swapPositionList.Sum(O => O.Value.PositionPnl.Normalize() + O.Value.RealizedPnl.Normalize()); + swap.TotalPnL = swapPositionList.Sum(O => O.Value.PositionPnl.Normalize()); if (PS.Config.Is国信金阳) { swap.PositionPnl = swapPositionList.Sum(O => O.Value.PositionPnl.Normalize() < 0 ? O.Value.PositionPnl.Normalize() : 0); @@ -1097,6 +1098,7 @@ namespace YLErp.Modules.RiskModule ParentKey = "场外", BusinessType = "标的交易", Quota_DV01 = gloabDv01, + PositionPnl = underPnl }; var unTrade = new QuotaMonitor_Global() { @@ -1109,6 +1111,7 @@ namespace YLErp.Modules.RiskModule { BusinessType = "全局", StockEqvNotional = Convert.ToDouble(posiStockEqvNotional), + PositionPnl = underly.PositionPnl + swap.PositionPnl, Quota_DV01_Upper = dv01Settings?.QuotaUpperLimit ?? double.NaN, Quota_DV01_Lower = dv01Settings?.QuotaLowerLimit ?? double.NaN, Quota_DV01_wUpper = dv01Settings?.WarningUpperLimit ?? double.NaN, @@ -1221,7 +1224,7 @@ namespace YLErp.Modules.RiskModule var temp = settings.Where(O => O.IsValid && O.Status == QuotaSettingApprovalStatus.Valid && (O.QuotaRange == obj.ClientId || O.QuotaRange == 0)); var stockEqvNotionalSettings = temp.Where(O => O.QuotaIndex == "名义本金" && O.QuotaRange == 0).FirstOrDefault()?.Clone(); var stockEqvNotionalSettingsClient = temp.Where(O => O.QuotaIndex == "名义本金" && O.QuotaRange == obj.ClientId).FirstOrDefault()?.Clone(); - if (stockEqvNotionalSettingsClient!=null) + if (stockEqvNotionalSettingsClient != null) { stockEqvNotionalSettings = stockEqvNotionalSettingsClient.Clone(); } @@ -1433,7 +1436,7 @@ namespace YLErp.Modules.RiskModule GammaCash = risk.GammaCash ?? 0, Vega = risk.Vega ?? 0, VegaCash = risk.VegaCash ?? 0, - PnL = (PS.Config.IsPVRounded ? risk.RoundedPositionPnl : risk.PositionPnl) ?? 0, + PnL = (PS.Config.IsPVRounded ? risk.RoundedPositionPnl : risk.PositionPnl) ?? 0 + risk.RealizedPnl, Quota_DV01 = risk.DV01 }; @@ -1505,8 +1508,7 @@ namespace YLErp.Modules.RiskModule if (item.trade.TradeType == "收益互换") { var sportPrice = item.trade.SpotPrice ?? 0; - var valueDate = QdpCalendarHelper.GetNonHolidayDefore(valuedateBLL.ValueDate.AddDays(-1)); - var bondPrice = EodPriceQueryService.GetBondPrice(valueDate, item.trade.UnderlyingCode); + var bondPrice = EodPriceQueryService.GetBondPrice(valuedateBLL.ValueDate, item.trade.UnderlyingCode); var basePrice = bondPrice == null ? 0 : bondPrice.ClosePrice; var vobp = bondPrice == null ? 0 : Convert.ToDouble(bondPrice.Vobp); var pricePercent = basePrice == 0 ? 0 : Math.Abs((sportPrice / basePrice) - 1); @@ -2145,7 +2147,7 @@ namespace YLErp.Modules.RiskModule QuotaMonitor_Underlying quotaMonitor = new QuotaMonitor_Underlying(); var um = underlyings.FirstOrDefault(f => f.UnderlyingCode == item.UnderlyingCode); quotaMonitor.UnderlyingCode = item.UnderlyingCode; - quotaMonitor.StockEqvNotional =Math.Abs(item.StockEqvNotional??0); + quotaMonitor.StockEqvNotional = Math.Abs(item.StockEqvNotional ?? 0); quotaMonitor.UnderlyingId = um?.id ?? 0; if (um != null && um.IsBond()) { @@ -3582,20 +3584,20 @@ namespace YLErp.Modules.RiskModule IsValid = true, Status = QuotaSettingApprovalStatus.Valid, }); - //交易-止损金额 - _quotaSettings.Add(new QuotaSetting() - { - QuotaType = QuotaTypeEnum.TRADE, - QuotaRange = 0, - QuotaIndex = "止损金额", - QuotaLowerLimit = null, - QuotaUpperLimit = null, - WarningLowerLimit = null, - WarningUpperLimit = null, - Percent = false, - IsValid = true, - Status = QuotaSettingApprovalStatus.Valid, - }); + ////交易-止损金额 + //_quotaSettings.Add(new QuotaSetting() + //{ + // QuotaType = QuotaTypeEnum.TRADE, + // QuotaRange = 0, + // QuotaIndex = "止损金额", + // QuotaLowerLimit = null, + // QuotaUpperLimit = null, + // WarningLowerLimit = null, + // WarningUpperLimit = null, + // Percent = false, + // IsValid = true, + // Status = QuotaSettingApprovalStatus.Valid, + //}); //交易-Delta金额 _quotaSettings.Add(new QuotaSetting() { @@ -4405,7 +4407,7 @@ namespace YLErp.Modules.RiskModule { List clientRiskCheckResps = new List(); var allList = QueryPrecheckQuotaSetting(false); - allList = allList.Where(x=>x.QuotaIndex!="DV01").ToList(); ; + allList = allList.Where(x => x.QuotaIndex != "DV01").ToList(); ; var precheckQuotaSettingList = allList.Where(O => O.Precheck).ToList(); List quotaIndexs = new List() { "名义本金", "轧差集中度", "轧差名义本金" }; if (clientRiskCheckReq.isClient) @@ -4416,9 +4418,9 @@ namespace YLErp.Modules.RiskModule { return clientRiskCheckResps; } - var clientPrecheckQuotaSettingList = precheckQuotaSettingList.Where(x=>x.QuotaRange== clientRiskCheckReq.clientId&&x.QuotaType==QuotaTypeEnum.CLIENT&&x.QuotaIndex=="名义本金").ToList(); - var allClientPrecheckQuotaSettingList= precheckQuotaSettingList.Where(x => x.QuotaRange == 0 && x.QuotaType == QuotaTypeEnum.CLIENT && x.QuotaIndex == "名义本金").ToList(); - if (clientPrecheckQuotaSettingList.Count>0) + var clientPrecheckQuotaSettingList = precheckQuotaSettingList.Where(x => x.QuotaRange == clientRiskCheckReq.clientId && x.QuotaType == QuotaTypeEnum.CLIENT && x.QuotaIndex == "名义本金").ToList(); + var allClientPrecheckQuotaSettingList = precheckQuotaSettingList.Where(x => x.QuotaRange == 0 && x.QuotaType == QuotaTypeEnum.CLIENT && x.QuotaIndex == "名义本金").ToList(); + if (clientPrecheckQuotaSettingList.Count > 0) { foreach (var item in allClientPrecheckQuotaSettingList) { @@ -4430,16 +4432,26 @@ namespace YLErp.Modules.RiskModule { throw new ServiceException("未找到客户信息"); } + try + { + RealtimePnlCalc.RealtimeSwapPosition(new OptUserInfo(0, "互换实时持仓服务", OptUserFrom.Service)); + } + catch (Exception ex) + { + LogFactory.GetLogger("RealtimeSwapPosition").Error("风控调用实时持仓异常", ex); + } + using var bondDb = new BondOmsDBContext(); var clientPositions = bondDb.client_position.AsNoTracking().ToList();//所有持仓 ClientPosition posi = new ClientPosition(); posi.commission = clientRiskCheckReq.commission; posi.side = clientRiskCheckReq.side; posi.security_id = clientRiskCheckReq.securityId; - posi.full_price_now = clientRiskCheckReq.price* ConsGlobal.bondShowPriceMultiple; + posi.full_price_now = clientRiskCheckReq.price * ConsGlobal.bondShowPriceMultiple; posi.deal_full_price_avg = clientRiskCheckReq.price * ConsGlobal.bondShowPriceMultiple; posi.client_id = clientRiskCheckReq.clientId; posi.position_qty = clientRiskCheckReq.qty / 10000; + posi.position_notional_principal = clientRiskCheckReq.qty; posi.direction = (int)SwapDirectionEnum.支付; clientPositions.Add(posi); var umCodes = clientPositions.Select(s => s.security_id).Distinct().ToList(); @@ -4486,7 +4498,6 @@ namespace YLErp.Modules.RiskModule { checkQuotaMoitorModel.Price *= ConsGlobal.bondPriceMultiple; checkQuotaMoitorModel.NowPrice *= ConsGlobal.bondPriceMultiple; - dealDate = QdpCalendarHelper.GetNonHolidayDefore(dealDate.AddDays(-1)); var bondPrice = EodPriceQueryService.GetBondPrice(dealDate, item.security_id); lastPrice = bondPrice != null ? bondPrice.ClosePrice : (um.Price ?? 0) * Convert.ToDouble(ConsGlobal.bondPriceMultiple); vobp = bondPrice != null ? bondPrice.Vobp ?? 0 : 0; @@ -4533,7 +4544,6 @@ namespace YLErp.Modules.RiskModule { List checkPoisiList = new List(); var dealDate = valuedateBLL.ValueDate; - dealDate = QdpCalendarHelper.GetNonHolidayDefore(dealDate.AddDays(-1)); using var bondDb = new BondOmsDBContext(); var clientPositions = bondDb.client_position.AsNoTracking().ToList();//所有持仓 Dictionary eodPriceDic = new Dictionary(); @@ -4717,7 +4727,6 @@ namespace YLErp.Modules.RiskModule { checkQuotaMoitorModel.Price *= ConsGlobal.bondPriceMultiple; checkQuotaMoitorModel.NowPrice *= ConsGlobal.bondPriceMultiple; - dealDate = QdpCalendarHelper.GetNonHolidayDefore(dealDate.AddDays(-1)); var bondPrice = EodPriceQueryService.GetBondPrice(dealDate, item.security_id); lastPrice = bondPrice != null ? bondPrice.ClosePrice : (um.Price ?? 0) * Convert.ToDouble(ConsGlobal.bondPriceMultiple); vobp = bondPrice != null ? bondPrice.Vobp ?? 0 : 0; @@ -5121,7 +5130,7 @@ namespace YLErp.Modules.RiskModule tag_prefix = quota.QuotaRange == 0 ? "客户合计" : "当前客户"; msgList.AddRange(checkClient(positionList, posiList, tag_prefix, new QuotaSetting[] { quota }, settingAll, warning)); } - + } break; @@ -5217,10 +5226,11 @@ namespace YLErp.Modules.RiskModule currentValue = null; var tag = $"{tag_prefix}({settingItem.QuotaIndex})"; CheckQuotaMoitorModel current = positionList.FirstOrDefault(x => x.Current); + double pnl = 0; switch (settingItem.QuotaIndex) { case "DV01": - var uDv = GetTradePositionDv01(); + var uDv = GetTradePositionDv01(ref pnl); currentValue = uDv; var tradePosiVal = posiList.Sum(s => s.DV01); var posiVal = positionList.Where(x => !x.Current).Sum(s => s.DV01); @@ -5240,10 +5250,11 @@ namespace YLErp.Modules.RiskModule { double? currentValue = null; double tradeValue = 0; + double pnl = 0; switch (checkItem.quotaType) { case "DV01": - tradeValue = GetTradePositionDv01(); + tradeValue = GetTradePositionDv01(ref pnl); currentValue = tradeValue + Convert.ToDouble(positionList.Sum(s => s.DV01)); var posiVal = positionList.Where(x => !x.Current).Sum(s => s.DV01); if (!ValidateQuoteResult(checkItem, currentValue, Convert.ToDouble(posiVal) + tradeValue)) @@ -5261,9 +5272,8 @@ namespace YLErp.Modules.RiskModule /// 算标的交易dv01 /// /// - private double GetTradePositionDv01() + private double GetTradePositionDv01(ref double pnl) { - var dealDate = QdpCalendarHelper.GetNonHolidayDefore(valuedateBLL.ValueDate.AddDays(-1)); double currentValue = 0; List tradetypes = new List { "利率债", "信用债", "其它债券" }; var tposis = DbContext.TradePosition.Where(x => tradetypes.Contains(x.TradeType)).AsNoTracking().ToList(); @@ -5284,13 +5294,14 @@ namespace YLErp.Modules.RiskModule } else { - var bondPrice = EodPriceQueryService.GetBondPrice(dealDate, item.UnderlyingCode); + var bondPrice = EodPriceQueryService.GetBondPrice(valuedateBLL.ValueDate, item.UnderlyingCode); lastPrice = bondPrice != null ? bondPrice.ClosePrice : (um.Price ?? 0) * Convert.ToDouble(ConsGlobal.bondPriceMultiple); vobp = bondPrice != null ? bondPrice.Vobp ?? 0 : 0; } } - var DV01 = Convert.ToDouble(vobp) * Math.Abs(item.Position) * contractSize * 0.01 * (item.PositionType == PositionTypeFlag.Long ? 1 : -1); + var DV01 = Convert.ToDouble(vobp) * item.Position * contractSize * 0.01; currentValue += DV01; + pnl += lastPrice * Math.Abs(item.Position) - Math.Abs(item.PositionCost); } return currentValue; } @@ -5513,7 +5524,7 @@ namespace YLErp.Modules.RiskModule return null; case "Delta金额": currentValue = Convert.ToDouble(current.Delta); - + if (!ValidateQuoteResult(checkItem)) { return checkItem; @@ -5533,7 +5544,7 @@ namespace YLErp.Modules.RiskModule checkItem.currentValue = currentValue; if (!ValidateQuoteResult(checkItem)) { - + return checkItem; } return null; @@ -5550,7 +5561,7 @@ namespace YLErp.Modules.RiskModule default: return null; } - + } private List checkUnderlying(List positionList, List posiList, string tag_prefix, QuotaSetting[] settings, List settingAll, bool warning) @@ -5618,11 +5629,6 @@ namespace YLErp.Modules.RiskModule messageList.Add(SetQuotaMsg(tag, setting.QuotaIndex, currentValue, Convert.ToDouble(tradePosiVal), posiVal, Convert.ToDouble(current.Pv), Convert.ToDouble(noPosiVal), null, upperLimit, lowerLimit, setting.Percent, warning)); break; case "轧差集中度": - //if (current.Circulation == 0) - //{ - // messageList.Add($"{tag}:{current.UnderlyingCode}发行规模数据未维护"); - // break; - //} currentValue = current.Circulation == 0 ? 0 : currentValue / Convert.ToDouble(current.Circulation); tradePosiVal = current.Circulation == 0 ? 0 : tradePosiVal / current.Circulation; posiVal = current.Circulation == 0 ? 0 : posiVal / Convert.ToDouble(current.Circulation); @@ -5652,14 +5658,14 @@ namespace YLErp.Modules.RiskModule { return null; } - var noQuoteSetting = settingAll.FirstOrDefault(x => x.QuotaType == QuotaTypeEnum.UNDERLYING && x.QuotaRange == quotaRange && x.QuotaIndex== checkItem.quotaType&&!x.Precheck);//是否设置了不事前检查 + var noQuoteSetting = settingAll.FirstOrDefault(x => x.QuotaType == QuotaTypeEnum.UNDERLYING && x.QuotaRange == quotaRange && x.QuotaIndex == checkItem.quotaType && !x.Precheck);//是否设置了不事前检查 if (noQuoteSetting != null) { return null; } currentPv = positionList.Where(s => s.UnderlyingCode == current.UnderlyingCode).Sum(s => s.Pv * (s.Side == 0 ? 1 : -1)); currentValue = Convert.ToDouble(currentPv); - currentValue = Math.Abs(currentValue??0); + currentValue = Math.Abs(currentValue ?? 0); posiPv = positionList.Where(s => s.UnderlyingCode == current.UnderlyingCode && !s.Current).Sum(s => s.Pv * (s.Side == 0 ? 1 : -1)); posiVal = Convert.ToDouble(posiPv); var tag = $"{tag_prefix}({checkItem.quotaType})"; @@ -5673,10 +5679,6 @@ namespace YLErp.Modules.RiskModule } return null; case "轧差集中度": - //if (current.Circulation == 0) - //{ - // throw new Exception($"{tag}:{current.UnderlyingCode}发行规模数据未维护"); - //} currentValue = current.Circulation == 0 ? 0 : currentValue / Convert.ToDouble(current.Circulation); posiPv = positionList.Where(s => s.UnderlyingCode == current.UnderlyingCode && !s.Current).Sum(s => s.Pv); posiVal = current.Circulation == 0 ? 0 : Convert.ToDouble(posiPv / current.Circulation); @@ -5706,7 +5708,7 @@ namespace YLErp.Modules.RiskModule CheckQuotaMoitorModel current = positionList.FirstOrDefault(x => x.Current); //settings 可能包含全部 var settingItem = settings.First(); - var noQuoteSetting = settingAll.FirstOrDefault(x => x.QuotaType == settingItem.QuotaType && x.QuotaRange == settingItem.QuotaRange &&x.QuotaIndex==settingItem.QuotaIndex && !x.Precheck);//是否设置了不事前检查 + var noQuoteSetting = settingAll.FirstOrDefault(x => x.QuotaType == settingItem.QuotaType && x.QuotaRange == settingItem.QuotaRange && x.QuotaIndex == settingItem.QuotaIndex && !x.Precheck);//是否设置了不事前检查 if (noQuoteSetting != null) { return messageList; @@ -5780,7 +5782,7 @@ namespace YLErp.Modules.RiskModule { return null; } - var noQuoteSetting = settingAll.FirstOrDefault(x => x.QuotaType == QuotaTypeEnum.CLIENT && x.QuotaRange == quotaRange&&x.QuotaIndex== checkItem.quotaType && !x.Precheck);//是否设置了不事前检查 + var noQuoteSetting = settingAll.FirstOrDefault(x => x.QuotaType == QuotaTypeEnum.CLIENT && x.QuotaRange == quotaRange && x.QuotaIndex == checkItem.quotaType && !x.Precheck);//是否设置了不事前检查 if (noQuoteSetting != null) { return null; diff --git a/YLErpDAL/Modules/SwapModule/SwapDealService.cs b/YLErpDAL/Modules/SwapModule/SwapDealService.cs index 6d97279d..ab6589a1 100644 --- a/YLErpDAL/Modules/SwapModule/SwapDealService.cs +++ b/YLErpDAL/Modules/SwapModule/SwapDealService.cs @@ -118,7 +118,7 @@ namespace YLErp.Modules.SwapModule floatEvent.PositionQty = 0; floatEvent.ContractSize = position.ContractSize; floatEvent.TradingAmount = floatEvent.Quantity * floatEvent.ContractSize; - var ratio = position.PosiDirection == (int)SwapDirectionEnum.收取 ? -1 : 1; + var ratio = position.PosiDirection == (int)SwapDirectionEnum.收取 ? -1m : 1m; floatEvent.TradingFeePending = position.PosiTradingFeePending; floatEvent.DataState = (int)SwapFlowDateStateEnum.完成; floatEvent.InterestMode = position.InterestMode; @@ -385,7 +385,7 @@ namespace YLErp.Modules.SwapModule { _closePosiNotionalValue = position.InterestPrincipalFix; _posiNotionalValue = position.InterestPrincipalFix; - newClosePercent = 1; + newClosePercent = 1m; } else if (position.InterestMode == (int)InterestModeEnum.多头存续名义本金) { @@ -410,8 +410,8 @@ namespace YLErp.Modules.SwapModule } if (!string.IsNullOrEmpty(position.FloatRateUnderlyingCode)) { - var rateDate = QdpCalendarHelper.GetNonHolidayDefore(td.StartDate.Value.AddDays(-1)); - if (EodPriceQueryService.TryGetReferencePrice(rateDate, position.FloatRateUnderlyingCode, out double floatRate)) + var rateDate = td.StartDate.Value.AddDays(-1); + if (EodPriceQueryService.TryGetPrice(rateDate, position.FloatRateUnderlyingCode, out double floatRate)) { position.FloatRate = Convert.ToDecimal(floatRate); positionClone.FloatRate = position.FloatRate; @@ -508,7 +508,7 @@ namespace YLErp.Modules.SwapModule { decimal InterestAmount = 0; decimal TdInterestAmount = 0; - var interestRatio = position.InterestDirection == 1 ? 1 : -1; + var interestRatio = position.InterestDirection == 1 ? 1m : -1m; if (position.InterestType == (int)InterestTypeEnum.复利) { var floateRate = preEodPosition.FloatRate; @@ -538,7 +538,7 @@ namespace YLErp.Modules.SwapModule { if (itemDays > 1)//日期超算情况 { - decimal days = (decimal)itemDays - 1; + decimal days = (decimal)itemDays - 1m; if (position.IsAnnualized) { InterestAmount = InterestAmount * (days / annualDays); @@ -554,8 +554,8 @@ namespace YLErp.Modules.SwapModule } - interest.InterestAmount = InterestAmount; - interest.TdInterestAmount = TdInterestAmount; + interest.InterestAmount = decimal.Parse(InterestAmount.ToString("0.0000")); + interest.TdInterestAmount = decimal.Parse(TdInterestAmount.ToString("0.0000")); interest.InterestClosePnL = interest.InterestAmount * interestRatio; } if (add) @@ -597,15 +597,15 @@ namespace YLErp.Modules.SwapModule { dynomicPrincipal = dynomicPrincipal + interest; tdDynomicPrincipal = tdDynomicPrincipal + interest; - if (rateDate > tradeDate) - { - dynomicPrincipal += interestProfitSum; - tdDynomicPrincipal += interestProfitSum; - } + //if (rateDate > tradeDate) + //{ + // dynomicPrincipal += interestProfitSum; + // tdDynomicPrincipal += interestProfitSum; + //} if (!string.IsNullOrEmpty(position.FloatRateUnderlyingCode)) { - var fr007RateDate = QdpCalendarHelper.GetNonHolidayDefore(rateDate.AddDays(-1)); - if (EodPriceQueryService.TryGetReferencePrice(fr007RateDate, position.FloatRateUnderlyingCode, out double floatRate1)) + var fr007RateDate = rateDate.AddDays(-1); + if (EodPriceQueryService.TryGetPrice(fr007RateDate, position.FloatRateUnderlyingCode, out double floatRate1)) { if (floatRate1 != 0) { @@ -634,8 +634,8 @@ namespace YLErp.Modules.SwapModule interest1 /= annualDays; tdinterest1 /= annualDays; } - interest += interest1; - tdinterest += tdinterest1; + interest += decimal.Parse(interest1.ToString("0.0000")); + tdinterest += decimal.Parse(tdinterest1.ToString("0.0000")); } else @@ -675,8 +675,8 @@ namespace YLErp.Modules.SwapModule tdDynomicPrincipal = tdDynomicPrincipal + interestProfitSum; if (!string.IsNullOrEmpty(position.FloatRateUnderlyingCode)) { - var fr007RateDate = QdpCalendarHelper.GetNonHolidayDefore(endDate.AddDays(-1)); - if (EodPriceQueryService.TryGetReferencePrice(fr007RateDate, position.FloatRateUnderlyingCode, out double floatRate1)) + var fr007RateDate = endDate.AddDays(-1); + if (EodPriceQueryService.TryGetPrice(fr007RateDate, position.FloatRateUnderlyingCode, out double floatRate1)) { if (floatRate1 != 0) { @@ -785,6 +785,7 @@ namespace YLErp.Modules.SwapModule /// public void AuotoSwapUnwind(int tradeid, decimal unwindPrice, decimal unwindPriceFee, decimal unwindNetFee, decimal unwindNet, DateTime valueDate, decimal unwindQty, decimal mergeQty, decimal penddingFee) { + unwindPriceFee = decimal.Parse(unwindPriceFee.ToString("F10")); var td = DbContext.trade.Find(tradeid); var positions = DbContext.swap_position.Where(x => x.SwapTradeId == td.id && !x.Invalid); List eventTypes = new List() { (int)SwapEventTypeEnum.平仓, (int)SwapEventTypeEnum.互换 }; @@ -823,8 +824,8 @@ namespace YLErp.Modules.SwapModule unwindData.CloseQty = unwindQty; if (position != null) { - var floatRatio = position.PosiDirection == 1 ? 1 : -1; - var longRatio = position.PositionType == 1 ? 1 : -1; + decimal floatRatio = position.PosiDirection == 1 ? 1m : -1m; + decimal longRatio = position.PositionType == 1 ? 1m : -1m; floatEvent.PositionId = position.PositionId; floatEvent.EventType = (int)SwapFlowEventTypeEnum.平仓; floatEvent.EventReason = "交易"; @@ -850,6 +851,7 @@ namespace YLErp.Modules.SwapModule var mergeClosePercent = mergeQty == 0 ? 0 : unwindQty / mergeQty; floatEvent.TradingFee = penddingFee * mergeClosePercent; floatEvent.MarkClosePnl = (unwindPriceFee - position.PosiNetPrice) * unwindData.PosiNotionalValue * floatRatio * longRatio; + floatEvent.MarkClosePnl = decimal.Parse(floatEvent.MarkClosePnl.ToString("0.00")); floatEvent.TradingAmount = floatEvent.Quantity * floatEvent.ContractSize; floatEvent.OptLog = "流水自动"; floatEvent.ClientId = td.ClientId; @@ -910,7 +912,7 @@ namespace YLErp.Modules.SwapModule unwindData.CloseQty = allClose ? unwindData.PositionQty : unwindQty; if (position != null) { - var floatRatio = position.PosiDirection == 1 ? 1 : -1; + decimal floatRatio = position.PosiDirection == 1 ? 1m : -1m; floatEvent.PositionId = position.id; floatEvent.EventType = (int)SwapEventTypeEnum.平仓; floatEvent.EventReason = "接口合约终止交易"; @@ -942,7 +944,7 @@ namespace YLErp.Modules.SwapModule var interestPositions = GetUnwindInterestsByHT(unwindData, td, interestAmount, fee); unwindData.FlowEvents.AddRange(interestPositions); CalcCloseAmount(unwindData); - DealUnwind(unwindData, td, false, "合约终止接口回执"); + DealUnwind(unwindData, td, "合约终止接口回执"); } private List GetUnwindInterestsByHT(UnwindData unwindData, trade td, decimal interestAmount, decimal fee) { @@ -965,7 +967,7 @@ namespace YLErp.Modules.SwapModule { _closePosiNotionalValue = item.InterestPrincipalFix; _posiNotionalValue = item.InterestPrincipalFix; - newClosePercent = 1; + newClosePercent = 1m; } else if (item.InterestMode == (int)InterestModeEnum.标的期初全价) { @@ -1012,7 +1014,7 @@ namespace YLErp.Modules.SwapModule return interests; } - private void DealUnwind(UnwindData unwindData, trade td, bool addLog = true, string actionMsg = "系统操作_自动平仓") + private void DealUnwind(UnwindData unwindData, trade td, string actionMsg = "系统操作_自动平仓") { int clientCashId = CloseTrade_ClientCashInCashOut(td, Convert.ToDouble(-unwindData.SwapRealizedPnL), ClientCashInCashOut.系统操作_平仓费, unwindData.ValueDate); if (unwindData.SwapMarginAmount != 0) @@ -1052,7 +1054,7 @@ namespace YLErp.Modules.SwapModule { var floatPosition = unwindData.FlowEvents.FirstOrDefault(x => !string.IsNullOrEmpty(x.UnderlyingCode)); var interestList = unwindData.FlowEvents.Where(x => string.IsNullOrEmpty(x.UnderlyingCode)); - var floatRatio = floatPosition.PayDirection == 1 ? 1 : -1; + decimal floatRatio = floatPosition.PayDirection == 1 ? 1m : -1m; var pnl = floatPosition.MarkClosePnl; unwindData.SwapCloseAmount = pnl; unwindData.SwapRealizedPnL = pnl; @@ -1064,7 +1066,7 @@ namespace YLErp.Modules.SwapModule { if (x.InterestMode == (int)InterestModeEnum.追加预付金 || x.InterestMode == (int)InterestModeEnum.初始预付金) { - var interestRatio = x.InterestDirection == 1 ? -1 : 1; + decimal interestRatio = x.InterestDirection == 1 ? -1m : 1m; unwindData.SwapMarginRebatePnl += x.InterestClosePnL; unwindData.SwapMarginAmount += x.InterestPrincipal * interestRatio; } @@ -1073,6 +1075,7 @@ namespace YLErp.Modules.SwapModule }); } + unwindData.SwapCloseAmount = decimal.Parse(unwindData.SwapCloseAmount.ToString("0.00")); unwindData.SwapRealizedPnL = unwindData.SwapCloseAmount; } /// @@ -1245,7 +1248,6 @@ namespace YLErp.Modules.SwapModule td.TradeAmount -= Convert.ToDouble(swapEvent.unwindData.CloseQty); } td.StockEqvNotional -= Convert.ToDouble(swapEvent.unwindData.CloseNotionalValue); - } td.UnWindDate = swapEvent.unwindData.UnwindDate; UpdateInitalPosition(flowList, swapEvent.unwindData, eventType); @@ -1339,7 +1341,7 @@ namespace YLErp.Modules.SwapModule item.OptLog = "手工操作"; if (item.PositionType > 0 && item.EventType == (int)SwapEventTypeEnum.平仓) { - int shortRatio = item.PositionType == (int)PositionTypeFlag.Long ? 1 : -1; + decimal shortRatio = item.PositionType == (int)PositionTypeFlag.Long ? -1m : 1m; item.TradingAmountFeeAvg = item.TradingAmountAvg + item.TradingFeePending / unwindData.CloseQty * shortRatio; item.TradingAmountNetFeeAvg = item.TradingAmountNetAvg + item.TradingFeePending / unwindData.CloseQty * shortRatio; } @@ -1359,7 +1361,7 @@ namespace YLErp.Modules.SwapModule var dealFloat = flowList.FirstOrDefault(x => !string.IsNullOrEmpty(x.UnderlyingCode)); if (dealFloat != null) { - var ratio = dealFloat.EventType == (int)SwapFlowEventTypeEnum.平仓 ? -1 : 1; + decimal ratio = dealFloat.EventType == (int)SwapFlowEventTypeEnum.平仓 ? -1m : 1m; position.PosiTradingFeePending += dealFloat.TradingFeePending * ratio; position.PosiDividendIncome += dealFloat.DividendPending; } diff --git a/YLErpDAL/Modules/SwapModule/SwapEndConfirmService.cs b/YLErpDAL/Modules/SwapModule/SwapEndConfirmService.cs index 2ec0f437..151cf8da 100644 --- a/YLErpDAL/Modules/SwapModule/SwapEndConfirmService.cs +++ b/YLErpDAL/Modules/SwapModule/SwapEndConfirmService.cs @@ -10,6 +10,8 @@ using YLErp.DBModels.Consts; using System.Linq.Expressions; using YLErp.QdpModule; using static YLErp.ConsGlobal; +using YLErp.Helpers; +using YLErp.Models; namespace YLErp.Modules.SwapModule { @@ -25,9 +27,9 @@ namespace YLErp.Modules.SwapModule public SearchListResult SearchEitherTradeWithCashList(SwapEndConfirmReq req) { var db = DbContext; - var actionList = new List() { (int)SwapEventTypeEnum.平仓,(int)SwapEventTypeEnum.合成持仓 }; + var actionList = new List() { (int)SwapEventTypeEnum.平仓, (int)SwapEventTypeEnum.合成持仓 }; var types = new List() { ContractTypeEnum.Clearing, ContractTypeEnum.UnWind }; - var flowQuery= PredicateBuilder.Create(n => actionList.Contains(n.EventType) && n.PayDirection > 0); + var flowQuery = PredicateBuilder.Create(n => actionList.Contains(n.EventType) && n.PayDirection > 0); var eventQuery = PredicateBuilder.Create(n => actionList.Contains(n.EventType) && !n.Invalid); var tradeQuery = buildTradeQuery(req); if (!string.IsNullOrEmpty(req.UnderlyingCodes)) @@ -53,15 +55,15 @@ namespace YLErp.Modules.SwapModule { id = flowEvent.id, trade = trade, - swap_flow_event= flowEvent, - swap_event= swapEvent, + swap_flow_event = flowEvent, + swap_event = swapEvent, swap_position = position, - ConfirmContractR= tcrConfirm, + ConfirmContractR = tcrConfirm, }; query = query.OrderByDescending(s => s.swap_flow_event.id); var retListResult = query.ToSearchList(req, isWithOrder: false); - var tradeIds = retListResult.rows.Select(s=>s.swap_flow_event.SwapTradeId).Distinct().ToList(); + var tradeIds = retListResult.rows.Select(s => s.swap_flow_event.SwapTradeId).Distinct().ToList(); var underlyingCodes = retListResult.rows.Select(r => r.swap_flow_event.UnderlyingCode).ToList(); var underlyings = DbContext.underlying_manager.Where(x => underlyingCodes.Contains(x.UnderlyingCode)).AsNoTracking().ToList(); List extendList = DbContext.trade_extend.AsNoTracking().Where(p => tradeIds.Contains(p.TradeId)).ToList(); @@ -71,7 +73,7 @@ namespace YLErp.Modules.SwapModule } foreach (var x in retListResult.rows) { - x.trade_contract_r = db.trade_contract_r.Where(O => types.Contains(O.Type) && O.IsValid&&O.TradeId==x.trade.id&&O.SwapFlowEventId==x.swap_flow_event.id).FirstOrDefault(); + x.trade_contract_r = db.trade_contract_r.Where(O => types.Contains(O.Type) && O.IsValid && O.TradeId == x.trade.id && O.SwapFlowEventId == x.swap_flow_event.id).FirstOrDefault(); var swapEventFlow = x.swap_flow_event; var um = underlyings.FirstOrDefault(x => x.UnderlyingCode == swapEventFlow.UnderlyingCode); if (um != null && um.IsBond()) @@ -85,14 +87,14 @@ namespace YLErp.Modules.SwapModule { GetTradeDocumentResults(req, x); } - if (x.swap_event!=null) + if (x.swap_event != null) { x.swap_event.unwindData = JsonHelper.Deserialize(x.swap_event.EventData); - if (x.trade.StructureType=="多空组合") + if (x.trade.StructureType == "多空组合") { UnwindData unwindData = new UnwindData(); unwindData.SwapCloseAmount = x.swap_flow_event.MarkClosePnl; - x.swap_event.unwindData= unwindData; + x.swap_event.unwindData = unwindData; } } var extend = extendList.FirstOrDefault(p => p.TradeId == x.swap_flow_event.SwapTradeId); @@ -107,7 +109,7 @@ namespace YLErp.Modules.SwapModule return retListResult; } - private Expression> buildTradeQuery(SwapEndConfirmReq req) + private Expression> buildTradeQuery(SwapEndConfirmReq req) { var tradeQuery = PredicateBuilder.Create(n => n.TradeType == "收益互换" && n.ValidState != ConsGlobal.InValid); if (req.UserAssets != null && req.UserClients != null) @@ -161,5 +163,57 @@ namespace YLErp.Modules.SwapModule x.ContractDocUrl = x.trade_contract_document?.RelativePath; x.ContractCode = x.trade_contract_r.ContractCode; } + + /// + /// 发送交易确认书邮件 + /// + /// + /// + public string SendConfirmEamil(int tradeId) + { + var tradeContract = DbContext.trade_contract_r.Where(x => x.IsValid && x.TradeId == tradeId && x.Type == ContractTypeEnum.Trade).FirstOrDefault(); + if (tradeContract == null) + { + return ""; + } + tradeContract.send_email_result = "发送中"; + DbContext.SaveChanges(); + var sendResult = SendEmail(tradeId); + if (string.IsNullOrEmpty(sendResult)) + { + tradeContract.send_email_result = "已发送"; + } + else + { + tradeContract.send_email_result = "发送失败:" + sendResult; + } + DbContext.SaveChanges(); + return tradeContract.send_email_result; + } + + /// + /// 发送邮件 + /// + /// + private string SendEmail(int tradeId) + { + var baseUrl = Environment.GetEnvironmentVariable("BondOmsInterface_BaseUrl"); + var sendEmailPUrl = "/swap/email/confirm/send?tradeId=" + tradeId; + if (!string.IsNullOrEmpty(baseUrl)) + { + var httpHelper = new HttpHelper(baseUrl, null); + var result = httpHelper.GetRequestNoAuth(sendEmailPUrl).Result; + if (result != null && result.success && !string.IsNullOrEmpty(result.data)) + { + return ""; + } + else + { + LogFactory.GetLogger().Error("发送邮件失败:tradeId=" + tradeId, new Exception(result?.message)); + return result?.message ?? "发送邮件失败"; + } + } + return "未配置邮件接口地址"; + } } } diff --git a/YLErpDAL/Modules/SwapModule/SwapEodPositionService.cs b/YLErpDAL/Modules/SwapModule/SwapEodPositionService.cs index 117e19c2..0352cfc1 100644 --- a/YLErpDAL/Modules/SwapModule/SwapEodPositionService.cs +++ b/YLErpDAL/Modules/SwapModule/SwapEodPositionService.cs @@ -1228,7 +1228,7 @@ namespace YLErp.Modules.SwapModule { return curretEod; } - var dealDate = um.IsBond() ? preSettleDate : curretEod.ValueDate; + var dealDate = curretEod.ValueDate; int shortRatio = eod.PositionType == (int)PositionTypeFlag.Long ? 1 : -1; int directionRatio = eod.PosiDirection == (int)SwapDirectionEnum.收取 ? 1 : -1; curretEod.PosiStatus = curretEod.PosiQuantity == 0 ? 1 : 0; @@ -1320,7 +1320,7 @@ namespace YLErp.Modules.SwapModule { return curretEod; } - var dealDate = um.IsBond() ? preSettleDate : curretEod.ValueDate; + var dealDate = curretEod.ValueDate; int shortRatio = eod.PositionType == (int)PositionTypeFlag.Long ? 1 : -1; int directionRatio = eod.PosiDirection == (int)SwapDirectionEnum.收取 ? 1 : -1; var price = UnderlyingCodePrice(eod.UnderlyingCode, dealDate, out decimal vobp); @@ -1443,7 +1443,7 @@ namespace YLErp.Modules.SwapModule { return curretEod; } - var dealDate = um.IsBond() ? preSettleDate : settleDate; + var dealDate = settleDate; curretEod.ValueDate = settleDate; curretEod.PosiStartDate = position.PosiStartDate; curretEod.PosiMatuirityDate = td.ExerciseDate.Value; @@ -2072,6 +2072,7 @@ namespace YLErp.Modules.SwapModule item.InterestRate = eodInterests.Sum(s => s.InterestRateDefault); item.NetSettmentAmount += item.InterestAmount + item.MarginInterestAmount + eodMargins.Sum(s => s.InterestPrincipalFix * (s.InterestDirection == (int)SwapDirectionEnum.收取 ? 1 : -1)); } + item.NetSettmentAmount = decimal.Parse(item.NetSettmentAmount.ToString("0.00")); if (item.position.PosiNotionalValue != 0 && item.position.PosiNetPrice != 0) { item.FloatRateAbs = item.position.PosiNotionalValue == 0 ? 0 : item.InterestAmount / (item.position.PosiNotionalValue * item.position.PosiNetPrice); diff --git a/YLErpDAL/Modules/SwapModule/SwapEventEmailService.cs b/YLErpDAL/Modules/SwapModule/SwapEventEmailService.cs index 7341da2d..0a471402 100644 --- a/YLErpDAL/Modules/SwapModule/SwapEventEmailService.cs +++ b/YLErpDAL/Modules/SwapModule/SwapEventEmailService.cs @@ -17,6 +17,7 @@ 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; @@ -46,25 +47,25 @@ namespace YLErp.Modules.SwapModule } 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 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)); + 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 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 + 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.StructureType!="多空组合"&&t.StructureType!= "定义文件型债券收益互换" + where t.ValidState == "Valid" && t.StructureType != "多空组合" && t.StructureType != "定义文件型债券收益互换" select new SwapEventEmailResponse { event_id = f.id, @@ -82,7 +83,7 @@ namespace YLErp.Modules.SwapModule from em in emTmp.DefaultIfEmpty() select new SwapEventEmailResponse { - event_id=0, + event_id = 0, client_id = f.ClientId, event_type = 3, send_email = em == null ? false : em.send_email, @@ -95,11 +96,11 @@ namespace YLErp.Modules.SwapModule var allReulst = dmaResults.Concat(noDmaResults); foreach (var item in allReulst) { - if (item.event_id>0) + if (item.event_id > 0) { if (!item.single.HasValue) { - var singleEvent = allReulst.Count(x => x.client_id == item.client_id&&x.single==null) == 1; + var singleEvent = allReulst.Count(x => x.client_id == item.client_id && x.single == null) == 1; if (singleEvent) { item.single = true; @@ -133,7 +134,7 @@ namespace YLErp.Modules.SwapModule } 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(); + var clientDuitys = GetClientDuitys(); DealNoDmaEmail(noDmaEmailDatas, request.ValueDate, clientDuitys); DealDmaEmail(dmaEmailDatas, request.ValueDate, clientDuitys); } @@ -157,13 +158,13 @@ namespace YLErp.Modules.SwapModule 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.StructureType != "多空组合" && t.StructureType != "定义文件型债券收益互换" && (em == null|| em.send_email==false) + where t.ValidState == "Valid" && t.StructureType != "多空组合" && t.StructureType != "定义文件型债券收益互换" && (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 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)); @@ -177,7 +178,7 @@ namespace YLErp.Modules.SwapModule /// private List CheckConfirmDoc(List flowEvents) { - var tradeIds = flowEvents.Select(s=>s.SwapTradeId).ToList(); + 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 @@ -189,28 +190,28 @@ namespace YLErp.Modules.SwapModule TradeId = r.TradeId, SwapFlowEventId = r.SwapFlowEventId, FileName = doc.FileName, - TradeNumber= r.TradeNumber, + TradeNumber = r.TradeNumber, }; var docLsit = query.ToList(); - List list=new List(); - List tradeNumbers=new List(); + 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) + SwapTradeContractDto doc = docLsit.FirstOrDefault(f => f.TradeId == item.SwapTradeId); + if (doc == null) { tradeNumbers.Add(item.SwapTradeNo); } else { - doc.ClientId = item.ClientId??0; + 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()) { @@ -226,11 +227,11 @@ namespace YLErp.Modules.SwapModule /// private List CheckSettlementDoc(List flowEvents) { - var flowEventIds= flowEvents.Select(s => s.id).ToList(); + 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) + where doc.Type == r.Type && r.IsValid && r.Type == ContractTypeEnum.Clearing && flowEventIds.Contains(r.SwapFlowEventId ?? 0) select new SwapTradeContractDto { Paths = doc.Paths, @@ -259,7 +260,7 @@ namespace YLErp.Modules.SwapModule doc.SwapFlowEventId = item.id; list.Add(doc); } - + } if (tradeNumbers.Any()) { @@ -273,13 +274,13 @@ namespace YLErp.Modules.SwapModule /// /// /// - private void SendNoDmaEmail(List swapTradeContracts,DateTime valueDate, List clientDuitys) + private void SendNoDmaEmail(List swapTradeContracts, DateTime valueDate, List clientDuitys) { - var flowEventContractGroup = swapTradeContracts.Where(x=>x.SwapFlowEventId>0).GroupBy(g=>g.ClientId); + 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)//单开单平 + var list = item.ToList(); + if (list.Count == 1)//单开单平 { SendNodmaEmail(list, valueDate, clientDuitys); } @@ -296,15 +297,15 @@ namespace YLErp.Modules.SwapModule /// /// /// - private void SendNodmaEmail( List swapTradeContracts, DateTime valueDate, List clientDuitys) + private void SendNodmaEmail(List swapTradeContracts, DateTime valueDate, List clientDuitys) { SwapTradeContractDto swapTradeContract = swapTradeContracts.First(); - var eventEmail= SaveEventEmail(swapTradeContract.SwapFlowEventId, swapTradeContract.ClientId, valueDate,true); + var eventEmail = SaveEventEmail(swapTradeContract.SwapFlowEventId, swapTradeContract.ClientId, valueDate, true); var emails = GetEmailTo(clientDuitys, swapTradeContracts); - List filePaths=new List(); + List filePaths = new List(); string title = $"【{valueDate.ToString("yyyy.MM.dd")}结算说明】{swapTradeContract.ClientName}"; string content = ""; - if (swapTradeContract.SwapFlowEventType==(int)SwapFlowEventTypeEnum.开仓) + if (swapTradeContract.SwapFlowEventType == (int)SwapFlowEventTypeEnum.开仓) { content = GetSingleEventOpenContent(swapTradeContract, valueDate); } @@ -314,7 +315,7 @@ namespace YLErp.Modules.SwapModule } var file = GetFileName(swapTradeContract.Paths, ".xlsx"); filePaths.Add(file); - var emailMsgId= SendEmailApi(title, emails, content,true, filePaths); + var emailMsgId = SendEmailApi(title, emails, content, true, filePaths); eventEmail.email_msg_id = emailMsgId; eventEmail.send_email = true; DbContext.SaveChanges(); @@ -344,19 +345,19 @@ namespace YLErp.Modules.SwapModule swapEventEmails.Add(eventEmail); } Dictionary dic = new Dictionary(); - var clientName= swapTradeContracts.First().ClientName; + 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 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); + content = GetComplexEventContent(dic, valueDate, clientName); var swapEventEmailIds = swapEventEmails.Select(s => s.id).ToList(); - var emailMsgId= SendEmailApi(title, emails, content, true, filePaths); + var emailMsgId = SendEmailApi(title, emails, content, true, filePaths); swapEventEmails.ForEach(x => { x.send_email = true; @@ -372,11 +373,11 @@ namespace YLErp.Modules.SwapModule 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 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 stockNotional = posiList.Sum(s => s.PosiNotionalValue) / wan; + var notionalStock = stockNotional; if (stockNotional >= wan) { @@ -385,17 +386,17 @@ namespace YLErp.Modules.SwapModule dic["openTotal"] = trades.Count; dic["openNotionalStock"] = (notionalStock).ToString("0.######") + (stockNotional >= wan ? "亿" : "万"); string tradeNumbers = string.Empty; - decimal marginAmountTotal = 0; - foreach ( var t in trades) + 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 ? -1 : 1)); + 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}

"; + tradeNumbers += $"

合约编号 {t.TradeNumber}

"; } marginAmountTotal /= wan; dic["openTradeNumber"] = tradeNumbers; dic["openPaySide"] = marginAmountTotal > 0 ? "我方" : ""; - dic["openMarginAmount"] = Math.Abs(marginAmountTotal).ToString("0.######"); + dic["openMarginAmount"] = Math.Abs(marginAmountTotal).ToString("0.######"); return marginAmountTotal; } /// @@ -403,26 +404,26 @@ namespace YLErp.Modules.SwapModule /// /// /// - private decimal DealCloseEventData(List swapTradeContracts,Dictionary dic) + 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(); + 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) + 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 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; + swapCloseAmountTotal += -(unwindData.SwapCloseAmount + unwindData.SwapMarginRebatePnl - unwindData.SwapMarginAmount) / wan; tradeNumbers += $"

合约编号 {flowEvent.SwapTradeNo}

"; } - + var notionalStock = stockNotionalTotal; if (stockNotionalTotal >= wan) { @@ -441,7 +442,7 @@ namespace YLErp.Modules.SwapModule /// /// /// - private string GetComplexEventContent(Dictionary dic,DateTime valueDate,string clientName) + private string GetComplexEventContent(Dictionary dic, DateTime valueDate, string clientName) { var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string templatePath = Path.Combine(sourcePath, "资金提示-轧差支付模板.docx"); @@ -464,9 +465,9 @@ namespace YLErp.Modules.SwapModule /// /// /// - private SwapEventEmail SaveEventEmail(long? eventId,int clientId,DateTime valueDate,bool single) + 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); + 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() @@ -475,14 +476,14 @@ namespace YLErp.Modules.SwapModule event_id = eventId, client_id = clientId, single = single, - send_remark= single?"结算提示-单开单平": "结算提示-轧差支付" + send_remark = single ? "结算提示-单开单平" : "结算提示-轧差支付" }; - swapEventEmail.SetCreator(UserId,UserName); + swapEventEmail.SetCreator(UserId, UserName); swapEventEmail.SetOpt(UserId, UserName); DbContext.swap_event_email.Add(swapEventEmail); DbContext.SaveChanges(); } - return swapEventEmail; + return swapEventEmail; } /// @@ -503,7 +504,7 @@ namespace YLErp.Modules.SwapModule event_id = eventId, client_id = clientId, single = false, - send_remark = "追缴预付金Email" + send_remark = "追缴预付金Email" }; swapEventEmail.SetCreator(UserId, UserName); swapEventEmail.SetOpt(UserId, UserName); @@ -520,13 +521,13 @@ namespace YLErp.Modules.SwapModule 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(); + 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) + if (client == null) { continue; } @@ -549,9 +550,9 @@ namespace YLErp.Modules.SwapModule private List GetClientDuitys() { using var db = new ClientDBContext(); - var clientContacts = db.clientduty.Where(x => x.ApprovalOrder < 1 + var clientContacts = db.clientduty.Where(x => x.ApprovalOrder < 1 && (x.DeadLine == null || x.DeadLine > DateTime.Now) - && x.IsReceiveEmail == 1 && x.Email != null + && x.IsReceiveEmail == 1 && x.Email != null && x.ContactTypeId.Contains("4")) .ToList(); return clientContacts; @@ -564,15 +565,15 @@ namespace YLErp.Modules.SwapModule /// /// /// - private string GetEmailTo(List clientDuitys,List swapTradeContracts) + 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)); + 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)) + if (!clientDuityQuery.Any(x => x.ClientId == swapTradeContract.Key)) { clientNumbers.Add(clientNumber); } @@ -581,7 +582,7 @@ namespace YLErp.Modules.SwapModule { throw new Exception($"客户{string.Join(",", clientNumbers)}未维护职责类型为联系人且接收相关邮件选项为是"); } - var emails = clientDuityQuery.Select(s=>s.Email).Distinct().ToList(); + var emails = clientDuityQuery.Select(s => s.Email).Distinct().ToList(); return string.Join(";", emails); } /// @@ -591,11 +592,11 @@ namespace YLErp.Modules.SwapModule /// /// /// - private Dictionary GetEmailTo(List clientDuitys,List clientIds) + 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(); + Dictionary dic = new Dictionary(); foreach (var t in clientIds) { var client = DataCacheProvider.GetClientDataSource().GetData(t); @@ -604,7 +605,7 @@ namespace YLErp.Modules.SwapModule { clientNumbers.Add(clientNumber); } - var emails = clientDuityQuery.Where(x=>x.ClientId==t).Select(s => s.Email).Distinct().ToList(); + var emails = clientDuityQuery.Where(x => x.ClientId == t).Select(s => s.Email).Distinct().ToList(); dic.Add(t, string.Join(";", emails)); } if (clientNumbers.Any()) @@ -619,28 +620,28 @@ namespace YLErp.Modules.SwapModule /// /// /// - private string GetSingleEventOpenContent(SwapTradeContractDto swapTradeContract,DateTime valueDate) + 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?-1:1)); - var posi = swapPositions.FirstOrDefault(x=>x.PosiDirection>0); - Dictionary dic=new Dictionary(); + 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) + 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["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 ? "我方" : "客户"; + dic["payDirect"] = marginAmount >= 0 ? "我方" : "客户"; var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string templatePath = Path.Combine(sourcePath, "资金提示-单开模板.docx"); var tempFolder = OtcAppContext.MapPath("~/App_Docs/Temp/结算报告"); @@ -651,9 +652,9 @@ namespace YLErp.Modules.SwapModule Directory.CreateDirectory(targetPath); } var clientName = swapTradeContract.ClientName; - var fileName = $"资金提示-单开{valueDate:yyyyMMdd}_{clientName}"; + var fileName = $"资金提示-单开{valueDate:yyyyMMdd}_{clientName}"; var targetFileName = Path.Combine(targetPath, $"{fileName}.docx"); - return GetEmailContent(templatePath,dic, targetFileName); + return GetEmailContent(templatePath, dic, targetFileName); } /// /// 获取单平邮件内容 @@ -668,7 +669,7 @@ namespace YLErp.Modules.SwapModule 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 payAmount = -(unwindData.SwapCloseAmount + unwindData.SwapMarginRebatePnl - unwindData.SwapMarginAmount) / wan; var notionalStock = stockNotional; if (stockNotional >= wan) { @@ -679,7 +680,7 @@ namespace YLErp.Modules.SwapModule dic["tradeNumber"] = swapTradeContract.TradeNumber; dic["notionalStock"] = notionalStock.ToString("0.######") + (stockNotional >= wan ? "亿" : "万"); dic["paySide"] = payAmount > 0 ? "我方" : ""; - dic["marginAmount"] = Math.Abs(payAmount).ToString("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/导出模板"); @@ -703,11 +704,11 @@ namespace YLErp.Modules.SwapModule /// /// /// - private string GetDmaContent(string clientName,DateTime valueDate,double marginAmount) + private string GetDmaContent(string clientName, DateTime valueDate, double marginAmount) { Dictionary dic = new Dictionary(); dic["clientName"] = clientName; - dic["settlementDate"] = valueDate.ToString("yyyy.MM.dd"); + dic["settlementDate"] = valueDate.ToString("yyyy.MM.dd"); dic["marginAmount"] = marginAmount; var sourcePath = OtcAppContext.MapPath("~/App_Docs/导出模板"); string templatePath = Path.Combine(sourcePath, "资金提示-追加预付金模板.docx"); @@ -726,7 +727,7 @@ namespace YLErp.Modules.SwapModule { var varDic = new JsonVarDic(modelDic); OfficeFileConverter.ConvertByUsingDocTemplate(templatePath, outputFilePath, varDic, false); - string content= DocHelper.GetContent(outputFilePath); + string content = DocHelper.GetContent(outputFilePath); File.Delete(outputFilePath); return content; } @@ -738,22 +739,9 @@ namespace YLErp.Modules.SwapModule /// /// /// - private string SendEmailApi(string subject,string mailTo,string body,bool isBodyHtml,List filesToAttach) + private string SendEmailApi(string subject, string mailTo, string body, bool isBodyHtml, List filesToAttach) { - //去重 - var toSet = mailTo.Split(new[] { ';', ',', ',' }, StringSplitOptions.RemoveEmptyEntries) - .ToHashSet(StringComparer.OrdinalIgnoreCase); - - var mailToArr = toSet.ToArray(); - return MailSender.SendApi(new MailSendingOption - { - MailTo = mailToArr, - Subject = subject, - Body = body, - IsBodyHtml = isBodyHtml, - FilesToAttach = filesToAttach, - CC = string.Empty - }); + return EmailHelper.SendMail(mailTo, subject, body, isBodyHtml, filesToAttach); } private string GetFileName(string baseName, string sufferFix) diff --git a/YLErpDAL/Modules/SwapModule/SwapFlowService.cs b/YLErpDAL/Modules/SwapModule/SwapFlowService.cs index 3a230e13..9ddecf0f 100644 --- a/YLErpDAL/Modules/SwapModule/SwapFlowService.cs +++ b/YLErpDAL/Modules/SwapModule/SwapFlowService.cs @@ -149,6 +149,7 @@ namespace YLErp.Modules.SwapModule public SearchListResult SearchEventList(SwapFlowQueryRequest req) { var predicate = PredicateBuilder.Create(n =>n.PositionType>0&&n.DataState>0); + List eventTypes = new List() { (int)SwapEventTypeEnum.确认交易, (int)SwapEventTypeEnum.平仓 }; if (req.TradeDate.HasValue) { predicate = predicate.And(n=>n.EventDate==req.TradeDate); @@ -175,7 +176,7 @@ namespace YLErp.Modules.SwapModule } var eventQuery =from se in DbContext.swap_flow_event.Where(predicate) join t in DbContext.trade.Where(x=>x.ValidState==ConsGlobal.Valid) on se.SwapTradeId equals t.id - join s in DbContext.swap_event.Where(x=>!x.Invalid) on se.EventId equals s.id into stemp + join s in DbContext.swap_event.Where(x => !x.Invalid && eventTypes.Contains(x.EventType)) on se.EventId equals s.id into stemp from s in stemp.DefaultIfEmpty() select se; @@ -262,7 +263,7 @@ namespace YLErp.Modules.SwapModule exportModel.PayDate = item.PayDate.OtcFormatDate(); exportModel.SwapTradeNo = item.SwapTradeNo; exportModel.SwapPositionIdPadding = item.SwapPositionIdPadding; - exportModel.EventType = ((SwapEventTypeEnum)item.EventType).ToString(); + exportModel.EventType = ((SwapFlowEventTypeEnum)item.EventType).ToString(); exportModel.EventReason = item.EventReason; exportModel.PayDirection = ((SwapDirectionEnum)item.PayDirection).ToString(); exportModel.PositionType = item.PositionType==1?"多头":"空头"; diff --git a/YLErpDAL/Modules/SwapModule/SwapTradeAutoService.cs b/YLErpDAL/Modules/SwapModule/SwapTradeAutoService.cs index 4f78a7a7..16f3a7c1 100644 --- a/YLErpDAL/Modules/SwapModule/SwapTradeAutoService.cs +++ b/YLErpDAL/Modules/SwapModule/SwapTradeAutoService.cs @@ -23,6 +23,7 @@ using YLErp.Model; using YLErp.Model.Enum; using YLErp.Models; using YLErp.Modules.AppModule; +using YLErp.Modules.EodModule.QueryModule; using YLErp.Modules.RiskModule; using YLErp.Modules.TradeMsgOutputModule; using YLErp.QdpModule; @@ -118,8 +119,9 @@ namespace YLErp.Modules.SwapModule string sql = $"select cd.id,{selectStr},co.settl_type from client_deal cd inner join client_order co on co.id=cd.client_order_id where cd.create_time<'{tomorrowDate.ToString("yyyy-MM-dd")}' and cd.create_time>='{valueDate.ToString("yyyy-MM-dd")}'"; return sql; } - public void ResetTradeByDate(DateTime valueDate, Action? action, List tradeIds) + public void ResetTradeByDate(DateTime valueDate, int? clientId, string underlyingCode, Action? action, List tradeIds) { + var swapEvents = DbContext.swap_event.Where(x => x.EventReason.Contains("自动") && x.ValueDate == valueDate); //bool resetSingle = false; if (tradeIds == null || tradeIds.Count() == 0) @@ -133,21 +135,25 @@ namespace YLErp.Modules.SwapModule var swaptrades = DbContext.trade.Where(x => tradeIds.Contains(x.id) && x.ValidState != ConsGlobal.InValid).ToList(); var swapflowMerges = DbContext.swap_flow_merge.Where(x => x.OccurTime == valueDate); var swapflowDeals = DbContext.swap_flow_deal.Where(x => x.OccurDate == valueDate); - var swapFlows = DbContext.swap_flow.Where(x => x.OccurTime == valueDate).ToList(); - //if (resetSingle == true) - //{ - // var trade = swaptrades.FirstOrDefault(); - // if (trade != null) - // { - // swapFlows = swapFlows.Where(x => x.ClientId == trade.ClientId && x.UnderlyingCode == trade.UnderlyingCode).ToList(); - // } - //} + var swapFlows = DbContext.swap_flow.Where(x => x.OccurTime == valueDate); + if (clientId.HasValue) + { + swapFlows = swapFlows.Where(x => x.ClientId == clientId); + swapflowDeals = swapflowDeals.Where(x => x.ClientId == clientId); + swapflowMerges = swapflowMerges.Where(x => x.ClientId == clientId); + } + if (!string.IsNullOrEmpty(underlyingCode)) + { + swapFlows = swapFlows.Where(x => x.UnderlyingCode == underlyingCode); + swapflowMerges = swapflowMerges.Where(x => x.UnderlyingCode == underlyingCode); + swapflowDeals = swapflowDeals.Where(x => x.UnderlyingCode == underlyingCode); + } var trsDealIds = swapFlows.Where(x => x.trs_deal_id > 0).Select(s => s.trs_deal_id ?? 0).ToList(); var swaptradesCount = swaptrades.Count(); decimal backProcessedCount = 0; if (swaptradesCount == 0) { - backProcessedCount=100; + backProcessedCount = 100; } foreach (var td in swaptrades) { @@ -162,7 +168,6 @@ namespace YLErp.Modules.SwapModule DbContext.swap_flow_merge.RemoveRange(swapflowMerges); DbContext.swap_flow_deal.RemoveRange(swapflowDeals); DbContext.SaveChanges(); - } /// @@ -550,7 +555,7 @@ namespace YLErp.Modules.SwapModule } if (cashNeedAfter) { - var flowEvents = DbContext.swap_flow_event.Where(x => x.EventDate == flowMerge.OccurTime && x.PayDate > x.UnwindDate && x.EventType == (int)SwapFlowEventTypeEnum.平仓 && x.DataState == (int)SwapFlowDateStateEnum.完成 &&x.ClientId== flowMerge.ClientId); + var flowEvents = DbContext.swap_flow_event.Where(x => x.EventDate == flowMerge.OccurTime && x.PayDate > x.UnwindDate && x.EventType == (int)SwapFlowEventTypeEnum.平仓 && x.DataState == (int)SwapFlowDateStateEnum.完成 && x.ClientId == flowMerge.ClientId && x.PayDirection > 0); var tradeIds = flowEvents.Select(s=>s.SwapTradeId).Distinct(); var trades = DbContext.trade.Where(x=> tradeIds.Contains(x.id)&&x.ValidState!=ConsGlobal.InValid); cashNeedAfter = !trades.Any(); diff --git a/YLErpDAL/Modules/SwapModule/TRSHedgingOrderService.cs b/YLErpDAL/Modules/SwapModule/TRSHedgingOrderService.cs index 8bc69d89..5c1e1207 100644 --- a/YLErpDAL/Modules/SwapModule/TRSHedgingOrderService.cs +++ b/YLErpDAL/Modules/SwapModule/TRSHedgingOrderService.cs @@ -97,7 +97,7 @@ namespace YLErp.Modules.SwapModule tradeIds = swapEvents.Select(s => s.SwapTradeId).ToList(); var swaptrades = DbContext.trade.Where(x => tradeIds.Contains(x.id) && x.ClientId == swapFlow.ClientId && x.UnderlyingCode == swapFlow.UnderlyingCode && x.ValidState != ConsGlobal.InValid).AsNoTracking().ToList(); tradeIds = swaptrades.Select(s => s.id).ToList(); - new SwapTradeAutoService(OptUserInfo.SystemUser).ResetTradeByDate(swapFlow.OccurTime.Value, null, tradeIds); + new SwapTradeAutoService(OptUserInfo.SystemUser).ResetTradeByDate(swapFlow.OccurTime.Value, swapFlow.ClientId, swapFlow.UnderlyingCode, null, tradeIds); } var _swapFlow = DbContext.swap_flow.Where(x => x.trs_deal_id == swapFlow.trs_deal_id).FirstOrDefault(); if (_swapFlow != null) diff --git a/YLErpDAL/Modules/TradeModule/DealModule/TradeExpireConfirmService.cs b/YLErpDAL/Modules/TradeModule/DealModule/TradeExpireConfirmService.cs index 65fa780c..a523d7ca 100644 --- a/YLErpDAL/Modules/TradeModule/DealModule/TradeExpireConfirmService.cs +++ b/YLErpDAL/Modules/TradeModule/DealModule/TradeExpireConfirmService.cs @@ -283,7 +283,7 @@ namespace YLErp.Modules.TradeModule.DealModule var underlyingIds = tradeUnwindTrades.Select(t => t.UnderlyingId).ToList(); var EodPriceProvider = new EodPriceProvider(valueDate); //批量结算的全是现金流交易就不用结算价 - if (!EodPriceQueryService.CheckDbExists(valueDate, preday) && tradeQuery.Any(t => t.TradeType != "现金流交易")) + if (!EodPriceQueryService.CheckDbExists(valueDate) && tradeQuery.Any(t => t.TradeType != "现金流交易")) { throw new ServiceException($"当日交易的结算价或收盘价未找到!"); } diff --git a/YLErpWeb/Controllers/PricingController.cs b/YLErpWeb/Controllers/PricingController.cs index 1e5ad4df..b0af74eb 100644 --- a/YLErpWeb/Controllers/PricingController.cs +++ b/YLErpWeb/Controllers/PricingController.cs @@ -539,26 +539,24 @@ namespace YLErp.Web.Controllers netPrice = price; if (udm.IsBond()) { - var date = QdpCalendarHelper.GetNonHolidayDefore(valuedateBLL.ValueDate.AddDays(-1)); - if (EodPriceQueryService.TryGetBondEodPrice(date, underlyingCode, out var eodPrice)) + if (EodPriceQueryService.TryGetBondEodPrice(valuedateBLL.ValueDate, underlyingCode, out var eodPrice)) { price = eodPrice.ClosePrice; netPrice = eodPrice.SettlePrice; } else { - price = price *Convert.ToDouble( ConsGlobal.bondPriceMultiple); + price = price * Convert.ToDouble(ConsGlobal.bondPriceMultiple); netPrice = price; } } - + } if (tradeDate != null && tradeDate != valuedateBLL.ValueDate) { var date = Convert.ToDateTime(tradeDate); if (udm.IsBond()) { - date = QdpCalendarHelper.GetNonHolidayDefore(date.AddDays(-1)); if (EodPriceQueryService.TryGetBondEodPrice(date, underlyingCode, out var eodPrice)) { price = eodPrice.ClosePrice; @@ -573,7 +571,7 @@ namespace YLErp.Web.Controllers netPrice = eodPrice.SettlePrice; } } - + } } diff --git a/YLErpWeb/Controllers/SwapTrade2Controller.cs b/YLErpWeb/Controllers/SwapTrade2Controller.cs index b66ac402..68da6f50 100644 --- a/YLErpWeb/Controllers/SwapTrade2Controller.cs +++ b/YLErpWeb/Controllers/SwapTrade2Controller.cs @@ -254,7 +254,7 @@ namespace YLErp.Web.Controllers /// public JsonResult TradeBackByDate(TradeBackModel model) { - new SwapTradeService(CurUser).TradeBack(model.TradeId, model.ValueDate); + new SwapTradeService(CurUser).TradeBack(model.TradeId, model.TradeDate); return JsonSuccess("回退成功"); } /// @@ -1050,5 +1050,16 @@ namespace YLErp.Web.Controllers return JsonSuccess("更新成功"); } + /// + /// 发送确认书邮件 + /// + /// + /// + public JsonResult SendConfimEmail(int tradeId) + { + SwapEndConfirmService service = new SwapEndConfirmService(CurUser); + var result = service.SendConfirmEamil(tradeId); + return JsonSuccess(result); + } } } \ No newline at end of file diff --git a/YLErpWeb/Controllers/tradeController.cs b/YLErpWeb/Controllers/tradeController.cs index 4b9d3d38..144a2320 100644 --- a/YLErpWeb/Controllers/tradeController.cs +++ b/YLErpWeb/Controllers/tradeController.cs @@ -4276,6 +4276,7 @@ namespace YLErp.Web.Controllers tradeContractR.id, tradeContractR.TradeId, tradeContractR.ContractCode, + tradeContractR.send_email_result, tradeContractDoc = tradeContractDoc2 }).ToList(); @@ -4287,6 +4288,7 @@ namespace YLErp.Web.Controllers trade.SyntheticUnderlyingTipsInfo = synthetic_underlyingBLL.GetUnderlyingTipsInfo(trade.UnderlyingCode); } var tradeContractinfo = tradeContractCodeList.FirstOrDefault(t => t.TradeId == trade.id); + trade.MetaDic["send_email_result"] = ""; if (tradeContractinfo != null) { trade.ContractCode = tradeContractinfo.ContractCode; @@ -4324,6 +4326,7 @@ namespace YLErp.Web.Controllers // trade.MetaDic["ContractDocUrl"] = Path.ChangeExtension((trade.MetaDic["ContractDocUrl"] ?? ""), "pdf"); // } //} + trade.MetaDic["send_email_result"] = string.IsNullOrEmpty(tradeContractinfo.send_email_result) ? "未发送" : tradeContractinfo.send_email_result; } } if (PS.Config.Is物产中大) diff --git a/YLErpWeb/Controllers/underlying_managerController.cs b/YLErpWeb/Controllers/underlying_managerController.cs index cdd8fd3a..3c3585bc 100644 --- a/YLErpWeb/Controllers/underlying_managerController.cs +++ b/YLErpWeb/Controllers/underlying_managerController.cs @@ -290,7 +290,6 @@ namespace YLErp.Web.Controllers } if (data.IsBond()) { - valuedate = QdpCalendarHelper.GetNonHolidayDefore(valuedate.Value.AddDays(-1)); //系统日期当天优先取日终价格如果取不到则使用行情价格 if (EodPriceQueryService.TryGetBondEodPrice(valuedate.Value, code, out var eodPrice)) { @@ -310,7 +309,7 @@ namespace YLErp.Web.Controllers price = eodPrice.GetPrice((SettlementTypeEnum)settlementType); } } - + if (valuedate != systemDate) { return JsonError("获取不到日终价格"); diff --git a/YLErpWeb/Hubs/SwapConfirmSendEmailHub.cs b/YLErpWeb/Hubs/SwapConfirmSendEmailHub.cs new file mode 100644 index 00000000..82f02bcd --- /dev/null +++ b/YLErpWeb/Hubs/SwapConfirmSendEmailHub.cs @@ -0,0 +1,108 @@ +using Microsoft.AspNetCore.SignalR; +using YLErp.DBModels; +using YLErp.Enums; +using YLErp.MailKit; +using YLErp.Modules.RiskModule; +using YLErp.Modules.SwapModule; +using static YLErp.ConsGlobal; + +namespace YLErp.Web.Hubs +{ + public class SwapConfirmSendEmailHub : Hub + { + private static bool isProcessing = false; + static readonly Dictionary _dic = new Dictionary(StringComparer.OrdinalIgnoreCase); + static readonly Dictionary _clientProgressDic = new Dictionary(); + public async Task StartProcessing(string jsonString) + { + SwapTradeSendEmailReq req = JsonHelper.Deserialize(jsonString); + var connectionId = Context.ConnectionId; + var client = Clients.Client(connectionId); + if (Context.User == null) + { + await client.SendAsync("ExceptionMessage", "登录已失效,请重新登录"); + return; + } + var user = Server.CacheProvider.Get("loginUser^" + Context.User.GetUserId()) as UserInfo; + if (user == null) + { + await client.SendAsync("ExceptionMessage", "登录已失效,请重新登录"); + return; + } + var service = new SwapEndConfirmService(user); + if (isProcessing) + { + await client.SendAsync("ExceptionMessage", "正在发送邮件,请稍后再试"); + foreach (var tradeId in req.tradeIds) { + var msg= GetProcess(tradeId,async (d) => { + await client.SendAsync("UpdateProgress", getUpdateProcess(tradeId, d)); + }); + await client.SendAsync("UpdateProgress", getUpdateProcess(tradeId, msg)); + } + await client.SendAsync("ProcessCompleted", ""); + return; + } + try + { + isProcessing = true; + _clientProgressDic.Clear(); + _dic.Clear(); + foreach (var tradeId in req.tradeIds) + { + _clientProgressDic[tradeId] = "发送中"; + await client.SendAsync("UpdateProgress", getUpdateProcess(tradeId, "发送中")); + if (PS.Config.ErpElement.MailMessageRateLimit > 0) + { + var milliSeconds = 60d * 1000 / PS.Config.ErpElement.MailMessageRateLimit; + + lock (_dic) + { + if (_dic.TryGetValue("sendEmail", out var dt)) + { + while (dt < DateTime.Now && dt.AddMilliseconds(milliSeconds) > DateTime.Now) + { + Thread.Sleep(500); + } + } + _dic["sendEmail"] = DateTime.Now; + } + } + var result = service.SendConfirmEamil(tradeId); + _clientProgressDic[tradeId] = result; + await client.SendAsync("UpdateProgress", getUpdateProcess(tradeId, result)); + } + isProcessing = false; + await client.SendAsync("ProcessCompleted", ""); + } + catch (Exception ex) + { + isProcessing = false; + await client.SendAsync("ExceptionMessage", ex.Message); + } + } + private string GetProcess(int tradeId,Action action) + { + if (_clientProgressDic.ContainsKey(tradeId)) + { + string process= _clientProgressDic[tradeId]; + if (action != null&& process=="发送中") + { + action.Invoke(process); + Thread.Sleep(1000); + return GetProcess(tradeId, action); + } + return process; + } + return ""; + } + private string getUpdateProcess(int tradeId,string msg) + { + SwapTradeSendEmailResp resp = new SwapTradeSendEmailResp() + { + tradeId = tradeId, + send_email_result = msg + }; + return JsonHelper.Serialize(resp); + } + } +} diff --git a/YLErpWeb/Hubs/SwapFlowResetHub.cs b/YLErpWeb/Hubs/SwapFlowResetHub.cs index 13b2f799..2b326a9f 100644 --- a/YLErpWeb/Hubs/SwapFlowResetHub.cs +++ b/YLErpWeb/Hubs/SwapFlowResetHub.cs @@ -41,9 +41,9 @@ namespace YLErp.Web.Hubs { var tradeIds= service.GetNeedResetTradeIds(req.clientId, req.underlyingCode, req.tradeDate); isProcessing = true; - service.ResetTradeByDate(req.tradeDate, (progress) => + service.ResetTradeByDate(req.tradeDate, req.clientId, req.underlyingCode, (progress) => { - client.SendAsync("UpdateProgress",Math.Round(progress,2)); + client.SendAsync("UpdateProgress", Math.Round(progress, 2)); }, tradeIds); isProcessing = false; await client.SendAsync("ProcessCompleted", ""); diff --git a/YLErpWeb/Models/TradeBackModel.cs b/YLErpWeb/Models/TradeBackModel.cs index 6f74ecfa..7e28dfba 100644 --- a/YLErpWeb/Models/TradeBackModel.cs +++ b/YLErpWeb/Models/TradeBackModel.cs @@ -9,9 +9,9 @@ namespace YLErp.Web.Models /// /// 回退到某一时间 /// - [DisplayName("回退至")] + //[DisplayName("回退至")] public DateTime ValueDate { get; set; } - + [DisplayName("回退至")] public DateTime TradeDate { get; set; } } } \ No newline at end of file diff --git a/YLErpWeb/Program.cs b/YLErpWeb/Program.cs index c69cb6a0..bcfe11cc 100644 --- a/YLErpWeb/Program.cs +++ b/YLErpWeb/Program.cs @@ -153,6 +153,7 @@ try { endpoints.MapHub("/swapflow/combookinghub"); // 映射Hub路径 endpoints.MapHub("/swapflow/resethub"); // 映射Hub路径 + endpoints.MapHub("/tradeconfirm/sendemailhub"); // 映射Hub路径 }); var provider = new FileExtensionContentTypeProvider(); provider.Mappings[".pdf"] = "application/pdf"; diff --git a/YLErpWeb/Views/SwapTrade2/tradeBack.cshtml b/YLErpWeb/Views/SwapTrade2/tradeBack.cshtml index 9782f64b..14215af0 100644 --- a/YLErpWeb/Views/SwapTrade2/tradeBack.cshtml +++ b/YLErpWeb/Views/SwapTrade2/tradeBack.cshtml @@ -5,7 +5,7 @@ } @section JS -{ + {