Files
zszq-trs/YLErpDAL/Modules/SuperviseReportModule/SAC/Service/ReportSwapConfirmationService.cs
T

1043 lines
47 KiB
C#

using BaseOUDAL;
using MathNet.Numerics;
using MoreLinq.Extensions;
using Qdp.Foundation.Implementations;
using System.Data;
using System.Text.Json;
using YieldChain.Helpers;
using YLErp.BLL;
using YLErp.DBModels.Consts;
using YLErp.DBModels.Enums;
using YLErp.Helpers;
using YLErp.Modules.EodModule;
using YLErp.Modules.SuperviseReportModule.SAC.Common;
using YLErp.Modules.SuperviseReportModule.SAC.Model;
using YLErp.QdpModule;
using static YLErp.DBModels.Consts.ConsReport;
namespace YLErp.Modules.SuperviseReportModule.SAC.Service
{
class ReportSwapConfirmationService : ReportBaseService
{
public ReportSwapConfirmationService(OptUserInfo optUser) : base(optUser)
{
}
protected override string _excelDataSourcePath => "交易相关\\";
protected override string _excelDataSourceFileName => "import_SwapConfirmation_template.xlsx";
protected override DataFlagsEnum BusiDataType => DataFlagsEnum.A1005;
private List<OptFlagsEnum> _validOperationType = null;
public override List<OptFlagsEnum> ValidOperationType
{
get
{
_validOperationType ??= new List<OptFlagsEnum>() { OptFlagsEnum.A, OptFlagsEnum.U, OptFlagsEnum.D, };
return _validOperationType;
}
}
protected override SuperviseReportTypeEnum ReportType => SuperviseReportTypeEnum.SAC_SwapConfirmation;
readonly List<SACReportNotes> noteList = new();
IEnumerable<SACReportNotes> SACReportNotesCache = null;
protected override BodyModel GenerateBody(out bool noData, out List<string> fileList)
{
fileList = new List<string>();
var model = new BodyModel();
var cacheKey = $"{BusiDataType}";
SACReportNotesCache = base.InitReportNotes(ReportType);
var dataList = new List<SwapConfirmationModel>();
if (_reqInfo.DataSource.HasFlag(SAC_ReportDataSourceEnum.Template))
{
dataList = GetSwapConfirmationModel(ref fileList);
}
if ((PS.Config.ErpElement.SAC_ReportDataSource & SAC_ReportDataSourceEnum.System) ==
SAC_ReportDataSourceEnum.System)
{
// 获取所有的交易确认事件
var queryDate = _reqInfo.ReportDate;
using (var db = new YLContext())
{
var confirmEventList = (from a in db.swap_event
where a.EventType == 9 && a.OptTime >= queryDate.Date &&
a.OptTime < queryDate.Date.AddDays(1)
select new
{
a.id,
swapTradeId = a.SwapTradeId,
a.ValueDate,
eventType = a.EventType,
eventData = a.EventData,
invalid = a.Invalid,
backId = a.BackId,
optTime = a.OptTime
}).OrderBy(O => O.optTime).ToList();
var swapTradeIds = confirmEventList.Select(O => O.swapTradeId);
if (swapTradeIds == null || swapTradeIds.Count() == 0)
{
noData = true;
return null;
}
var codeList = ReportStatus.GetCacheInfo(cacheKey);
var query = (from t in db.trade
join tr in db.trade_contract_r
on t.id equals tr.TradeId
join sp in db.swap_position.Where(O => !O.Invalid && !O.IsInitial) on t.id equals sp.SwapTradeId
where swapTradeIds.Contains(t.id) &&
(tr.Type == "交易确认书" && tr.IsValid)
select new
{
t.id,
sp.PosiNotionalValue,
sp.PositionType,
t.ClientId,
t.TradeDate,
t.ExerciseDate,
t.SettlementDate,
t.ExerciseMode,
t.BuySell,
TradeType = t.StructureType ?? t.TradeType,
t.OptionType,
t.OriginalStockEqvNotional,
t.IsMoneynessOption,
t.SpotPrice,
t.Strike,
t.MarginTemplateName,
t.MarginType,
t.InitialMargin,
t.UnderlyingCode,
t.AnnualizeFactor,
tr.ContractCode,
sp.InterestMode,
sp.InterestRateDefault,
sp.FloatRateUnderlyingCode,
sp.InterestDirection,
sp.InterestSwapInterval,
t.OpponentRole,
sp.InterestPrincipalFix,
sp.PosiDirection
}).ToList();
var group = query.GroupBy(O => O.ContractCode).ToDictionary(K => K.Key, V => V.ToList());
List<int> ids = group.Values.SelectMany(O => O.Select(x => x.id)).Distinct().ToList();
Dictionary<int, Dictionary<string, string>> metaDic = DbContext.TradeMeta
.Where(O => ids.Contains(O.TradeId)).AsEnumerable().GroupBy(O => O.TradeId)
.ToDictionary(K => K.Key, V => V.ToDictionary(K1 => K1.MetaKey, V1 => V1.MetaValue));
foreach (var item in group)
{
var confirmationNo = item.Key;
if (ReportStatus.CheckCacheInfo(cacheKey, confirmationNo))
{
continue;
}
//如果存在重复数据,则始终用较新的数据
SwapConfirmationModel info = new SwapConfirmationModel();
info.ConfirmationNo = confirmationNo;
SACReportNotes note = base.GetReportNotes(ReportType, formatInfoTag(info)).FirstOrDefault();
if (note == null && _operationType == OptFlagsEnum.A)
{
info.OperationType = OptFlagsEnum.A;
note = new SACReportNotes() { IsValid = true, };
}
else
{
if (note == null)
{
continue;
}
switch (_operationType)
{
case OptFlagsEnum.A:
continue; //新增数据已报送,跳过
case OptFlagsEnum.U:
if (!note.changeStatus)
{
continue; //交易没有被修改过,跳过
}
info.OperationType = OptFlagsEnum.U;
note.IsValid = true;
break;
case OptFlagsEnum.D:
// 如果有删除事件,报废止
info.OperationType = OptFlagsEnum.D;
note.IsValid = false;
break;
case OptFlagsEnum.NONE:
default:
throw new ServiceException("未知操作类型");
}
}
if (info.OperationType != _operationType)
{
continue;
}
var first = item.Value.First();
if (metaDic.ContainsKey(first.id))
{
var metaInfo = metaDic[first.id];
info.MasterAgrmtNo = metaInfo.ContainsKey(ConsTradeMetaKey.MainProtocolCode)
? metaInfo[ConsTradeMetaKey.MainProtocolCode]
: "";
info.SupAgrmtNo = metaInfo.ContainsKey(ConsTradeMetaKey.SupProtocolCode)
? metaInfo[ConsTradeMetaKey.SupProtocolCode]
: "";
info.ClearingAgency = metaInfo.ContainsKey(ConsTradeMetaKey.ClearingAgency)
? ClearingAgencyMap[metaInfo[ConsTradeMetaKey.ClearingAgency]]
: "";
info.TradingPlace = metaInfo.ContainsKey(ConsTradeMetaKey.TradingPlace)
? TradingPlaceMap[metaInfo[ConsTradeMetaKey.TradingPlace]]
: "";
if (info.TradingPlace == "1") //跳过交易场所为报价系统的交易;
{
continue;
}
}
if (info.OperationType != OptFlagsEnum.A)
{
info.ConfirmationID = note.BizId; //确认书编号;
}
info.ConfirmationType = ReportTypeMap[info.OperationType == OptFlagsEnum.A ? "首次" : "变更"];
info.FillParty = FillPartyMap["甲方"];
#region 费用端支付
List<CostPaymentTupleDto> costPaymentTupleDtos = new List<CostPaymentTupleDto>();
item.Value.ForEach(O =>
{
// 说明是浮动腿,获取多空方向,肯定都是一致的,不然不可能是同一个交易编号,一直循环修改也没问题
if (O.PosiDirection > 0)
{
switch (O.PositionType)
{
case 1:
info.SwapType = "0";
break;
case 2:
info.SwapType = "1";
break;
case 3:
info.SwapType = "2";
break;
}
}
else
{
if (O.InterestDirection > 0)
{
var costPaymentTupleDto = new CostPaymentTupleDto();
// 计算初始保证金
if (O.InterestMode == 5 || O.InterestMode == 6)
{
costPaymentTupleDto.InterestPrincipalFix = O.InterestPrincipalFix;
}
else
{
// 生成费用端支付
costPaymentTupleDto.InterestRateDefault = O.InterestRateDefault;
costPaymentTupleDto.FloatRateUnderlyingCode = O.FloatRateUnderlyingCode;
costPaymentTupleDto.InterestDirection = O.InterestDirection;
costPaymentTupleDto.PaymentFreq = GetPaymentFreq(O.InterestSwapInterval);
}
costPaymentTupleDtos.Add(costPaymentTupleDto);
}
}
});
List<PaymentMethodModel> paymentMethodModels = new List<PaymentMethodModel>();
costPaymentTupleDtos.ForEach(cpt =>
{
var paymentMethod = new PaymentMethodModel();
paymentMethodModels.Add(paymentMethod);
paymentMethod.ConfirmationNo = confirmationNo;
paymentMethod.PaymentFreq = cpt.PaymentFreq;
paymentMethod.ReferenceofFloatingInterestRate = cpt.FloatRateUnderlyingCode;
if (cpt.FloatRateUnderlyingCode == null || cpt.FloatRateUnderlyingCode.Equals("") ||
cpt.FloatRateUnderlyingCode.Equals("--"))
{
paymentMethod.PaymentMethod = "3";
}
else
{
paymentMethod.PaymentMethod = "2";
}
if (cpt.InterestDirection == 1)
{
// 收取
if ("乙方".Equals(first.OpponentRole))
{
paymentMethod.Payer = "1";
}
else
{
paymentMethod.Payer = "0";
}
}
else
{
if ("乙方".Equals(first.OpponentRole))
{
paymentMethod.Payer = "0";
}
else
{
paymentMethod.Payer = "1";
}
}
if (cpt.FloatRateUnderlyingCode == null || cpt.FloatRateUnderlyingCode.Equals("") ||
cpt.FloatRateUnderlyingCode.Equals("--"))
{
if (cpt.InterestRateDefault == 0)
{
paymentMethod.FixedInterestRate = "0";
}
{
paymentMethod.FixedInterestRate =
cpt.InterestRateDefault.RoundToMultiple(100).ToString();
}
}
if (cpt.FloatRateUnderlyingCode != null)
{
paymentMethod.FloatInterestRate = "99";
}
if (cpt.FloatRateUnderlyingCode != null && !cpt.FloatRateUnderlyingCode.Equals("") &&
cpt.InterestRateDefault != null)
{
paymentMethod.BasePoint = cpt.InterestRateDefault.RoundToMultiple(100).ToString();
}
});
info.CostPaymentTuple = paymentMethodModels ;
#endregion
var variety = DataCacheProvider.GetVariety(first.UnderlyingCode);
info.StartDate = first.TradeDate?.ToString("yyyy-MM-dd");
info.DueDate = first.ExerciseDate?.ToString("yyyy-MM-dd");
info.SettlementDate = (first.SettlementDate ?? first.ExerciseDate)?.ToString("yyyy-MM-dd");
info.Currency = ((int)CurrencyEnum.CNY).ToString();
info.NotinalPrincipleAmt = (first.OriginalStockEqvNotional)?.ToString("0.00");
info.UndrlygAssetType = string.IsNullOrWhiteSpace(variety.MainCategoryDesc)
? UndrlygAssetTypeMap["其他"]
: UndrlygAssetTypeMap[variety.MainCategoryDesc];
var count = item.Value.Select(O => O.UnderlyingCode).Distinct().Count();
info.PtyAUndrlygAssetNo = UndrlygAssetNoMap[count == 1 ? "0" : "1"];
#region 履约担保
var files = db.trade_file.Where(O => O.TradeId == first.id).ToArray();
info.PerformanceGuaranteeType = first.MarginType == MarginTypeEnum.NONE
? PerformanceGuaranteeMap["无履约担保"]
: PerformanceGuaranteeMap["部分担保"];
if (first.MarginType != MarginTypeEnum.NONE)
{
info.PerformanceCollProvider = PerformanceCollProviderMap["乙方"];
info.PartyUseColl =
ConsReport.BoolMap[
valuedateBLL.SystemDate.PartyUseColl ||
PS.Config.Company == Configuration.CompanyEnum.东莞
? "是"
: "否"]; //todo:读取用户输入
info.CollInstruction = valuedateBLL.SystemDate.CollInstruction; //todo:读取用户输入
info.CalculateCollInterest = BoolMap["否"];
if (first.InterestPrincipalFix == 0)
{
info.PerformanceCollInitialRatio = "0";
}
else
{
if (first.OriginalStockEqvNotional != 0)
{
info.PerformanceCollInitialRatio = (first.InterestPrincipalFix * 100 /
first.OriginalStockEqvNotional?.ToDecimal())
.ToString();
}
}
info.PerformanceCollAddtlRatio = "100";
info.PerformanceCollOffsetRatio = "100";
info.MaintainGuaranteeRatio = info.PerformanceCollInitialRatio;
var file_PerformanceGuarante =
files.FirstOrDefault(O => O.Path.ToLower().EndsWith("履约保证书.pdf"));
info.PerformanceGuaranteeAtt = Path.GetFileName(file_PerformanceGuarante?.Path);
info.PerformanceGuaranteeRemark = file_PerformanceGuarante?.Description;
info.PerformanceCollTuple = new List<SwapPerformanceGuaranteeAttModel>();
info.PerformanceCollTuple.Add(new SwapPerformanceGuaranteeAttModel()
{
PerformanceCollType = PerformanceCollTypeMap["现金"],
PerformanceCollRange = /*item.MarginType == MarginTypeEnum.DEFAULT ? PerformanceCollRangeMap["本笔交易对应主协议框架下的所有交易"] :*/
PerformanceCollRangeMap["仅本笔交易"]
});
if (!ReportStatus.CheckFileLength(file_PerformanceGuarante?.Path))
{
break;
}
fileList.Add(file_PerformanceGuarante?.Path);
}
else
{
info.PerformanceCollInitialRatio = "0";
info.MaintainGuaranteeRatio = "0";
}
#endregion
var file_ComplianceOpinion = files.FirstOrDefault(O => O.Path.ToLower().EndsWith("合规意见书.pdf"));
if (!string.IsNullOrWhiteSpace(file_ComplianceOpinion?.Path))
{
string fileName = Path.GetFileName(file_ComplianceOpinion?.Path);
info.ComplianceOpinion = fileName;
if (!ReportStatus.CheckFileLength(file_ComplianceOpinion?.Path))
{
break;
}
fileList.Add(file_ComplianceOpinion?.Path);
}
var client = DataCacheProvider.GetClientDataSource().GetData(first.ClientId);
info.PtyAPrOfitCalculationInfo = "详见交易确认书及定义性文件";
if (client.ClientType == "产品")
{
if (info.FillParty == FillPartyMap["甲方"])
{
info.PtyBPdctName = client.Name ?? "";
info.PytBPdctCode = client.Number ?? "";
}
else
{
info.PtyAPdctName = client.Name ?? "";
info.PytAPdctCode = client.Number ?? "";
}
}
info.ExceID = base.formatExceID();
// 把要报的交易确认书缓存起来
ReportStatus.AddCacheInfo(cacheKey, confirmationNo);
foreach (var swapTradeId in swapTradeIds)
{
ReportStatus.AddCacheInfo($"{cacheKey}_{info.ConfirmationNo}_{_operationType}", swapTradeId.ToString());
}
dataList.Add(info);
note.id = 0;
note.InfoCache =
$"{{\"NotinalPrincipleAmt\":\"{info.NotinalPrincipleAmt}\",\"DueDate\":\"{info.DueDate}\",\"Tag\":\"{info.ConfirmationNo}\",\"Source\":\"System\"}}";
note.ExceId = info.ExceID;
note.CreateTime = DateTime.Now;
note.FileTag = FileTag;
note.ReportType = ReportType;
note.ReportDate = _reqInfo.ReportDate;
note.InfoTag = formatInfoTag(info, true);
note.OptTime = note.CreateTime;
note.RetCode = "";
note.RetMsg = "";
note.ReportResponse = false;
note.BizId = "";
note.changeStatus = false;
noteList.Add(note);
}
}
}
var subsystemDataList = loadSubsystemDataSource<SwapConfirmationModel>(fileList, AddSubsystemNote);
if (subsystemDataList != null && subsystemDataList.Count > 0)
{
dataList.AddRange(subsystemDataList);
}
fileList = fileList.Distinct().ToList();
noData = dataList.Count == 0;
model.SwapConfirmation = dataList;
return model;
}
public bool AddSubsystemNote(SwapConfirmationModel model, List<string> fileList, string tag)
{
var note = base.GetReportNotes(ReportType, formatInfoTag(model, true), dataSource: SACReportNotesCache)
.FirstOrDefault(); //参数true要加,要不A和D会查到同一条记录,在D时候,就会和A相同的数据
if (note == null)
{
note = new SACReportNotes()
{
InfoCache =
$"{{\"NotinalPrincipleAmt\":\"{model.NotinalPrincipleAmt}\",\"DueDate\":\"{model.DueDate}\",\"Tag\":\"{model.ConfirmationNo}\",\"Source\":\"Subsystem\",\"SubFileTag\":\"{tag}\",\"ExceID\":\"{model.ExceID}\"}}",
IsValid = true,
};
}
else
{
switch (model.OperationType)
{
case OptFlagsEnum.A:
return false; //新增数据已报送,跳过
case OptFlagsEnum.U:
//多次U的时候,每次用最新的tag来赋值SubFileTag
note.InfoCache =
$"{{\"NotinalPrincipleAmt\":\"{model.NotinalPrincipleAmt}\",\"DueDate\":\"{model.DueDate}\",\"Tag\":\"{model.ConfirmationNo}\",\"Source\":\"Subsystem\",\"SubFileTag\":\"{tag}\",\"ExceID\":\"{model.ExceID}\"}}";
note.IsValid = true;
break;
case OptFlagsEnum.D:
note.IsValid = false;
break;
case OptFlagsEnum.NONE:
default:
throw new ServiceException("未知操作类型");
}
}
if (!string.IsNullOrWhiteSpace(model.PerformanceGuaranteeAtt))
{
fileList.Add(model.PerformanceGuaranteeAtt);
}
if (!string.IsNullOrWhiteSpace(model.ComplianceOpinion))
{
fileList.Add(model.ComplianceOpinion);
}
model.ExceID = base.formatExceID(SACReportNotesCache);
note.id = 0;
note.ExceId = model.ExceID;
note.CreateTime = DateTime.Now;
note.FileTag = FileTag;
note.ReportType = ReportType;
note.ReportDate = _reqInfo.ReportDate;
note.InfoTag = formatInfoTag(model, true);
note.OptTime = note.CreateTime;
note.RetCode = "";
note.RetMsg = "";
note.ReportResponse = false;
note.BizId = "";
note.changeStatus = false;
noteList.Add(note);
return true;
}
/// <summary>
/// 根据利息互换区间判断支付频率
/// </summary>
/// <param name="interestSwapInterval">JSON字符串,包含ObservationIntervalDto列表</param>
/// <returns>"0":期初支付, "1":期末支付, "2":多次支付</returns>
private string GetPaymentFreq(string interestSwapInterval)
{
if (string.IsNullOrWhiteSpace(interestSwapInterval))
{
return "1"; // 默认期末支付
}
List<ObservationIntervalDto> list = null;
try
{
list = JsonSerializer.Deserialize<List<ObservationIntervalDto>>(interestSwapInterval);
}
catch (JsonException ex)
{
throw new ServiceException("观察日列表json解析异常");
}
if (list == null || list.Count == 0)
{
return "1"; // 默认期末支付
}
int count = 0;
// tempDict的key:(是/否),value:出现的位置
Dictionary<int, int> tempDict = new Dictionary<int, int>();
for (int i = 0; i < list.Count; i++)
{
ObservationIntervalDto item = list[i];
if (item.Settlement == 1)
{
count++;
}
tempDict[item.Settlement] = i;
}
if (count != 0)
{
// 1.如果是有多个"是"就是多次支付
return "2";
}
else
{
// 则证明只有一个是,判断是的位置,如果是首个,则证明是期初支付,否则期末支付(如果一个是都没有默认是期末支付)
if (tempDict.TryGetValue(1, out int index))
{
if (index == 0) // 注意:C#索引从0开始,Java代码中判断的是1(可能是从1开始的索引)
{
return "0"; // 期初支付
}
else
{
return "1"; // 期末支付
}
}
else
{
return "1"; // 默认期末支付
}
}
}
private List<SwapConfirmationModel> GetSwapConfirmationModel(ref List<string> fileList)
{
var result = new List<SwapConfirmationModel>();
var path = "";
if (_excelDataSource != null && _excelDataSource.Tables.Contains("互换交易确认书明细"))
{
var sourcePath = Path.Combine(_excelDataSourceRootPath, "附件");
var dt = _excelDataSource.Tables["互换交易确认书明细"];
for (var i = 1; i < dt.Rows.Count; i++)
{
if (string.IsNullOrWhiteSpace(dt.Rows[i][0]?.ToString()))
{
//第一列空白说明数据结束了;
break;
}
var optType = OptFlagsEnum.NONE;
switch (dt.Rows[i][3]?.ToString())
{
case "0":
case "A":
case "首次":
optType = OptFlagsEnum.A;
break;
case "1":
case "U":
case "变更":
optType = OptFlagsEnum.U;
break;
case "2":
case "D":
case "废止":
optType = OptFlagsEnum.D;
break;
}
if (optType != _operationType)
{
continue;
}
var model = new SwapConfirmationModel
{
OperationType = optType,
MasterAgrmtNo = GetDataSetValue(dt, i, 0),
SupAgrmtNo = GetDataSetValue(dt, i, 1),
ConfirmationNo = GetDataSetValue(dt, i, 2),
ConfirmationType = ConsReport.ReportTypeMap[optType == OptFlagsEnum.A ? "首次" : "变更"],
FillParty = ConsReport.FillPartyMap[GetDataSetValue(dt, i, 4)],
SwapType = ConsReport.SwapTypeMap[GetDataSetValue(dt, i, 5)],
StartDate = GetDataSetValue(dt, i, 6),
DueDate = GetDataSetValue(dt, i, 7),
SettlementDate = GetDataSetValue(dt, i, 8)
};
var currencyStr = GetDataSetValue(dt, i, 9);
currencyStr = currencyStr == "其他" ? "Other" : currencyStr;
if (Enum.TryParse(currencyStr.ToUpper(), out CurrencyEnum currency))
{
model.Currency = ((int)currency).ToString();
}
model.NotinalPrincipleAmt = GetDataSetValue(dt, i, 10);
model.ClearingAgency = ConsReport.ClearingAgencyMap[GetDataSetValue(dt, i, 11)];
model.TradingPlace = ConsReport.TradingPlaceMap[GetDataSetValue(dt, i, 12)];
model.TradingPlaceOther = GetDataSetValue(dt, i, 13);
model.UndrlygAssetType = ConsReport.UndrlygAssetTypeMap[GetDataSetValue(dt, i, 14)];
model.ConfirmationRemark = GetDataSetValue(dt, i, 15);
model.PerformanceGuaranteeType = ConsReport.PerformanceGuaranteeMap[GetDataSetValue(dt, i, 16)];
model.PerformanceCollProvider = ConsReport.PerformanceCollProviderMap[GetDataSetValue(dt, i, 17)];
model.PartyUseColl = ConsReport.BoolMap[GetDataSetValue(dt, i, 18)];
model.CollInstruction = GetDataSetValue(dt, i, 19);
model.CalculateCollInterest = ConsReport.BoolMap[GetDataSetValue(dt, i, 20)];
model.PerformanceCollInitialRatio = GetDataSetValue(dt, i, 21);
model.PerformanceCollAddtlRatio = GetDataSetValue(dt, i, 22);
model.PerformanceCollOffsetRatio = GetDataSetValue(dt, i, 23);
model.MaintainGuaranteeRatio = GetDataSetValue(dt, i, 24);
model.PerformanceGuaranteeAtt = GetDataSetValue(dt, i, 25);
model.PerformanceGuaranteeRemark = GetDataSetValue(dt, i, 26);
model.Remark = GetDataSetValue(dt, i, 27);
model.ComplianceOpinion = GetDataSetValue(dt, i, 28);
model.PtyAUndrlygAssetNo = ConsReport.UndrlygAssetNoMap[GetDataSetValue(dt, i, 29)];
model.PtyAPrOfitCalculationInfo = GetDataSetValue(dt, i, 30);
model.PtyAProfitRemark = GetDataSetValue(dt, i, 31);
model.PtyAPdctName = GetDataSetValue(dt, i, 32);
model.PytAPdctCode = GetDataSetValue(dt, i, 33);
model.PtyBPdctName = GetDataSetValue(dt, i, 34);
model.PytBPdctCode = GetDataSetValue(dt, i, 35);
model.Blank1 = GetDataSetValue(dt, i, 36);
model.Blank2 = GetDataSetValue(dt, i, 37);
model.CostPaymentTuple = GetCostPaymentTuple(model.ConfirmationNo);
model.PerformanceCollTuple = GetPerformanceGuaranteeAttModel(model.ConfirmationNo);
var notinalPrincipleAmt = GetDataSetValueToDouble(dt, i, 10);
var cacheValue = (model.ConfirmationNo ?? "").ToString();
if (cacheValue.IsNullOrWhiteSpace())
{
continue;
}
if (ReportStatus.CheckCacheInfo(CacheKey, cacheValue))
{
continue;
}
var note = base.GetReportNotes(ReportType, formatInfoTag(model), dataSource: SACReportNotesCache)
.FirstOrDefault();
if (note == null && _operationType == OptFlagsEnum.A)
{
note = new SACReportNotes() { IsValid = true, };
}
else
{
if (note == null)
{
continue;
}
switch (_operationType)
{
case OptFlagsEnum.A:
continue; //新增数据已报送,跳过
case OptFlagsEnum.U:
note.IsValid = true;
break;
case OptFlagsEnum.D:
note.IsValid = false;
break;
case OptFlagsEnum.NONE:
default:
throw new ServiceException("未知操作类型");
}
var reportCacheDic = JsonHelper.ToObject<Dictionary<string, string>>(note.InfoCache) ??
new Dictionary<string, string>();
if (_operationType == OptFlagsEnum.U)
{
if (reportCacheDic.ContainsKey("DueDate") &&
!reportCacheDic["DueDate"].StartsWith(model.DueDate) &&
!model.DueDate.StartsWith(reportCacheDic["DueDate"]))
{
throw new ServiceException("补正时,如果该交易还有存续期记录,到期日字段不能修改");
}
if (reportCacheDic.ContainsKey("NotinalPrincipleAmt") &&
reportCacheDic["NotinalPrincipleAmt"] != model.NotinalPrincipleAmt &&
reportCacheDic["NotinalPrincipleAmt"] != notinalPrincipleAmt.ToString("0"))
{
throw new ServiceException("补正时,如果该交易还有存续期记录,名义本金额(人民币)字段不能修改");
}
}
}
if (model.OperationType != OptFlagsEnum.A)
{
model.ConfirmationID = note.BizId; //确认书编号;
}
if (!string.IsNullOrWhiteSpace(model.PerformanceGuaranteeAtt))
{
path = Path.Combine(sourcePath, model.PerformanceGuaranteeAtt);
if (!ReportStatus.CheckFileLength(path))
{
break;
}
fileList.Add(path);
}
if (!string.IsNullOrWhiteSpace(model.ComplianceOpinion))
{
path = Path.Combine(sourcePath, model.ComplianceOpinion);
if (!ReportStatus.CheckFileLength(path))
{
break;
}
fileList.Add(path);
}
model.ExceID = base.formatExceID(SACReportNotesCache);
result.Add(model);
ReportStatus.AddCacheInfo(CacheKey, cacheValue);
note.id = 0;
note.InfoCache =
$"{{\"NotinalPrincipleAmt\":\"{model.NotinalPrincipleAmt}\",\"DueDate\":\"{model.DueDate}\",\"Tag\":\"{model.ConfirmationNo}\",\"Source\":\"Template\"}}";
note.ExceId = model.ExceID;
note.CreateTime = DateTime.Now;
note.FileTag = FileTag;
note.ReportType = ReportType;
note.ReportDate = _reqInfo.ReportDate;
note.InfoTag = formatInfoTag(model, true);
note.OptTime = note.CreateTime;
note.RetCode = "";
note.RetMsg = "";
note.ReportResponse = false;
note.BizId = "";
note.changeStatus = false;
noteList.Add(note);
}
}
return result;
}
private List<PaymentMethodModel> GetCostPaymentTuple(string confirmationNo)
{
var result = new List<PaymentMethodModel>();
if (_excelDataSource != null && _excelDataSource.Tables.Contains("收益互换交易费用支付端"))
{
var dt = _excelDataSource.Tables["收益互换交易费用支付端"];
for (var i = 1; i < dt.Rows.Count; i++)
{
if (string.IsNullOrWhiteSpace(dt.Rows[i][0]?.ToString()))
{
//第一列空白说明数据结束了;
break;
}
if (dt.Rows[i][0]?.ToString().Trim() != confirmationNo)
{
continue;
}
var model = new PaymentMethodModel
{
PaymentMethod = ConsReport.PaymentMethodMap[GetDataSetValue(dt, i, 1)],
Payer = ConsReport.PayerMap[GetDataSetValue(dt, i, 2)],
PaymentFreq = ConsReport.PaymentFreqMap[GetDataSetValue(dt, i, 3)],
FixedInterestRate = GetDataSetValue(dt, i, 4),
FloatInterestRate = ConsReport.RefRateTypeMap[GetDataSetValue(dt, i, 5)],
ReferenceofFloatingInterestRate = GetDataSetValue(dt, i, 6),
BasePoint = GetDataSetValue(dt, i, 7),
Blank1 = GetDataSetValue(dt, i, 8),
Blank2 = GetDataSetValue(dt, i, 9)
};
result.Add(model);
}
}
return result;
}
private List<SwapPerformanceGuaranteeAttModel> GetPerformanceGuaranteeAttModel(string confirmationNo)
{
var result = new List<SwapPerformanceGuaranteeAttModel>();
if (_excelDataSource != null && _excelDataSource.Tables.Contains("履约担保品明细"))
{
var dt = _excelDataSource.Tables["履约担保品明细"];
for (var i = 1; i < dt.Rows.Count; i++)
{
if (string.IsNullOrWhiteSpace(dt.Rows[i][0]?.ToString()))
{
//第一列空白说明数据结束了;
break;
}
if (dt.Rows[i][0]?.ToString().Trim() != confirmationNo)
{
continue;
}
var model = new SwapPerformanceGuaranteeAttModel
{
PerformanceCollType = ConsReport.PerformanceCollTypeMap[GetDataSetValue(dt, i, 1)],
PerformanceCollRange = ConsReport.PerformanceCollRangeMap[GetDataSetValue(dt, i, 2)],
MultiConfirmationID = GetDataSetValue(dt, i, 3),
Remarks = GetDataSetValue(dt, i, 4)
};
result.Add(model);
}
}
return result;
}
private string formatInfoTag(SwapConfirmationModel model, bool suffixType = false)
{
var result = $"{BusiDataType.ToString()}_{model.ConfirmationNo.Replace("_", "-")}_成交_";
if (suffixType)
{
result = $"{result}{_operationType}";
}
return result;
}
protected override string _changeCodeOfInfoTag(string infoTag, string newCode, out string originalCode)
{
var arr = infoTag.Split('_');
if (arr.Length != 4)
{
throw new ServiceException($"InfoTag信息不匹配:{infoTag}");
}
originalCode = arr[1];
arr[1] = newCode.Replace("_", "-");
return string.Join("_", arr);
}
protected override List<SacInfo> CheckBodyValue(BodyModel model, out bool checkStatus)
{
var result = new List<SacInfo>();
if (model?.SwapConfirmation != null)
{
var helper = new Common.CheckHelper<SwapConfirmationModel>();
var pAttHelper = new Common.CheckHelper<SwapPerformanceGuaranteeAttModel>();
var cAttHelper = new Common.CheckHelper<PaymentMethodModel>();
for (var i = 0; i < model.SwapConfirmation.Count; i++)
{
var listRoot = new List<SacInfo>();
var item = model.SwapConfirmation[i];
if (item.IgnoreCheck)
{
continue;
}
helper.ExecuteCheck(item, (name, value, msg) =>
{
listRoot.Add(new SacInfo(name, value, msg));
});
if (item.CostPaymentTuple != null)
{
for (var j = 0; j < item.CostPaymentTuple.Count; j++)
{
var listItem = new List<SacInfo>();
var attItem = item.CostPaymentTuple[j];
cAttHelper.ExecuteCheck(attItem, (name, value, msg) =>
{
listItem.Add(new SacInfo(name, value, msg));
});
if (listItem.Count > 0)
{
var temp = new SacInfo("CostPaymentTuple", j) { SubMaps = new List<SacInfo>(listItem) };
listRoot.Add(temp);
}
}
}
if (item.PerformanceCollTuple != null)
{
for (var j = 0; j < item.PerformanceCollTuple.Count; j++)
{
var listItem = new List<SacInfo>();
var attItem = item.PerformanceCollTuple[j];
pAttHelper.ExecuteCheck(attItem, (name, value, msg) =>
{
listItem.Add(new SacInfo(name, value, msg));
});
if (listItem.Count > 0)
{
var temp = new SacInfo("PerformanceCollTuple", j)
{
SubMaps = new List<SacInfo>(listItem)
};
listRoot.Add(temp);
}
}
}
if (listRoot.Count > 0)
{
var errMsg = new SacInfo("SwapConfirmation", i)
{
FieldValue = item.ConfirmationNo, SubMaps = new List<SacInfo>(listRoot)
};
result.Add(errMsg);
}
}
}
checkStatus = result.Count > 0;
return result;
}
public override bool BeforeOfGenerated(out string errMsg)
{
errMsg = "";
foreach (var file in xmlAttachmentList)
{
try
{
File.Delete(file);
}
catch (Exception e)
{
LogFactory.GetLogger<ReportMasterAgrmtProductService>().Error(e);
}
;
}
for (var i = 0; i < noteList.Count; i++)
{
base.SaveReportNotes(noteList[i]);
}
return true;
}
}
// 费用端支付,data transform object
class CostPaymentTupleDto
{
public decimal InterestRateDefault { get; set; }
public decimal InterestPrincipalFix { get; set; }
public string FloatRateUnderlyingCode { get; set; }
public string PaymentFreq { get; set; }
public int InterestDirection { get; set; }
}
/// <summary>
/// 观察日区间DTO
/// </summary>
public class ObservationIntervalDto
{
/// <summary>
/// 结算标识:0-否,1-是
/// </summary>
public int Settlement { get; set; }
// 根据实际JSON结构添加其他属性
// public DateTime? StartDate { get; set; }
// public DateTime? EndDate { get; set; }
}
}