using Autofac.Core; using BaseOUDAL; using CsvHelper; using DocumentFormat.OpenXml.Spreadsheet; using Microsoft.AspNetCore.Authorization; using System.Collections.Concurrent; using System.Linq; using System.Web.Mvc; using YLErp.BLL; using YLErp.BLL.Eod; using YLErp.Configuration; using YLErp.DBModels; using YLErp.DBModels.Consts; using YLErp.Enums; using YLErp.Model.Enum; using YLErp.Modules.SalesModule; using YLErp.Modules.SwapModule; using YLErp.Modules.SwapModule.Dto; using YLErp.Modules.TradeModule; using YLErp.Modules.TradeModule.DealModule; using YLErp.Modules.TradeModule.DocGenerateModule; using YLErp.Modules.TradeMsgOutputModule; using YLErp.QdpModule; namespace YLErp.Web.Controllers { /// /// 新版交易互换 /// public class SwapTrade2Controller : BaseController { #region 框架合约 //按年份判断是否有IB日历,优先用IB,没有则用CHN private string GetBestCountry(int year) { var hasIB = CalendarBLL.GetAllcalendarModel() .Any(c => c.Year == year && "ib".Equals(c.Country, StringComparison.OrdinalIgnoreCase)); return hasIB ? "ib" : "chn"; } [MyAuthorize("交易管理-互换交易")] public ActionResult TradeList(string settleDate = null, string observationDate = null) { ViewBag.settleDate = settleDate; ViewBag.observationDate = observationDate; return View(); } public ActionResult TradeEdit(string enid, bool isUseApproval = false) { ViewBag.isUseApproval = isUseApproval; var intid = DecryptInt(enid); trade r = null; if (intid == 0) { TradeExtendJson tradeExtendJson = new TradeExtendJson() { FlowBookMode = (int)FlowBookModeEnum.否, FloatingPnlAnnualized = false, NeedOpenFee = false, OpenFeeType = 0, InterestCalcMode = "10", SettlementRules=0, DividendPayDate=0 }; var tradeDateCountry = GetBestCountry(valuedateBLL.ValueDate.Year); r = new trade() { TradeType = "收益互换", UnderlyingInstrumentType = "Stock", StartDate = valuedateBLL.ValueDate, TradeDate = QdpCalendarHelper.GetNonHolidayDefore(valuedateBLL.ValueDate.AddDays(-1), tradeDateCountry), TraderId = CurUser.UserId, TraderName = CurUser.UserName, MarginTemplateName = "系统默认", OpponentRole = "乙方", OriginalStockEqvNotional = 0, StructureType = "普通收益互换", InitialMargin = 0 }; r.StructureType = "普通债券类收益互换"; tradeExtendJson.FlowBookMode = (int)FlowBookModeEnum.先进先出; r.trade_extend = new trade_extend() { ExtendJson = JsonHelper.Serialize(tradeExtendJson) }; r.MetaDic = new Dictionary { { "清算机构", "甲方" } }; return View(r); } SwapTradeService swapTradeService = new SwapTradeService(CurUser); r = swapTradeService.GetSwapTrade(intid); if (r == null) { return ShowError("没有找到交易数据"); } return View(r); } /// /// 详情 /// /// /// /// /// /// public ActionResult TradeView(string enid, bool isFromPositionReport = false, bool isOnlyCloseButton = false, string operationStatus = "") { var intid = DecryptInt(enid); SwapTradeService swapTradeService = new SwapTradeService(CurUser); var tradeObj = swapTradeService.GetSwapTrade(intid); if (tradeObj == null) { return ShowError("没有找到交易数据"); } TradeViewModel model; model = new TradeViewModel(tradeObj) { IsFromPositionReport = false, BinaryCalculation = valuedateBLL.BinaryCalculation, IsOnlyCloseButton = isOnlyCloseButton, OperationStatus = operationStatus }; //获取交易销售提成数据 model.SalesCommission = new SalesCommissionDataService(CurUser).GetSalesCommissionInfoDtos(intid); return View(model); } /// /// 多空组合平仓详情 /// /// /// /// public ActionResult CloseDetial(string enid, DateTime valueDate) { var intid = DecryptInt(enid); var closeModel = new SwapEodPositionService(CurUser).GetCloseDetails(intid, valueDate); return View(closeModel); } /// /// 撤销审批 /// /// /// public JsonResult traderevoke(string enid) { var intid = DecryptInt(enid); new SwapTradeService(CurUser).TradeRevoke(intid); return JsonSuccess(""); } /// /// 校验交易上一日是否收盘 /// /// /// public JsonResult CheckEodTrade(string enid) { var intid = DecryptInt(enid); new SwapDealService(CurUser).CheckEodTrade(intid); return JsonSuccess(""); } /// /// 校验收益结算操作(不检查收盘限制) /// /// /// public JsonResult CheckEodTradeForIncome(string enid) { var intid = DecryptInt(enid); new SwapDealService(CurUser).CheckEodTradeForIncome(intid); return JsonSuccess(""); } /// /// 收益互换 平仓 /// /// /// public ActionResult SwapUnwind(string enid, bool isUseApproval = false) { var intid = DecryptInt(enid); var model = new SwapDealService(CurUser).InitUnwind(intid); ViewBag.isUseApproval = isUseApproval; var hasProcess = new SwapDealService(CurUser).HasTradeProcess(); //需要审批或者复核的交易都会显示行权审核提交按钮 ViewBag.IsShowReCheckClose = (valuedateBLL.SystemDate.CloseReCheck == 1) || (valuedateBLL.SystemDate.CloseReApprove == 1 && hasProcess); return View(model); } /// /// 收益互换 互换 /// /// /// public ActionResult SwapIncome(string enid, bool isUseApproval = false) { var intid = DecryptInt(enid); var model = new SwapDealService(CurUser).InitIncome(intid); ViewBag.isUseApproval = isUseApproval; var hasProcess = new SwapDealService(CurUser).HasTradeProcess(); //需要审批或者复核的交易都会显示行权审核提交按钮 ViewBag.IsShowReCheckClose = (valuedateBLL.SystemDate.CloseReCheck == 1) || (valuedateBLL.SystemDate.CloseReApprove == 1 && hasProcess); return View(model); } /// /// 收益互换 多空组合平仓 /// /// /// public ActionResult SwapLongShortUnwind(string enid, bool isUseApproval = false) { var intid = DecryptInt(enid); var model = new SwapDealService(CurUser).InitLongShortUnwind(intid, SwapEventTypeEnum.平仓); ViewBag.isUseApproval = isUseApproval; var hasProcess = new SwapDealService(CurUser).HasTradeProcess(); //需要审批或者复核的交易都会显示行权审核提交按钮 ViewBag.IsShowReCheckClose = (valuedateBLL.SystemDate.CloseReCheck == 1) || (valuedateBLL.SystemDate.CloseReApprove == 1 && hasProcess); return View(model); } /// /// 收益互换 多空组合互换 /// /// /// public ActionResult SwapLongShortSwap(string enid, bool isUseApproval = false) { var intid = DecryptInt(enid); var model = new SwapDealService(CurUser).InitLongShortUnwind(intid, SwapEventTypeEnum.互换); ViewBag.isUseApproval = isUseApproval; var hasProcess = new SwapDealService(CurUser).HasTradeProcess(); //需要审批或者复核的交易都会显示行权审核提交按钮 ViewBag.IsShowReCheckClose = (valuedateBLL.SystemDate.CloseReCheck == 1) || (valuedateBLL.SystemDate.CloseReApprove == 1 && hasProcess); return View(model); } /// /// 操作历史 /// /// /// public ActionResult OperationHistory(string enid) { ViewBag.Enid = enid; return View(); } public ActionResult tradeBack(string enid) { var id = DecryptInt(enid); var trade = new SwapTradeService(CurUser).GetTrade(id); var model = new TradeBackModel() { TradeId = id, ValueDate = valuedateBLL.ValueDate <= trade.ExerciseDate ? valuedateBLL.ValueDate : trade.ExerciseDate.Value, TradeDate = trade.TradeDate.Value }; return View(model); } /// /// 操作历史查询 /// /// /// public JsonResult GetOperationHistorys(string enid) { var intid = DecryptInt(enid); var result = new SwapEventService(CurUser).GetOpreationHistorys(intid); return JsonSuccess("", result); } /// /// 交易回退 /// /// /// public JsonResult TradeBackByDate(TradeBackModel model) { new SwapTradeService(CurUser).TradeBack(model.TradeId, model.TradeDate); return JsonSuccess("回退成功"); } /// /// 平仓利息腿信息 /// /// /// /// /// public JsonResult GetUnwindInterestList(DateTime valueDate,DateTime unwindDate, int tradeId, decimal closePercent, int eventType, decimal notionalValue = 0, decimal posiNotionalValue = 0) { // 前端按"占期初(original)"语义传 closePercent(A);后端 GetUnwindInterests 按"占剩余(remaining)"语义(B)计算。 // 多空互换前端不传 notionalValue/posiNotionalValue(默认 0),则跳过转换保持原行为。 var convertedClosePercent = SwapDealService.ToRemainingClosePercent(closePercent, notionalValue, posiNotionalValue); var interests = new SwapDealService(CurUser).GetUnwindInterests(valueDate, unwindDate, tradeId, convertedClosePercent, eventType); foreach (var interest in interests) { interest.TdInterestAmount=Math.Round(interest.TdInterestAmount, ConsGlobal.MoneyRound,MidpointRounding.AwayFromZero); interest.InterestAmount=Math.Round(interest.InterestAmount, ConsGlobal.MoneyRound,MidpointRounding.AwayFromZero); interest.InterestClosePnL=Math.Round(interest.InterestClosePnL, ConsGlobal.MoneyRound,MidpointRounding.AwayFromZero); } return JsonSuccess("", interests); } /// ///单标的 平仓 /// /// /// public JsonResult SwapUnwindJson(UnwindData unwindData) { new SwapDealService(CurUser).SwapUnwind(unwindData); return JsonSuccess("平仓成功"); } /// ///多空组合 平仓 /// /// /// public JsonResult SwapLongShortUnwindJson(UnwindData unwindData) { new SwapDealService(CurUser).SwapLongShortUnwind(unwindData); return JsonSuccess("平仓成功"); } /// ///多空组合 互换 /// /// /// public JsonResult SwapLongShortJson(UnwindData unwindData) { new SwapDealService(CurUser).SwapLongShort(unwindData); return JsonSuccess("互换成功"); } /// /// 互换 /// /// /// public JsonResult SwapIncomeJson(UnwindData unwindData) { new SwapDealService(CurUser).SwapIncome(unwindData); return JsonSuccess("互换成功"); } /// /// 互换/平仓提交申请 /// /// /// /// public JsonResult ApplyUnwind(UnwindData unwindData, int eventType) { new SwapDealService(CurUser).ApplySwapTrade(unwindData, eventType); return JsonSuccess("提交成功"); } /// /// 框架合约保存 /// /// /// [HttpPost] public JsonResult tradeEditJson(trade req) { if (req == null) { return JsonError("数据不能为空"); } SwapTradeService swapTradeService = new SwapTradeService(CurUser); if (!string.IsNullOrEmpty(req.EncryptId)) { req.id = DecryptInt(req.EncryptId); } try { bool edit = req.id != 0; var r= swapTradeService.SaveTrade(req); Task.Run(() => { RealtimePnlCalc.RealtimeSwapPosition(new OptUserInfo(0, "互换实时持仓服务", OptUserFrom.Service)); }); return JsonSuccess("更新成功", r); } catch (Exception e) { LogFactory.GetLogger("交易保存").Error(e); return JsonError("保存失败:" + e.GetBaseException().Message, e.ToJson()); } } /// /// 删除交易 /// /// /// [HttpPost] public JsonResult deletetrade(string id) { var intid = DecryptInt(id); new SwapTradeService(CurUser).deleteTrade(intid); return JsonSuccess("操作成功"); } /// /// 互换列表查询json /// /// /// [HttpPost] public JsonResult TradeQuery(SwapTradeQueryRequest req) { var swapTradeService = new SwapTradeService(CurUser); req.AssetIds = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.AssetIds).ToList(); var sList = swapTradeService.SearchList(req, out var gsum); return Json(sList); } /// /// 日终归档测试 /// /// /// /// public JsonResult AutoSwapEod(DateTime settleDate, DateTime preSettleDate) { new SwapEodPositionService(CurUser).SwapPositionCompose(settleDate, preSettleDate, null); return JsonSuccess("归档成功"); } #region 展期 /// /// 展期信息 /// /// 交易加密id /// public ActionResult ExtensionTime(string enid) { ViewBag.Enid = enid; var intid = DecryptInt(enid); var extension = new SwapEventService(CurUser).GetExtensionTime(intid); return View(extension); } /// /// 获取展期历史操作记录 /// /// /// public JsonResult GetHistoryExtensions(string enid) { var intid = DecryptInt(enid); var list = new SwapEventService(CurUser).GetExtenstionTimeEvents(intid); return JsonSuccess("", list); } /// /// 保存展期信息 /// /// /// public JsonResult SaveExtension(swap_event swap_Event) { var id = new SwapEventService(CurUser).SaveExtensionTime(swap_Event); return JsonSuccess("保存成功", id); } /// /// 删除展期信息 /// /// /// public JsonResult DeleteExtension(long id) { new SwapEventService(CurUser).DeleteExtensionTime(id); return JsonSuccess("删除成功"); } #endregion #endregion #region 互换清算 #region 场内资金账号 public ActionResult OnSiteCapitalAccount() { return View(); } /// /// 获取交易对手方交易编码 /// /// /// public JsonResult GetClientTradeNumbers(int clientId) { var tradeNumbers = new SwapTradeService(CurUser).GetSwapTradeNumbers(clientId); return JsonSuccess("", tradeNumbers); } /// /// 获取场内交易资金账号列表 /// /// public JsonResult GetCapitalAcountList(SwapCapitalAccountQueryRequest req) { var retListResult = new SwapCapitalAccountService(CurUser).SearchList(req); return Json(retListResult); } /// /// 保存场内资金账号 /// /// public JsonResult SaveCapitalAccount(swap_fund_account req) { req.id = DecryptInt(req.EncryptId); new SwapCapitalAccountService(CurUser).SaveCapitalAccount(req); return JsonSuccess(""); } /// /// 删除场内资金账号 /// /// public JsonResult DeleteCapitalAccount(string enid) { var intid = DecryptInt(enid); new SwapCapitalAccountService(CurUser).DeleteCapitalAccount(intid); return JsonSuccess(""); } /// /// 获取场内资金账号 /// /// /// public JsonResult GetCapitalAccount(string enid) { var intid = DecryptInt(enid); var capitalAccount = new SwapCapitalAccountService(CurUser).GetCapitalAccount(intid); return Json(capitalAccount); } /// /// 根据资金账号获取详情 /// /// /// public JsonResult GetCapitalAccountByFoundAccount(string foundAccount) { var capitalAccount = new SwapCapitalAccountService(CurUser).GetCapitalAccountByFoundAccount(foundAccount); return JsonSuccessData(capitalAccount); } #endregion #region 成交簿记 #region step1 导入 /// /// 成交流水簿记导入列表 /// /// public ActionResult SwapflowList() { return View(); } /// /// 从电子盘数据库导入流水 /// /// /// public JsonResult GenerateSwapTradeFromDb(DateTime? tradeDate, bool reset) { tradeDate = tradeDate == null ? valuedateBLL.ValueDate : tradeDate.Value; var service = new SwapTradeAutoService(CurUser); service.GenerateSwapTradeFromDb(tradeDate.Value, reset); return JsonSuccess(); } /// /// 成交流水簿记导入查询 /// /// /// public JsonResult SwapflowQuery(SwapFlowQueryRequest req) { req.step = req.step == 0 ? 1 : req.step; var service = new SwapFlowService(CurUser); if (req.step == 1)//流水导入 { var retListResult = service.SearchList(req); return Json(retListResult); } else if (req.step == 2)//流水汇总 { var retListResult = service.SearchMergeList(req); return Json(retListResult); } else if (req.step == 3)//流水开平仓 { var retListResult = service.SearchEventList(req); return Json(retListResult); } else//合成持仓 { var retListResult = service.SearchComposeList(req); return Json(retListResult); } } /// /// 删除流水 /// /// /// public JsonResult DeleteSwapflow(string enid, int step) { var intid = DecryptLong(enid); step = step == 0 ? 1 : step; var service = new SwapFlowService(CurUser); if (step == 1) { service.DeleteSwapFlow(intid); } else { service.DeleteSwapFlowMerge(intid); } return JsonSuccess(""); } /// /// 获取流水详情 /// /// /// public JsonResult GetSwapflow(string enid, int step) { var intid = DecryptLong(enid); step = step == 0 ? 1 : step; var service = new SwapFlowService(CurUser); if (step == 1) { var swapflow = service.GetSwapFlow(intid); return Json(swapflow); } else { var swapflow = service.GetSwapFlowMerge(intid); return Json(swapflow); } } /// /// 保存流水 /// /// public JsonResult SaveSwapflow(swap_flow req, int step) { req.id = DecryptLong(req.EncryptId); step = step == 0 ? 1 : step; var service = new SwapFlowService(CurUser); if (step == 1) { service.SaveSwapFlow(req); } else { service.SaveSwapFlowMerge(req); } return JsonSuccess(""); } /// /// 获取任务状态 /// /// public JsonResult GetJobState() { var job = yldb.system_job.FirstOrDefault(x => x.JobName == "互换流水合成持仓"); if (job == null) { return Json(0); } return Json(job.JobState); } /// /// 互换成交流水导入 /// /// public JsonResult ImportSwapflow() { if (Request.Form.Files.Count == 0) { return JsonError("上传文件不存在"); } var file = Request.Form.Files[0]; if (!System.IO.Path.GetExtension(file.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) { return JsonError("请上传压缩包(.xlsx)格式文件"); } using var stream = file.OpenReadStream(); new SwapFlowImportService(CurUser).ImportSwapTradesFromExcel(stream, out var TotalNum, out var SuccessNum); return Json(new { success = true, totalNum = TotalNum, successNum = SuccessNum }); } #endregion #region step2 汇总 /// /// 成交流水簿记导入查询 /// /// /// public JsonResult SwapflowMergeQuery(SwapFlowQueryRequest req) { var retListResult = new SwapFlowService(CurUser).SearchMergeList(req); return Json(retListResult); } /// /// 流水汇总 /// /// public JsonResult SwapFlowMerge(DateTime tradeDate) { new SwapFlowService(CurUser).SwapFlowMerge(tradeDate); return JsonSuccess(); } #endregion #region step3 开平仓事件 public JsonResult SwapFlowEvent(DateTime tradeDate) { new SwapFlowEventService(CurUser).SwapFlowEvent(tradeDate); return JsonSuccess(); } [MyAuthorize("交易管理-互换开平仓事件流水")] public ActionResult EventList() { return View(); } /// /// 开平仓事件导出 /// /// /// public object ExportSwapFlowEvent(SwapFlowQueryRequest req) { req.page = 1; req.rows = 10000; var bytes = new SwapFlowService(CurUser).exprotSwapFlowEventExcel(req); return File(bytes, xlsxMimeType, $"互换开平仓事件流水_{DateTime.Now:yyyyMMddHHmmss}.xlsx"); } #endregion #region 合成持仓 public JsonResult SwapFlowEventCompose(DateTime tradeDate) { new SwapEodPositionService(CurUser).SwapFlowEventCompose(tradeDate); return JsonSuccess(); } #endregion #endregion #region fr007 /// /// 查询最新一条FR007数据 /// /// public JsonResult SearchTodayWhetherFRData(DateTime dateTime) { var service = new SwapFlowService(CurUser); var data = service.SearchTodayFRData(dateTime); return Json(data); } /// /// 删除FR007数据 /// /// 要删除的RF007数据Id /// public JsonResult DeleteFRData(int id) { var service = new SwapFlowService(CurUser); bool flag = service.DeleteFRData(id); return Json(flag); } /// /// 新增或者修改FR007数据 /// /// 新增为空 修改时是要修改的FR007数据 /// FR007价格 /// 新增或者修改时间 [AllowAnonymous] public JsonResult AddOrUpdateFRData(double price, DateTime dateTime) { var service = new SwapFlowService(CurUser); bool flag = service.AddOrUpdateFRdata(price, dateTime); return Json(flag); } #endregion #endregion #region 估值 #region 风险控制-日终持仓 /// /// 日终持仓-互换 /// /// [MyAuthorize("风险控制-日终持仓风险_互换")] public ViewResult EodPositionRisks(int? index) { index = index == null ? 1 : index; ViewBag.TabIndex = index; ViewBag.lastDate_eod = EodOperationBase.GetLastSettlementDate(valuedateBLL.ValueDate); return View(); } /// /// 日终持仓-互换查询 /// /// /// public JsonResult EodPositionRiskQuery(EodSwapPositionQueryRequest req) { req.BookIds = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.BookIds).ToList(); req.UserAssets = CurUser.GetAssetUnitIds(); req.UserClients = CurUser.GetClientIdsByCurUser(); var service = new SwapEodPositionService(CurUser); var retListResult = service.SearchEodPositionList(req); return Json(retListResult); } /// /// 日终持仓-互换框架合约查询 /// /// /// public JsonResult EodSwapRiskQuery(EodSwapQueryRequest req) { req.BookIds = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.BookIds).ToList(); req.UserAssets = CurUser.GetAssetUnitIds(); req.UserClients = CurUser.GetClientIdsByCurUser(); var service = new SwapEodPositionService(CurUser); var retListResult = service.SearchEodSwapList(req); return Json(retListResult); } #endregion #region 结算报告 /// /// 互换持仓 /// /// /// /// /// [MyAuthorize("结算管理-每日估值报告")] public ActionResult TradeMarketReport_PositionSwapFlow(int? clientId, string startTime, string endTime, bool ParentFlag) { ViewBag.ClientId = clientId; ViewBag.StartTime = startTime; ViewBag.EndTime = endTime; ViewBag.ParentFlag = ParentFlag; return View(); } /// /// 互换交易流水 /// /// /// /// /// [MyAuthorize("结算管理-每日估值报告")] public ActionResult TradeMarketReport_HistoricalPositionSwapFlow(int? clientId, string startTime, string endTime, bool ParentFlag) { ViewBag.ClientId = clientId; ViewBag.StartTime = startTime; ViewBag.EndTime = endTime; ViewBag.ParentFlag = ParentFlag; return View(); } /// /// 互换估值 /// /// /// /// /// [MyAuthorize("结算管理-每日估值报告")] public ActionResult TradeMarketReport_EodPosition(int? clientId, string startTime, string endTime, bool ParentFlag) { ViewBag.ClientId = clientId; ViewBag.StartTime = startTime; ViewBag.EndTime = endTime; ViewBag.ParentFlag = ParentFlag; ViewBag.StructureType = "普通债券类收益互换"; return View(); } /// /// 互换持仓明细 /// /// /// [HttpPost] public JsonResult clientTradePositionSwapFlowQuery(ClientSwapPositionRequest req) { var result = new SwapEodPositionService(CurUser).SearchPositionList(req); return Json(result); } /// /// 互换交易流水 /// /// /// [HttpPost] public JsonResult clientTradePositionSwapFlowEventQuery(ClientSwapPositionRequest req) { var result = new SwapFlowEventService(CurUser).SearchPositionFlowEvent(req); return Json(result); } /// /// 互换估值 /// /// /// [HttpPost] public JsonResult clientEodSwapPositionQuery(ClientSwapPositionRequest req) { var result = new SwapEodPositionService(CurUser).SearchEodPositionList(req); return Json(result); } #endregion #endregion #region 结算通知书 public ActionResult tradeEndConfirmList() { return View(); } /// /// 包括提前确认书和到期结算书 /// public JsonResult EitherEndTradeReportQuery(SwapEndConfirmReq req) { req.AssetIdList = AssetUnitModel.IntersectAssetUnits(req.AssetIdGroupList, req.AssetIdList).ToList(); req.UserAssets = CurUser.GetAssetUnitIds(); req.UserClients = CurUser.GetClientIdsByCurUser(CurUser.交易管理_查看所有交易); req.CurUserTradeIds = CurUser.GetTradeIdsByCurUser(); var sList = new SwapEndConfirmService(CurUser).SearchEitherTradeWithCashList(req); return Json(sList); } /// /// 生成结算确认书 /// public JsonResult GJGenerateSettleBillByFlowEventIds(List flowEventIds, string docType) { if ("doc".Equals(docType, StringComparison.OrdinalIgnoreCase)) { docType = "DOCX"; } docType = docType.ToLower(); var results = new List(); var files = new List(); var errors = new List(); results = new SwapSettlementBillGenerateService(CurUser).Generate(flowEventIds, docType, CurUser.UserId, CurUser.UserName).ToList(); errors = results.Where(n => !string.IsNullOrWhiteSpace(n.ErrorMessage)).Select(n => n.ErrorMessage).ToList(); var outPutFilePaths = results.Select(n => n.OutputFilePath).Distinct(); files = DocFileHelper.CheckResultDocFilePath(outPutFilePaths); if (errors.Any()) { return JsonError(string.Join("\r\n", errors.AsEnumerable()), files); } return JsonSuccess("生成成功", files); } /// /// 批量删除结算确认书 /// /// /// public JsonResult BatchDelDoc(List flowEventIds) { new SwapSettlementBillGenerateService(CurUser).DelDoc(flowEventIds); return JsonSuccess(""); } /// /// 批量下载结算确认书 /// public async Task BatchDownLoadDoc(DownloadDocReq req) { if (req.docpdf == null) { return ShowError("请选择文档类型!"); } if (string.IsNullOrWhiteSpace(req.docpdf[0])) { return ShowError("请选择文档类型!"); } var types = new List() { ContractTypeEnum.Clearing, ContractTypeEnum.UnWind }; if (req.TradeDateStart == null) { req.TradeDateStart = DateTime.MinValue; } if (req.TradeDateEnd == null) { req.TradeDateEnd = DateTime.MaxValue; } var db_trade_contract_r = yldb.trade_contract_r.AsQueryable(); var db_swap_flow_event = yldb.swap_flow_event.Where(s => s.EventType == (int)SwapEventTypeEnum.平仓); var query = from doc in yldb.trade_contract_document join r in db_trade_contract_r on doc.Code equals r.ContractCode join fe in db_swap_flow_event on r.SwapFlowEventId equals fe.id where doc.Type == r.Type && fe.EventDate >= req.TradeDateStart && fe.EventDate <= req.TradeDateEnd && r.IsValid && types.Contains(r.Type) select new { doc.ClientId, doc.Paths, TradeCashId = r.TradeCashId ?? 0, r.Type, r.TradeId, r.TradeNumber, r.ContractCode, r.SwapFlowEventId, doc.SealResult, doc.StampDocumentFileName, doc.EncryptId, doc.Comments, doc.FileName }; var isSelect = false; if (req.TradeIds != null && req.TradeIds.Any(O => O != 0)) { isSelect = true; query = query.Where(O => req.TradeIds.Contains(O.TradeId)); } if (req.FlowEventIds != null && req.FlowEventIds.Any(O => O != 0)) { isSelect = true; query = query.Where(O => req.FlowEventIds.Contains(O.SwapFlowEventId ?? 0)); } if (req.DocType != null) { query = query.Where(O => O.Type == req.DocType); } if (!isSelect && !req.TradeNumber.IsNullOrWhiteSpace()) { query = query.Where(O => O.TradeNumber == req.TradeNumber); } if (!isSelect && !req.ContractCode.IsNullOrWhiteSpace()) { query = query.Where(O => O.ContractCode == req.ContractCode); } if (!isSelect && req.ClientIds != null && req.ClientIds.Any(O => O != 0)) { query = query.Where(O => req.ClientIds.Contains(O.ClientId ?? 0)); } var datas = query.ToList(); if (datas.Count == 0) { return ShowError("未找到确认书文件,请确认筛选条件是否有效!"); } var filePathList = new List(datas.Count * req.docpdf.Count()); foreach (var item in datas) { var path = item.Paths; if (!string.IsNullOrEmpty(path)) { var fName = GetFileName(path, ".xlsx"); if (!string.IsNullOrEmpty(fName)) { filePathList.Add(fName); } } } var fileName = $"确认书文件{DateTime.Now:yyyyMMddHHmmss}.zip"; ZipHelper.zipFiles(filePathList.Distinct().ToArray(), filePathList[0], out var buffer); return File(buffer, "application/zip", fileName); } private string GetFileName(string baseName, string sufferFix) { var fName = Path.ChangeExtension(baseName, sufferFix); if (!string.IsNullOrWhiteSpace(fName) && (fName[0] != '/' || fName[0] != '\\')) { fName = fName.Insert(0, "/"); } fName = OtcAppContext.MapPath(fName); if (!System.IO.File.Exists(fName)) { fName += "x"; }//解决数据库中存的后缀名是doc但实际文件是docx的问题; if (System.IO.File.Exists(fName)) { return fName; } else { return null; } } #endregion /// /// 更新支付日期 /// /// /// [HttpPost] public JsonResult UpdatePayDate(UpdatePayDateDto req) { if (req == null) { return JsonError("数据不能为空"); } SwapFlowService service = new SwapFlowService(CurUser); service.UpdatePayDate(req); return JsonSuccess("更新成功"); } /// /// 发送确认书邮件 /// /// /// public JsonResult SendConfimEmail(int tradeId) { SwapEndConfirmService service = new SwapEndConfirmService(CurUser); var result = service.SendConfirmEamil(tradeId); return JsonSuccess(result); } } }