@@ -0,0 +1,66 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace YLErp.DBModels
|
||||
{
|
||||
[Table("eod_bond_lending_rate")]
|
||||
public class eod_bond_lending_rate
|
||||
{
|
||||
[Key]
|
||||
public long id { get; set; }
|
||||
|
||||
[DisplayName("业务唯一代码")]
|
||||
public string RecordCode { get; set; }
|
||||
|
||||
[DisplayName("业务日期")]
|
||||
public DateTime ValueDate { get; set; }
|
||||
|
||||
[DisplayName("标的债券代码")]
|
||||
public string UnderlyingSecurityId { get; set; }
|
||||
|
||||
[DisplayName("标的债券名称")]
|
||||
public string UnderlyingSymbol { get; set; }
|
||||
|
||||
[DisplayName("前收盘费率(%)")]
|
||||
public decimal? PreCloseRate { get; set; }
|
||||
|
||||
[DisplayName("前加权平均费率(%)")]
|
||||
public decimal? PreWeightedAvgRate { get; set; }
|
||||
|
||||
[DisplayName("开盘费率(%)")]
|
||||
public decimal? OpenRate { get; set; }
|
||||
|
||||
[DisplayName("最新费率(%)")]
|
||||
public decimal? LatestRate { get; set; }
|
||||
|
||||
[DisplayName("最高费率(%)")]
|
||||
public decimal? HighRate { get; set; }
|
||||
|
||||
[DisplayName("最低费率(%)")]
|
||||
public decimal? LowRate { get; set; }
|
||||
|
||||
[DisplayName("收盘费率(%)")]
|
||||
public decimal? CloseRate { get; set; }
|
||||
|
||||
[DisplayName("加权平均费率(%)")]
|
||||
public decimal? WeightedAvgRate { get; set; }
|
||||
|
||||
[DisplayName("成交量(元)")]
|
||||
public decimal? TurnoverAmount { get; set; }
|
||||
|
||||
[DisplayName("操作人ID")]
|
||||
public int OptId { get; set; }
|
||||
|
||||
[DisplayName("操作人名称")]
|
||||
public string OptName { get; set; }
|
||||
|
||||
[DisplayName("操作时间")]
|
||||
public DateTime OptDate { get; set; }
|
||||
|
||||
[DisplayName("数据来源")]
|
||||
public string DataSource { get; set; }
|
||||
|
||||
[DisplayName("源行情时间")]
|
||||
public string SourceTime { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -255,6 +255,7 @@ namespace YLErp.BLL
|
||||
public DbSet<eod_trade_risk_hedgevol_s> eod_trade_risk_hedgevol_s { get; set; }
|
||||
public DbSet<eod_trade_risk_openvol_s> eod_trade_risk_openvol_s { get; set; }
|
||||
public DbSet<eod_currency_rate> eod_currency_rate { get; set; }
|
||||
public DbSet<eod_bond_lending_rate> eod_bond_lending_rate { get; set; }
|
||||
public DbSet<StockBlackWhite> Stock_BlackWhite { get; set; }
|
||||
public DbSet<SalesCommissionInfo> SalesCommissionInfo { get; set; }
|
||||
public DbSet<SalesCommissionDetail> SalesCommissionDetail { get; set; }
|
||||
|
||||
@@ -280,6 +280,36 @@ namespace YLErp.Modules.DataProviderModule
|
||||
return bondPrice;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取债券借贷费率最新行情
|
||||
/// </summary>
|
||||
/// <param name="valueDate"></param>
|
||||
/// <param name="underlyingSecurityId"></param>
|
||||
/// <returns></returns>
|
||||
public static eod_bond_lending_rate GetBondLendingRate(DateTime valueDate, string underlyingSecurityId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(underlyingSecurityId))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var db = DbContextFactory.GetYLDbContext();
|
||||
return db.eod_bond_lending_rate
|
||||
.Where(x => x.UnderlyingSecurityId == underlyingSecurityId && x.ValueDate <= valueDate.Date)
|
||||
.OrderByDescending(x => x.ValueDate)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
/// <summary>
|
||||
/// 尝试获取债券借贷费率最新行情
|
||||
/// </summary>
|
||||
/// <param name="valueDate"></param>
|
||||
/// <param name="underlyingSecurityId"></param>
|
||||
/// <param name="bondLendingRate"></param>
|
||||
/// <returns></returns>
|
||||
public static bool TryGetBondLendingRate(DateTime valueDate, string underlyingSecurityId, out eod_bond_lending_rate bondLendingRate)
|
||||
{
|
||||
return (bondLendingRate = GetBondLendingRate(valueDate, underlyingSecurityId)) != null;
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取标的收盘价格
|
||||
/// </summary>
|
||||
/// <param name="code">标的代码</param>
|
||||
|
||||
@@ -26,6 +26,13 @@ namespace YLErp.Modules.RiskEngine
|
||||
/// </summary>
|
||||
public string TriggerPoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前平仓请求提交的平仓日期
|
||||
/// </summary>
|
||||
public DateTime? UnwindDate { get; set; }
|
||||
|
||||
public DateTime? PayDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 数据库上下文,供规则公式直接查询数据库
|
||||
/// </summary>
|
||||
@@ -396,6 +403,8 @@ namespace YLErp.Modules.RiskEngine
|
||||
{
|
||||
TradeId = ctx.TradeId,
|
||||
TriggerPoint = ctx.TriggerPoint,
|
||||
UnwindDate = ctx.UnwindDate,
|
||||
PayDate = ctx.PayDate,
|
||||
DbContext = ctx.DbContext
|
||||
};
|
||||
return runner(globals).GetAwaiter().GetResult();
|
||||
|
||||
@@ -14,11 +14,33 @@ namespace YLErp.Modules.RiskEngine
|
||||
/// </summary>
|
||||
public static class RiskCalendarHelper
|
||||
{
|
||||
private const string CalendarDateFormat = "yyyy,MM,dd";
|
||||
|
||||
/// <summary>
|
||||
/// 日历数据异常直接影响平仓日期校验和上一交易日取数,单独使用固定 logger 名称便于线上按模块检索。
|
||||
/// </summary>
|
||||
private static readonly IYcLogger Logger = LogFactory.GetLogger("RiskCalendarHelper");
|
||||
|
||||
/// <summary>
|
||||
/// calendar.HolidayJson 历史主格式是 yyyy,MM,dd;这里额外兼容常见日期格式,避免历史数据被静默当作交易日。
|
||||
/// 解析后统一转成 DateTime.Date,后续交易日判断不再依赖原始字符串格式。
|
||||
/// </summary>
|
||||
private static readonly string[] SupportedCalendarDateFormats =
|
||||
{
|
||||
CalendarDateFormat,
|
||||
"yyyy/MM/dd",
|
||||
"yyyy-MM-dd",
|
||||
"yyyyMMdd",
|
||||
"yyyy-MM-ddTHH:mm:ss",
|
||||
"yyyy-MM-ddTHH:mm:ssK",
|
||||
"yyyy-MM-ddTHH:mm:ss.fffK"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 按当前风控执行使用的数据库上下文保存日历缓存,同一次风控检查内复用,数据库上下文释放后不阻止缓存被回收。
|
||||
/// </summary>
|
||||
private static readonly ConditionalWeakTable<YLContext, Dictionary<string, HashSet<string>>> HolidayCaches =
|
||||
new ConditionalWeakTable<YLContext, Dictionary<string, HashSet<string>>>();
|
||||
private static readonly ConditionalWeakTable<YLContext, Dictionary<string, HashSet<DateTime>>> HolidayCaches =
|
||||
new ConditionalWeakTable<YLContext, Dictionary<string, HashSet<DateTime>>>();
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定日期的上一银行间交易日。
|
||||
@@ -33,6 +55,24 @@ namespace YLErp.Modules.RiskEngine
|
||||
return GetPreviousTradingDay(dbContext, date, "IB", "银行间");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断指定日期是否为银行间交易日。
|
||||
/// </summary>
|
||||
/// <param name="dbContext">当前风控执行使用的数据库上下文。</param>
|
||||
/// <param name="date">待判断的平仓日期。</param>
|
||||
/// <returns>日期不在银行间非交易日集合中时返回 true。</returns>
|
||||
/// <exception cref="ArgumentNullException">数据库上下文为空。</exception>
|
||||
/// <exception cref="Exception">缺少银行间日历或日历内容异常。</exception>
|
||||
public static bool IsInterbankTradingDay(YLContext dbContext, DateTime date)
|
||||
{
|
||||
if (dbContext == null)
|
||||
throw new ArgumentNullException(nameof(dbContext));
|
||||
|
||||
var holidayCache = HolidayCaches.GetOrCreateValue(dbContext);
|
||||
var holidays = GetHolidays(dbContext, date.Year, "IB", "银行间", holidayCache);
|
||||
return !holidays.Contains(date.Date);
|
||||
}
|
||||
|
||||
public static DateTime GetPreviousExchangeTradingDay(YLContext dbContext, DateTime date)
|
||||
{
|
||||
return GetPreviousTradingDay(dbContext, date, "CHN", "交易所");
|
||||
@@ -51,10 +91,9 @@ namespace YLErp.Modules.RiskEngine
|
||||
for (var i = 0; i < 370; i++)
|
||||
{
|
||||
var holidays = GetHolidays(dbContext, currentDate.Year, country, calendarName, holidayCache);
|
||||
var currentDateText = currentDate.ToString("yyyy,MM,dd", CultureInfo.InvariantCulture);
|
||||
|
||||
// calendar.HolidayJson 存的是非交易日;不在非交易日集合内,即认为是对应市场的交易日。
|
||||
if (!holidays.Contains(currentDateText))
|
||||
if (!holidays.Contains(currentDate))
|
||||
return currentDate;
|
||||
|
||||
currentDate = currentDate.AddDays(-1);
|
||||
@@ -64,30 +103,51 @@ namespace YLErp.Modules.RiskEngine
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定年份的银行间非交易日集合。
|
||||
/// 获取指定年份的非交易日集合。
|
||||
/// </summary>
|
||||
/// <param name="dbContext">当前风控执行使用的数据库上下文。</param>
|
||||
/// <param name="year">日历年份。</param>
|
||||
/// <param name="holidayCache">单次风控检查内按市场和年份共享的非交易日缓存。</param>
|
||||
/// <returns>格式为 yyyy,MM,dd 的非交易日集合。</returns>
|
||||
private static HashSet<string> GetHolidays(YLContext dbContext, int year, string country, string calendarName, Dictionary<string, HashSet<string>> holidayCache)
|
||||
/// <returns>按 Date 归一化后的非交易日集合。</returns>
|
||||
private static HashSet<DateTime> GetHolidays(YLContext dbContext, int year, string country, string calendarName, Dictionary<string, HashSet<DateTime>> holidayCache)
|
||||
{
|
||||
// 缓存需要同时区分市场和年份,避免银行间与交易所同一年日历相互串用。
|
||||
var cacheKey = $"{country.ToUpperInvariant()}:{year}";
|
||||
var normalizedCountry = NormalizeCountry(country);
|
||||
var cacheKey = $"{normalizedCountry}:{year}";
|
||||
if (holidayCache.TryGetValue(cacheKey, out var holidays))
|
||||
return holidays;
|
||||
|
||||
// 同一年可能存在多种市场日历,按规则对应的市场代码读取非交易日。
|
||||
var calendar = dbContext.calendar
|
||||
.Where(c => c.Year == year && (c.ValidState == null || c.ValidState != ConsGlobal.InValid))
|
||||
.ToList()
|
||||
.FirstOrDefault(c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
|
||||
// 先按年份和有效状态缩小范围,再在内存里做 Trim + ToUpperInvariant 匹配,兼容历史 Country 存在大小写或前后空格的情况。
|
||||
// 这里没有在数据库查询里直接 Trim,是为了避免不同 EF/数据库提供方对字符串函数翻译不一致。
|
||||
var validCalendars = dbContext.calendar
|
||||
.Where(c => c.Year == year
|
||||
&& (c.ValidState == null || c.ValidState != ConsGlobal.InValid)
|
||||
&& c.Country != null)
|
||||
.ToList();
|
||||
var matchedCalendars = validCalendars.Where(c => NormalizeCountry(c.Country) == normalizedCountry).ToList();
|
||||
var calendar = matchedCalendars.FirstOrDefault();
|
||||
|
||||
if (calendar == null)
|
||||
throw new Exception($"未找到{year}年{calendarName}日历");
|
||||
{
|
||||
var availableCountries = string.Join(",", validCalendars.Select(c => c.Country?.Trim()).Where(c => !string.IsNullOrWhiteSpace(c)).Distinct());
|
||||
Logger.Error($"[风控日历] 未找到目标市场日历 - Year:{year}, CalendarName:{calendarName}, Country:{normalizedCountry}, AvailableCountries:{availableCountries}");
|
||||
throw new Exception($"未找到{year}年{calendarName}日历,Country={normalizedCountry},当前可用日历:{availableCountries}");
|
||||
}
|
||||
if (matchedCalendars.Count > 1)
|
||||
{
|
||||
// 多条匹配不改变原有“取第一条”的行为,只记录数据质量问题,避免线上突然因历史重复配置中断风控。
|
||||
Logger.Info($"[风控日历] 同一年存在多个匹配市场日历,使用第一条 - Year:{year}, CalendarName:{calendarName}, Country:{normalizedCountry}, MatchedIds:{string.Join(",", matchedCalendars.Select(c => c.id))}");
|
||||
}
|
||||
if (!string.Equals(calendar.Country, normalizedCountry, StringComparison.Ordinal))
|
||||
{
|
||||
// Country 能通过归一化匹配说明历史数据存在大小写或空格差异,只在日历首次加载时记录一次,便于后续清洗数据。
|
||||
Logger.Info($"[风控日历] 日历Country已归一化匹配 - Year:{year}, CalendarName:{calendarName}, RawCountry:{calendar.Country}, NormalizedCountry:{normalizedCountry}, CalendarId:{calendar.id}");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(calendar.HolidayJson))
|
||||
{
|
||||
Logger.Error($"[风控日历] HolidayJson为空 - Year:{year}, CalendarName:{calendarName}, Country:{normalizedCountry}, CalendarId:{calendar.id}");
|
||||
throw new Exception($"{year}年{calendarName}日历HolidayJson为空");
|
||||
}
|
||||
|
||||
List<string> holidayList;
|
||||
try
|
||||
@@ -96,12 +156,70 @@ namespace YLErp.Modules.RiskEngine
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error($"[风控日历] HolidayJson解析失败 - Year:{year}, CalendarName:{calendarName}, Country:{normalizedCountry}, CalendarId:{calendar.id}, Error:{ex.Message}");
|
||||
throw new Exception($"{year}年{calendarName}日历HolidayJson解析失败", ex);
|
||||
}
|
||||
|
||||
holidays = new HashSet<string>(holidayList ?? new List<string>());
|
||||
// 日历解析和日志统计只在缓存未命中时执行;同一次风控检查内重复判断交易日不会重复解析 HolidayJson。
|
||||
holidays = NormalizeHolidays(holidayList, year, calendarName, normalizedCountry, calendar.id);
|
||||
holidayCache[cacheKey] = holidays;
|
||||
return holidays;
|
||||
}
|
||||
|
||||
private static string NormalizeCountry(string country)
|
||||
{
|
||||
return (country ?? string.Empty).Trim().ToUpperInvariant();
|
||||
}
|
||||
|
||||
private static HashSet<DateTime> NormalizeHolidays(IEnumerable<string> holidayList, int year, string calendarName, string normalizedCountry, int calendarId)
|
||||
{
|
||||
var holidays = new HashSet<DateTime>();
|
||||
var formatCounts = new Dictionary<string, int>();
|
||||
var rawCount = 0;
|
||||
var blankCount = 0;
|
||||
var duplicateCount = 0;
|
||||
foreach (var holidayText in holidayList ?? Enumerable.Empty<string>())
|
||||
{
|
||||
rawCount++;
|
||||
if (string.IsNullOrWhiteSpace(holidayText))
|
||||
{
|
||||
blankCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 每条原始日期只在缓存加载阶段解析一次;正常数据只累计格式分布,避免大量节假日逐条写日志。
|
||||
var holidayDate = ParseHolidayDate(holidayText, year, calendarName, normalizedCountry, calendarId, out var matchedFormat);
|
||||
if (!holidays.Add(holidayDate))
|
||||
{
|
||||
duplicateCount++;
|
||||
}
|
||||
formatCounts[matchedFormat] = formatCounts.TryGetValue(matchedFormat, out var count) ? count + 1 : 1;
|
||||
}
|
||||
Logger.Info($"[风控日历] HolidayJson日期归一化完成 - Year:{year}, CalendarName:{calendarName}, Country:{normalizedCountry}, CalendarId:{calendarId}, RawCount:{rawCount}, HolidayCount:{holidays.Count}, BlankCount:{blankCount}, DuplicateCount:{duplicateCount}, Formats:{string.Join(",", formatCounts.Select(item => item.Key + ":" + item.Value))}");
|
||||
return holidays;
|
||||
}
|
||||
|
||||
private static DateTime ParseHolidayDate(string holidayText, int year, string calendarName, string normalizedCountry, int calendarId, out string matchedFormat)
|
||||
{
|
||||
var normalizedHolidayText = holidayText.Trim();
|
||||
foreach (var format in SupportedCalendarDateFormats)
|
||||
{
|
||||
if (DateTime.TryParseExact(normalizedHolidayText, format, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var holidayDate))
|
||||
{
|
||||
matchedFormat = format;
|
||||
return holidayDate.Date;
|
||||
}
|
||||
}
|
||||
|
||||
// 支持带时区的历史数据;最终取日期部分用于非交易日集合匹配,避免字符串格式差异导致静默漏判。
|
||||
if (DateTimeOffset.TryParse(normalizedHolidayText, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out var holidayDateOffset))
|
||||
{
|
||||
matchedFormat = "DateTimeOffset.TryParse";
|
||||
return holidayDateOffset.Date;
|
||||
}
|
||||
|
||||
Logger.Error($"[风控日历] HolidayJson日期格式无法识别 - Year:{year}, CalendarName:{calendarName}, Country:{normalizedCountry}, CalendarId:{calendarId}, RawValue:{holidayText}");
|
||||
throw new Exception($"{year}年{calendarName}日历HolidayJson存在无法识别的日期格式:{holidayText}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,13 @@ namespace YLErp.Modules.RiskEngine
|
||||
/// </summary>
|
||||
public string TriggerPoint { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前平仓请求提交的平仓日期,供平仓阶段规则直接使用。
|
||||
/// </summary>
|
||||
public DateTime? UnwindDate { get; set; }
|
||||
|
||||
public DateTime? PayDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 数据库上下文,供规则公式直接查询数据库
|
||||
/// </summary>
|
||||
|
||||
@@ -202,8 +202,7 @@ namespace YLErp.Modules.RiskEngine
|
||||
"BOOK_CONFIRM",
|
||||
"CLOSE_REVIEW",
|
||||
"UPLOAD_CONFIRMATION",
|
||||
"EVENT_TRIGGER",
|
||||
"FUND_PAYMENT"
|
||||
"EVENT_TRIGGER"
|
||||
};
|
||||
|
||||
|
||||
@@ -792,11 +791,10 @@ namespace YLErp.Modules.RiskEngine
|
||||
|
||||
private static readonly Dictionary<string, string> TriggerPointCnMap = new Dictionary<string, string>
|
||||
{
|
||||
["BOOK_CONFIRM"] = "交易录入确认",
|
||||
["CLOSE_REVIEW"] = "平仓审核",
|
||||
["BOOK_CONFIRM"] = "簿记交易确认",
|
||||
["CLOSE_REVIEW"] = "平仓审核提交",
|
||||
["UPLOAD_CONFIRMATION"] = "上传确认书",
|
||||
["EVENT_TRIGGER"] = "事件触发",
|
||||
["FUND_PAYMENT"] = "资金支付"
|
||||
["EVENT_TRIGGER"] = "事件发生时"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Qdp.Foundation.Utilities;
|
||||
using YLErp.BLL;
|
||||
using YLErp.DBModels;
|
||||
using YLErp.Enums;
|
||||
|
||||
namespace YLErp.Modules.RiskEngine
|
||||
{
|
||||
/// <summary>
|
||||
/// 新风控通用试算服务,负责按业务触发时点执行规则、保存试算结果并校验二次确认。
|
||||
/// </summary>
|
||||
public class RiskTrialService : YLBaseService
|
||||
{
|
||||
private readonly IYcLogger _logger = LogFactory.GetLogger("RiskTrialService");
|
||||
|
||||
/// <summary>
|
||||
/// 使用当前业务服务的用户和数据库上下文创建新风控试算服务。
|
||||
/// </summary>
|
||||
/// <param name="baseService">当前业务服务。</param>
|
||||
public RiskTrialService(YLBaseService baseService) : base(baseService)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行一次独立于老风控的新风控试算并保存试算记录。
|
||||
/// quotaTrial 在现有交易确认和平仓链路中按“每次试算快照/历史流水”使用,不作为审批状态表;二次确认会重新试算并生成新的快照。
|
||||
/// </summary>
|
||||
/// <param name="context">包含交易、触发时点及业务日期的风控上下文。</param>
|
||||
/// <param name="trialSource">试算来源,由具体业务场景约定。</param>
|
||||
/// <param name="confirmation">二次确认信息;首次试算传空。</param>
|
||||
/// <returns>包含阻断、审批、提示及本次试算记录ID的统一结果。</returns>
|
||||
public RiskTrialResult CheckRisk(RiskContext context, int trialSource, RiskTrialConfirmation confirmation = null)
|
||||
{
|
||||
if (context == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(context));
|
||||
}
|
||||
if (context.TradeId <= 0)
|
||||
{
|
||||
throw new ArgumentException("交易ID必须大于0", nameof(context));
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(context.TriggerPoint))
|
||||
{
|
||||
throw new ArgumentException("风控触发时点不能为空", nameof(context));
|
||||
}
|
||||
|
||||
var ignoreRiskRuleIds = new HashSet<string>();
|
||||
var confirmationExpired = false;
|
||||
if (confirmation != null)
|
||||
{
|
||||
confirmationExpired = !TryLoadIgnoreRiskRuleIds(context, trialSource, confirmation, ignoreRiskRuleIds);
|
||||
}
|
||||
|
||||
var riskResult = new RiskEngineService(this).EvaluateRisk(context, context.TriggerPoint);
|
||||
// 与交易确认流程保持一致:二次确认放行范围包含“需审批”和“提示”,避免已确认过的提示规则重复弹出。
|
||||
var currentApprovalRules = riskResult.TriggeredRules
|
||||
.Where(rule => rule.ControlStrategy == RiskControlStrategy.Approval)
|
||||
.ToList();
|
||||
var currentTipRules = riskResult.TriggeredRules
|
||||
.Where(rule => rule.ControlStrategy == RiskControlStrategy.ShowTip)
|
||||
.ToList();
|
||||
// 二次提交时,若首次试算记录有效,则剔除已确认过的审批和提示规则;记录过期或上下文不匹配时重新展示全部当前命中的审批和提示规则。
|
||||
var pendingApprovalRules = confirmationExpired
|
||||
? currentApprovalRules
|
||||
: currentApprovalRules.Where(rule => !ignoreRiskRuleIds.Contains(rule.RuleId)).ToList();
|
||||
var pendingTipRules = confirmationExpired
|
||||
? currentTipRules
|
||||
: currentTipRules.Where(rule => !ignoreRiskRuleIds.Contains(rule.RuleId)).ToList();
|
||||
var trial = CreateQuotaTrial(context, trialSource, riskResult, pendingApprovalRules, pendingTipRules);
|
||||
// 与交易确认 RunQuotaTrial/RunNewRiskTrial 保持一致:每次风控执行保存一条 quotaTrial 快照,用于详情展示、历史追溯和二次确认时效校验,不回写上一条记录为已确认。
|
||||
new Modules.RiskModule.QuotaMonitorService(this).SaveQuotaTrial(trial);
|
||||
|
||||
var result = new RiskTrialResult
|
||||
{
|
||||
Blocked = riskResult.Blocked,
|
||||
NeedApproval = pendingApprovalRules.Any(),
|
||||
ShowTip = pendingTipRules.Any(),
|
||||
ConfirmationExpired = confirmationExpired,
|
||||
TrialDataId = trial.id,
|
||||
Message = trial.RiskWarningDetails,
|
||||
ApprovalRuleIds = pendingApprovalRules.Concat(pendingTipRules)
|
||||
.Select(rule => rule.RuleId)
|
||||
.Where(ruleId => !string.IsNullOrWhiteSpace(ruleId))
|
||||
.Distinct()
|
||||
.ToList()
|
||||
};
|
||||
result.Passed = !result.Blocked && !result.NeedApproval;
|
||||
|
||||
_logger.Info($"[新风控试算] TradeId: {context.TradeId}, TriggerPoint: {context.TriggerPoint}, TrialSource: {trialSource}, TrialDataId: {result.TrialDataId}, Passed: {result.Passed}, Blocked: {result.Blocked}, NeedApproval: {result.NeedApproval}, ShowTip: {result.ShowTip}, ConfirmationExpired: {result.ConfirmationExpired}");
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 校验二次确认记录,并恢复首次试算中已确认的审批和提示规则ID。
|
||||
/// </summary>
|
||||
private bool TryLoadIgnoreRiskRuleIds(RiskContext context, int trialSource, RiskTrialConfirmation confirmation, ISet<string> ignoreRiskRuleIds)
|
||||
{
|
||||
if (confirmation.TrialDataId <= 0 || confirmation.ExpireSeconds <= 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var trial = DbContext.quotaTrial.FirstOrDefault(item => item.id == confirmation.TrialDataId);
|
||||
if (trial == null
|
||||
|| trial.TradeId != context.TradeId
|
||||
|| trial.TrialSource != trialSource
|
||||
|| !trial.OptDate.HasValue
|
||||
|| !HasMatchingRequestContext(trial.RiskWarningDetails, context))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if (DateTime.Now - trial.OptDate.Value > TimeSpan.FromSeconds(confirmation.ExpireSeconds))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var ruleId in GetIgnoreRiskRuleIds(confirmation, trial.RiskWarningDetails))
|
||||
{
|
||||
ignoreRiskRuleIds.Add(ruleId);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 校验二次提交与首次试算的触发点和平仓日期一致,避免复用其他业务参数生成的审批记录。
|
||||
/// </summary>
|
||||
private static bool HasMatchingRequestContext(string details, RiskContext context)
|
||||
{
|
||||
var expectedContext = BuildRequestContext(context);
|
||||
return (details ?? string.Empty)
|
||||
.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
|
||||
.Any(line => string.Equals(line, expectedContext, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private static IEnumerable<string> GetIgnoreRiskRuleIds(RiskTrialConfirmation confirmation, string details)
|
||||
{
|
||||
var ignoreRiskRuleIds = confirmation.IgnoreRiskRuleIds ?? new List<string>();
|
||||
return ignoreRiskRuleIds.Any()
|
||||
? ignoreRiskRuleIds.Where(ruleId => !string.IsNullOrWhiteSpace(ruleId)).Select(ruleId => ruleId.Trim()).Distinct()
|
||||
: ParseIgnoreRiskRuleIds(details);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从系统生成的审批和提示规则明细中恢复规则ID,兼容未回传忽略规则ID的旧入口。
|
||||
/// </summary>
|
||||
private static IEnumerable<string> ParseIgnoreRiskRuleIds(string details)
|
||||
{
|
||||
const string ruleIdPrefix = "规则ID:";
|
||||
var inConfirmableSection = false;
|
||||
foreach (var line in (details ?? string.Empty).Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
|
||||
{
|
||||
if (line.StartsWith("[风控引擎] 规则触发:", StringComparison.Ordinal))
|
||||
{
|
||||
inConfirmableSection = line.StartsWith("[风控引擎] 规则触发:需审批", StringComparison.Ordinal)
|
||||
|| line.StartsWith("[风控引擎] 规则触发:提示", StringComparison.Ordinal);
|
||||
continue;
|
||||
}
|
||||
if (!inConfirmableSection)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var ruleIdStart = line.IndexOf(ruleIdPrefix, StringComparison.Ordinal);
|
||||
if (ruleIdStart < 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
ruleIdStart += ruleIdPrefix.Length;
|
||||
var ruleIdEnd = line.IndexOf(';', ruleIdStart);
|
||||
var ruleId = (ruleIdEnd < 0 ? line.Substring(ruleIdStart) : line.Substring(ruleIdStart, ruleIdEnd - ruleIdStart)).Trim();
|
||||
if (!string.IsNullOrWhiteSpace(ruleId))
|
||||
{
|
||||
yield return ruleId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将新风控引擎结果转换为现有试算记录,供详情页面和二次确认复用。
|
||||
/// </summary>
|
||||
private QuotaTrial CreateQuotaTrial(RiskContext context, int trialSource, RiskResult riskResult, IReadOnlyCollection<TriggeredRuleInfo> pendingApprovalRules, IReadOnlyCollection<TriggeredRuleInfo> pendingTipRules)
|
||||
{
|
||||
// 业务入口已通过Find加载交易,优先复用当前上下文跟踪的实体,避免重复查询数据库。
|
||||
var trade = DbContext.trade.Local.FirstOrDefault(item => item.id == context.TradeId)
|
||||
?? DbContext.trade.Find(context.TradeId);
|
||||
var trial = new QuotaTrial
|
||||
{
|
||||
TradeId = context.TradeId,
|
||||
TradeNumber = trade?.TradeNumber ?? string.Empty,
|
||||
ClientName = trade?.ClientName ?? string.Empty,
|
||||
TrialSource = trialSource,
|
||||
TrialStatus = riskResult.Blocked
|
||||
? QuotaTrialStatusEnum.Error
|
||||
: pendingApprovalRules.Any() ? QuotaTrialStatusEnum.RiskWarning : QuotaTrialStatusEnum.Success,
|
||||
NewRiskBlocked = riskResult.Blocked,
|
||||
NewRiskNeedApproval = pendingApprovalRules.Any(),
|
||||
RiskWarningDetails = BuildRiskDetails(context, riskResult, pendingApprovalRules, pendingTipRules)
|
||||
};
|
||||
trial.ApprovalRuleIds = pendingApprovalRules.Concat(pendingTipRules)
|
||||
.Select(rule => rule.RuleId)
|
||||
.Where(ruleId => !string.IsNullOrWhiteSpace(ruleId))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
return trial;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按控制策略生成与现有试算详情页面兼容的规则明细。
|
||||
/// </summary>
|
||||
private static string BuildRiskDetails(RiskContext context, RiskResult riskResult, IReadOnlyCollection<TriggeredRuleInfo> pendingApprovalRules, IReadOnlyCollection<TriggeredRuleInfo> pendingTipRules)
|
||||
{
|
||||
var lines = new List<string>
|
||||
{
|
||||
BuildRequestContext(context)
|
||||
};
|
||||
AppendRuleDetails(lines, "禁止", riskResult.TriggeredRules.Where(rule => rule.ControlStrategy == RiskControlStrategy.Block));
|
||||
AppendRuleDetails(lines, "需审批", pendingApprovalRules);
|
||||
AppendRuleDetails(lines, "提示", pendingTipRules);
|
||||
return string.Join("\n", lines);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成首次试算的业务请求标识,供二次确认严格校验业务参数。
|
||||
/// </summary>
|
||||
private static string BuildRequestContext(RiskContext context)
|
||||
{
|
||||
return $"[风控引擎] 请求上下文:触发点:{GetTriggerPointDisplayName(context.TriggerPoint)};平仓日期:{context.UnwindDate?.Date:yyyy-MM-dd};支付日期:{context.PayDate?.Date:yyyy-MM-dd}";
|
||||
}
|
||||
|
||||
private static string GetTriggerPointDisplayName(string triggerPoint)
|
||||
{
|
||||
return triggerPoint switch
|
||||
{
|
||||
"BOOK_CONFIRM" => "簿记交易确认",
|
||||
"CLOSE_REVIEW" => "平仓审核提交",
|
||||
"UPLOAD_CONFIRMATION" => "上传确认书",
|
||||
"EVENT_TRIGGER" => "事件发生时",
|
||||
_ => triggerPoint ?? string.Empty
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 追加指定控制策略的规则明细。
|
||||
/// </summary>
|
||||
private static void AppendRuleDetails(ICollection<string> lines, string strategyName, IEnumerable<TriggeredRuleInfo> rules)
|
||||
{
|
||||
var ruleList = rules.ToList();
|
||||
if (!ruleList.Any())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lines.Add($"[风控引擎] 规则触发:{strategyName}");
|
||||
foreach (var rule in ruleList)
|
||||
{
|
||||
var detail = $"应用ID:{rule.ApplicationId?.ToString() ?? "-"};规则ID:{rule.RuleId};规则名称:{rule.RuleName};规则说明:{rule.RuleText}";
|
||||
if (!string.IsNullOrWhiteSpace(rule.Message))
|
||||
{
|
||||
detail += $";信息:{rule.Message}";
|
||||
}
|
||||
lines.Add(detail);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新风控二次确认参数。
|
||||
/// </summary>
|
||||
public class RiskTrialConfirmation
|
||||
{
|
||||
/// <summary>
|
||||
/// 首次风控试算记录ID。
|
||||
/// </summary>
|
||||
public int TrialDataId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 首次试算允许确认放行的有效时长,单位为秒。
|
||||
/// </summary>
|
||||
public int ExpireSeconds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 首次试算返回并经前端回传的需忽略规则ID。
|
||||
/// </summary>
|
||||
public List<string> IgnoreRiskRuleIds { get; set; } = new List<string>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新风控通用试算结果。
|
||||
/// </summary>
|
||||
public class RiskTrialResult
|
||||
{
|
||||
public bool Passed { get; set; }
|
||||
public bool Blocked { get; set; }
|
||||
public bool NeedApproval { get; set; }
|
||||
public bool ShowTip { get; set; }
|
||||
public bool ConfirmationExpired { get; set; }
|
||||
public int TrialDataId { get; set; }
|
||||
public string Message { get; set; }
|
||||
public List<string> ApprovalRuleIds { get; set; } = new List<string>();
|
||||
}
|
||||
}
|
||||
@@ -519,8 +519,10 @@ namespace YLErp.Modules.RiskEngine
|
||||
/// </summary>
|
||||
private static string BuildBooleanMessage(glms_risk_variable variable, ValueExecuteResult value, bool expected)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(value.DetailMessage))
|
||||
return value.DetailMessage.Trim();
|
||||
|
||||
var parts = new List<string>();
|
||||
AddDetail(parts, value.DetailMessage);
|
||||
parts.Add($"{variable.VariableName}为{FormatDisplayValue(value.Value)}");
|
||||
parts.Add($"期望为{FormatDisplayValue(expected)}");
|
||||
return string.Join(",", parts);
|
||||
|
||||
+870
-118
File diff suppressed because it is too large
Load Diff
@@ -6892,7 +6892,8 @@ namespace YLErp.Modules.RiskModule
|
||||
return true;
|
||||
}
|
||||
/// <summary>
|
||||
/// 保存试算结果
|
||||
/// 保存试算结果。
|
||||
/// 新试算对象按历史快照新增;传入已有ID时仅更新该次试算的说明、来源和操作信息,不承担审批状态流转职责。
|
||||
/// </summary>
|
||||
/// <param name="obj">试算结果</param>
|
||||
public void SaveQuotaTrial(QuotaTrial obj)
|
||||
@@ -6922,6 +6923,40 @@ namespace YLErp.Modules.RiskModule
|
||||
DbContext.SaveChanges();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存平仓风控试算说明,并保留首次试算时间作为二次确认超时起点。
|
||||
/// </summary>
|
||||
/// <param name="trialDataId">平仓风控试算记录ID。</param>
|
||||
/// <param name="remark">用户填写的特批说明。</param>
|
||||
/// <returns>更新后的平仓风控试算记录。</returns>
|
||||
public QuotaTrial SaveCloseRiskTrialRemark(int trialDataId, string remark)
|
||||
{
|
||||
if (trialDataId <= 0)
|
||||
{
|
||||
throw new ServiceException("无效的平仓风控试算记录");
|
||||
}
|
||||
if (string.IsNullOrWhiteSpace(remark))
|
||||
{
|
||||
throw new ServiceException("必须填写说明内容,才可以提交平仓");
|
||||
}
|
||||
|
||||
const int closeTrialSource = 2;
|
||||
var trial = DbContext.quotaTrial.FirstOrDefault(item => item.id == trialDataId);
|
||||
if (trial == null
|
||||
|| trial.TrialSource != closeTrialSource
|
||||
|| trial.TrialStatus != QuotaTrialStatusEnum.RiskWarning)
|
||||
{
|
||||
throw new ServiceException("未找到有效的平仓风控审批记录");
|
||||
}
|
||||
|
||||
// 仅保存说明和操作人,不更新OptDate,避免重置首次试算的确认超时时间。
|
||||
trial.Remark = remark.Trim();
|
||||
trial.OptId = UserId;
|
||||
trial.OptName = UserName;
|
||||
DbContext.SaveChanges();
|
||||
return trial;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1979,6 +1979,33 @@ namespace YLErp.Modules.SwapModule
|
||||
SwapCalcTrace.Write(interestTrace);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单标的平仓
|
||||
/// </summary>
|
||||
/// <param name="unwindData"></param>
|
||||
/// <param name="confirmation">新风控二次确认信息;首次提交传空。</param>
|
||||
/// <returns>本次平仓的新风控试算结果。</returns>
|
||||
/// <exception cref="ServiceException"></exception>
|
||||
public YLErp.Modules.RiskEngine.RiskTrialResult SwapUnwind(UnwindData unwindData, YLErp.Modules.RiskEngine.RiskTrialConfirmation confirmation)
|
||||
{
|
||||
if (unwindData == null)
|
||||
{
|
||||
throw new ServiceException("平仓信息不能为空");
|
||||
}
|
||||
|
||||
if (FindTrade(unwindData.SwapTradeId) == null)
|
||||
{
|
||||
throw new ServiceException("未找到交易信息");
|
||||
}
|
||||
var riskTrialResult = CheckCloseRisk(unwindData, confirmation);
|
||||
if (!riskTrialResult.Passed)
|
||||
{
|
||||
return riskTrialResult;
|
||||
}
|
||||
SwapUnwind(unwindData);
|
||||
return riskTrialResult;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单标的平仓
|
||||
/// </summary>
|
||||
@@ -2381,6 +2408,29 @@ namespace YLErp.Modules.SwapModule
|
||||
SaveAllChanges();
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// 互换/平仓提交审核
|
||||
/// </summary>
|
||||
/// <param name="unwindData"></param>
|
||||
/// <param name="eventType"></param>
|
||||
/// <param name="confirmation">新风控二次确认信息;首次提交传空。</param>
|
||||
/// <returns>平仓事件返回新风控试算结果,互换事件返回空。</returns>
|
||||
/// <exception cref="ServiceException"></exception>
|
||||
public YLErp.Modules.RiskEngine.RiskTrialResult ApplySwapTrade(UnwindData unwindData, int eventType, YLErp.Modules.RiskEngine.RiskTrialConfirmation confirmation)
|
||||
{
|
||||
YLErp.Modules.RiskEngine.RiskTrialResult riskTrialResult = null;
|
||||
if (eventType == (int)SwapEventTypeEnum.平仓)
|
||||
{
|
||||
riskTrialResult = CheckCloseRisk(unwindData, confirmation);
|
||||
if (!riskTrialResult.Passed)
|
||||
{
|
||||
return riskTrialResult;
|
||||
}
|
||||
}
|
||||
ApplySwapTrade(unwindData, eventType);
|
||||
return riskTrialResult;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 互换/平仓提交审核
|
||||
/// </summary>
|
||||
@@ -2436,6 +2486,33 @@ namespace YLErp.Modules.SwapModule
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行互换交易平仓审核时点的新风控试算。
|
||||
/// </summary>
|
||||
/// <param name="unwindData">包含本次平仓日期和交易ID的平仓请求。</param>
|
||||
/// <param name="confirmation">新风控二次确认信息;首次提交传空。</param>
|
||||
/// <returns>包含阻断、审批、提示及试算记录ID的新风控结果。</returns>
|
||||
/// <exception cref="ServiceException">平仓请求为空。</exception>
|
||||
private YLErp.Modules.RiskEngine.RiskTrialResult CheckCloseRisk(UnwindData unwindData, YLErp.Modules.RiskEngine.RiskTrialConfirmation confirmation)
|
||||
{
|
||||
if (unwindData == null)
|
||||
{
|
||||
throw new ServiceException("平仓信息不能为空");
|
||||
}
|
||||
|
||||
const string triggerPoint = "CLOSE_REVIEW";
|
||||
const int closeTrialSource = 2;
|
||||
var riskContext = new YLErp.Modules.RiskEngine.RiskContext
|
||||
{
|
||||
TradeId = unwindData.SwapTradeId,
|
||||
TriggerPoint = triggerPoint,
|
||||
UnwindDate = unwindData.UnwindDate,
|
||||
PayDate = unwindData.PayDate
|
||||
};
|
||||
return new YLErp.Modules.RiskEngine.RiskTrialService(this).CheckRisk(riskContext, closeTrialSource, confirmation);
|
||||
}
|
||||
|
||||
private void ValidateIncomeValueDate(UnwindData unwindData, trade td)
|
||||
{
|
||||
var maxIncomeValueDate = GetMaxIncomeValueDate(td).Date;
|
||||
|
||||
@@ -13,6 +13,8 @@ using YLErp.DBModels;
|
||||
using YLErp.DBModels.Consts;
|
||||
using YLErp.Enums;
|
||||
using YLErp.Model.Enum;
|
||||
using YLErp.Modules.RiskEngine;
|
||||
using YLErp.Modules.RiskModule;
|
||||
using YLErp.Modules.SalesModule;
|
||||
using YLErp.Modules.SwapModule;
|
||||
using YLErp.Modules.SwapModule.Dto;
|
||||
@@ -445,12 +447,14 @@ namespace YLErp.Web.Controllers
|
||||
/// <summary>
|
||||
///单标的 平仓
|
||||
/// </summary>
|
||||
/// <param name="swap_Deal"></param>
|
||||
/// <returns></returns>
|
||||
public JsonResult SwapUnwindJson(UnwindData unwindData)
|
||||
/// <param name="unwindData">本次单标的平仓数据。</param>
|
||||
/// <param name="trialDataId">首次新风控试算记录ID;二次确认时传入。</param>
|
||||
/// <param name="ignoreRiskRuleIds">首次试算返回的需忽略规则ID;二次确认时传入。</param>
|
||||
/// <returns>平仓结果或新风控确认信息。</returns>
|
||||
public JsonResult SwapUnwindJson(UnwindData unwindData, int? trialDataId = null, string ignoreRiskRuleIds = null)
|
||||
{
|
||||
new SwapDealService(CurUser).SwapUnwind(unwindData);
|
||||
return JsonSuccess("平仓成功");
|
||||
var result = new SwapDealService(CurUser).SwapUnwind(unwindData, CreateRiskTrialConfirmation(trialDataId, ignoreRiskRuleIds));
|
||||
return BuildCloseRiskResult(result, "平仓成功");
|
||||
}
|
||||
/// <summary>
|
||||
/// 互换
|
||||
@@ -465,13 +469,112 @@ namespace YLErp.Web.Controllers
|
||||
/// <summary>
|
||||
/// 互换/平仓提交申请
|
||||
/// </summary>
|
||||
/// <param name="unwindData"></param>
|
||||
/// <param name="eventType"></param>
|
||||
/// <returns></returns>
|
||||
public JsonResult ApplyUnwind(UnwindData unwindData, int eventType)
|
||||
/// <param name="unwindData">本次互换或平仓数据。</param>
|
||||
/// <param name="eventType">事件类型。</param>
|
||||
/// <param name="trialDataId">首次新风控试算记录ID;平仓二次确认时传入。</param>
|
||||
/// <param name="ignoreRiskRuleIds">首次试算返回的需忽略规则ID;二次确认时传入。</param>
|
||||
/// <returns>提交结果或新风控确认信息。</returns>
|
||||
public JsonResult ApplyUnwind(UnwindData unwindData, int eventType, int? trialDataId = null, string ignoreRiskRuleIds = null)
|
||||
{
|
||||
new SwapDealService(CurUser).ApplySwapTrade(unwindData, eventType);
|
||||
return JsonSuccess("提交成功");
|
||||
var result = new SwapDealService(CurUser).ApplySwapTrade(unwindData, eventType, CreateRiskTrialConfirmation(trialDataId, ignoreRiskRuleIds));
|
||||
return BuildCloseRiskResult(result, "提交成功");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存平仓风控特批说明,不改变首次试算时间。
|
||||
/// 平仓二次确认会重新执行风控并生成新的 quotaTrial 快照,本接口只补充首次试算记录的用户说明和审计日志。
|
||||
/// </summary>
|
||||
/// <param name="trialDataId">平仓风控试算记录ID。</param>
|
||||
/// <param name="remark">用户填写的特批说明。</param>
|
||||
/// <returns>保存结果。</returns>
|
||||
public JsonResult SaveCloseRiskTrialRemark(int trialDataId, string remark)
|
||||
{
|
||||
try
|
||||
{
|
||||
var trial = new QuotaMonitorService(CurUser)
|
||||
.SaveCloseRiskTrialRemark(trialDataId, remark);
|
||||
new TradeRiskCheckLogService(CurUser).AddLog(trial);
|
||||
return JsonSuccess();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogFactory.GetLogger("SaveCloseRiskTrialRemark").Error(ex);
|
||||
return JsonError("保存平仓风控试算说明失败!");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据首次试算记录ID创建平仓新风控二次确认参数。
|
||||
/// </summary>
|
||||
/// <param name="trialDataId">首次新风控试算记录ID。</param>
|
||||
/// <param name="ignoreRiskRuleIds">首次试算返回的需忽略规则ID,多个ID使用逗号分隔。</param>
|
||||
/// <returns>首次提交返回空,二次确认返回包含有效期和需忽略规则ID的确认参数。</returns>
|
||||
private static RiskTrialConfirmation CreateRiskTrialConfirmation(int? trialDataId, string ignoreRiskRuleIds)
|
||||
{
|
||||
if (!trialDataId.HasValue)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var expireSeconds = 300;
|
||||
var expireSecondsConfig = AppManager.GetAppConfigValue("ProjectConfig", "Trade.RiskWarningConfirmExpireSeconds");
|
||||
if (!string.IsNullOrWhiteSpace(expireSecondsConfig)
|
||||
&& int.TryParse(expireSecondsConfig, out var configuredExpireSeconds)
|
||||
&& configuredExpireSeconds > 0)
|
||||
{
|
||||
expireSeconds = configuredExpireSeconds;
|
||||
}
|
||||
return new RiskTrialConfirmation
|
||||
{
|
||||
TrialDataId = trialDataId.Value,
|
||||
ExpireSeconds = expireSeconds,
|
||||
IgnoreRiskRuleIds = ParseIgnoreRiskRuleIds(ignoreRiskRuleIds)
|
||||
};
|
||||
}
|
||||
|
||||
private static List<string> ParseIgnoreRiskRuleIds(string ignoreRiskRuleIds)
|
||||
{
|
||||
return (ignoreRiskRuleIds ?? string.Empty)
|
||||
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(ruleId => ruleId.Trim())
|
||||
.Where(ruleId => !string.IsNullOrWhiteSpace(ruleId))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将平仓新风控结果转换为控制器统一JSON响应。
|
||||
/// </summary>
|
||||
/// <param name="result">新风控试算结果;互换事件不执行平仓风控时为空。</param>
|
||||
/// <param name="successMessage">业务执行成功后的提示。</param>
|
||||
/// <returns>阻断、二次确认或业务成功响应。</returns>
|
||||
private JsonResult BuildCloseRiskResult(RiskTrialResult result, string successMessage)
|
||||
{
|
||||
if (result == null || result.Passed)
|
||||
{
|
||||
return JsonSuccess(successMessage, result?.ShowTip == true ? new { result.TrialDataId, result.Message } : null);
|
||||
}
|
||||
if (result.Blocked)
|
||||
{
|
||||
// 风控阻断属于可预期的业务结果,返回成功协议供前端打开只读试算详情,不进入通用请求失败分支。
|
||||
return JsonSuccessData(new
|
||||
{
|
||||
proccessType = "QuotaTrialError",
|
||||
result.TrialDataId,
|
||||
message = string.IsNullOrWhiteSpace(result.Message)
|
||||
? "平仓风控校验未通过"
|
||||
: result.Message
|
||||
});
|
||||
}
|
||||
return JsonSuccessData(new
|
||||
{
|
||||
proccessType = "AdditionalProcessing",
|
||||
source = "RiskWarning",
|
||||
type = "RiskWarningConfirm",
|
||||
result.TrialDataId,
|
||||
ignoreRiskRuleIds = result.ApprovalRuleIds,
|
||||
message = result.ConfirmationExpired ? $"原风控确认已超时,请重新确认。{result.Message}" : result.Message
|
||||
});
|
||||
}
|
||||
/// <summary>
|
||||
/// 框架合约保存
|
||||
|
||||
@@ -619,22 +619,75 @@ const vue = new Vue({
|
||||
postUrl = "/swaptrade2/ApplyUnwind";
|
||||
postData.eventType = 2;//互换3,平仓2
|
||||
}
|
||||
main.confirm(msg,
|
||||
function () {
|
||||
//重新计算百分比
|
||||
var thisObj2 = thisObj;
|
||||
main.post(postUrl, postData).done(function (res) {
|
||||
if (res.success) {
|
||||
thisObj2.closetrade_cashWindow();
|
||||
// 提交平仓并处理新风控阻断、二次确认和成功提示。
|
||||
var submitClose = function (trialDataId, ignoreRiskRuleIds) {
|
||||
var requestData = _.cloneDeep(postData);
|
||||
if (trialDataId) {
|
||||
requestData.trialDataId = trialDataId;
|
||||
}
|
||||
if (ignoreRiskRuleIds && ignoreRiskRuleIds.length > 0) {
|
||||
requestData.ignoreRiskRuleIds = ignoreRiskRuleIds.join(',');
|
||||
}
|
||||
main.post(postUrl, requestData).done(function (res) {
|
||||
var riskData = res.obj;
|
||||
if (riskData && riskData.proccessType === "QuotaTrialError") {
|
||||
// 禁止类规则只展示试算详情,不允许继续提交平仓。
|
||||
if (riskData.TrialDataId) {
|
||||
layer.open({
|
||||
type: 2,
|
||||
title: "风控试算详情",
|
||||
shadeClose: false,
|
||||
shade: 0.4,
|
||||
area: ['800px', '500px'],
|
||||
content: "/trade/showQuotaTrial?id=" + riskData.TrialDataId,
|
||||
btn: ["关闭"]
|
||||
});
|
||||
}
|
||||
else {
|
||||
try {
|
||||
thisObj2.closetrade_cashWindow();
|
||||
} catch (e) {
|
||||
else if (res.msg) {
|
||||
main.message(res.msg);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (res.success && riskData && riskData.proccessType === "AdditionalProcessing" && riskData.TrialDataId) {
|
||||
// 审批类规则由用户填写说明并确认,二次提交回传试算记录ID和需忽略规则ID。
|
||||
var riskTrialLayerIndex = layer.open({
|
||||
type: 2,
|
||||
title: "风控试算详情",
|
||||
shadeClose: false,
|
||||
shade: 0.4,
|
||||
area: ['800px', '500px'],
|
||||
content: "/trade/showQuotaTrial?id=" + riskData.TrialDataId,
|
||||
btn: ["交易特批", "取消"],
|
||||
yes: function (index) {
|
||||
var trialPage = window["layui-layer-iframe" + index].page;
|
||||
if (!trialPage.Data.Remark || trialPage.Data.Remark.length <= 0) {
|
||||
main.message("必须填写说明内容,才可以提交平仓");
|
||||
return;
|
||||
}
|
||||
// 平仓使用专用接口且只提交记录ID和说明,避免客户端覆盖试算来源或刷新首次试算时间。
|
||||
main.post("/SwapTrade2/SaveCloseRiskTrialRemark", {
|
||||
trialDataId: riskData.TrialDataId,
|
||||
remark: trialPage.Data.Remark
|
||||
}).done(function () {
|
||||
layer.close(riskTrialLayerIndex);
|
||||
submitClose(riskData.TrialDataId, riskData.ignoreRiskRuleIds || []);
|
||||
});
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (res.success) {
|
||||
// 提示类规则不阻断平仓,成功后展示本次风控提示。
|
||||
if (riskData && riskData.TrialDataId && riskData.Message) {
|
||||
main.message(riskData.Message);
|
||||
}
|
||||
});
|
||||
thisObj.closetrade_cashWindow();
|
||||
}
|
||||
});
|
||||
};
|
||||
main.confirm(msg, function () {
|
||||
submitClose();
|
||||
});
|
||||
},
|
||||
getSumbitText: function () {
|
||||
return g_isShowReCheckClose ? "审核提交" : "保存";
|
||||
|
||||
Reference in New Issue
Block a user