山证bug修复及功能 迁移

This commit is contained in:
吴方海
2024-06-04 18:19:49 +08:00
parent df65cd0add
commit acbd2e7678
39 changed files with 709 additions and 406 deletions
@@ -40,5 +40,9 @@ namespace YLErp.DBModels
/// 是否发送邮件
/// </summary>
public bool? send_email { get; set; }
/// <summary>
/// 邮件发送结果
/// </summary>
public string send_email_result { get; set; }
}
}
+11 -3
View File
@@ -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 == "远期")
+1 -1
View File
@@ -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);
}
+19 -4
View File
@@ -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<string> filesToAttach, string ccEmail)
private static string doSendMail(string mailTo, string subject, string body, bool isBodyHtml, IEnumerable<string> 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;
}
}
}
+14
View File
@@ -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;
}
}
+16
View File
@@ -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<int>();
}
public List<int> tradeIds;
}
}
+14
View File
@@ -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; }
}
}
@@ -525,6 +525,8 @@ namespace YLErp.Modules.CalculationModule
public double PFE { get; set; }
public double QuotePFE { get; set; }
public double RealPnl { get;set; }
}
@@ -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
/// <returns></returns>
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;
}
@@ -21,7 +21,7 @@ namespace YLErp.Modules.DataCacheModule
{
class UnderlyingDbDataSource : IUnderlyingDataSource, IBasketPriceProvider, IDataUpdater, IDataSource, IDataSource<underlying_manager>, IDataSourceEvent, IJsonSerializable
{
private readonly YLContext _context=new YLContext();
private readonly YLContext _context = new YLContext();
/// <summary>
/// 查询过滤条件
/// </summary>
@@ -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
{
@@ -55,14 +55,10 @@ namespace YLErp.Modules.DataProviderModule
/// </summary>
public EodPriceProvider Initialize(IEnumerable<string> underlyingCodes = null)
{
if (!PreValueDate.HasValue)
{
PreValueDate = QdpCalendarHelper.GetNonHoliday(ValueDate.AddDays(-1));
}
using var db = DbContextFactory.GetYLDbContext();
var predicate1 = PredicateBuilder.Create<eod_commodity_future_price>(eodprice => eodprice.ValueDate == ValueDate);
var predicate2 = PredicateBuilder.Create<eod_stock_price>(eodprice => eodprice.ValueDate == ValueDate);
var predicate3 = PredicateBuilder.Create<ChinaBondValuation>(eodprice => eodprice.valuation_date == PreValueDate);
var predicate3 = PredicateBuilder.Create<ChinaBondValuation>(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);
}
@@ -13,12 +13,12 @@ namespace YLErp.Modules.DataProviderModule
/// <summary>
/// 检查数据库是否有数据
/// </summary>
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);
}
/// <summary>
@@ -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;
}
/// <summary>
/// 获取某日之前最新价格
/// </summary>
/// <param name="valueDate"></param>
/// <param name="underlyingCode"></param>
/// <param name="price"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 尝试获取标的某日的日终价
/// </summary>
@@ -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))
@@ -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, "结算价格未入库");
}
@@ -22,7 +22,7 @@ namespace YLErp.Modules.EodModule.SettlementModule
/// </summary>
public void Execute()
{
if (!_context.OtcTrades.Any()&& !hasSwaptrade())
if (!_context.OtcTrades.Any() && !hasSwaptrade())
{
return;
}
@@ -34,7 +34,7 @@ namespace YLErp.Modules.EodModule.SettlementModule
IQueryable<string> 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();
}
@@ -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();
@@ -149,6 +149,7 @@ namespace YLErp.Modules.ExchangeTradeModule
{
throw new ServiceException(dto.TradeType+"交易类型必须填写债券标的");
}
dto.TradeSinglePrice /= 100;
break;
}
@@ -1065,11 +1065,12 @@ namespace YLErp.Modules.RiskModule
setValue(swap, swapSetting);
var positionList = new List<KeyValuePair<trade, realtime_trade_risk>>();
var gloabDv01 = GetTradePositionDv01();
double underPnl = 0;
var gloabDv01 = GetTradePositionDv01(ref underPnl);
if (dict.ContainsKey("互换"))
{
var swapPositionList = dict["互换"].Select(O => new KeyValuePair<trade, realtime_trade_risk>(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<ClientRiskCheckItem> clientRiskCheckResps = new List<ClientRiskCheckItem>();
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<string> quotaIndexs = new List<string>() { "名义本金", "轧差集中度", "轧差名义本金" };
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<CheckQuotaMoitorModel> checkPoisiList = new List<CheckQuotaMoitorModel>();
var dealDate = valuedateBLL.ValueDate;
dealDate = QdpCalendarHelper.GetNonHolidayDefore(dealDate.AddDays(-1));
using var bondDb = new BondOmsDBContext();
var clientPositions = bondDb.client_position.AsNoTracking().ToList();//所有持仓
Dictionary<string, EodPrice> eodPriceDic = new Dictionary<string, EodPrice>();
@@ -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
/// </summary>
/// <returns></returns>
private double GetTradePositionDv01()
private double GetTradePositionDv01(ref double pnl)
{
var dealDate = QdpCalendarHelper.GetNonHolidayDefore(valuedateBLL.ValueDate.AddDays(-1));
double currentValue = 0;
List<string> tradetypes = new List<string> { "利率债", "信用债", "其它债券" };
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<string> checkUnderlying(List<CheckQuotaMoitorModel> positionList, List<CheckQuotaMoitorModel> posiList, string tag_prefix, QuotaSetting[] settings, List<QuotaSetting> 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;
+32 -30
View File
@@ -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
/// <param name="unwindPriceFee"></param>
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<int> eventTypes = new List<int>() { (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<swap_flow_event> 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;
}
/// <summary>
@@ -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;
}
@@ -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<SwapTradeContractGroup> SearchEitherTradeWithCashList(SwapEndConfirmReq req)
{
var db = DbContext;
var actionList = new List<int>() { (int)SwapEventTypeEnum.,(int)SwapEventTypeEnum. };
var actionList = new List<int>() { (int)SwapEventTypeEnum., (int)SwapEventTypeEnum. };
var types = new List<string>() { ContractTypeEnum.Clearing, ContractTypeEnum.UnWind };
var flowQuery= PredicateBuilder.Create<swap_flow_event>(n => actionList.Contains(n.EventType) && n.PayDirection > 0);
var flowQuery = PredicateBuilder.Create<swap_flow_event>(n => actionList.Contains(n.EventType) && n.PayDirection > 0);
var eventQuery = PredicateBuilder.Create<swap_event>(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<trade_extend> 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<UnwindData>(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<Func<trade,bool>> buildTradeQuery(SwapEndConfirmReq req)
private Expression<Func<trade, bool>> buildTradeQuery(SwapEndConfirmReq req)
{
var tradeQuery = PredicateBuilder.Create<trade>(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;
}
/// <summary>
/// 发送交易确认书邮件
/// </summary>
/// <param name="tradeId"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 发送邮件
/// </summary>
/// <returns></returns>
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<SendEmailResult>(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 "未配置邮件接口地址";
}
}
}
@@ -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);
@@ -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<SwapEventEmail>(n => n.event_date == req.Valuedate);
var flowEventPredicate = PredicateBuilder.Create<swap_flow_event>(n => n.PositionType > 0 && eventTypes.Contains(n.EventType) && n.UnwindDate == req.Valuedate.Value&&n.DataState==(int)SwapFlowDateStateEnum.);
var flowEventPredicate = PredicateBuilder.Create<swap_flow_event>(n => n.PositionType > 0 && eventTypes.Contains(n.EventType) && n.UnwindDate == req.Valuedate.Value && n.DataState == (int)SwapFlowDateStateEnum.);
var clientSpanPredicate = PredicateBuilder.Create<ClientSpan>(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<SwapTradeContractDto>();
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
/// <exception cref="Exception"></exception>
private List<SwapTradeContractDto> CheckConfirmDoc(List<swap_flow_event> 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<SwapTradeContractDto> list=new List<SwapTradeContractDto>();
List<string> tradeNumbers=new List<string>();
List<SwapTradeContractDto> list = new List<SwapTradeContractDto>();
List<string> tradeNumbers = new List<string>();
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
/// <exception cref="Exception"></exception>
private List<SwapTradeContractDto> CheckSettlementDoc(List<swap_flow_event> 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
/// </summary>
/// <param name="swapTradeContracts"></param>
/// <param name="valueDate"></param>
private void SendNoDmaEmail(List<SwapTradeContractDto> swapTradeContracts,DateTime valueDate, List<ClientDuty> clientDuitys)
private void SendNoDmaEmail(List<SwapTradeContractDto> swapTradeContracts, DateTime valueDate, List<ClientDuty> 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
/// <param name="swapTradeContracts"></param>
/// <param name="valueDate"></param>
/// <param name="clientDuitys"></param>
private void SendNodmaEmail( List<SwapTradeContractDto> swapTradeContracts, DateTime valueDate, List<ClientDuty> clientDuitys)
private void SendNodmaEmail(List<SwapTradeContractDto> swapTradeContracts, DateTime valueDate, List<ClientDuty> 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<string> filePaths=new List<string>();
List<string> filePaths = new List<string>();
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<string, JToken> dic = new Dictionary<string, JToken>();
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<SwapTradeContractDto> swapTradeContracts, Dictionary<string, JToken> 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 += $"<p>合约编号 {t.TradeNumber}</p>";
tradeNumbers += $"<p>合约编号 {t.TradeNumber}</p>";
}
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;
}
/// <summary>
@@ -403,26 +404,26 @@ namespace YLErp.Modules.SwapModule
/// </summary>
/// <param name="swapTradeContracts"></param>
/// <param name="dic"></param>
private decimal DealCloseEventData(List<SwapTradeContractDto> swapTradeContracts,Dictionary<string, JToken> dic)
private decimal DealCloseEventData(List<SwapTradeContractDto> swapTradeContracts, Dictionary<string, JToken> 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<UnwindData>(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 += $"<p>合约编号 {flowEvent.SwapTradeNo}</p>";
}
var notionalStock = stockNotionalTotal;
if (stockNotionalTotal >= wan)
{
@@ -441,7 +442,7 @@ namespace YLErp.Modules.SwapModule
/// <param name="valueDate"></param>
/// <param name="clientName"></param>
/// <returns></returns>
private string GetComplexEventContent(Dictionary<string, JToken> dic,DateTime valueDate,string clientName)
private string GetComplexEventContent(Dictionary<string, JToken> 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
/// <param name="valueDate"></param>
/// <param name="single"></param>
/// <returns></returns>
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;
}
/// <summary>
@@ -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<EventEmail> EventEmailEmails, DateTime valueDate, List<ClientDuty> 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<ClientDuty> 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
/// <param name="swapTradeContracts"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private string GetEmailTo(List<ClientDuty> clientDuitys,List<SwapTradeContractDto> swapTradeContracts)
private string GetEmailTo(List<ClientDuty> clientDuitys, List<SwapTradeContractDto> 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<string> clientNumbers = new List<string>();
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);
}
/// <summary>
@@ -591,11 +592,11 @@ namespace YLErp.Modules.SwapModule
/// <param name="trades"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
private Dictionary<int,string> GetEmailTo(List<ClientDuty> clientDuitys,List<int> clientIds)
private Dictionary<int, string> GetEmailTo(List<ClientDuty> clientDuitys, List<int> clientIds)
{
var clientDuityQuery = clientDuitys.Where(x => clientIds.Contains(x.ClientId ?? 0));
List<string> clientNumbers = new List<string>();
Dictionary<int, string> dic=new Dictionary<int, string>();
Dictionary<int, string> dic = new Dictionary<int, string>();
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
/// <param name="swapTradeContract"></param>
/// <param name="valueDate"></param>
/// <returns></returns>
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<string, JToken> dic=new Dictionary<string, JToken>();
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<string, JToken> dic = new Dictionary<string, JToken>();
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);
}
/// <summary>
/// 获取单平邮件内容
@@ -668,7 +669,7 @@ namespace YLErp.Modules.SwapModule
var unwindData = JsonHelper.Deserialize<UnwindData>(swapEvent.EventData);
Dictionary<string, JToken> dic = new Dictionary<string, JToken>();
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
/// <param name="valueDate"></param>
/// <param name="marginAmount"></param>
/// <returns></returns>
private string GetDmaContent(string clientName,DateTime valueDate,double marginAmount)
private string GetDmaContent(string clientName, DateTime valueDate, double marginAmount)
{
Dictionary<string, JToken> dic = new Dictionary<string, JToken>();
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
/// <param name="body"></param>
/// <param name="isBodyHtml"></param>
/// <param name="filesToAttach"></param>
private string SendEmailApi(string subject,string mailTo,string body,bool isBodyHtml,List<string> filesToAttach)
private string SendEmailApi(string subject, string mailTo, string body, bool isBodyHtml, List<string> 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)
@@ -149,6 +149,7 @@ namespace YLErp.Modules.SwapModule
public SearchListResult<swap_flow_event> SearchEventList(SwapFlowQueryRequest req)
{
var predicate = PredicateBuilder.Create<swap_flow_event>(n =>n.PositionType>0&&n.DataState>0);
List<int> eventTypes = new List<int>() { (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?"多头":"空头";
@@ -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<decimal>? action, List<int> tradeIds)
public void ResetTradeByDate(DateTime valueDate, int? clientId, string underlyingCode, Action<decimal>? action, List<int> 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();
}
/// <summary>
@@ -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();
@@ -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)
@@ -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($"当日交易的结算价或收盘价未找到!");
}
+4 -6
View File
@@ -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;
}
}
}
}
+12 -1
View File
@@ -254,7 +254,7 @@ namespace YLErp.Web.Controllers
/// <returns></returns>
public JsonResult TradeBackByDate(TradeBackModel model)
{
new SwapTradeService(CurUser).TradeBack(model.TradeId, model.ValueDate);
new SwapTradeService(CurUser).TradeBack(model.TradeId, model.TradeDate);
return JsonSuccess("回退成功");
}
/// <summary>
@@ -1050,5 +1050,16 @@ namespace YLErp.Web.Controllers
return JsonSuccess("更新成功");
}
/// <summary>
/// 发送确认书邮件
/// </summary>
/// <param name="tradeId"></param>
/// <returns></returns>
public JsonResult SendConfimEmail(int tradeId)
{
SwapEndConfirmService service = new SwapEndConfirmService(CurUser);
var result = service.SendConfirmEamil(tradeId);
return JsonSuccess(result);
}
}
}
+3
View File
@@ -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物产中大)
@@ -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("获取不到日终价格");
+108
View File
@@ -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<string, DateTime> _dic = new Dictionary<string, DateTime>(StringComparer.OrdinalIgnoreCase);
static readonly Dictionary<int, string> _clientProgressDic = new Dictionary<int, string>();
public async Task StartProcessing(string jsonString)
{
SwapTradeSendEmailReq req = JsonHelper.Deserialize<SwapTradeSendEmailReq>(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<string> 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);
}
}
}
+2 -2
View File
@@ -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", "");
+2 -2
View File
@@ -9,9 +9,9 @@ namespace YLErp.Web.Models
/// <summary>
/// 回退到某一时间
/// </summary>
[DisplayName("回退至")]
//[DisplayName("回退至")]
public DateTime ValueDate { get; set; }
[DisplayName("回退至")]
public DateTime TradeDate { get; set; }
}
}
+1
View File
@@ -153,6 +153,7 @@ try
{
endpoints.MapHub<SwapFlowCombookingHub>("/swapflow/combookinghub"); // 映射Hub路径
endpoints.MapHub<SwapFlowResetHub>("/swapflow/resethub"); // 映射Hub路径
endpoints.MapHub<SwapConfirmSendEmailHub>("/tradeconfirm/sendemailhub"); // 映射Hub路径
});
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".pdf"] = "application/pdf";
+2 -2
View File
@@ -5,7 +5,7 @@
}
@section JS
{
{
<script type="text/javascript">
$(function () {
$(".datepicker").datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, showOtherMonths: true, selectOtherMonths: true });
@@ -46,7 +46,7 @@
<form id="tradeBackForm" method="post" onsubmit="return false;">
<div class="form-layout">
<input type="hidden" value="@Model.TradeId" name="TradeId" id="TradeId" />
@Html.MyDateFor(model => model.ValueDate, true)
@Html.MyDateFor(model => model.TradeDate, true)
</div>
<div class="form-buttons">
@@ -45,6 +45,7 @@
</style>
}
@section JS{
<script src="~/statics/libs/signalr/dist/browser/signalr.min.js"></script>
<script src="~/Scripts/app/tradeHelper.js?v=@HtmlUtil.JsVersion"></script>
<script type="text/javascript">
var page = @Json.Serialize(pageObj);
@@ -85,6 +86,7 @@
@MyControls.Btn("批量生成交易确认书", "BatchCreateContracts()")
}
@MyControls.Btn("批量下载交易确认书", "BatchDownLoadDoc()")
<button class="btn btn-primary" id="batchSendEmail" style="margin-left:16px;">批量发送邮件</button>
@if (PS.GetErpConfig().IsAutoSealAndUploadFiles && !PS.GetErpConfig().IsAutoSealAfterGeneratedBook)
{
@MyControls.Btn("批量确认书用印", "BatchSealContracts()")
@@ -1639,30 +1639,6 @@ var colModel_trade = [
formatter: function (cellvalue, options, rowObject) {
return formatQuotaAbs(rowObject, 'DeltaCash');
}
}, {
name: 'PnL',
label: '盈亏',
index: 'PnL',
width: 120,
align: 'right',
sortable: false,
formatter: function (cellvalue, options, rowObject) {
return !cellvalue || cellvalue == "NaN" ? "" : cellvalue.toLocaleString();
},
cellattr: function (cellvalue, options, rowObject) {
var style = "style='" + checkQuota(rowObject, 'PnL', 'Loss') + "'";
return style;
}
}, {
name: 'Quota_Loss_Upper',
label: '止损限额',
index: 'Quota_Loss_Upper',
width: 120,
align: 'right',
sortable: false,
formatter: function (cellvalue, options, rowObject) {
return formatQuotaAbs(rowObject, 'Loss');
}
}, {
name: 'Quota_SwapPercent_Upper',
label: '互换价格偏离比例限额',
@@ -184,7 +184,7 @@ function SearchClick(isSearchclick) {
listGrid.trigger('reloadGrid');
}
function SendEmail(event_id, client_id,event_date) {
function SendEmail(event_id, client_id, event_date) {
var emailData = [{ client_id: client_id, event_id: event_id }];
var postData = { EventEmailEmails: emailData, ValueDate: event_date }
SendEmailAjax(postData);
@@ -196,11 +196,15 @@ function SendEmailAll() {
return;
}
var emailDataArr = [];
var valueDate;
var valueDate = $("#DateValueDate").val();
if (!valueDate || valueDate.lenth == 0) {
main.message("请选择日期");
return;
}
for (var i = 0; i < rowSelectObjs.length; i++) {
var emailData = { client_id: rowSelectObjs[i].client_id, event_id: rowSelectObjs[i].event_id };
event_date = rowSelectObjs[i].event_date;
if (rowSelectObjs[i].send_email!=true) {
if (rowSelectObjs[i].send_email != true) {
emailDataArr.push(emailData);
}
}
@@ -215,10 +219,10 @@ function SendEmailAjax(postData) {
main.post("/SwapEventEmail/SendEmail", postData).done(function (resp) {
SearchClick();
})
}
}
function EditSettlementEmail() {
var emails = $("#SettlementEmail").val();
if (emails != undefined && emails!="") {
if (emails != undefined && emails != "") {
var emailArr = emails.split(';');
var checkEmailError = false;
emailArr.forEach((item) => {
@@ -19,7 +19,7 @@ const vue = new Vue({
multiplier: 1,
oriClosePercent: model.ClosePercent,
ratio: 1,
shortRatio:1,
shortRatio: 1,
},
computed: {
maxUnwindDate() {
@@ -194,11 +194,12 @@ const vue = new Vue({
let longRatio = thisObj.floatPosition.PositionType == 1 ? 1 : -1;
let TradingFee = thisObj.floatPosition.TradingFee == "" ? 0 : parseFloat(thisObj.floatPosition.TradingFee);
let TradingFeePending = thisObj.floatPosition.TradingFeePending == "" ? 0 : parseFloat(thisObj.floatPosition.TradingFeePending);
thisObj.floatPosition.MarkClosePnl = thisObj.deal.CloseNotionalValue * (thisObj.floatPosition.TradingAmountAvg - thisObj.initPosiNetPrice) * floatRatio * longRatio;
thisObj.floatPosition.MarkClosePnl = thisObj.floatPosition.MarkClosePnl + (TradingFee + TradingFeePending) * floatRatio*-1 + parseFloat(thisObj.floatPosition.DividendIn);
thisObj.floatPosition.MarkClosePnl = Math.round(thisObj.deal.CloseNotionalValue * (thisObj.floatPosition.TradingAmountAvg - thisObj.initPosiNetPrice) * floatRatio * longRatio * 10000) / 10000;
thisObj.floatPosition.MarkClosePnl = Number(thisObj.floatPosition.MarkClosePnl.toFixed(2));
thisObj.floatPosition.MarkClosePnl = thisObj.floatPosition.MarkClosePnl + (TradingFee + TradingFeePending) * floatRatio * -1 + parseFloat(thisObj.floatPosition.DividendIn);
thisObj.floatPosition.MarkClosePnl = otcformat.trading.StockEqvNotional(thisObj.floatPosition.MarkClosePnl);
thisObj.calcCloseAmount();
},
changeTradingFee() {//修改交易费用
this.calcFloatClosePnl();
@@ -244,6 +245,8 @@ const vue = new Vue({
thisObj.deal.SwapRealizedPnL = parseFloat(thisObj.deal.SwapRealizedPnL) + interestAmount;
thisObj.deal.SwapMarginAmount = parseFloat(thisObj.deal.SwapMarginAmount) + parseFloat(x.InterestPrincipal) * interestRatio;
});
thisObj.deal.SwapRealizedPnL = Number(thisObj.deal.SwapRealizedPnL.toFixed(2));
thisObj.deal.SwapCloseAmount = Number(thisObj.deal.SwapCloseAmount.toFixed(2));
thisObj.deal.SwapCloseAmount = otcformat.trading.StockEqvNotional(thisObj.deal.SwapCloseAmount);
thisObj.deal.SwapRealizedPnL = otcformat.trading.StockEqvNotional(thisObj.deal.SwapRealizedPnL);
thisObj.deal.SwapMarginRebatePnl = otcformat.trading.StockEqvNotional(thisObj.deal.SwapMarginRebatePnl);
@@ -18,10 +18,24 @@ const colModelGrid = (new function () {
{
name: '',
label: '操作',
width: 350,
width: 450,
align: 'left',
formatter: showToolName
},
{
name: 'MetaDic.send_email_result',
label: '邮件状态',
index: 'MetaDic.send_email_result',
sortIndex: i++,
width: 70,
align: 'left',
sortable: false,
formatter: function (cellValue, options, rowObject) {
var html = "";
html += "<lable id=\"email_result{0}\">{1}</lable>".template(rowObject.id, rowObject.MetaDic.send_email_result);
return html;
}
},
{
name: 'EncryptId',
hidden: true,
@@ -303,7 +317,7 @@ const colModelGrid = (new function () {
});
}
this.ViewErrInfo = function (code) {
main.post("/trade/GetSealErrMsg/", {code:code},
main.post("/trade/GetSealErrMsg/", { code: code },
{
success: function (resp) {
main.alert(resp.msg);
@@ -320,23 +334,23 @@ const colModelGrid = (new function () {
align: 'left',
formatter: function (cellValue, options, rowObject) {
var templateHtml = "";
if(page.IsAutoSealAndUploadFiles && !page.IsAutoSealAfterGeneratedBook){
if (page.IsAutoSealAndUploadFiles && !page.IsAutoSealAfterGeneratedBook) {
templateHtml += "<input type=\"button\" class=\"wentiEdit\" {2} value=\"用印\" />";
}
var canGenerate = page.canGenerate == true ? "" : "disabled";
templateHtml += "<input type=\"button\" class=\"wentiEdit\" {0} value=\"上传\" +" + canGenerate +"/>" +
templateHtml += "<input type=\"button\" class=\"wentiEdit\" {0} value=\"上传\" +" + canGenerate + "/>" +
"<input type=\"button\" class=\"wentiEdit\" {1} value=\"下载\" />";
var html = (templateHtml)
.template(
(rowObject.MetaDic.ContractDocUrl ? 'onclick="colModelGrid.upload(\'{0}\',\'{1}\')"'.template(rowObject.MetaDic.ContractEncryptId, rowObject.EncryptId) : "disabled"),
(rowObject.MetaDic.StampDocumentFileName ? 'onclick="main.downloadFiles(\'{0}\')"'.template(rowObject.MetaDic.StampDocumentFileName) : "disabled"));
if(page.IsAutoSealAndUploadFiles && !page.IsAutoSealAfterGeneratedBook) {
if (page.IsAutoSealAndUploadFiles && !page.IsAutoSealAfterGeneratedBook) {
html = (templateHtml)
.template(
(rowObject.MetaDic.ContractDocUrl ? 'onclick="colModelGrid.upload(\'{0}\',\'{1}\')"'.template(rowObject.MetaDic.ContractEncryptId, rowObject.EncryptId) : "disabled"),
(rowObject.MetaDic.StampDocumentFileName ? 'onclick="main.downloadFiles(\'{0}\')"'.template(rowObject.MetaDic.StampDocumentFileName) : "disabled"),
('onclick="SealContract(\'{0}\')"'.template(rowObject.MetaDic.ContractRId))
);
);
}
if (rowObject.MetaDic.ContractDocUrl) {
html = html + (rowObject.MetaDic.ContractStatus === "草稿" || !rowObject.MetaDic.ContractStatus ? "未用印" : rowObject.MetaDic.ContractStatus);
@@ -348,7 +362,7 @@ const colModelGrid = (new function () {
}
if (page.IsAutoSealAndUploadFiles) {
var colObj1 = {
name: 'SealResult',
label: '电子章用印结果',
@@ -503,6 +517,7 @@ $(function () {
let underlyingCtrl = new tradeHelper.UnderlyingSelectCtrl('#UnderlyingId').setFlag(tradeHelper.UnderlyingSelectFlag.OtcTrade);
ContractTypeCtrl = new ContractTypeCtrl(document.getElementById('ContractTypeCtrl'));
SendEmailHub();
});
function gridComplete() {
@@ -604,7 +619,7 @@ function BatchDownLoadDoc() {
var endDate = $("#DateToTradeDate").val();
var clientIds = $("#ClientId").val();
var tradeids = "";
var jgrid = jQuery('#listGrid');
@@ -617,8 +632,8 @@ function BatchDownLoadDoc() {
'<div class="form-group">' +
'<label style="padding:10px 12px 10px">' + tip + '</label><br />' +
'<label class="col-sm-5 control-label">文档类型</label>' +
'<label class="btn btn-sm btn-primary" style="border:none"><input type="checkbox" checked name="docType" value="PDF"> PDF</label>' +
'<label class="btn btn-sm btn-primary" style="border:none"><input type="checkbox" checked name="docType" value="DOC"> DOC</label>';
'<label class="btn btn-sm btn-primary" style="border:none"><input type="checkbox" checked name="docType" value="DOC"> DOC</label>' +
'<label class="btn btn-sm btn-primary" style="border:none"><input type="checkbox" checked name="docType" value="PDF"> PDF</label>';
if (page.IsZheQi) {
htmlContent += '<br/><label class="col-sm-5 control-label">下载用印文件</label>' +
'<select id="Seal" style="margin-top:5px;"><option>是</option><option>否</option></select>';
@@ -783,60 +798,51 @@ function BatchMailContracts() {
}
function SealContract(id){
function SealContract(id) {
var ids = [];
ids.push(id);
main.post("/trade/IsContractGenerated/", { ids: ids,types:["交易确认书"] }).done(function (res) {
if (res.success) {
main.post("/trade/SealContracts/", { ids: ids,types:["交易确认书"] }).done(function (resp) {
if (resp.success) {
SearchClick(true);
}
});
}
}).fail(function(res){
});
}
function BatchSealContracts(){
var jgrid = jQuery('#listGrid');
var ids = main.GetGridIds(jgrid,"MetaDic.ContractRId");
if (ids.length == 0) {
main.alert("请至少选择一笔交易"); return;
}
main.post("/trade/IsContractGenerated/", { ids: ids,types:["交易确认书"] }).done(function (res) {
main.post("/trade/IsContractGenerated/", { ids: ids, types: ["交易确认书"] }).done(function (res) {
if (res.success) {
main.post("/trade/SealContracts/", { ids: ids,types:["交易确认书"] }).done(function (res) {
if (res.success) {
main.post("/trade/SealContracts/", { ids: ids, types: ["交易确认书"] }).done(function (resp) {
if (resp.success) {
SearchClick(true);
}
});
}
}).fail(function(res){
}).fail(function (res) {
});
}
function sentMail(tradeid,clientid) {
var url = "/trs_hub_api/swap/email/confirm/send?tradeId=" + tradeid;
$.ajax({
type: "get",
url: url,
success: function (res) {
},
beforeSend(jqXHR) {
main.waitMe(true);
},
complete(jqXHR, textStatus) {
main.waitMe(false);
function BatchSealContracts() {
var jgrid = jQuery('#listGrid');
var ids = main.GetGridIds(jgrid, "MetaDic.ContractRId");
if (ids.length == 0) {
main.alert("请至少选择一笔交易"); return;
}
main.post("/trade/IsContractGenerated/", { ids: ids, types: ["交易确认书"] }).done(function (res) {
if (res.success) {
main.post("/trade/SealContracts/", { ids: ids, types: ["交易确认书"] }).done(function (res) {
if (res.success) {
SearchClick(true);
}
});
}
}).fail(function (res) {
});
}
function sentMail(tradeid, clientid) {
main.post("/swaptrade2/SendConfimEmail?tradeId=" + tradeid).done(function (res) {
if (res.success) {
SearchClick(true);
}
});
}
function showDownload(cellvalue, options, rowObject) {
@@ -860,8 +866,8 @@ function showToolName(cellValue, options, rowObject) {
var title = page.IsAutoSealAndUploadFiles && page.IsAutoSealAfterGeneratedBook ? "生成并用印" : "生成确认书";
var canGenerate = page.canGenerate == true ? "" : "disabled";
var isWait = (rowObject.MetaDic.SealResult == "用印等待中");
html += "<input type=\"button\" class='wentiEdit' title='{2}' onclick=\"gJGenerateConfirmBook({0},{3},{1})\" value='{2}' {4}/>".template(rowObject.id, rowObject.MetaDic.HasGeneratedConfirmBook, title, isWait, canGenerate);
var isWait = (rowObject.MetaDic.SealResult == "用印等待中");
html += "<input type=\"button\" class='wentiEdit' title='{2}' onclick=\"gJGenerateConfirmBook({0},{3},{1})\" value='{2}' {4}/>".template(rowObject.id, rowObject.MetaDic.HasGeneratedConfirmBook, title, isWait, canGenerate);
if (rowObject.MetaDic.ContractDocUrl && page.canSendEmail == true) {
html += "<input type=\"button\" class=\"wentiEdit\" title='发送交易所在的交易确认书到客户对应接收Email' onclick=\"sentMail('{0}','{2}')\" value=\"{1}\" />"
.template(rowObject.id, "发送Email", rowObject.ClientId);
@@ -871,12 +877,11 @@ function showToolName(cellValue, options, rowObject) {
}
var canUpload = page.canGenerate == true && rowObject.MetaDic.ContractDocUrl ? "" : "disabled";
html += "<input type=\"button\" class=\"wentiEdit\" value=\"上传\" onclick=\"colModelGrid.uploadNew('{0}')\" {1} />".template(rowObject.MetaDic.ContractEncryptId, canUpload);
return html;
}
function starttradeView(id, tradeType) {
if (tradeType.indexOf("收益互换") >= 0 || tradeType=="多空组合") {
if (tradeType.indexOf("收益互换") >= 0 || tradeType == "多空组合") {
main.open("查看交易", "/swaptrade2/tradeView/?enid=" + id + "&isOnlyCloseButton=true", { area: ['90%', '90%'] });
}
else {
@@ -945,7 +950,7 @@ function showcolumnChooser() {
main.showcolumnChooser(jgrid, page.configcolumn);
}
function gJGenerateConfirmBook(id, isWait,hasGeneratedConfirmBook) {
function gJGenerateConfirmBook(id, isWait, hasGeneratedConfirmBook) {
if (page.IsAutoSealAndUploadFiles) {
//if (isWait) {
@@ -959,15 +964,15 @@ function gJGenerateConfirmBook(id, isWait,hasGeneratedConfirmBook) {
}
if (hasGeneratedConfirmBook == "True") {
if (!page.IsAutoSealAndUploadFiles) {
if (!confirm("确认覆盖已有的交易确认书?")) {
return;
}
}
}
var tradeIds = [];
@@ -994,7 +999,7 @@ function gJGenerateConfirmBook(id, isWait,hasGeneratedConfirmBook) {
// });
//}
}
@@ -1037,8 +1042,8 @@ function gJGenerateConfirmBook(id, isWait,hasGeneratedConfirmBook) {
'<div class="form-group">' +
'<label class="col-sm-4 control-label">文档类型</label>' +
'<div class="btn-group col-sm-8" data-toggle="buttons">' +
'<label class="btn btn-sm btn-primary active" style="border:none"><input type="radio" checked name="docType" value="PDF"> PDF</label>' +
'<label class="btn btn-sm btn-primary" style="border:none"><input type="radio" name="docType" value="DOCX"> DOC</label>' +
'<label class="btn btn-sm btn-primary" style="border:none"><input type="radio" checked name="docType" value="DOCX"> DOC</label>' +
'<label class="btn btn-sm btn-primary active" style="border:none"><input type="radio" name="docType" value="PDF"> PDF</label>' +
'</div>' +
'</div>' +
templateHtml +
@@ -1122,4 +1127,50 @@ function setValidation(elId, selectedDate, isSetMax) {
function ConfirmTemplateChoose() {
window.location.href = "/client/ClientTemplateChoose";
}
// 交易确认书邮件发送
function SendEmailHub() {
// 创建SignalR连接并连接到服务器上的Hub
var connection = new signalR.HubConnectionBuilder()
.withUrl('/tradeconfirm/sendemailhub')
.build();
connection.start()
.then(function () {
$("#batchSendEmail").click(function () {
var jgrid = jQuery('#listGrid');
var ids = main.GetGridIds(jgrid);
if (ids.length == 0) {
main.alert("请至少选择一笔交易"); return;
}
var req = {
tradeIds: ids,
}
connection.invoke('StartProcessing', JSON.stringify(req));
main.waitMe(true);
});
}).catch(function (error) {
console.error(error);
});;
// 监听服务器发送的消息。
connection.on('UpdateProgress', function (msg) {
if (msg != null && msg != '') {
let jsonObject = JSON.parse(msg);
$("#email_result" + jsonObject.tradeId).text(jsonObject.send_email_result);
}
});
// 监听服务器发送的异常消息。
connection.on('ExceptionMessage', function (msg) {
if (msg.indexOf("正在发送邮件") < 0) {
main.waitMe(false);
SearchClick(true);
}
main.alert(msg);
});
// 监听服务器发送的完成消息。
connection.on('ProcessCompleted', function () {
main.alert("邮件发送处理完毕");
main.waitMe(false);
SearchClick(true);
});
}