using System.Data; using System.Text.RegularExpressions; using System.Xml; using YieldChain.Helpers; using YLErp.BLL; using YLErp.Commons; using YLErp.DBModels.Enums; using YLErp.Helpers; using YLErp.Modules.ClientModule; using YLErp.Modules.SuperviseReportModule.SAC.Common; using YLErp.Modules.SuperviseReportModule.SAC.Model; using static YLErp.DBModels.Consts.ConsReport; namespace YLErp.Modules.SuperviseReportModule.SAC.Service { public class ReportService : YLBaseService { public ReportService(OptUserInfo optUser) : base(optUser) { } /// /// 生成报送文件锁 /// private static AutoResetEvent generateSuperviseLock = new AutoResetEvent(true); /// /// 操作报送文件锁 /// private static AutoResetEvent optionSuperviseLock = new AutoResetEvent(true); #region 生成报送文件 /// /// 生成报送文件 /// /// /// public List Execute(ReportInfo req) { LogFactory.GetLogger("Execute").Info($"7"); if (req.ReportTypes == null || req.ReportTypes.Count == 0) { throw new ServiceException("请选择要报送的类型"); } LogFactory.GetLogger("Execute").Info($"8"); List reportList = new List(); var useBreak = false; try { LogFactory.GetLogger("Execute").Info($"9"); generateSuperviseLock.WaitOne(); ReportStatusModel reportStatus = new ReportStatusModel(); do { LogFactory.GetLogger("Execute").Info($"10"); reportStatus.ResetCurrentLength(); //放开存在未报送报告时,阻塞其他报告生成的限制,可能引起的业务中先后顺序的问题(比如一定要先新增后修改的问题)需要客户自己判断; //var report = DbContext.supervise_report.Where(O => O.ReportType == SuperviseReportTypeEnum.SAC && O.ReportReponseStatus <= ReportSentStatus.SENDING).FirstOrDefault(); //if (report != null) //{ // throw new ServiceException($"{UserBLL.GetById((int)report.optUserId)?.Name} 名下存在未发送或发送中的记录,请稍后操作"); //} LogFactory.GetLogger("Execute").Info($"10"); Dictionary serviceDict = new Dictionary(); req.ReportTypes.Sort(); foreach (var item in req.ReportTypes) { SuperviseReportTypeEnum type = (SuperviseReportTypeEnum)item; var service = ReportBaseService.ReportFactory(OptUser, type); if (!service.CheckRequestParamer(req, out string errMsg)) { throw new ServiceException(errMsg); } serviceDict[item] = service; } LogFactory.GetLogger("Execute").Info($"11"); ReportBaseService.MaxExceIndex = queryCurrentExceIndex(); List checkMsgArr = new List(); ReportResponse res = new ReportResponse(); res.Infos = new List(); res.Index = queryCurrentFileIndex(req.ReportDate); LogFactory.GetLogger("Execute").Info($"12"); foreach (var service in serviceDict) { try { ReportRootModel model = null; service.Value.WriteDb = DbContext; service.Value.FileNumber = res.Index; service.Value.ReportStatus = reportStatus; if (service.Key == (int)SuperviseReportTypeEnum.SAC_EventReport) { model = service.Value.Execute(req, req.EventReportStatus); res.Infos.Add(model); checkMsgArr.Add(service.Value.CheckValue(model, out _)); } else if (service.Key == (int)SuperviseReportTypeEnum.SAC_OtherReport) { model = service.Value.Execute(req, req.OtherReportStatus); res.Infos.Add(model); checkMsgArr.Add(service.Value.CheckValue(model, out _)); } else if (service.Key == (int)SuperviseReportTypeEnum.SAC_PeriodicReportSAC) { model = service.Value.Execute(req, req.SACReportStatus); res.Infos.Add(model); checkMsgArr.Add(service.Value.CheckValue(model, out _)); } else if (service.Key == (int)SuperviseReportTypeEnum.SAC_PeriodicReportNAFMII) { model = service.Value.Execute(req, req.NAFMIIReportStatus); res.Infos.Add(model); checkMsgArr.Add(service.Value.CheckValue(model, out _)); } else if (service.Key == (int)SuperviseReportTypeEnum.SAC_PeriodicReportISDA) { model = service.Value.Execute(req, req.ISDAReportStatus); res.Infos.Add(model); checkMsgArr.Add(service.Value.CheckValue(model, out _)); } else if (service.Key == (int)SuperviseReportTypeEnum.SAC_PeriodicReportQuarter) { model = service.Value.Execute(req, req.PeriodicReportQuarterStatus); res.Infos.Add(model); checkMsgArr.Add(service.Value.CheckValue(model, out _)); } else { foreach (var item in service.Value.ValidOperationType) { LogFactory.GetLogger("Execute").Info($"OperationType:" + item.ToString()); model = service.Value.Execute(req, item); LogFactory.GetLogger("Execute").Info($"OperationType1:" + item.ToString()); res.Infos.Add(model); checkMsgArr.Add(service.Value.CheckValue(model, out _)); } } } catch (Exception ex) { LogFactory.GetLogger("Execute").Info($"Exception" + ex.ToString()); throw; } } res.Infos = res.Infos.Where(O => O != null).ToList(); if (res.Infos.Count == 0) { if (useBreak) { break; } else { throw new ServiceException("不存在要报送的数据"); } } if (checkMsgArr.Any(O => O != null)) { var exception = new ServiceException("数据校验未通过"); exception.Tag = checkMsgArr.Where(O => O != null).ToList(); throw exception; } string zipPath = ""; try { optionSuperviseLock.WaitOne(); zipPath = ReportBaseService.ZipFile(res); } finally { optionSuperviseLock.Set(); } foreach (var item in serviceDict) { if (!item.Value.BeforeOfGenerated(out string errMsg)) { throw new ServiceException(errMsg); } } DBModels.SuperviseReport reportInfo = new DBModels.SuperviseReport() { ReportType = SuperviseReportTypeEnum.SAC, ReportDate = req.ReportDate, DataDate = req.DataDate, SenderCode = req.SenderCode, ReceiverCode = req.ReceiverCode, LastMonthCash = req.LastMonthCash, LatestMonthCash = req.LatestMonthCash, LatestNetAssets = req.LatestNetAssets, SRCReportStatus = req.SACReportStatus, NAFMIIReportStatus = req.NAFMIIReportStatus, ISDAReportStatus = req.ISDAReportStatus, EventReportStatus = req.EventReportStatus, OtherReportStatus = req.OtherReportStatus, PeriodicReportQuarterStatus = req.PeriodicReportQuarterStatus, FileTag = res.FileTag, FilePath = zipPath, ReportReponseStatus = ReportSentStatus.NONE, ReportReponseCode = "", ReportReponseMessage = "未知", ReportReponsePath = "", optDate = DateTime.Now, optUserId = OptUser.UserId, }; reportList.Add(reportInfo); DbContext.supervise_report.Add(reportInfo); DbContext.SaveChanges(); useBreak = reportStatus.Continue; } while (reportStatus.Continue); return reportList; } finally { generateSuperviseLock.Set(); } } /// /// 获取当前记录序号 /// /// private int queryCurrentExceIndex() { var exceId = DbContext.sac_report_notes.OrderByDescending(O => O.ExceId).Select(O => O.ExceId).FirstOrDefault(); int index = 1; if (!string.IsNullOrWhiteSpace(exceId)) { exceId = Regex.Match(exceId, @"\d{8}$").Value; index = int.Parse(exceId) + 1; } return index; } /// /// 获取当前报送文件序号 /// /// /// private int queryCurrentFileIndex(DateTime date) { var fileId = DbContext.supervise_report.Where(O => O.ReportDate == date && O.ReportType == SuperviseReportTypeEnum.SAC).OrderByDescending(O => O.FileTag).Select(O => O.FileTag).FirstOrDefault(); int index = 1; if (!string.IsNullOrWhiteSpace(fileId)) { fileId = Regex.Match(fileId, @"\d{4}$").Value; index = int.Parse(fileId) + 1; } return index; } #endregion /// /// 发送报送文件 /// /// /// public ReturnInfo SentReport(int id) { //if (DbContext.supervise_report.Where(O => O.ReportType == SuperviseReportTypeEnum.SAC && O.id < id && O.ReportReponseStatus <= ReportSentStatus.SENDING).Any()) //{ // return Return.Fail("请按照生成顺序发送报告,并等待收到结果后再操作"); //} try { var fileInfo = DbContext.supervise_report.Where(O => O.id == id).FirstOrDefault(); if (fileInfo == null) { return Return.Fail("记录不存在,请刷新页面后重试"); } var absPath = OtcAppContext.MapPath(fileInfo.FilePath); if (!System.IO.File.Exists(absPath)) { return Return.Fail("文件不存在"); } string targetPath = PS.Config.ErpElement.SAC_FDEPOutboxPath ?? ""; if (string.IsNullOrWhiteSpace(targetPath) && string.IsNullOrWhiteSpace(PS.Config.ErpElement.SAC_RemotePath_Outbox)) { return Return.Fail("发件箱地址不存在"); } if (targetPath.ToLower().Contains("{yyyy}")) { targetPath = targetPath.ToLower().Replace("{yyyy}", DateTime.Now.ToString("yyyy")); } if (targetPath.ToLower().Contains("{mm}")) { targetPath = targetPath.ToLower().Replace("{mm}", DateTime.Now.ToString("MM")); } if (targetPath.ToLower().Contains("{dd}")) { targetPath = targetPath.ToLower().Replace("{dd}", DateTime.Now.ToString("dd")); } IdentityScope identityScope = null; FtpHelper ftpHelper = null; try { if (!string.IsNullOrWhiteSpace(PS.Config.ErpElement.SAC_RemotePath_Outbox) && !string.IsNullOrWhiteSpace(PS.Config.ErpElement.SAC_RemoteUser) && !string.IsNullOrWhiteSpace(PS.Config.ErpElement.SAC_RemotePassword)) { if (PS.Config.ErpElement.SAC_RemotePath_Outbox.ToLower().StartsWith("ftp")) { ftpHelper = new FtpHelper(PS.Config.ErpElement.SAC_RemotePath_Outbox, PS.Config.ErpElement.SAC_RemoteUser, PS.Config.ErpElement.SAC_RemotePassword, PS.Config.ErpElement.SAC_FtpUsePassive, 3000, PS.Config.ErpElement.SAC_EnableSsl); } else { identityScope = new IdentityScope(PS.Config.ErpElement.SAC_RemoteUser, PS.Config.ErpElement.SAC_RemotePath_Outbox, PS.Config.ErpElement.SAC_RemotePassword); } } if (ftpHelper == null) { if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } targetPath = Path.Combine(targetPath, fileInfo.FileTag + ".zip"); File.Copy(absPath, targetPath); File.Create(absPath + ".ok").Close(); File.Copy(absPath + ".ok", targetPath + ".ok"); } else { if (ftpHelper.UploadFile(absPath, targetPath, out string msg)) { File.Create(absPath + ".ok").Close(); ftpHelper.UploadFile(absPath + ".ok", targetPath, out msg); } else { LogFactory.GetLogger("SentReport-SaveDb").Error(msg); } } try { fileInfo.ReportReponseStatus = ReportSentStatus.SENDING; fileInfo.optDate = DateTime.Now; fileInfo.optUserId = UserId; DbContext.SaveChanges(); } catch (Exception ex) { LogFactory.GetLogger("SentReport-SaveDb").Error(ex); } return Return.Success("成功,结果将稍后更新,请至历史报送列表中查看"); } catch (Exception ex) { LogFactory.GetLogger("SentReport-SaveDb").Error(ex); } finally { identityScope?.Dispose(); } } catch (Exception ex) { LogFactory.GetLogger("SentReport").Error(ex); } return Return.Success("报送失败,请检查日志"); } /// /// 删除报送文件 /// /// /// public bool DeleteReport(string fileTag) { try { var xmlFileTag = (fileTag ?? "").Replace("YSP_", ""); var query = DbContext.supervise_report.Where(O => O.FileTag.StartsWith(fileTag) || O.FileTag.StartsWith(xmlFileTag)); var tags = query.Select(O => O.FileTag); DbContext.supervise_report.RemoveRange(query); var sacNotes = DbContext.sac_report_notes.Where(O => tags.Contains(O.FileTag)).ToList(); sacNotes.ForEach(O => { O.OptTime = DateTime.Now; O.FileTag = "xx" + O.FileTag; }); DbContext.SaveChanges(); return true; } catch (Exception ex) { LogFactory.GetLogger("DeleteReport").Error(ex); return false; } } #region 处理报送响应文件 private static readonly HashSet _responseFileNames = new HashSet(); private static readonly HashSet _errFileNames = new HashSet(); private const string responseDir = "/App_Docs/Download/ReportResponse/"; private const string tempDir = "/App_Docs/Download/ReportResponse/Temp/"; private static bool runStatus = false; public static void ListensResponse() { if (runStatus) { return; } runStatus = true; IdentityScope identityScope = null; FtpHelper ftpHelper = null; try { if (!string.IsNullOrWhiteSpace(PS.Config.ErpElement.SAC_RemotePath) && !string.IsNullOrWhiteSpace(PS.Config.ErpElement.SAC_RemoteUser) && !string.IsNullOrWhiteSpace(PS.Config.ErpElement.SAC_RemotePassword)) { if (PS.Config.ErpElement.SAC_RemotePath.ToLower().StartsWith("ftp")) { ftpHelper = new FtpHelper(PS.Config.ErpElement.SAC_RemotePath, PS.Config.ErpElement.SAC_RemoteUser, PS.Config.ErpElement.SAC_RemotePassword, PS.Config.ErpElement.SAC_FtpUsePassive, 3000, PS.Config.ErpElement.SAC_EnableSsl); } else { identityScope = new IdentityScope(PS.Config.ErpElement.SAC_RemoteUser, PS.Config.ErpElement.SAC_RemotePath, PS.Config.ErpElement.SAC_RemotePassword); } } string path = PS.Config.ErpElement.SAC_FDEPInboxPath ?? ""; if (string.IsNullOrWhiteSpace(path) && string.IsNullOrWhiteSpace(PS.Config.ErpElement.SAC_RemotePath)) { return; } if (path.ToLower().Contains("{yyyy}")) { path = path.ToLower().Replace("{yyyy}", DateTime.Now.ToString("yyyy")); } if (path.ToLower().Contains("{mm}")) { path = path.ToLower().Replace("{mm}", DateTime.Now.ToString("MM")); } if (path.ToLower().Contains("{dd}")) { path = path.ToLower().Replace("{dd}", DateTime.Now.ToString("dd")); } if (ftpHelper == null ? !Directory.Exists(path) : !ftpHelper.ExistDirectorie(path)) { return; } string[] fileNames = ftpHelper == null ? Directory.GetFiles(path) : ftpHelper.GetDirectories(path); var fileNameArr = fileNames.Except(_responseFileNames).Except(_errFileNames).ToArray(); string resDir = OtcAppContext.MapPath(responseDir); if (!Directory.Exists(resDir)) { Directory.CreateDirectory(resDir); } string tDir = OtcAppContext.MapPath(tempDir); if (!Directory.Exists(tDir)) { Directory.CreateDirectory(tDir); } string targetName = ""; string msg = ""; foreach (var item in fileNameArr) { targetName = Path.Combine(resDir, Path.GetFileName(item)); var extensionName = Path.GetExtension(targetName); if (extensionName.ToLower() != ".zip" || File.Exists(targetName)) { _responseFileNames.Add(item); continue; } LogFactory.GetLogger("ListensResponse").Info($"发现新文件:{targetName}"); if (ftpHelper == null) { try { File.Copy(item, targetName); } catch (IOException ex) { LogFactory.GetLogger("ListensResponse").Error(ex); } } else { targetName = ftpHelper.DownloadFile($"{path}{item}", resDir, out msg); } LogFactory.GetLogger("ListensResponse").Info($"准备解压:{targetName} to {tDir}"); var outPath = ZipHelper.unZipFile(targetName, tDir, out msg); if (msg.StartsWith("解压失败")) { LogFactory.GetLogger("ListensResponse").Info($"解压失败,跳过本次解析:{msg}"); File.Delete(targetName); continue; } LogFactory.GetLogger("ListensResponse").Info($"解压操作:{msg}"); if (msg.StartsWith("解压成功")) { saveReportResponse(outPath, Regex.Replace(targetName, @"^.+(?=\\App_Docs\\Download)", "").Replace("\\", "/")); } else { LogFactory.GetLogger("ListensResponse").Error($"文件:{item}\r\n{msg}"); _errFileNames.Add(item); } _responseFileNames.Add(item); } setTimeOutReportResponse(); } catch (Exception ex) { LogFactory.GetLogger("ListensResponse").Error(ex, ex.ToString()); } finally { identityScope?.Dispose(); runStatus = false; } } private static void setTimeOutReportResponse() { using (var db = DbContextFactory.GetYLDbContext()) { var time = DateTime.Now.AddMinutes(-10); var timeOutQuery = db.supervise_report.Where(O => O.ReportReponseStatus == ReportSentStatus.SENDING && O.optDate < time); foreach (var item in timeOutQuery) { item.ReportReponseStatus = ReportSentStatus.ERROR; item.ReportReponseCode = "-000001"; item.ReportReponseMessage = "超时"; } db.SaveChanges(); } } private static void saveReportResponse(string path, string zipPath) { var files = Directory.EnumerateFiles(path); using (var db = DbContextFactory.GetYLDbContext()) { List status = new List(); List fileTagList = new List(); foreach (var item in files) { LogFactory.GetLogger("ListensResponse").Info($"处理文件:{item}"); var tag = Path.GetFileNameWithoutExtension(item); var arr = tag.Split('_').ToList(); if (arr.Count < 6) { continue; } if (arr.Count == 6) { arr.Insert(3, "YSP"); } var temp = arr[1]; arr[1] = arr[2]; arr[2] = temp; arr.RemoveAt(arr.Count - 1); tag = string.Join("_", arr); fileTagList.Add(tag); LogFactory.GetLogger("ListensResponse").Info($"生成tag:{tag}"); var reportInfo = db.supervise_report.Where(O => O.FileTag == tag).FirstOrDefault(); if (reportInfo == null) { continue; } LogFactory.GetLogger("ListensResponse").Info($"找到文件记录:{reportInfo.id}"); var xml = File.ReadAllText(item); ReportRootModel model = XmlHelper.Deserialize(xml); reportInfo.ReportReponseCode = model.Header.RetCode; reportInfo.ReportReponseMessage = model.Header.RetMsg; reportInfo.ReportReponseStatus = reportInfo.ReportReponseCode == "000000" && (reportInfo.ReportType != SuperviseReportTypeEnum.SAC || status.All(O => O)) ? ReportSentStatus.SUCCESS : ReportSentStatus.ERROR; reportInfo.optDate = DateTime.Now; status.Add(reportInfo.ReportReponseCode == "000000"); if (reportInfo.ReportType == SuperviseReportTypeEnum.SAC) { LogFactory.GetLogger("ListensResponse").Info($"修改压缩文件记录:{reportInfo.id}"); reportInfo.ReportReponsePath = zipPath; } else { if (model.Body == null) { continue; } var kingstarViewResponseSqlList = new List(); switch (reportInfo.ReportType) { case SuperviseReportTypeEnum.SAC_MasterAgrmt: setSacNotes(db, model.Body.MasterAgrmt, model.Header); break; case SuperviseReportTypeEnum.SAC_MasterAgrmtProduct: setSacNotes(db, model.Body.MasterAgrmtProduct, model.Header); break; case SuperviseReportTypeEnum.SAC_SupAgrmt: setSacNotes(db, model.Body.SupAgrmt, model.Header); break; case SuperviseReportTypeEnum.SAC_PerformanceGuaranteeAgrmt: setSacNotes(db, model.Body.PerformanceGuaranteeAgrmt, model.Header); break; case SuperviseReportTypeEnum.SAC_OptionConfirmation: setSacNotes(db, model.Body.OptionConfirmation, model.Header); break; case SuperviseReportTypeEnum.SAC_SwapConfirmation: setSacNotes(db, model.Body.SwapConfirmation, model.Header); LogFactory.GetLogger("kingstarViewResponse").Info($"开始业务:SwapConfirmation"); CreateKingstarViewResponseSql(db, kingstarViewResponseSqlList, model.Body.SwapConfirmation); LogFactory.GetLogger("kingstarViewResponse").Info($"结束业务:SwapConfirmation"); break; case SuperviseReportTypeEnum.SAC_OptionTermination: model.Body.OptionTermination.ForEach(O => { ((ReportBaseModel)O).BizID = O.BizID; ((ReportBaseModel)O).DurationEventNO = O.DurationEventNO; }); setSacNotes(db, model.Body.OptionTermination, model.Header); break; case SuperviseReportTypeEnum.SAC_SwapDurationManagement: model.Body.SwapDurationManagement.ForEach(O => { ((ReportBaseModel)O).BizID = O.BizID; ((ReportBaseModel)O).DurationEventNO = O.DurationEventNO; }); setSacNotes(db, model.Body.SwapDurationManagement, model.Header); LogFactory.GetLogger("kingstarViewResponse").Info($"开始业务:SwapDurationManagement"); CreateKingstarViewResponseSql(db, kingstarViewResponseSqlList, model.Body.SwapDurationManagement); LogFactory.GetLogger("kingstarViewResponse").Info($"结束业务:SwapDurationManagement"); break; case SuperviseReportTypeEnum.SAC_PeriodicReportSAC: ((ReportBaseModel)model.Body.PeriodicReportSAC).BizID = model.Body.PeriodicReportSAC.BizID; ((ReportBaseModel)model.Body.PeriodicReportSAC).DurationEventNO = model.Body.PeriodicReportSAC.DurationEventNO; setSacNotes(db, model.Body.PeriodicReportSAC, model.Header); break; case SuperviseReportTypeEnum.SAC_PeriodicReportNAFMII: ((ReportBaseModel)model.Body.PeriodicReportNAFMII).BizID = model.Body.PeriodicReportNAFMII.BizID; ((ReportBaseModel)model.Body.PeriodicReportNAFMII).DurationEventNO = model.Body.PeriodicReportNAFMII.DurationEventNO; setSacNotes(db, model.Body.PeriodicReportNAFMII, model.Header); break; case SuperviseReportTypeEnum.SAC_PeriodicReportISDA: ((ReportBaseModel)model.Body.PeriodicReportISDA).BizID = model.Body.PeriodicReportISDA.BizID; ((ReportBaseModel)model.Body.PeriodicReportISDA).DurationEventNO = model.Body.PeriodicReportISDA.DurationEventNO; setSacNotes(db, model.Body.PeriodicReportISDA, model.Header); break; case SuperviseReportTypeEnum.SAC_EventReport: ((ReportBaseModel)model.Body.EventReport).BizID = model.Body.EventReport.BizID; ((ReportBaseModel)model.Body.EventReport).DurationEventNO = model.Body.EventReport.DurationEventNO; setSacNotes(db, model.Body.EventReport, model.Header); break; case SuperviseReportTypeEnum.SAC_OtherReport: ((ReportBaseModel)model.Body.OtherReport).BizID = model.Body.OtherReport.BizID; ((ReportBaseModel)model.Body.OtherReport).DurationEventNO = model.Body.OtherReport.DurationEventNO; setSacNotes(db, model.Body.OtherReport, model.Header); break; case SuperviseReportTypeEnum.SAC_PeriodicReportQuarter: ((ReportBaseModel)model.Body.PeriodicReportQuarter).BizID = model.Body.PeriodicReportQuarter.BizID; ((ReportBaseModel)model.Body.PeriodicReportQuarter).DurationEventNO = model.Body.PeriodicReportQuarter.DurationEventNO; setSacNotes(db, model.Body.PeriodicReportQuarter, model.Header); break; case SuperviseReportTypeEnum.SAC_ContractNumberProcess: ((ReportBaseModel)model.Body.ContractNumberProcess).BizID = model.Body.ContractNumberProcess.BizID; ((ReportBaseModel)model.Body.ContractNumberProcess).DurationEventNO = model.Body.ContractNumberProcess.DurationEventNO; setSacNotes(db, model.Body.ContractNumberProcess, model.Header); break; case SuperviseReportTypeEnum.SAC_SwapEquityPayment: model.Body.SwapEquityPayment.ForEach(O => { ((ReportBaseModel)O).BizID = O.BizID; ((ReportBaseModel)O).DurationEventNO = O.DurationEventNO; }); setSacNotes(db, model.Body.SwapEquityPayment, model.Header); LogFactory.GetLogger("kingstarViewResponse").Info($"开始业务:SwapEquityPayment"); CreateKingstarViewResponseSql(db, kingstarViewResponseSqlList, model.Body.SwapEquityPayment); LogFactory.GetLogger("kingstarViewResponse").Info($"结束业务:SwapEquityPayment"); break; case SuperviseReportTypeEnum.SAC_ConfirmationAtt: model.Body.ConfirmationAtt.ForEach(O => { ((ReportBaseModel)O).BizID = O.BizID; ((ReportBaseModel)O).DurationEventNO = O.DurationEventNO; }); setSacNotes(db, model.Body.ConfirmationAtt, model.Header); //金仕达视图 LogFactory.GetLogger("kingstarViewResponse").Info($"开始业务:ConfirmationAtt"); CreateKingstarViewResponseSql(db, kingstarViewResponseSqlList, model.Body.ConfirmationAtt); LogFactory.GetLogger("kingstarViewResponse").Info($"结束业务:ConfirmationAtt"); break; default: break; } if (kingstarViewResponseSqlList.Count > 0) { KingstarViewResponse(kingstarViewResponseSqlList); } } db.SaveChanges(); } var subSystemInboxPath = PS.Config.ClientElement.SAC_SubSystemInboxPath; LogFactory.GetLogger("ListensResponse").Info($"开始x1111subSystemInboxPath:{subSystemInboxPath}"); LogFactory.GetLogger("ListensResponse").Info($"Path:{path}"); if (!string.IsNullOrEmpty(subSystemInboxPath)) { ResponseSubsystem(db, path, subSystemInboxPath, fileTagList); } } } private const string responseSubsystemDir = "/App_Docs/Download/ReportResponse/Subsystem/"; /// /// 解析一个zip文件 /// /// /// zip文件解压后的文件夹路径 /// /// private static void ResponseSubsystem(YLContext db, string path, string subSystemInboxPath, List fileTagList) { LogFactory.GetLogger("ListensResponse").Info($"path:{path}"); LogFactory.GetLogger("ListensResponse").Info($"subSystemInboxPath:{subSystemInboxPath}"); LogFactory.GetLogger("ListensResponse").Info($"fileTagListCount:{fileTagList.Count()}"); LogFactory.GetLogger("ListensResponse").Info($"fileTagList:{string.Join(",", fileTagList)}"); var responseRootDir = OtcAppContext.MapPath(responseSubsystemDir); if (!Directory.Exists(responseRootDir)) Directory.CreateDirectory(responseRootDir); LogFactory.GetLogger("ListensResponse").Info($"responseRootDir:{responseRootDir}"); var noteList = db.sac_report_notes.Where(O => fileTagList.Contains(O.FileTag) && O.InfoCache.Contains("Subsystem")).Select(O => O.InfoCache).ToArray().Select(O => Regex.Match(O, @"(?<=SubFileTag)[^,]+(?=,)").Value).ToHashSet(); LogFactory.GetLogger("ListensResponse").Info($"noteListCount:{noteList.Count()}"); LogFactory.GetLogger("ListensResponse").Info($"noteList:{string.Join(",", noteList)}"); var fileNames = Directory.GetFiles(path);//zip对应文件夹下的xml文件列表 LogFactory.GetLogger("ListensResponse").Info($"fileNames:{fileNames.Count()}"); foreach (var item in noteList) { LogFactory.GetLogger("ListensResponse").Info($"item:{item}"); LogFactory.GetLogger("ListensResponse").Info($"itemLength:{item.Length}"); var filetag = item.Substring(3, item.Length - 4); var resDir = Path.Combine(responseRootDir, filetag); if (Directory.Exists(resDir))//存在先删除目录和下边文件,避免文件夹重名和文件重名,而出现错误 { ClearResDirContent(resDir); } Directory.CreateDirectory(resDir);//重新创建 foreach (var fileName in fileNames) { var targetName = Path.Combine(resDir, Path.GetFileName(fileName)); LogFactory.GetLogger("ListensResponse").Info($"targetName:{targetName}"); LogFactory.GetLogger("ListensResponse").Info($"fileName:{fileName}"); File.Copy(fileName, targetName); LogFactory.GetLogger("ListensResponse").Info($"okxxxx"); } string[] tempFileNames = Directory.GetFiles(resDir); var totalFilePath = ""; var groupFileDic = new Dictionary>(); foreach (var fileItem in tempFileNames) { var tag = Path.GetFileNameWithoutExtension(fileItem); if (tag.Length < 41) { totalFilePath = fileItem; continue; } LogFactory.GetLogger("ListensResponse").Info("xxx"); HandleXmlFile(db, fileItem, filetag, resDir); LogFactory.GetLogger("ListensResponse").Info("yyyy"); } tempFileNames = Directory.GetFiles(resDir); LogFactory.GetLogger("ListensResponse").Info(string.Join(",", tempFileNames)); var smallFileCount = 0; LogFactory.GetLogger("ListensResponse").Info("zzz"); LogFactory.GetLogger("ListensResponse").Info("temFileNames:" + string.Join(",", tempFileNames)); LogFactory.GetLogger("ListensResponse").Info("temFileNamesCount:" + tempFileNames.Length); foreach (var fileItem in tempFileNames)//解压文件夹下的xml文件 { var tag = Path.GetFileNameWithoutExtension(fileItem); LogFactory.GetLogger("ListensResponse").Info("fileItem:" + fileItem); LogFactory.GetLogger("ListensResponse").Info("tag.Length" + tag.Length); if (tag.Length >= 41) smallFileCount++; } if (smallFileCount == 0) { LogFactory.GetLogger("ListensResponse").Info($"smallFileCount==0"); File.Delete(totalFilePath); Directory.Delete(resDir); } else { LogFactory.GetLogger("ListensResponse").Info($"smallFileCount!=0"); var newFileName = RenameTotalXmlFileName(resDir, totalFilePath, filetag); UpdateTotalXmlFileNumber(newFileName, filetag); LogFactory.GetLogger("ListensResponse").Info("yyyyyzzzz"); CreateSubsystemResponse(resDir, subSystemInboxPath, filetag); LogFactory.GetLogger("ListensResponse").Info("sssz"); } } } private static string RenameTotalXmlFileName(string resDir, string totalFilePath, string filetag) { LogFactory.GetLogger("ListensResponse").Info($"resDir:{resDir}"); LogFactory.GetLogger("ListensResponse").Info($"totalFilePath:{totalFilePath}"); LogFactory.GetLogger("ListensResponse").Info($"filetag:{filetag}"); var totalTag = Path.GetFileNameWithoutExtension(totalFilePath); var newFileName = Path.Combine(resDir, CovertResponseTag(filetag) + totalTag.Substring(31) + ".xml"); FileInfo fi = new FileInfo(totalFilePath); fi.MoveTo(newFileName); //File.Move(totalFilePath, newFileName); //File.Delete(totalFilePath); return newFileName; } private static void RenameXmlFileName(string resDir, string xmlFile, string filetag) { var oldFileTag = Path.GetFileNameWithoutExtension(xmlFile);//OTC_123654_000899_YSP_20220714_0007 var newFileName = Path.Combine(resDir, CovertResponseTag(filetag) + oldFileTag.Substring(31) + ".xml"); FileInfo fi = new FileInfo(xmlFile); fi.MoveTo(newFileName); if (xmlFile != newFileName) File.Delete(xmlFile); LogFactory.GetLogger("ListensResponse").Info($"move:{xmlFile} to {newFileName}"); //RenameFile(xmlFile, newFileName); } private static string CovertResponseTag(string filetag) { return CovertResponseTag(filetag, true); } private static string CovertResponseTag(string filetag, bool removeYsp) { var arr = filetag.Split('_').ToList(); var temp = arr[1]; arr[1] = arr[2]; arr[2] = temp; var tag = string.Join("_", arr); if (removeYsp) tag = tag.Replace("_YSP", ""); return tag; } private static void ClearResDirContent(string resDir) { string[] fileList = Directory.GetFiles(resDir); foreach (var file in fileList) { File.Delete(file); } Directory.Delete(resDir); } private static void UpdateTotalXmlFileNumber(string xmlFile, string fileTag) { var xmldoc = new XmlDocument(); xmldoc.Load(xmlFile); UpdateXmlFileNumber(xmldoc, fileTag); xmldoc.Save(xmlFile); } private static void UpdateXmlFileNumber(XmlDocument xmldoc, string fileTag) { var layerHeadName = "/Root/Header"; var headerNode = xmldoc.SelectSingleNode(layerHeadName); var fileNumber = fileTag.Split("_".ToCharArray())[5]; headerNode.SelectSingleNode("FileNumber").InnerText = fileNumber; } /// /// 压缩文件生成响应zip文件 /// /// /// /// private static void CreateSubsystemResponse(string resDir, string subSystemInboxPath, string fileTag) { LogFactory.GetLogger("CreateSubsystemResponse").Info($"reportNote:null,excefileTag=" + fileTag); var marketZipFile = Path.Combine(subSystemInboxPath, CovertResponseTag(fileTag, false) + ".zip"); LogFactory.GetLogger("CreateSubsystemResponse").Info($"reportNote:null,marketZipFile=" + marketZipFile); ZipHelper.zipFile(resDir, marketZipFile); LogFactory.GetLogger("CreateSubsystemResponse").Info($"reportNote:null,zipFile成功"); ClearResDirContent(resDir);//删除临时文件夹,要不A和D操作会用同名文件夹,拷贝会出现文件已经存在问题 } private static void HandleXmlFile(YLContext db, string xmlFile, string fileTag, string resDir) { var xmldoc = new XmlDocument(); xmldoc.Load(xmlFile); UpdateXmlFileNumber(xmldoc, fileTag); LogFactory.GetLogger("ListensResponse").Info($"xml= {xmldoc.ToString()}"); var layerName = "/Root/Body"; var bodyNode = xmldoc.SelectSingleNode(layerName); var bodyChildlist = bodyNode.ChildNodes; int totalCount = bodyChildlist.Count; var tag = ""; for (var i = 0; i < totalCount; i++) { var bodyChildNode = bodyChildlist[i]; var excelId = bodyChildNode.FirstChild.InnerText; var reportNote = db.sac_report_notes.FirstOrDefault(x => x.ExceId == excelId); if (reportNote == null) { LogFactory.GetLogger("ListensResponse").Info($"reportNote:null,excelId=" + excelId); bodyNode.RemoveChild(bodyChildNode); i--; totalCount--; continue; } var infoCacheDict = JsonHelper.Deserialize>(reportNote.InfoCache); if (!infoCacheDict.TryGetValue("SubFileTag", out tag) || string.IsNullOrEmpty(tag)) { LogFactory.GetLogger("ListensResponse").Info($"SubFileTag:null,SubFileTag=" + tag); bodyNode.RemoveChild(bodyChildNode); i--; totalCount--; continue; } if (tag != fileTag) { bodyNode.RemoveChild(bodyChildNode); i--; totalCount--; continue; } var source = ""; if (!infoCacheDict.TryGetValue("Source", out source) || string.IsNullOrEmpty(source) || source != "Subsystem") { bodyNode.RemoveChild(bodyChildNode); i--; totalCount--; continue; } var oldExcelId = ""; if (!infoCacheDict.TryGetValue("ExceID", out oldExcelId) || string.IsNullOrEmpty(oldExcelId)) { bodyNode.RemoveChild(bodyChildNode); i--; totalCount--; continue; } bodyChildNode.FirstChild.InnerText = oldExcelId; } xmldoc.Save(xmlFile); if (bodyNode.ChildNodes.Count == 0) { File.Delete(xmlFile); return; } //修改文件名 LogFactory.GetLogger("ListensResponse").Info($"文件保留,xmlFile=" + xmlFile); RenameXmlFileName(resDir, xmlFile, fileTag); } private static void setSacNotes(YLContext db, ReportBaseModel model, HeaderModel header) { if (model == null) { return; } setSacNotes(db, new[] { model }, header); } public static void CreateKingstarViewResponseSql(YLContext db, List kingstarViewResponseList, IEnumerable model) { string schema = PS.Config.ErpElement.KingstarViewTableSchema.IsNullOrWhiteSpace() ? "" : $"\"{PS.Config.ErpElement.KingstarViewTableSchema}\"."; var exceIds = model.Select(O => O.ExceID); LogFactory.GetLogger("kingstarViewResponse").Info($"exceIds:{string.Join(",", exceIds)}"); var dict = db.sac_report_notes.Where(O => exceIds.Contains(O.ExceId)).ToDictionary(K => K.ExceId, V => V); LogFactory.GetLogger("kingstarViewResponse").Info($"dict count:{dict.Count}"); foreach (var item in model) { LogFactory.GetLogger("kingstarViewResponse").Info($"开始excelId:{item.ExceID}"); if (!dict.ContainsKey(item.ExceID)) continue; var note = dict[item.ExceID]; var infoCacheDict = JsonHelper.Deserialize>(note.InfoCache); if (infoCacheDict["Source"] != "KingstarView") continue; var curDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00"); var batchDate = DateTime.Now.ToString("yyyyMMdd"); var curTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var eventNo = item.DurationEventNO; var bizzType = ""; switch (note.ReportType) { case SuperviseReportTypeEnum.SAC_SwapConfirmation: bizzType = "SWAPID"; break; case SuperviseReportTypeEnum.SAC_SwapDurationManagement: bizzType = "SWAPDURATION"; break; case SuperviseReportTypeEnum.SAC_SwapEquityPayment: bizzType = "SWAPRIGHTPAY"; break; case SuperviseReportTypeEnum.SAC_ConfirmationAtt: bizzType = "CONFIRMATIONATTR"; break; } infoCacheDict.TryGetValue("Tag", out string bizzID); var rptID = item.BizID; var sqlMapping = $"INSERT INTO {schema}TRANS_RPT_MAPPING(BIZZ_ID,RPT_ID,BIZZ_TYPE,CREATED_DATETIME,PUSH_TIME,EVENT_DATE,EVENT_NO)VALUES('{bizzID}','{rptID}','{bizzType}',to_date('{curDate}', 'yyyy-mm-dd hh24:mi:ss'),to_date('{curTime}', 'yyyy-mm-dd hh24:mi:ss'),to_date('{curDate}', 'yyyy-mm-dd hh24:mi:ss'),'{eventNo}')"; LogFactory.GetLogger("kingstarViewResponse").Info($"sqlMapping:{sqlMapping}"); kingstarViewResponseList.Add(sqlMapping); var guidKey = Guid.NewGuid().ToString("N"); const string taskName = "KS_SWAP_NEW_CONFIRMATION_ETL"; const string taskDecc = "监管新规报备视图跑批任务"; var resultFlag = note.RetCode == "000000" ? "SUCCESS" : "FAILED"; var sqlLog = $"INSERT INTO {schema}ADM_EODBATCH_LOG(LOG_ID,BATCH_DATE,TASK_NAME,TASK_DESC,LOG_DATETIME,RESULT_FLAG)VALUES('{guidKey}','{batchDate}','{taskName}','{taskDecc}',to_date('{curTime}', 'yyyy-mm-dd hh24:mi:ss'),'{resultFlag}')"; kingstarViewResponseList.Add(sqlLog); LogFactory.GetLogger("kingstarViewResponse").Info($"sqlLog:{sqlLog}"); LogFactory.GetLogger("kingstarViewResponse").Info($"开始excelId:{item.ExceID}"); } } private static void KingstarViewResponse(List sqlList) { var connection = PS.Config.ErpElement.KingstarViewConnectionString; LogFactory.GetLogger("kingstarViewResponse").Info($"链接字符串:{connection}"); using (var db = new DbHelper(connection)) { db.ExecuteNoSqlsQuery(sqlList); } LogFactory.GetLogger("kingstarViewResponse").Info($"Success!"); } private static void setSacNotes(YLContext db, IEnumerable model, HeaderModel header) { var exceIds = model.Select(O => O.ExceID); var dict = db.sac_report_notes.Where(O => exceIds.Contains(O.ExceId)).ToDictionary(K => K.ExceId, V => V); List sendFileId = new List(); foreach (var item in model) { if (!dict.ContainsKey(item.ExceID)) { continue; } var note = dict[item.ExceID]; LogFactory.GetLogger("ListensResponse").Info($"找到文件明细:{note.id}"); note.RetCode = item.RetCode; note.RetMsg = item.RetMsg; note.ReportResponse = note.RetCode == "000000"; note.BizId = item.BizID ?? ""; note.OptTime = DateTime.Now; LogFactory.GetLogger("ListensResponse").Info($"更新文件明细:{note.ToJson()}"); if (note.ReportResponse) { Dictionary infoCacheDict = JsonHelper.Deserialize>(note.InfoCache); infoCacheDict["DurationEventNO"] = item.DurationEventNO ?? ""; note.InfoCache = infoCacheDict.ToJson(); if (note.ReportType == SuperviseReportTypeEnum.SAC_MasterAgrmt || note.ReportType == SuperviseReportTypeEnum.SAC_MasterAgrmtProduct || note.ReportType == SuperviseReportTypeEnum.SAC_SupAgrmt || note.ReportType == SuperviseReportTypeEnum.SAC_PerformanceGuaranteeAgrmt) { int dataId = 0; LogFactory.GetLogger("ListensResponse").Info($"客户协议相关明细:{note.DataId}"); if (int.TryParse(note.DataId, out dataId)) { sendFileId.Add(dataId); } }//展期报告成功后要修改交易报告记录中的到期日 else if (note.InfoTag.Contains("_展期_") && (note.ReportType == SuperviseReportTypeEnum.SAC_OptionTermination || note.ReportType == SuperviseReportTypeEnum.SAC_SwapDurationManagement)) { EditTradeDueDate(db, note); }//如果是废止报告,要把该报告对应的所有新增和修改的报告状态修改为无效 if (note.InfoTag.EndsWith("_D")) { ValidSacNote(db, note); } } } if (sendFileId.Count > 0) { LogFactory.GetLogger("ListensResponse").Info($"修改客户文件报送状态:{sendFileId.ToJson()}"); new ClientFileService(OptUserInfo.SystemUser).ChangeFileSentStates(sendFileId); } } /// /// 修改交易报告记录中的到期日 /// /// /// private static void EditTradeDueDate(YLContext db, SACReportNotes note) { var code = note.InfoTag.Split('_')[1]; var dateStr = ""; if (note.InfoTag.EndsWith("_D")) {//废止报告使用原到期日覆盖 dateStr = Regex.Match(note.InfoCache, "(?<=OldMaturityDate\":\")[^\"]+(?=\")").Value; } else {//非废止报告使用新到期日覆盖 dateStr = Regex.Match(note.InfoCache, "(?<=NewMaturityDate\":\")[^\"]+(?=\")").Value; } if (!string.IsNullOrEmpty(dateStr)) { var notes = db.sac_report_notes .Where(O => O.ReportType == (note.ReportType - 2) && O.InfoTag.Contains(code) && O.IsValid == true && O.ReportResponse) .OrderByDescending(O => O.OptTime).ToList(); foreach (var n in notes) {//覆盖交易到期日 n.InfoCache = Regex.Replace(n.InfoCache, "(?<=DueDate\":\")[^\"]+(?=\")", dateStr); } } } /// /// 把该报告对应的所有新增和修改的报告状态修改为无效 /// /// /// private static void ValidSacNote(YLContext db, SACReportNotes note) { Dictionary infoCacheDict = JsonHelper.Deserialize>(note.InfoCache); if (!infoCacheDict.TryGetValue("Tag", out string tag)) { tag = " "; } tag = $"\"Tag\":\"{tag}\""; var infoTag = note.InfoTag.Remove(note.InfoTag.Length - 1); //因为履约保证书的InfoCache字段值是附件名,允许被修改,所以不作为筛选条件; var arr = db.sac_report_notes .Where(O => O.IsValid && (O.ReportType == SuperviseReportTypeEnum.SAC_PerformanceGuaranteeAgrmt || O.ReportType == SuperviseReportTypeEnum.SAC_OptionConfirmation || O.ReportType == SuperviseReportTypeEnum.SAC_SwapConfirmation || O.ReportType == SuperviseReportTypeEnum.SAC_OptionTermination || O.ReportType == SuperviseReportTypeEnum.SAC_SwapDurationManagement || O.ReportType == SuperviseReportTypeEnum.SAC_SwapEquityPayment || O.InfoCache.Contains(tag)) && O.InfoTag.Contains(infoTag)).ToArray(); foreach (var item1 in arr) { if (!note.InfoTag.Contains("_展期_") && (item1.ReportType == SuperviseReportTypeEnum.SAC_OptionTermination || item1.ReportType == SuperviseReportTypeEnum.SAC_SwapDurationManagement)) { Dictionary dict2 = JsonHelper.Deserialize>(item1.InfoCache); if (!infoCacheDict.ContainsKey("ValueDate") || !dict2.ContainsKey("ValueDate") || infoCacheDict["ValueDate"] != dict2["ValueDate"]) { continue; } } item1.IsValid = false; } } #endregion #region 查询报送信息 /// /// 查询已报送的文件 /// /// /// /// /// public IQueryable QueryReportHistoryFromDb() { var query = DbContext.supervise_report.AsQueryable(); return query; } /// /// 查询报送文件 /// /// /// public ReturnInfo QueryReportInfo(DateTime reportDate) { DateTime lastMonthEnd = reportDate.AddDays(-reportDate.Day); var superviseReport = DbContext.supervise_report .Where(O => O.ReportDate <= reportDate) .OrderByDescending(O => O.ReportDate) .ThenByDescending(O => O.optDate) .FirstOrDefault(); if (PS.Config.Company == Configuration.CompanyEnum.中金 && superviseReport == null) { superviseReport = DbContext.supervise_report .OrderByDescending(O => O.ReportDate) .ThenByDescending(O => O.optDate) .FirstOrDefault(); } ReportInfo info = new ReportInfo(); info.ReportDate = reportDate; if (superviseReport != null) { info.SenderCode = superviseReport.SenderCode; info.ReceiverCode = superviseReport.ReceiverCode; if (reportDate.Year == superviseReport.ReportDate.Year && reportDate.Month == superviseReport.ReportDate.Month) { info.LastMonthCash = superviseReport.LastMonthCash; info.LatestMonthCash = superviseReport.LatestMonthCash; } else if (reportDate.Year == superviseReport.ReportDate.Year && reportDate.Month == (superviseReport.ReportDate.Month - 1)) { info.LastMonthCash = superviseReport.LatestMonthCash; } info.LatestNetAssets = superviseReport.LatestNetAssets; } return Return.Success(info); } /// /// 查询报送详情 /// /// /// public List> QueryDetails(int id) { var tag = DbContext.supervise_report.Where(O => O.id == id).Select(O => O.FileTag).FirstOrDefault(); tag = (tag ?? "").Replace("YSP_", ""); var reports = (from report in DbContext.supervise_report.Where(O => O.FileTag.StartsWith(tag)) join notes in DbContext.sac_report_notes on report.FileTag equals notes.FileTag select new { report, notes }).ToArray().GroupBy(O => O.report.FileTag) .ToDictionary(K => K.First().report, V => V.Select(O => O.notes).Distinct().ToList()); List> result = new List>(); foreach (var item in reports) { Dictionary dict = new Dictionary(); dict["FileTag"] = item.Key.FileTag; dict["FileType"] = EnumHelper.GetDescriptionByName(item.Key.ReportType); dict["ExceId"] = "-"; dict["BizID"] = "-"; dict["RetCode"] = item.Key.ReportReponseCode; dict["RetMsg"] = item.Key.ReportReponseMessage; result.Add(dict); foreach (var note in item.Value) { dict = new Dictionary(); dict["FileTag"] = note.InfoCache; dict["FileType"] = "-"; dict["ExceId"] = note.ExceId; dict["BizID"] = note.BizId; dict["RetCode"] = note.RetCode; dict["RetMsg"] = note.RetMsg; result.Add(dict); } } return result; } /// /// 查询收益说明 /// /// /// public Dictionary> QueryReportDesc(List pGroups = null) { if (pGroups == null) { pGroups = new List(); } if (pGroups.Count == 0) { pGroups.Add(DBModels.Consts.ConsAppConfig.ReportDescOption); pGroups.Add(DBModels.Consts.ConsAppConfig.ReportDescSwap); } var query = DbContext.AppConfig .Where(O => pGroups.Contains(O.PGroup)) .AsEnumerable() .GroupBy(O => O.PGroup) .Select(n => new { n.Key, List = n.Select(m => new { m.PName, m.PValue }) }) .AsEnumerable() .ToDictionary( K => K.Key, V => V.List.ToDictionary(K => K.PName, V1 => V1.PValue)); return query; } /// /// 保存收益说明 /// /// public int SaveReportDesc(Dictionary> obj) { List pGroups = new List { DBModels.Consts.ConsAppConfig.ReportDescOption, DBModels.Consts.ConsAppConfig.ReportDescSwap }; DbContext.BulkDelete($"{nameof(AppConfig.PGroup)} in @pGroups", new { pGroups }); foreach (var group in obj) { foreach (var item in group.Value) { if (item.Value.IsNullOrWhiteSpace()) { continue; } DbContext.AppConfig.Add(new AppConfig() { CreateTime = DateTime.Now, OptDate = DateTime.Now, PGroup = group.Key, PName = item.Key, PType = "string", PValue = item.Value, Remark = "证券业报送中的收益描述信息" }); } } return DbContext.SaveChanges(); } /// /// 报送预览 /// /// /// /// public List GetSupervisePreview(string fileTag, string fileType) { #if DEBUG { //var requestPath = OtcAppContext.MapPath("/App_Docs/Download/Report"); //var ds = Directory.GetFiles(requestPath, "*.zip"); //foreach (var item in ds) //{ // var filename = Path.GetFileNameWithoutExtension(item); // string[] farr = filename.Split('_'); // var datetime = DateTime.ParseExact(farr[3], "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); // var pathStr = ZipHelper.unZipFile(item, Path.GetDirectoryName(item), out string msg); // if (msg != "解压失败") // { // bool status = false; // var fs = Directory.GetFiles(pathStr, "*.xml"); // SuperviseReport dbreport = null; // List list = new List(); // foreach (var fname in fs) // { // var xml = File.ReadAllText(fname); // var obj = XmlHelper.Deserialize(xml); // var filetag = Path.GetFileNameWithoutExtension(fname); // var reportType = SuperviseReportTypeEnum.SAC; // farr = filetag.Split('_'); // var dataFlag = (DataFlagsEnum)Enum.Parse(typeof(DataFlagsEnum), farr[5]); // if ((int)dataFlag >= 4 && (int)dataFlag <= 7) // { // reportType = (SuperviseReportTypeEnum)dataFlag + 1; // } // else if ((int)dataFlag == 8) // { // reportType = (SuperviseReportTypeEnum)dataFlag - 4; // } // else if ((int)dataFlag >= 9 && (int)dataFlag <= 10) // { // reportType = (SuperviseReportTypeEnum)dataFlag + 3; // } // else if ((int)dataFlag >= 11 && (int)dataFlag <= 13) // { // reportType = (SuperviseReportTypeEnum)dataFlag - 2; // } // else // { // reportType = (SuperviseReportTypeEnum)dataFlag; // } // List modeList = null; // switch (reportType) // { // case SuperviseReportTypeEnum.SAC_MasterAgrmt: // modeList = obj.Body.MasterAgrmt.Cast().ToList(); // break; // case SuperviseReportTypeEnum.SAC_MasterAgrmtProduct: // modeList = obj.Body.MasterAgrmtProduct.Cast().ToList(); // break; // case SuperviseReportTypeEnum.SAC_SupAgrmt: // modeList = obj.Body.SupAgrmt.Cast().ToList(); // break; // case SuperviseReportTypeEnum.SAC_PerformanceGuaranteeAgrmt: // modeList = obj.Body.PerformanceGuaranteeAgrmt.Cast().ToList(); // break; // case SuperviseReportTypeEnum.SAC_OptionConfirmation: // modeList = obj.Body.OptionConfirmation.Cast().ToList(); // break; // case SuperviseReportTypeEnum.SAC_SwapConfirmation: // modeList = obj.Body.SwapConfirmation.Cast().ToList(); // break; // case SuperviseReportTypeEnum.SAC_OptionTermination: // modeList = obj.Body.OptionTermination.Cast().ToList(); // break; // case SuperviseReportTypeEnum.SAC_SwapTermination: // modeList = obj.Body.SwapTermination.Cast().ToList(); // break; // case SuperviseReportTypeEnum.SAC_PeriodicReportSAC: // modeList = new List() { (ReportBaseModel)obj.Body.PeriodicReportSAC }; // break; // case SuperviseReportTypeEnum.SAC_PeriodicReportNAFMII: // modeList = new List() { (ReportBaseModel)obj.Body.PeriodicReportNAFMII }; // break; // case SuperviseReportTypeEnum.SAC_PeriodicReportISDA: // modeList = new List() { (ReportBaseModel)obj.Body.PeriodicReportISDA }; // break; // case SuperviseReportTypeEnum.SAC_EventReport: // modeList = new List() { (ReportBaseModel)obj.Body.EventReport }; // break; // case SuperviseReportTypeEnum.SAC_OtherReport: // modeList = new List() { (ReportBaseModel)obj.Body.OtherReport }; // break; // case SuperviseReportTypeEnum.SAC_PeriodicReportQuarter: // modeList = new List() { (ReportBaseModel)obj.Body.PeriodicReportQuarter }; // break; // case SuperviseReportTypeEnum.SAC_ContractNumberProcess: // modeList = new List() { (ReportBaseModel)obj.Body.ContractNumberProcess }; // break; // default: // break; // } // foreach (var mitem in modeList) // { // if (string.IsNullOrEmpty(mitem.ExceID)) // { // status = false; // continue; // } // status = true; // var notes = DbContext.sac_report_notes.Where(O => O.ExceId == mitem.ExceID).FirstOrDefault(); // if (notes == null) // { // var dbnotes = new SACReportNotes() // { // FileTag = filetag, // ReportType = reportType, // InfoTag = "", // ReportDate = datetime, // ExceId = mitem.ExceID ?? "", // BizId = "", // changeStatus = false, // InfoCache = "", // ReportResponse = false, // RetCode = "", // RetMsg = "", // DataId = "", // IsValid = true, // CreateTime = DateTime.Now, // OptTime = DateTime.Now // }; // DbContext.sac_report_notes.Add(dbnotes); // } // } // if (status) // { // dbreport = DbContext.supervise_report.Where(O => O.FileTag == fname).FirstOrDefault(); // if (dbreport == null) // { // var dbre = new SuperviseReport() // { // ReportType = reportType, // ReportDate = datetime, // SenderCode = farr[1], // ReceiverCode = farr[2], // LastMonthCash = 0, // LatestMonthCash = 0, // LatestNetAssets = 0, // EventReportStatus = 0, // OtherReportStatus = 0, // FileTag = filetag, // FilePath = "", // ReportReponseStatus = ReportSentStatus.SENDING, // ReportReponseCode = "", // ReportReponseMessage = "", // ReportReponsePath = "", // optDate = DateTime.Now, // optUserId = UserId // }; // list.Add(dbre); // } // } // } // if (status) // { // dbreport = DbContext.supervise_report.Where(O => O.FileTag == item).FirstOrDefault(); // if (dbreport == null) // { // var dbre = new SuperviseReport() // { // ReportType = SuperviseReportTypeEnum.SAC, // ReportDate = datetime, // SenderCode = farr[1], // ReceiverCode = farr[2], // LastMonthCash = 0, // LatestMonthCash = 0, // LatestNetAssets = 0, // EventReportStatus = 0, // OtherReportStatus = 0, // FileTag = filename, // FilePath = "/App_Docs/Download/Report/" + Path.GetFileName(item), // ReportReponseStatus = ReportSentStatus.SENDING, // ReportReponseCode = "", // ReportReponseMessage = "", // ReportReponsePath = "", // optDate = DateTime.Now, // optUserId = UserId // }; // list.Add(dbre); // DbContext.supervise_report.AddRange(list); // DbContext.SaveChanges(); // list.Clear(); // } // } // } //} } { //var requestPath = OtcAppContext.MapPath("/App_Docs/Download/ReportResponse"); //var ds = Directory.GetFiles(requestPath, "*.zip"); //foreach (var item in ds) //{ // var filename = Path.GetFileNameWithoutExtension(item); // string[] farr = filename.Split('_'); // string temp = farr[1]; // farr[1] = farr[2]; // farr[2] = temp; // filename = string.Join("_", farr); // var datetime = DateTime.ParseExact(farr[3], "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); // var pathStr = ZipHelper.unZipFile(item, Path.GetDirectoryName(item), out string msg); // if (msg != "解压失败") // { // var fs = Directory.GetFiles(pathStr, "*.xml"); // SuperviseReport dbreport = null; // foreach (var fname in fs) // { // var filetag = Path.GetFileNameWithoutExtension(fname); // farr = filetag.Split('_'); // temp = farr[1]; // farr[1] = farr[2]; // farr[2] = temp; // filetag = string.Join("_", farr).Replace("_R", ""); // var xml = File.ReadAllText(fname); // var obj = XmlHelper.Deserialize(xml); // if (obj.Header.RetCode == "000000") // { // var reportType = SuperviseReportTypeEnum.SAC; // if (farr[5] != "R") // { // var dataFlag = (DataFlagsEnum)Enum.Parse(typeof(DataFlagsEnum), farr[5]); // if ((int)dataFlag >= 4 && (int)dataFlag <= 7) // { // reportType = (SuperviseReportTypeEnum)dataFlag + 1; // } // else if ((int)dataFlag == 8) // { // reportType = (SuperviseReportTypeEnum)dataFlag - 4; // } // else if ((int)dataFlag >= 9 && (int)dataFlag <= 10) // { // reportType = (SuperviseReportTypeEnum)dataFlag + 3; // } // else if ((int)dataFlag >= 11 && (int)dataFlag <= 13) // { // reportType = (SuperviseReportTypeEnum)dataFlag - 2; // } // else // { // reportType = (SuperviseReportTypeEnum)dataFlag; // } // List modeList = null; // switch (reportType) // { // case SuperviseReportTypeEnum.SAC_MasterAgrmt: // modeList = obj.Body.MasterAgrmt.Select(O => { var tt = ((ReportBaseModel)O); tt.BizID = O.BizID; return tt; }).ToList(); // break; // case SuperviseReportTypeEnum.SAC_MasterAgrmtProduct: // modeList = obj.Body.MasterAgrmtProduct.Select(O => { var tt = ((ReportBaseModel)O); tt.BizID = O.BizID; return tt; }).ToList(); // break; // case SuperviseReportTypeEnum.SAC_SupAgrmt: // modeList = obj.Body.SupAgrmt.Select(O => { var tt = ((ReportBaseModel)O); tt.BizID = O.BizID; return tt; }).ToList(); // break; // case SuperviseReportTypeEnum.SAC_PerformanceGuaranteeAgrmt: // modeList = obj.Body.PerformanceGuaranteeAgrmt.Select(O => { var tt = ((ReportBaseModel)O); tt.BizID = O.BizID; return tt; }).ToList(); // break; // case SuperviseReportTypeEnum.SAC_OptionConfirmation: // modeList = obj.Body.OptionConfirmation.Select(O => { var tt = ((ReportBaseModel)O); tt.BizID = O.BizID; return tt; }).ToList(); // break; // case SuperviseReportTypeEnum.SAC_SwapConfirmation: // modeList = obj.Body.SwapConfirmation.Select(O => { var tt = ((ReportBaseModel)O); tt.BizID = O.BizID; return tt; }).ToList(); // break; // case SuperviseReportTypeEnum.SAC_OptionTermination: // modeList = obj.Body.OptionTermination.Select(O => { var tt = ((ReportBaseModel)O); tt.BizID = O.BizID; return tt; }).ToList(); // break; // case SuperviseReportTypeEnum.SAC_SwapTermination: // modeList = obj.Body.SwapTermination.Select(O => { var tt = ((ReportBaseModel)O); tt.BizID = O.BizID; return tt; }).ToList(); // break; // case SuperviseReportTypeEnum.SAC_PeriodicReportSAC: // ((ReportBaseModel)obj.Body.PeriodicReportSAC).BizID = obj.Body.PeriodicReportSAC.BizID; // modeList = new List() { (ReportBaseModel)obj.Body.PeriodicReportSAC }; // break; // case SuperviseReportTypeEnum.SAC_PeriodicReportNAFMII: // ((ReportBaseModel)obj.Body.PeriodicReportNAFMII).BizID = obj.Body.PeriodicReportNAFMII.BizID; // modeList = new List() { (ReportBaseModel)obj.Body.PeriodicReportNAFMII }; // break; // case SuperviseReportTypeEnum.SAC_PeriodicReportISDA: // ((ReportBaseModel)obj.Body.PeriodicReportISDA).BizID = obj.Body.PeriodicReportISDA.BizID; // modeList = new List() { (ReportBaseModel)obj.Body.PeriodicReportISDA }; // break; // case SuperviseReportTypeEnum.SAC_EventReport: // ((ReportBaseModel)obj.Body.EventReport).BizID = obj.Body.EventReport.BizID; // modeList = new List() { (ReportBaseModel)obj.Body.EventReport }; // break; // case SuperviseReportTypeEnum.SAC_OtherReport: // ((ReportBaseModel)obj.Body.OtherReport).BizID = obj.Body.OtherReport.BizID; // modeList = new List() { (ReportBaseModel)obj.Body.OtherReport }; // break; // case SuperviseReportTypeEnum.SAC_PeriodicReportQuarter: // ((ReportBaseModel)obj.Body.PeriodicReportQuarter).BizID = obj.Body.PeriodicReportQuarter.BizID; // modeList = new List() { (ReportBaseModel)obj.Body.PeriodicReportQuarter }; // break; // case SuperviseReportTypeEnum.SAC_ContractNumberProcess: // ((ReportBaseModel)obj.Body.ContractNumberProcess).BizID = obj.Body.ContractNumberProcess.BizID; // modeList = new List() { (ReportBaseModel)obj.Body.ContractNumberProcess }; // break; // default: // break; // } // foreach (var mitem in modeList) // { // var notes = DbContext.sac_report_notes.Where(O => O.ExceId == mitem.ExceID).FirstOrDefault(); // if (notes == null) // { // continue; // } // notes.BizId = mitem.BizID; // notes.ReportResponse = mitem.RetCode == "000000"; // notes.RetCode = mitem.RetCode; // notes.RetMsg = mitem.RetMsg; // }; // } // } // dbreport = DbContext.supervise_report.Where(O => O.FileTag == filetag).FirstOrDefault(); // if (dbreport != null) // { // dbreport.ReportReponseStatus = obj.Header.RetCode == "000000" ? ReportSentStatus.SUCCESS : ReportSentStatus.ERROR; // dbreport.ReportReponseCode = obj.Header.RetCode; // dbreport.ReportReponseMessage = obj.Header.RetMsg; // dbreport.ReportReponsePath = obj.Header.BusiDataType == DataFlagsEnum.NONE ? "/App_Docs/Download/Report/" + Path.GetFileName(item) : ""; // } // } // } // DbContext.SaveChanges(); //} } #endif List result = new List(); string[] arr = fileTag.Split('_');//OTC_151089_000899_20210104_0002_A1008_A var rootPath = OtcAppContext.MapPath("/App_Docs/Download/"); var pathName = string.Empty; var xmlPath = string.Empty; var zipPath = string.Empty; switch (fileType) { case "send"://OTC_151089_000899_20210104_0002 pathName = $"{arr[0]}_{arr[1]}_{arr[2]}_YSP_{arr[3]}_{arr[4]}";//目录名 rootPath = Path.Combine(rootPath, "Report");//zip文件目录 zipPath = Path.Combine(rootPath, pathName + ".zip");//zip文件路径 if (!File.Exists(zipPath)) { pathName = $"{arr[0]}_{arr[1]}_{arr[2]}_{arr[3]}_{arr[4]}";//目录名 zipPath = Path.Combine(rootPath, pathName + ".zip");//zip文件路径 } rootPath = Path.Combine(rootPath, "Temp");//临时文件根目录 pathName = Path.Combine(rootPath, pathName);//解压目录 xmlPath = Path.Combine(pathName, fileTag + ".xml");//预览文件路径 break; case "recv"://OTC_000899_151089_20210104_0002 pathName = $"{arr[0]}_{arr[2]}_{arr[1]}_YSP_{arr[3]}_{arr[4]}";//目录名 xmlPath = $"{arr[0]}_{arr[2]}_{arr[1]}_{arr[3]}_{arr[4]}_{arr[5]}_{arr[6]}_R.xml";//预览文件名 rootPath = Path.Combine(rootPath, "ReportResponse");//zip文件目录 zipPath = Path.Combine(rootPath, pathName + ".zip");//zip文件路径 if (!File.Exists(zipPath)) { pathName = $"{arr[0]}_{arr[2]}_{arr[1]}_{arr[3]}_{arr[4]}";//目录名 zipPath = Path.Combine(rootPath, pathName + ".zip");//zip文件路径 } rootPath = Path.Combine(rootPath, "Temp");//临时文件根目录 pathName = Path.Combine(rootPath, pathName);//解压目录 xmlPath = Path.Combine(pathName, xmlPath);//预览文件路径 break; default: throw new ServiceException("未知操作类型"); } try { optionSuperviseLock.WaitOne(); if (!Directory.Exists(pathName)) { Directory.CreateDirectory(pathName); ZipHelper.unZipFile(zipPath, rootPath, out string msg); if (msg.StartsWith("解压失败")) { Directory.Delete(pathName, true); LogFactory.GetLogger("SupervisePreview").Info($"解压失败:{msg}"); throw new ServiceException(msg); } } XmlDocument doc = new XmlDocument(); doc.Load(xmlPath); var node = doc.GetElementsByTagName("Root")[0]; SacInfo info = new SacInfo(node.Name, ""); ReadXmlNode(node, info); info.formatFieldDescription(); result.Add(info); } catch (ServiceException ex) { throw new ServiceException("预览失败:报送文件不存在或其他原因,详情请查看系统日志.", ex); } catch (Exception ex) { LogFactory.GetLogger("SupervisePreview").Error(ex); throw new ServiceException("预览失败"); } finally { optionSuperviseLock.Set(); } return result; } private void ReadXmlNode(XmlNode node, SacInfo sacInfo) { if ((node.HasChildNodes && node.ChildNodes.Count == 1 && node.ChildNodes[0].NodeType == XmlNodeType.Text)) { sacInfo.FieldValue = node.InnerText; } else { foreach (XmlNode item in node.ChildNodes) { var sItem = new SacInfo(item.Name, item.Value); ReadXmlNode(item, sItem); sacInfo.SubMaps.Add(sItem); } } } #endregion } }