using Myshipping.Core; using Furion.DependencyInjection; using Furion.DynamicApiController; using Mapster; using Microsoft.AspNetCore.Mvc; using SqlSugar; using System.Linq; using System.Threading.Tasks; using Myshipping.Application.Entity; using Microsoft.AspNetCore.Authorization; using Furion; using Microsoft.AspNetCore.Http; using Furion.DataEncryption; using System.Collections.Generic; using System.Security.Claims; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Furion.FriendlyException; using Furion.Logging; using System; using Microsoft.Extensions.Logging; using System.Reflection; using System.ComponentModel; using Myshipping.Application.Service.BookingOrder.Dto; using Myshipping.Application.ConfigOption; using System.IO; using Yitter.IdGenerator; using Myshipping.Core.Entity; using Furion.RemoteRequest.Extensions; using System.Net.Http; using Myshipping.Core.Service; using Myshipping.Application.EDI; using System.Text; using System.Web; using Newtonsoft.Json.Linq; using Myshipping.Core.Helper; using Myshipping.Application.Enum; using Org.BouncyCastle.Asn1.X500; using System.Drawing.Drawing2D; using StackExchange.Profiling.Internal; using Myshipping.Application; using Myshipping.Application.EDI.PIL; using Newtonsoft.Json; using Myshipping.Application.EDI.TSL; using Myshipping.Application.EDI.WY; using Myshipping.Application.EDI.YML; using Myshipping.Application.EDI.YT; using System.Runtime.InteropServices; using System.Threading; using Furion.JsonSerialization; using System.Xml.Linq; using Myshipping.Application.Helper; using System.Net; using Furion.DistributedIDGenerator; using System.Linq.Expressions; using Myshipping.Core.Extension; using System.Text.RegularExpressions; using MathNet.Numerics.Distributions; using Microsoft.IdentityModel.Tokens; using Myshipping.Application.EDI.ESL; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Formula.Functions; using NPOI.HPSF; using MimeKit; using NPOI.SS.Formula; using NPOI.Util; using System.Collections.Specialized; using System.Net.Http.Headers; using MySqlX.XDevAPI.Common; using Ubiety.Dns.Core; using static ICSharpCode.SharpZipLib.Zip.ExtendedUnixData; using System.Security.Cryptography; using Myshipping.Application.Service.DataSync.Dto; using RabbitMQ.Client; using System.Configuration; using System.Collections; using System.Security.Principal; using Myshipping.Core.Const; using ICSharpCode.SharpZipLib.BZip2; using Myshipping.Application.EDI.VOLTA; using TinyPinyin; using Furion.EventBus; namespace Myshipping.Application { /// /// 订舱服务 /// [ApiDescriptionSettings("Application", Name = "BookingOrder", Order = 1)] public class BookingOrderService : IBookingOrderService, IDynamicApiController, ITransient { private readonly SqlSugarRepository _rep; private readonly SqlSugarRepository _repCtn; private readonly SqlSugarRepository _ctndetailrep; private readonly SqlSugarRepository _bookinglog; private readonly SqlSugarRepository _bookinglogdetail; private readonly SqlSugarRepository _bookingremark; private readonly SqlSugarRepository _bookingfile; private readonly ISysDataUserMenu _right; private readonly SqlSugarRepository _repPrint; private readonly ILogger _logger; private readonly ISysCacheService _cache; private readonly IDjyWebsiteAccountConfigService _webAccountConfig; private readonly SqlSugarRepository _repStatuslog; private readonly SqlSugarRepository _statuslogdetail; private readonly SqlSugarRepository _repPrintTemplate; private readonly SqlSugarRepository _repLetterYard; private readonly SqlSugarRepository _repUser; private readonly SqlSugarRepository _repOrderUrl; private readonly SqlSugarRepository _repOrderContact; private readonly SqlSugarRepository _repSampleBill; private readonly SqlSugarRepository _repUserMail; private readonly SqlSugarRepository _repTenant; private readonly SqlSugarRepository _repBookingStatus; private readonly SqlSugarRepository _bookingEDIExt; private readonly SqlSugarRepository _vesselInfo; private readonly SqlSugarRepository _repUserConfig; private readonly SqlSugarRepository _excelrep; private readonly SqlSugarRepository _serviceItem; private readonly SqlSugarRepository _goodsStatus; private readonly SqlSugarRepository _goodsStatusConfig; private readonly SqlSugarRepository _djycustomer; private readonly SqlSugarRepository _bookingTemplate; private readonly SqlSugarRepository _paraGoodsInfoRepository; private readonly SqlSugarRepository _paraContractNoInfoRepository; private readonly SqlSugarRepository _djyWebsiteAccountConfigRepository; private readonly SqlSugarRepository _repPrintTemplateShare; private readonly IHttpContextAccessor _httpContextAccessor; private readonly ISysOrgService _orgService; private readonly IBookingGoodsStatusConfigService _GoodsConfig; private readonly SqlSugarRepository _repLineOpMgrConfig; private readonly SqlSugarRepository _repSysEmp; private readonly SqlSugarRepository _repAutoYard; private readonly SqlSugarRepository _repextendstate; private readonly IServiceWorkFlowManageService _serviceWorkFlowManageService; private readonly IDjyUserConfigService _djyUserConfigService; private readonly IEventPublisher _publisher; const string CONST_MAPPING_MODULE = "BOOK_OR_CLOSING"; const string CONST_MAPPING_MODULE_ROUTE = "BOOK_OR_CLOSING_RT"; const string CONST_MAPPING_MODULE_VOLTA = "BOOK_CLOSING_VOLTA"; private const string PrintRecentListTypeKey = "booking_print_recent_list"; const string CONST_TSL_EDI_URL = "tsl_edi_declare_url"; const string CONST_TSL_TYPE_CODE = "TslWeb"; const string CONST_ONE_SOFILE_CATE_CODE = "one_so_file_template"; const string PRINT_DATASOURCE_KEY = "booking_order"; public BookingOrderService(SqlSugarRepository rep, SqlSugarRepository repCtn, SqlSugarRepository ctndetailrep, SqlSugarRepository bookinglog, SqlSugarRepository bookinglogdetail, SqlSugarRepository bookingremark, SqlSugarRepository bookingfile, SqlSugarRepository repUserConfig, SqlSugarRepository repPrint, SqlSugarRepository dicdata, SqlSugarRepository statuslog, SqlSugarRepository statuslogdetail, SqlSugarRepository repPrintTemplateShare, SqlSugarRepository vesselInfo, SqlSugarRepository repextendstate, ILogger logger, ISysCacheService cache, IDjyWebsiteAccountConfigService webAccountConfig, ISysDataUserMenu right, SqlSugarRepository paraGoodsInfoRepository, SqlSugarRepository repPrintTemplate, SqlSugarRepository repLetterYard, SqlSugarRepository repUser, SqlSugarRepository bookingTemplate, SqlSugarRepository repOrderUrl, SqlSugarRepository repOrderContact, SqlSugarRepository repSampleBill, SqlSugarRepository djycustomer, SqlSugarRepository excelrep, SqlSugarRepository repUserMail, SqlSugarRepository goodsStatus, SqlSugarRepository goodsStatusConfig, SqlSugarRepository repTenant, SqlSugarRepository repBookingStatus, SqlSugarRepository bookingEDIExt, SqlSugarRepository serviceItem, SqlSugarRepository paraContractNoInfoRepository, IHttpContextAccessor httpContextAccessor, IBookingGoodsStatusConfigService GoodsConfig, SqlSugarRepository djyWebsiteAccountConfigRepository, ISysOrgService orgService, SqlSugarRepository repLineOpMgrConfig, SqlSugarRepository repSysEmp, SqlSugarRepository repAutoYard, IServiceWorkFlowManageService serviceWorkFlowManageService, IDjyUserConfigService djyUserConfigService, IEventPublisher publisher) { this._logger = logger; this._rep = rep; this._repCtn = repCtn; this._ctndetailrep = ctndetailrep; this._bookinglog = bookinglog; this._bookinglogdetail = bookinglogdetail; this._bookingremark = bookingremark; this._bookingfile = bookingfile; this._repPrint = repPrint; this._right = right; this._cache = cache; this._webAccountConfig = webAccountConfig; this._repStatuslog = statuslog; this._statuslogdetail = statuslogdetail; this._repPrintTemplate = repPrintTemplate; this._repLetterYard = repLetterYard; this._repUser = repUser; this._repOrderUrl = repOrderUrl; this._repOrderContact = repOrderContact; this._repSampleBill = repSampleBill; this._repUserMail = repUserMail; this._repTenant = repTenant; this._repBookingStatus = repBookingStatus; this._bookingEDIExt = bookingEDIExt; this._repUserConfig = repUserConfig; this._excelrep = excelrep; this._serviceItem = serviceItem; this._goodsStatus = goodsStatus; this._goodsStatusConfig = goodsStatusConfig; this._bookingTemplate = bookingTemplate; this._djycustomer = djycustomer; this._paraGoodsInfoRepository = paraGoodsInfoRepository; this._paraContractNoInfoRepository = paraContractNoInfoRepository; this._orgService = orgService; this._vesselInfo = vesselInfo; this._repPrintTemplateShare = repPrintTemplateShare; _httpContextAccessor = httpContextAccessor; _GoodsConfig = GoodsConfig; _djyWebsiteAccountConfigRepository = djyWebsiteAccountConfigRepository; this._repLineOpMgrConfig = repLineOpMgrConfig; this._repSysEmp = repSysEmp; this._repAutoYard = repAutoYard; this._repextendstate = repextendstate; _serviceWorkFlowManageService = serviceWorkFlowManageService; _djyUserConfigService = djyUserConfigService; _publisher = publisher; } #region 主表和箱信息 /// /// 分页查询订舱主表 /// /// /// [HttpPost("/BookingOrder/PageData")] public async Task PageData(BookingOrderInput input) { var reqId = Guid.NewGuid().ToString(); //请求id,跟踪请求耗时 var ticks = DateTime.Now; if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"PageData {reqId} Stage 0 "); } //获取菜单列表权限 List userlist = await _right.GetDataScopeList(MenuConst.MenuBookingOrder); List userlistString = userlist?.Select(u => u.ToString())?.ToList(); List pidlist = new List(); if (!string.IsNullOrWhiteSpace(input.SEALNO) || !string.IsNullOrWhiteSpace(input.CNTRNO)) { pidlist = await _repCtn.AsQueryable().WhereIF(!string.IsNullOrWhiteSpace(input.SEALNO), x => x.SEALNO.StartsWith(input.SEALNO)).WhereIF(!string.IsNullOrWhiteSpace(input.CNTRNO), x => x.CNTRNO.StartsWith(input.CNTRNO)).Select(x => x.BILLID).ToListAsync(); } //默认首次查询取开船日期范围 var ftoday = DateTime.Now.AddDays(-15); var etoday = DateTime.Now.AddDays(30); //List userlist = await DataFilterExtensions.GetDataScopeIdList(); if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageData {reqId} Stage 1 {et.TotalMilliseconds}"); } //按部门查询 List saleUserList = null; List opUserList = null; if (input.OrgSale.HasValue) { var tmpList = await _orgService.GetUserIdListInOrg(input.OrgSale.Value); saleUserList = tmpList.Select(x => x.ToString()).ToList(); } if (input.OrgOp.HasValue) { var tmpList = await _orgService.GetUserIdListInOrg(input.OrgOp.Value); opUserList = tmpList.Select(x => x.ToString()).ToList(); } if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageData {reqId} Stage 2 {et.TotalMilliseconds}"); } #region var query = _rep.AsQueryable().Filter(null, true).Where(x => x.TenantId == UserManager.TENANT_ID) .WhereIF(!input.ISDel, x => x.IsDeleted == false) .WhereIF(input.ISDel, x => x.IsDeleted == true) .WhereIF(input.firstFlag, x => (x.ETD <= etoday && x.ETD >= ftoday || x.ETD == null) && (x.CreatedUserId == UserManager.UserId || x.OPID == UserManager.UserId.ToString() || x.DOCID == UserManager.UserId.ToString() || x.ROUTEID == UserManager.UserId.ToString() || x.LineManageID == UserManager.UserId.ToString() || x.CUSTSERVICEID == UserManager.UserId.ToString() || x.SALEID == UserManager.UserId.ToString())) //首次加载数据:ETD前后15天,且创建人、操作是当前人 .Where(x => x.ParentId == 0 || x.ParentId == null) //台账只查询主单!! .WhereIF(input.Id != 0, x => x.Id == input.Id) .WhereIF(pidlist != null && pidlist.Count > 0, x => pidlist.Contains(x.Id)) .WhereIF(!string.IsNullOrWhiteSpace(input.BSNO), u => u.BSNO.Contains(input.BSNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.BSSTATUS), u => u.BSSTATUS == input.BSSTATUS) .WhereIF(input.BBSDATE != null, u => u.BSDATE >= input.BBSDATE) .WhereIF(input.EBSDATE != null, u => u.BSDATE <= input.EBSDATE) .WhereIF(!string.IsNullOrWhiteSpace(input.MBLNO) && !input.MBLNO.Contains(','), u => u.MBLNO.Contains(input.MBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.TMBLNO) && !input.TMBLNO.Contains(','), u => u.TMBLNO.Contains(input.TMBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.HBLNO) && !input.HBLNO.Contains(','), u => u.HBLNO.Contains(input.HBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.MBLNO) && input.MBLNO.Contains(','), u => input.MBLNO.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Contains(u.MBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.HBLNO) && input.HBLNO.Contains(','), u => input.HBLNO.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Contains(u.HBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.BOOKINGNO), u => u.BOOKINGNO.Contains(input.BOOKINGNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONTRACTNO), u => u.CONTRACTNO.Contains(input.CONTRACTNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.SERVICECONTRACTNO), u => u.SERVICECONTRACTNO.Contains(input.SERVICECONTRACTNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPER), u => u.SHIPPER.Contains(input.SHIPPER)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEE), u => u.CONSIGNEE.Contains(input.CONSIGNEE)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTY), u => u.NOTIFYPARTY.Contains(input.NOTIFYPARTY)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTY2), u => u.NOTIFYPARTY2.Contains(input.NOTIFYPARTY2)) .WhereIF(!string.IsNullOrWhiteSpace(input.YARDID), u => u.YARDID == input.YARDID) .WhereIF(!string.IsNullOrWhiteSpace(input.VESSELID), u => u.VESSELID.Contains(input.VESSELID)) .WhereIF(!string.IsNullOrWhiteSpace(input.VESSEL), u => u.VESSEL.ToLower().Contains(input.VESSEL.ToLower())) .WhereIF(!string.IsNullOrWhiteSpace(input.VOYNO), u => u.VOYNO.Contains(input.VOYNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.VOYNOINNER), u => u.VOYNOINNER.Contains(input.VOYNOINNER)) .WhereIF(input.BETD != null, u => u.ETD >= input.BETD) .WhereIF(input.EETD != null, u => u.ETD < input.EETD.Value.AddDays(1)) .WhereIF(input.BATD != null, u => u.ATD >= input.BATD) .WhereIF(input.EATD != null, u => u.ATD < input.EATD.Value.AddDays(1)) .WhereIF(input.BCLOSINGDATE != null, u => u.CLOSINGDATE >= input.BCLOSINGDATE) .WhereIF(input.ECLOSINGDATE != null, u => u.CLOSINGDATE <= input.ECLOSINGDATE) .WhereIF(input.BCLOSEDOCDATE != null, u => u.CLOSEDOCDATE >= input.BCLOSEDOCDATE) .WhereIF(input.ECLOSEDOCDATE != null, u => u.CLOSEDOCDATE <= input.ECLOSEDOCDATE) .WhereIF(input.BCLOSEVGMDATE != null, u => u.CLOSEVGMDATE >= input.BCLOSEVGMDATE) .WhereIF(input.ECLOSEVGMDATE != null, u => u.CLOSEVGMDATE <= input.ECLOSEVGMDATE) .WhereIF(input.BETA != null, u => u.ETA >= input.BETA) .WhereIF(input.EETA != null, u => u.ETA < input.EETA.Value.AddDays(1)) .WhereIF(!string.IsNullOrWhiteSpace(input.PLACERECEIPT), u => u.PLACERECEIPT.Contains(input.PLACERECEIPT)) .WhereIF(!string.IsNullOrWhiteSpace(input.PORTLOAD), u => u.PORTLOAD.Contains(input.PORTLOAD)) .WhereIF(!string.IsNullOrWhiteSpace(input.PORTLOADID), u => u.PORTLOADID == input.PORTLOADID) .WhereIF(!string.IsNullOrWhiteSpace(input.PORTDISCHARGEID), u => u.PORTDISCHARGEID == input.PORTDISCHARGEID) .WhereIF(!string.IsNullOrWhiteSpace(input.PORTDISCHARGE), u => u.PORTDISCHARGE.Contains(input.PORTDISCHARGE)) .WhereIF(!string.IsNullOrWhiteSpace(input.PLACEDELIVERY), u => u.PLACEDELIVERY.Contains(input.PLACEDELIVERY)) .WhereIF(!string.IsNullOrWhiteSpace(input.PLACEDELIVERYID), u => u.PLACEDELIVERYID == input.PLACEDELIVERYID) .WhereIF(!string.IsNullOrWhiteSpace(input.DESTINATION), u => u.DESTINATION.Contains(input.DESTINATION)) .WhereIF(!string.IsNullOrWhiteSpace(input.DESTINATIONID), u => u.DESTINATIONID == input.DESTINATIONID) .WhereIF(!string.IsNullOrWhiteSpace(input.NOBILL), u => u.NOBILL == input.NOBILL) .WhereIF(!string.IsNullOrWhiteSpace(input.COPYNOBILLL), u => u.COPYNOBILL == input.COPYNOBILLL) .WhereIF(!string.IsNullOrWhiteSpace(input.ISSUETYPE), u => u.ISSUETYPE == input.ISSUETYPE) .WhereIF(input.BISSUEDATE != null, u => u.ISSUEDATE >= input.BISSUEDATE) .WhereIF(input.EISSUEDATE != null, u => u.ISSUEDATE < input.EISSUEDATE.Value.AddDays(1)) .WhereIF(!string.IsNullOrWhiteSpace(input.ISSUEPLACE), u => u.ISSUEPLACE.Contains(input.ISSUEPLACE)) .WhereIF(!string.IsNullOrWhiteSpace(input.ISSUEPLACEID), u => u.ISSUEPLACEID == input.ISSUEPLACEID) .WhereIF(!string.IsNullOrWhiteSpace(input.BLFRT), u => u.BLFRT == input.BLFRT) .WhereIF(!string.IsNullOrWhiteSpace(input.PREPARDATID), u => u.PREPARDATID == input.PREPARDATID) .WhereIF(!string.IsNullOrWhiteSpace(input.PREPARDAT), u => u.PREPARDAT == input.PREPARDAT) .WhereIF(!string.IsNullOrWhiteSpace(input.PAYABLEAT), u => u.PAYABLEAT.Contains(input.PAYABLEAT)) .WhereIF(!string.IsNullOrWhiteSpace(input.PAYABLEATID), u => u.PAYABLEATID == input.PAYABLEATID) .WhereIF(!string.IsNullOrWhiteSpace(input.SERVICE), u => u.SERVICE.Contains(input.SERVICE)) .WhereIF(!string.IsNullOrWhiteSpace(input.MARKS), u => u.MARKS.Contains(input.MARKS)) .WhereIF(!string.IsNullOrWhiteSpace(input.HSCODE), u => u.HSCODE.Contains(input.HSCODE)) .WhereIF(!string.IsNullOrWhiteSpace(input.DESCRIPTION), u => u.DESCRIPTION.Contains(input.DESCRIPTION)) .WhereIF(!string.IsNullOrWhiteSpace(input.KINDPKGS), u => u.KINDPKGS == input.KINDPKGS) .WhereIF(!string.IsNullOrWhiteSpace(input.CNTRTOTAL), u => u.CNTRTOTAL.StartsWith(input.CNTRTOTAL)) .WhereIF(!string.IsNullOrWhiteSpace(input.CARRIERID), u => u.CARRIERID == input.CARRIERID) .WhereIF(!string.IsNullOrWhiteSpace(input.CARRIER), u => u.CARRIER.Contains(input.CARRIER)) .WhereIF(!string.IsNullOrWhiteSpace(input.CARGOID), u => u.CARGOID == input.CARGOID) .WhereIF(!string.IsNullOrWhiteSpace(input.DCLASS), u => u.DCLASS == input.DCLASS) .WhereIF(!string.IsNullOrWhiteSpace(input.DUNNO), u => u.DUNNO == input.DUNNO) .WhereIF(!string.IsNullOrWhiteSpace(input.DPAGE), u => u.DPAGE == input.DPAGE) .WhereIF(!string.IsNullOrWhiteSpace(input.DLABEL), u => u.DLABEL == input.DLABEL) .WhereIF(!string.IsNullOrWhiteSpace(input.LINKMAN), u => u.LINKMAN == input.LINKMAN) .WhereIF(!string.IsNullOrWhiteSpace(input.TEMPID), u => u.TEMPID == input.TEMPID) .WhereIF(!string.IsNullOrWhiteSpace(input.TEMPSET), u => u.TEMPSET == input.TEMPSET) .WhereIF(!string.IsNullOrWhiteSpace(input.REEFERF), u => u.REEFERF == input.REEFERF) .WhereIF(!string.IsNullOrWhiteSpace(input.HUMIDITY), u => u.HUMIDITY == input.HUMIDITY) .WhereIF(!string.IsNullOrWhiteSpace(input.TEMPMIN), u => u.TEMPMIN == input.TEMPMIN) .WhereIF(!string.IsNullOrWhiteSpace(input.TEMPMAX), u => u.TEMPMAX == input.TEMPMAX) .WhereIF(input.ISCONTAINERSOC != null, u => u.ISCONTAINERSOC == input.ISCONTAINERSOC) .WhereIF(!string.IsNullOrWhiteSpace(input.SOREMARK), u => u.SOREMARK.Contains(input.SOREMARK)) .WhereIF(!string.IsNullOrWhiteSpace(input.SIREMARK), u => u.SIREMARK.Contains(input.SIREMARK)) .WhereIF(!string.IsNullOrWhiteSpace(input.YARDREMARK), u => u.YARDREMARK.Contains(input.YARDREMARK)) .WhereIF(!string.IsNullOrWhiteSpace(input.COMPID), u => u.COMPID == input.COMPID) .WhereIF(!string.IsNullOrWhiteSpace(input.COMPNAME), u => u.COMPNAME.Contains(input.COMPNAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERNAME), u => u.SHIPPERNAME.Contains(input.SHIPPERNAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERCITY), u => u.SHIPPERCITY.Contains(input.SHIPPERCITY)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERPROVINCE), u => u.SHIPPERPROVINCE == input.SHIPPERPROVINCE) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERPOSTCODE), u => u.SHIPPERPOSTCODE == input.SHIPPERPOSTCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERCOUNTRY), u => u.SHIPPERCOUNTRY == input.SHIPPERCOUNTRY) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERATTN), u => u.SHIPPERATTN.Contains(input.SHIPPERATTN)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERTEL), u => u.SHIPPERTEL == input.SHIPPERTEL) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEENAME), u => u.CONSIGNEENAME.Contains(input.CONSIGNEENAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEECITY), u => u.CONSIGNEECITY.Contains(input.CONSIGNEECITY)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEEPROVINCE), u => u.CONSIGNEEPROVINCE == input.CONSIGNEEPROVINCE) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEEPOSTCODE), u => u.CONSIGNEEPOSTCODE == input.CONSIGNEEPOSTCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEERCOUNTRY), u => u.CONSIGNEERCOUNTRY == input.CONSIGNEERCOUNTRY) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEEATTN), u => u.CONSIGNEEATTN.Contains(input.CONSIGNEEATTN)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEETEL), u => u.CONSIGNEETEL == input.CONSIGNEETEL) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYNAME), u => u.NOTIFYPARTYNAME.Contains(input.NOTIFYPARTYNAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYCITY), u => u.NOTIFYPARTYCITY.Contains(input.NOTIFYPARTYCITY)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYPROVINCE), u => u.NOTIFYPARTYPROVINCE == input.NOTIFYPARTYPROVINCE) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYPOSTCODE), u => u.NOTIFYPARTYPOSTCODE == input.NOTIFYPARTYPOSTCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYCOUNTRY), u => u.NOTIFYPARTYCOUNTRY == input.NOTIFYPARTYCOUNTRY) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYATTN), u => u.NOTIFYPARTYATTN.Contains(input.NOTIFYPARTYATTN)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYTEL), u => u.NOTIFYPARTYTEL == input.NOTIFYPARTYTEL) .WhereIF(!string.IsNullOrWhiteSpace(input.PONO), u => u.PONO.Contains(input.PONO)) .WhereIF(!string.IsNullOrWhiteSpace(input.OPID), u => u.OPID == input.OPID) .WhereIF(!string.IsNullOrWhiteSpace(input.DOCID), u => u.DOCID == input.DOCID) .WhereIF(!string.IsNullOrWhiteSpace(input.OP), u => u.OP == input.OP) .WhereIF(!string.IsNullOrWhiteSpace(input.DOC), u => u.DOC == input.DOC) .WhereIF(!string.IsNullOrWhiteSpace(input.SALEID), u => u.SALEID == input.SALEID) .WhereIF(!string.IsNullOrWhiteSpace(input.SALE), u => u.SALE.Contains(input.SALE)) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTSERVICEID), u => u.CUSTSERVICEID == input.CUSTSERVICEID) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTSERVICE), u => u.CUSTSERVICE.Contains(input.CUSTSERVICE)) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTOMERNAME), u => u.CUSTOMERNAME.Contains(input.CUSTOMERNAME)) .WhereIF(input.CUSTOMERID != null && input.CUSTOMERID != 0, u => u.CUSTOMERID == input.CUSTOMERID) .WhereIF(!string.IsNullOrWhiteSpace(input.FORWARDER), u => u.FORWARDER.Contains(input.FORWARDER)) .WhereIF(!string.IsNullOrWhiteSpace(input.AGENTID), u => u.AGENTID == input.AGENTID) .WhereIF(!string.IsNullOrWhiteSpace(input.FORWARDERID), u => u.FORWARDERID == input.FORWARDERID) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPAGENCY), u => u.SHIPAGENCY.Contains(input.SHIPAGENCY)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPAGENCYID), u => u.SHIPAGENCYID == input.SHIPAGENCYID) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTOMSER), u => u.CUSTOMSER.Contains(input.CUSTOMSER)) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTOMSERID), u => u.CUSTOMSERID == input.CUSTOMSERID) .WhereIF(!string.IsNullOrWhiteSpace(input.TRUCKER), u => u.TRUCKER.Contains(input.TRUCKER)) .WhereIF(!string.IsNullOrWhiteSpace(input.TRUCKERID), u => u.TRUCKERID == input.TRUCKERID) .WhereIF(!string.IsNullOrWhiteSpace(input.AGENTNAME), u => u.AGENTNAME.Contains(input.AGENTNAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.WEITUO), u => u.WEITUO.Contains(input.WEITUO)) .WhereIF(!string.IsNullOrWhiteSpace(input.SCACCODE), u => u.SCACCODE == input.SCACCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.ITNCODE), u => u.ITNCODE == input.ITNCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTNO), u => u.CUSTNO.Contains(input.CUSTNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.TRANSPORTID), u => u.TRANSPORTID == input.TRANSPORTID) .WhereIF(!string.IsNullOrWhiteSpace(input.TRANSPORT), u => u.TRANSPORT.Contains(input.TRANSPORT)) .WhereIF(!string.IsNullOrWhiteSpace(input.YARDCONTRACTTEL), u => u.YARDCONTRACTTEL == input.YARDCONTRACTTEL) .WhereIF(!string.IsNullOrWhiteSpace(input.YARDCONTRACTEMAIL), u => u.YARDCONTRACTEMAIL == input.YARDCONTRACTEMAIL) .WhereIF(!string.IsNullOrWhiteSpace(input.LANECODE), u => u.LANECODE == input.LANECODE) .WhereIF(!string.IsNullOrWhiteSpace(input.LANENAME), u => u.LANENAME.Contains(input.LANENAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.ROUTEID), u => u.ROUTEID == input.ROUTEID) .WhereIF(!string.IsNullOrWhiteSpace(input.ROUTE), u => u.ROUTE.Contains(input.ROUTE)) .WhereIF(!string.IsNullOrWhiteSpace(input.LineManageID), u => u.LineManageID == input.LineManageID) .WhereIF(!string.IsNullOrWhiteSpace(input.LineManage), u => u.LineManage.Contains(input.LineManage)) .WhereIF(!string.IsNullOrWhiteSpace(input.ShippingMethod), u => u.ShippingMethod.Contains(input.ShippingMethod)) .WhereIF(!string.IsNullOrWhiteSpace(input.CreatedUserName), u => u.CreatedUserName.Contains(input.CreatedUserName)) .WhereIF(!string.IsNullOrWhiteSpace(input.FREIGHTPAYER), u => u.FREIGHTPAYER.Contains(input.FREIGHTPAYER)) .WhereIF(!string.IsNullOrWhiteSpace(input.DZRemark), u => u.DZRemark.Contains(input.DZRemark)) .WhereIF(!string.IsNullOrWhiteSpace(input.CZRemark), u => u.CZRemark.Contains(input.CZRemark)) .WhereIF(!string.IsNullOrWhiteSpace(input.ZhanCangFlag), u => u.ZhanCangFlag == input.ZhanCangFlag) .WhereIF(!string.IsNullOrWhiteSpace(input.BSSTATUSNAME), u => u.BSSTATUSNAME == input.BSSTATUSNAME) .WhereIF(input.BDELETETIME != null, u => u.DeleteTime >= input.BDELETETIME) .WhereIF(input.EDELETETIME != null, u => u.DeleteTime < input.EDELETETIME.Value.AddDays(1)) .WhereIF(saleUserList != null && saleUserList.Count > 0, o => saleUserList.Contains(o.SALEID)) .WhereIF(opUserList != null && opUserList.Count > 0, o => opUserList.Contains(o.OPID)) .WhereIF(userlist != null && userlist.Count() > 0, u => userlist.Contains((long)u.CreatedUserId) || UserManager.UserId.ToString() == u.ROUTEID || UserManager.Name.ToString() == u.ROUTE || UserManager.UserId.ToString() == u.LineManageID || UserManager.Name.ToString() == u.LineManage || UserManager.UserId.ToString() == u.SALEID || UserManager.Name.ToString() == u.SALE || userlistString.Contains(u.OPID) || UserManager.Name.ToString() == u.OP || userlistString.Contains(u.DOCID) || UserManager.Name.ToString() == u.DOC || UserManager.UserId.ToString() == u.CUSTSERVICEID || UserManager.Name.ToString() == u.CUSTSERVICE); if (!string.IsNullOrEmpty(input.SortField) || input.MultiSort == null || input.MultiSort.Count == 0) { query = query.OrderBy(PageInputOrder.OrderBuilder(input.SortField, input.DescSort)); } else { query = query.OrderBy(PageInputOrder.MultiOrderBuilder(input.MultiSort)); } #endregion /* //标识没有台账查询 bool isHasBKOrderQuery = query.QueryBuilder.WhereInfos.Any(a => !Regex.IsMatch(a, "`?\\bTenantId\\b`?\\s?\\=\\s?\\@\\bTenantId") && !Regex.IsMatch(a, "`?\\bIsDeleted\\b`\\s?\\=\\s?\\@\\bIsDeleted") && !Regex.IsMatch(a, "`?ParentId\\b`\\s?\\=\\s?\\@[a-zA-Z]+.*`?ParentId\\b`\\s\\bIS\\b\\s\\bNULL\\b")); if(!isHasBKOrderQuery) { //如果没有台账查询条件,需要先取近一个月的 } */ var entities = await query.ToPagedListAsync(input.PageNo, input.PageSize); //var sql = query.ToSqlString(); if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageData {reqId} Stage 3 {et.TotalMilliseconds}"); } var list = entities.Adapt>(); if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageData {reqId} Stage 4 {et.TotalMilliseconds}"); } var bookingidlist = list.Items.Select(x => x.Id).ToList(); var itgoodsStatus = new List(); var itconfigs = new List(); var pageColsCfg = _djyUserConfigService.Multi(new string[] { "booking_list_column" }) .GetAwaiter().GetResult().FirstOrDefault(); bool isUseGoodsStatus = true; //这里因为个人配置的不是标准的格式化数据,所以这里只做了正则匹配 if (pageColsCfg != null && !string.IsNullOrWhiteSpace(pageColsCfg.ConfigJson)) { isUseGoodsStatus = Regex.IsMatch(pageColsCfg.ConfigJson, "\\\"field\\\"\\s?\\:\\s?\\\"goodsStatusList\\\""); _logger.LogInformation("取到个人配置里是否展示 goodsStatusList(货物状态)={rlt}", (isUseGoodsStatus ? "展示" : "隐藏")); } List statusList = new List(); if (App.Configuration["ServiceStatusOpenAuto"] == "1") { if (isUseGoodsStatus) { var curTenant = list.Items.FirstOrDefault()?.TenantId; QueryServiceProjectWithStatusBatch batchQuery = new QueryServiceProjectWithStatusBatch { BookingIds = bookingidlist.ToArray(), QueryType = TrackingQueryTypeEnum.QUERY_SERVICE_ALL, TenantId = curTenant.HasValue ? curTenant.Value : 0 }; var queryRlt = _serviceWorkFlowManageService.GetEnableStatusListByBusinessBatch(batchQuery) .GetAwaiter().GetResult(); if (queryRlt.succ) { statusList = JSON.Deserialize>(JSON.Serialize(queryRlt.ext)); } } } else { //货物状态 itgoodsStatus = _goodsStatus.AsQueryable().LeftJoin(_goodsStatusConfig.AsQueryable(), (goods, config) => config.Id == goods.ConfigId && bookingidlist.Contains((long)goods.bookingId)). OrderBy((goods, config) => config.Sort). Select((goods, config) => new ITGoodsStatusDto { bookingid = goods.bookingId, ConfigId = goods.ConfigId, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = goods.FinishTime, ExtData = goods.ExtData, Remark = goods.Remark, CreatedUserId = config.CreatedUserId, Sort = config.Sort }).ToList(); var configID = itgoodsStatus.Select(x => x.ConfigId) .Distinct().ToList(); itconfigs = _goodsStatusConfig.AsQueryable() .Where(x => configID.Contains(x.Id)).Select(config => new ITConfigsDto { bookingid = "", ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = "", ExtData = "", Remark = "", CreatedUserId = config.CreatedUserId, Sort = config.Sort }).ToList(); } if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageData {reqId} Stage 5 {et.TotalMilliseconds}"); } //提箱返场 var statusloglist = _repStatuslog.AsQueryable().Filter(null, true).Where(x => bookingidlist.Contains((long)x.BookingId) && (x.Status == "提箱" || x.Status == "返场") && x.IsDeleted == false).ToList(); var statuslogId = statusloglist.Select(x => x.Id).ToList(); //运踪状态详情 var statuslogdetaillist = _statuslogdetail.AsQueryable().Where(x => statuslogId.Contains(x.PId)).ToList(); //运踪状态 var BookingStatusList = _repBookingStatus.AsQueryable().Filter(null, true).Where(x => bookingidlist.Contains((long)x.BookingId)).ToList(); //备注 var bookingremarkList = _bookingremark.AsQueryable().Filter(null, true).Where(x => bookingidlist.Contains(x.PId)).ToList(); if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageData {reqId} Stage 6 {et.TotalMilliseconds}"); } foreach (var item in list.Items) { #region 查询条件 var sta = BookingStatusList.Where(x => x.BookingId == item.Id).ToList(); if (sta != null) { item.bookstatus = sta; } var st = bookingremarkList.Where(x => x.PId == item.Id).ToList(); if (st != null) { item.bookremark = st; } //变更日期类型 if (!string.IsNullOrWhiteSpace(item.ETD)) { item.ETD = Convert.ToDateTime(item.ETD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.ETA)) { item.ETA = Convert.ToDateTime(item.ETA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.YgtETD)) { item.YgtETD = Convert.ToDateTime(item.YgtETD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.ATD)) { item.ATD = Convert.ToDateTime(item.ATD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.StartETA)) { item.StartETA = Convert.ToDateTime(item.StartETA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.StartATA)) { item.StartATA = Convert.ToDateTime(item.StartATA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.MiddleETA)) { item.MiddleETA = Convert.ToDateTime(item.MiddleETA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.MiddleETD)) { item.MiddleETD = Convert.ToDateTime(item.MiddleETD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.MiddleATA)) { item.MiddleATA = Convert.ToDateTime(item.MiddleATA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.MiddleATD)) { item.MiddleATD = Convert.ToDateTime(item.MiddleATD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.ATA)) { item.ATA = Convert.ToDateTime(item.ATA).ToString("yyyy-MM-dd"); } #endregion if (App.Configuration["ServiceStatusOpenAuto"] == "1") { if (isUseGoodsStatus) { var currStatusList = statusList.Where(a => long.Parse(a.BusiId) == item.Id).ToList(); if (currStatusList.Count > 0) { if (currStatusList.Any(a => a.StatusSKUCode.Equals("YFVGM", StringComparison.OrdinalIgnoreCase) && a.IsYield)) { var currStus = currStatusList.FirstOrDefault(a => a.StatusSKUCode.Equals("YFVGM", StringComparison.OrdinalIgnoreCase) && a.IsYield); if (currStus != null) item.IsVGM = currStus?.ActDate.Value; } if (currStatusList.Any(a => a.StatusSKUCode.Equals("YFCD", StringComparison.OrdinalIgnoreCase) && a.IsYield)) { var currStus = currStatusList.FirstOrDefault(a => a.StatusSKUCode.Equals("YFCD", StringComparison.OrdinalIgnoreCase) && a.IsYield); if (currStus != null) item.IsCanDan = currStus?.ActDate.Value; } if (currStatusList.Any(a => a.StatusSKUCode.Equals("ZZFX", StringComparison.OrdinalIgnoreCase) && a.IsYield)) { var currStus = currStatusList.FirstOrDefault(a => a.StatusSKUCode.Equals("ZZFX", StringComparison.OrdinalIgnoreCase) && a.IsYield); if (currStus != null) item.IsZZFX = currStus?.ActDate.Value; } item.GoodsStatusList = currStatusList.OrderBy(a => a.CalcSortNo) .Select(a => new GoodsStatusList { FinishTime = a.ActDate, IsLast = a.IsEnd, Sort = a.ActSortNo, StatusName = a.ShowName, SystemCode = a.StatusSKUCode, ExtData = !string.IsNullOrWhiteSpace(a.ActVal) ? a.ActVal : string.Empty, Remark = !string.IsNullOrWhiteSpace(a.ActRemark) ? a.ActRemark : string.Empty }).ToList(); } else { item.GoodsStatusList = new List(); } } else { item.GoodsStatusList = new List(); } } else { var itgoods = itgoodsStatus.Where(x => x.CreatedUserId == item.CreatedUserId && x.bookingid == item.Id).OrderBy(x => x.Sort). Select(x => new GoodsStatusList { ConfigId = x.ConfigId, StatusName = x.StatusName, SystemCode = x.SystemCode, FinishTime = x.FinishTime, ExtData = x.ExtData, Remark = x.Remark, Sort = x.Sort }).ToList(); var itconfig = itconfigs.Where(x => x.CreatedUserId == item.CreatedUserId).OrderBy(x => x.Sort). Select(x => new GoodsStatusList { ConfigId = x.ConfigId, StatusName = x.StatusName, SystemCode = x.SystemCode, FinishTime = null, ExtData = x.ExtData, Remark = x.Remark, Sort = x.Sort }).ToList(); foreach (var ii in itgoods) { itconfig.RemoveAll(x => x.ConfigId == ii.ConfigId); } item.IsVGM = itgoods.Where(x => x.SystemCode == "YFVGM").FirstOrDefault() == null ? null : itgoods.Where(x => x.SystemCode == "YFVGM").Select(x => x.FinishTime).FirstOrDefault(); item.IsCanDan = itgoods.Where(x => x.SystemCode == "YFCD").FirstOrDefault() == null ? null : itgoods.Where(x => x.SystemCode == "YFCD").Select(x => x.FinishTime).FirstOrDefault(); item.IsZZFX = itgoods.Where(x => x.SystemCode == "ZZFX").FirstOrDefault() == null ? null : itgoods.Where(x => x.SystemCode == "ZZFX").Select(x => x.FinishTime).FirstOrDefault(); item.GoodsStatusList = itgoods.Union(itconfig).OrderBy(x => x.Sort).ToList(); } //获取提箱返场状态 //var statuslog = statusloglist.Where(x => x.BookingId == item.Id).OrderByDescending(x => x.CreatedTime).ToList(); //var dto = statuslog.Adapt>(); //foreach (var it in dto) //{ // var detail = statuslogdetaillist.Where(x => x.PId == it.Id).ToList(); // it.detail = detail.Adapt>(); //} //item.statuslogs = dto; var statusids = statusloglist.Where(x => x.BookingId == item.Id).Select(x => x.Id).ToList(); var dto = statuslogdetaillist.Where(x => statusids.Contains(x.PId)).ToList(); List CNTRNODtolist = new List(); foreach (var d in dto) { var ctn = CNTRNODtolist.Where(x => x.CNTRNO == d.CNTRNO).FirstOrDefault(); if (ctn == null) { if (d.Status == "提箱") { CNTRNODtolist.Add(new CNTRNODto { BookingId = item.Id, CNTRNO = d.CNTRNO, TXOPTime = d.OPTime, FCOPTime = null }); } if (d.Status == "返场") { CNTRNODtolist.Add(new CNTRNODto { BookingId = item.Id, CNTRNO = d.CNTRNO, FCOPTime = d.OPTime, TXOPTime = null }); } } else { if (d.Status == "提箱") { ctn.TXOPTime = d.OPTime; } if (d.Status == "返场") { ctn.FCOPTime = d.OPTime; } } } item.statuslogs1 = CNTRNODtolist; var extendstate = await _repextendstate.FirstOrDefaultAsync(x => x.bookingId == item.Id); if (extendstate != null) { item.ExtendState = extendstate; } } if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageData {reqId} Stage 7 {et.TotalMilliseconds}"); } return list; } /// /// 分页查询订舱主表(新) /// /// /// [HttpPost("/BookingOrder/PageDataNew")] public async Task PageDataNew(BookingOrderInputNew input) { var reqId = Guid.NewGuid().ToString(); //请求id,跟踪请求耗时 var ticks = DateTime.Now; if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"PageDataNew {reqId} Stage 0 "); } //获取菜单列表权限 List userlist = await _right.GetDataScopeList(MenuConst.MenuBookingOrder); List userlistString = userlist?.Select(u => u.ToString())?.ToList(); List pidlist = new List(); if (!string.IsNullOrWhiteSpace(input.SEALNO) || !string.IsNullOrWhiteSpace(input.CNTRNO)) { pidlist = await _repCtn.AsQueryable().WhereIF(!string.IsNullOrWhiteSpace(input.SEALNO), x => x.SEALNO.StartsWith(input.SEALNO)).WhereIF(!string.IsNullOrWhiteSpace(input.CNTRNO), x => x.CNTRNO.StartsWith(input.CNTRNO)).Select(x => x.BILLID).ToListAsync(); } //默认首次查询取开船日期范围 var ftoday = DateTime.Now.AddDays(-15); var etoday = DateTime.Now.AddDays(30); //List userlist = await DataFilterExtensions.GetDataScopeIdList(); if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageDataNew {reqId} Stage 1 {et.TotalMilliseconds}"); } //按部门查询 List saleUserList = null; List opUserList = null; if (input.OrgSale.HasValue) { var tmpList = await _orgService.GetUserIdListInOrg(input.OrgSale.Value); saleUserList = tmpList.Select(x => x.ToString()).ToList(); } if (input.OrgOp.HasValue) { var tmpList = await _orgService.GetUserIdListInOrg(input.OrgOp.Value); opUserList = tmpList.Select(x => x.ToString()).ToList(); } if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageDataNew {reqId} Stage 2 {et.TotalMilliseconds}"); } #region var query = _rep.AsQueryable().Filter(null, true).Where(x => x.TenantId == UserManager.TENANT_ID) .WhereIF(!input.ISDel, x => x.IsDeleted == false) .WhereIF(input.ISDel, x => x.IsDeleted == true) .WhereIF(input.firstFlag, x => (x.ETD <= etoday && x.ETD >= ftoday || x.ETD == null) && (x.CreatedUserId == UserManager.UserId || x.OPID == UserManager.UserId.ToString() || x.DOCID == UserManager.UserId.ToString() || x.ROUTEID == UserManager.UserId.ToString() || x.LineManageID == UserManager.UserId.ToString() || x.CUSTSERVICEID == UserManager.UserId.ToString() || x.SALEID == UserManager.UserId.ToString())) //首次加载数据:ETD前后15天,且创建人、操作是当前人 .Where(x => x.ParentId == 0 || x.ParentId == null) //台账只查询主单!! .WhereIF(input.Id != 0, x => x.Id == input.Id) .WhereIF(pidlist != null && pidlist.Count > 0, x => pidlist.Contains(x.Id)) .WhereIF(!string.IsNullOrWhiteSpace(input.BSNO), u => u.BSNO.Contains(input.BSNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.BSSTATUS), u => u.BSSTATUS == input.BSSTATUS) .WhereIF(input.BBSDATE != null, u => u.BSDATE >= input.BBSDATE) .WhereIF(input.EBSDATE != null, u => u.BSDATE <= input.EBSDATE) .WhereIF(!string.IsNullOrWhiteSpace(input.MBLNO) && !input.MBLNO.Contains(','), u => u.MBLNO.Contains(input.MBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.TMBLNO) && !input.TMBLNO.Contains(','), u => u.TMBLNO.Contains(input.TMBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.HBLNO) && !input.HBLNO.Contains(','), u => u.HBLNO.Contains(input.HBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.MBLNO) && input.MBLNO.Contains(','), u => input.MBLNO.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Contains(u.MBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.HBLNO) && input.HBLNO.Contains(','), u => input.HBLNO.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Contains(u.HBLNO.Trim())) .WhereIF(!string.IsNullOrWhiteSpace(input.BOOKINGNO), u => u.BOOKINGNO.Contains(input.BOOKINGNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONTRACTNO), u => u.CONTRACTNO.Contains(input.CONTRACTNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.SERVICECONTRACTNO), u => u.SERVICECONTRACTNO.Contains(input.SERVICECONTRACTNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPER), u => u.SHIPPER.Contains(input.SHIPPER)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEE), u => u.CONSIGNEE.Contains(input.CONSIGNEE)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTY), u => u.NOTIFYPARTY.Contains(input.NOTIFYPARTY)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTY2), u => u.NOTIFYPARTY2.Contains(input.NOTIFYPARTY2)) .WhereIF(!string.IsNullOrWhiteSpace(input.YARDID), u => u.YARDID == input.YARDID) .WhereIF(!string.IsNullOrWhiteSpace(input.VESSELID), u => u.VESSELID.Contains(input.VESSELID)) .WhereIF(!string.IsNullOrWhiteSpace(input.VESSEL), u => u.VESSEL.ToLower().Contains(input.VESSEL.ToLower())) .WhereIF(!string.IsNullOrWhiteSpace(input.VOYNO), u => u.VOYNO.Contains(input.VOYNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.VOYNOINNER), u => u.VOYNOINNER.Contains(input.VOYNOINNER)) .WhereIF(input.BETD != null, u => u.ETD >= input.BETD) .WhereIF(input.EETD != null, u => u.ETD < input.EETD.Value.AddDays(1)) .WhereIF(input.BATD != null, u => u.ATD >= input.BATD) .WhereIF(input.EATD != null, u => u.ATD < input.EATD.Value.AddDays(1)) .WhereIF(input.BCLOSINGDATE != null, u => u.CLOSINGDATE >= input.BCLOSINGDATE) .WhereIF(input.ECLOSINGDATE != null, u => u.CLOSINGDATE <= input.ECLOSINGDATE) .WhereIF(input.BCLOSEDOCDATE != null, u => u.CLOSEDOCDATE >= input.BCLOSEDOCDATE) .WhereIF(input.ECLOSEDOCDATE != null, u => u.CLOSEDOCDATE <= input.ECLOSEDOCDATE) .WhereIF(input.BCLOSEVGMDATE != null, u => u.CLOSEVGMDATE >= input.BCLOSEVGMDATE) .WhereIF(input.ECLOSEVGMDATE != null, u => u.CLOSEVGMDATE <= input.ECLOSEVGMDATE) .WhereIF(input.BETA != null, u => u.ETA >= input.BETA) .WhereIF(input.EETA != null, u => u.ETA < input.EETA.Value.AddDays(1)) .WhereIF(!string.IsNullOrWhiteSpace(input.PLACERECEIPT), u => u.PLACERECEIPT.Contains(input.PLACERECEIPT)) .WhereIF(!string.IsNullOrWhiteSpace(input.PORTLOAD), u => u.PORTLOAD.Contains(input.PORTLOAD)) .WhereIF(!string.IsNullOrWhiteSpace(input.PORTLOADID), u => u.PORTLOADID == input.PORTLOADID) .WhereIF(!string.IsNullOrWhiteSpace(input.PORTDISCHARGEID), u => u.PORTDISCHARGEID == input.PORTDISCHARGEID) .WhereIF(!string.IsNullOrWhiteSpace(input.PORTDISCHARGE), u => u.PORTDISCHARGE.Contains(input.PORTDISCHARGE)) .WhereIF(!string.IsNullOrWhiteSpace(input.PLACEDELIVERY), u => u.PLACEDELIVERY.Contains(input.PLACEDELIVERY)) .WhereIF(!string.IsNullOrWhiteSpace(input.PLACEDELIVERYID), u => u.PLACEDELIVERYID == input.PLACEDELIVERYID) .WhereIF(!string.IsNullOrWhiteSpace(input.DESTINATION), u => u.DESTINATION.Contains(input.DESTINATION)) .WhereIF(!string.IsNullOrWhiteSpace(input.DESTINATIONID), u => u.DESTINATIONID == input.DESTINATIONID) .WhereIF(!string.IsNullOrWhiteSpace(input.NOBILL), u => u.NOBILL == input.NOBILL) .WhereIF(!string.IsNullOrWhiteSpace(input.COPYNOBILLL), u => u.COPYNOBILL == input.COPYNOBILLL) .WhereIF(!string.IsNullOrWhiteSpace(input.ISSUETYPE), u => u.ISSUETYPE == input.ISSUETYPE) .WhereIF(input.BISSUEDATE != null, u => u.ISSUEDATE >= input.BISSUEDATE) .WhereIF(input.EISSUEDATE != null, u => u.ISSUEDATE < input.EISSUEDATE.Value.AddDays(1)) .WhereIF(!string.IsNullOrWhiteSpace(input.ISSUEPLACE), u => u.ISSUEPLACE.Contains(input.ISSUEPLACE)) .WhereIF(!string.IsNullOrWhiteSpace(input.ISSUEPLACEID), u => u.ISSUEPLACEID == input.ISSUEPLACEID) .WhereIF(!string.IsNullOrWhiteSpace(input.BLFRT), u => u.BLFRT == input.BLFRT) .WhereIF(!string.IsNullOrWhiteSpace(input.PREPARDATID), u => u.PREPARDATID == input.PREPARDATID) .WhereIF(!string.IsNullOrWhiteSpace(input.PREPARDAT), u => u.PREPARDAT == input.PREPARDAT) .WhereIF(!string.IsNullOrWhiteSpace(input.PAYABLEAT), u => u.PAYABLEAT.Contains(input.PAYABLEAT)) .WhereIF(!string.IsNullOrWhiteSpace(input.PAYABLEATID), u => u.PAYABLEATID == input.PAYABLEATID) .WhereIF(!string.IsNullOrWhiteSpace(input.SERVICE), u => u.SERVICE.Contains(input.SERVICE)) .WhereIF(!string.IsNullOrWhiteSpace(input.MARKS), u => u.MARKS.Contains(input.MARKS)) .WhereIF(!string.IsNullOrWhiteSpace(input.HSCODE), u => u.HSCODE.Contains(input.HSCODE)) .WhereIF(!string.IsNullOrWhiteSpace(input.DESCRIPTION), u => u.DESCRIPTION.Contains(input.DESCRIPTION)) .WhereIF(!string.IsNullOrWhiteSpace(input.KINDPKGS), u => u.KINDPKGS == input.KINDPKGS) .WhereIF(!string.IsNullOrWhiteSpace(input.CNTRTOTAL), u => u.CNTRTOTAL.StartsWith(input.CNTRTOTAL)) .WhereIF(!string.IsNullOrWhiteSpace(input.CARRIERID), u => u.CARRIERID == input.CARRIERID) .WhereIF(!string.IsNullOrWhiteSpace(input.CARRIER), u => u.CARRIER.Contains(input.CARRIER)) .WhereIF(!string.IsNullOrWhiteSpace(input.CARGOID), u => u.CARGOID == input.CARGOID) .WhereIF(!string.IsNullOrWhiteSpace(input.DCLASS), u => u.DCLASS == input.DCLASS) .WhereIF(!string.IsNullOrWhiteSpace(input.DUNNO), u => u.DUNNO == input.DUNNO) .WhereIF(!string.IsNullOrWhiteSpace(input.DPAGE), u => u.DPAGE == input.DPAGE) .WhereIF(!string.IsNullOrWhiteSpace(input.DLABEL), u => u.DLABEL == input.DLABEL) .WhereIF(!string.IsNullOrWhiteSpace(input.LINKMAN), u => u.LINKMAN == input.LINKMAN) .WhereIF(!string.IsNullOrWhiteSpace(input.TEMPID), u => u.TEMPID == input.TEMPID) .WhereIF(!string.IsNullOrWhiteSpace(input.TEMPSET), u => u.TEMPSET == input.TEMPSET) .WhereIF(!string.IsNullOrWhiteSpace(input.REEFERF), u => u.REEFERF == input.REEFERF) .WhereIF(!string.IsNullOrWhiteSpace(input.HUMIDITY), u => u.HUMIDITY == input.HUMIDITY) .WhereIF(!string.IsNullOrWhiteSpace(input.TEMPMIN), u => u.TEMPMIN == input.TEMPMIN) .WhereIF(!string.IsNullOrWhiteSpace(input.TEMPMAX), u => u.TEMPMAX == input.TEMPMAX) .WhereIF(input.ISCONTAINERSOC != null, u => u.ISCONTAINERSOC == input.ISCONTAINERSOC) .WhereIF(!string.IsNullOrWhiteSpace(input.SOREMARK), u => u.SOREMARK.Contains(input.SOREMARK)) .WhereIF(!string.IsNullOrWhiteSpace(input.SIREMARK), u => u.SIREMARK.Contains(input.SIREMARK)) .WhereIF(!string.IsNullOrWhiteSpace(input.YARDREMARK), u => u.YARDREMARK.Contains(input.YARDREMARK)) .WhereIF(!string.IsNullOrWhiteSpace(input.COMPID), u => u.COMPID == input.COMPID) .WhereIF(!string.IsNullOrWhiteSpace(input.COMPNAME), u => u.COMPNAME.Contains(input.COMPNAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERNAME), u => u.SHIPPERNAME.Contains(input.SHIPPERNAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERCITY), u => u.SHIPPERCITY.Contains(input.SHIPPERCITY)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERPROVINCE), u => u.SHIPPERPROVINCE == input.SHIPPERPROVINCE) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERPOSTCODE), u => u.SHIPPERPOSTCODE == input.SHIPPERPOSTCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERCOUNTRY), u => u.SHIPPERCOUNTRY == input.SHIPPERCOUNTRY) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERATTN), u => u.SHIPPERATTN.Contains(input.SHIPPERATTN)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPPERTEL), u => u.SHIPPERTEL == input.SHIPPERTEL) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEENAME), u => u.CONSIGNEENAME.Contains(input.CONSIGNEENAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEECITY), u => u.CONSIGNEECITY.Contains(input.CONSIGNEECITY)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEEPROVINCE), u => u.CONSIGNEEPROVINCE == input.CONSIGNEEPROVINCE) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEEPOSTCODE), u => u.CONSIGNEEPOSTCODE == input.CONSIGNEEPOSTCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEERCOUNTRY), u => u.CONSIGNEERCOUNTRY == input.CONSIGNEERCOUNTRY) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEEATTN), u => u.CONSIGNEEATTN.Contains(input.CONSIGNEEATTN)) .WhereIF(!string.IsNullOrWhiteSpace(input.CONSIGNEETEL), u => u.CONSIGNEETEL == input.CONSIGNEETEL) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYNAME), u => u.NOTIFYPARTYNAME.Contains(input.NOTIFYPARTYNAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYCITY), u => u.NOTIFYPARTYCITY.Contains(input.NOTIFYPARTYCITY)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYPROVINCE), u => u.NOTIFYPARTYPROVINCE == input.NOTIFYPARTYPROVINCE) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYPOSTCODE), u => u.NOTIFYPARTYPOSTCODE == input.NOTIFYPARTYPOSTCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYCOUNTRY), u => u.NOTIFYPARTYCOUNTRY == input.NOTIFYPARTYCOUNTRY) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYATTN), u => u.NOTIFYPARTYATTN.Contains(input.NOTIFYPARTYATTN)) .WhereIF(!string.IsNullOrWhiteSpace(input.NOTIFYPARTYTEL), u => u.NOTIFYPARTYTEL == input.NOTIFYPARTYTEL) .WhereIF(!string.IsNullOrWhiteSpace(input.PONO), u => u.PONO.Contains(input.PONO)) .WhereIF(!string.IsNullOrWhiteSpace(input.OPID), u => u.OPID == input.OPID) .WhereIF(!string.IsNullOrWhiteSpace(input.DOCID), u => u.DOCID == input.DOCID) .WhereIF(!string.IsNullOrWhiteSpace(input.OP), u => u.OP == input.OP) .WhereIF(!string.IsNullOrWhiteSpace(input.DOC), u => u.DOC == input.DOC) .WhereIF(!string.IsNullOrWhiteSpace(input.SALEID), u => u.SALEID == input.SALEID) .WhereIF(!string.IsNullOrWhiteSpace(input.SALE), u => u.SALE.Contains(input.SALE)) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTSERVICEID), u => u.CUSTSERVICEID == input.CUSTSERVICEID) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTSERVICE), u => u.CUSTSERVICE.Contains(input.CUSTSERVICE)) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTOMERNAME), u => u.CUSTOMERNAME.Contains(input.CUSTOMERNAME)) .WhereIF(input.CUSTOMERID != null && input.CUSTOMERID != 0, u => u.CUSTOMERID == input.CUSTOMERID) .WhereIF(!string.IsNullOrWhiteSpace(input.FORWARDER), u => u.FORWARDER.Contains(input.FORWARDER)) .WhereIF(!string.IsNullOrWhiteSpace(input.AGENTID), u => u.AGENTID == input.AGENTID) .WhereIF(!string.IsNullOrWhiteSpace(input.FORWARDERID), u => u.FORWARDERID == input.FORWARDERID) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPAGENCY), u => u.SHIPAGENCY.Contains(input.SHIPAGENCY)) .WhereIF(!string.IsNullOrWhiteSpace(input.SHIPAGENCYID), u => u.SHIPAGENCYID == input.SHIPAGENCYID) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTOMSER), u => u.CUSTOMSER.Contains(input.CUSTOMSER)) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTOMSERID), u => u.CUSTOMSERID == input.CUSTOMSERID) .WhereIF(!string.IsNullOrWhiteSpace(input.TRUCKER), u => u.TRUCKER.Contains(input.TRUCKER)) .WhereIF(!string.IsNullOrWhiteSpace(input.TRUCKERID), u => u.TRUCKERID == input.TRUCKERID) .WhereIF(!string.IsNullOrWhiteSpace(input.AGENTNAME), u => u.AGENTNAME.Contains(input.AGENTNAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.WEITUO), u => u.WEITUO.Contains(input.WEITUO)) .WhereIF(!string.IsNullOrWhiteSpace(input.SCACCODE), u => u.SCACCODE == input.SCACCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.ITNCODE), u => u.ITNCODE == input.ITNCODE) .WhereIF(!string.IsNullOrWhiteSpace(input.CUSTNO), u => u.CUSTNO.Contains(input.CUSTNO)) .WhereIF(!string.IsNullOrWhiteSpace(input.TRANSPORTID), u => u.TRANSPORTID == input.TRANSPORTID) .WhereIF(!string.IsNullOrWhiteSpace(input.TRANSPORT), u => u.TRANSPORT.Contains(input.TRANSPORT)) .WhereIF(!string.IsNullOrWhiteSpace(input.YARDCONTRACTTEL), u => u.YARDCONTRACTTEL == input.YARDCONTRACTTEL) .WhereIF(!string.IsNullOrWhiteSpace(input.YARDCONTRACTEMAIL), u => u.YARDCONTRACTEMAIL == input.YARDCONTRACTEMAIL) .WhereIF(!string.IsNullOrWhiteSpace(input.LANECODE), u => u.LANECODE == input.LANECODE) .WhereIF(!string.IsNullOrWhiteSpace(input.LANENAME), u => u.LANENAME.Contains(input.LANENAME)) .WhereIF(!string.IsNullOrWhiteSpace(input.ROUTEID), u => u.ROUTEID == input.ROUTEID) .WhereIF(!string.IsNullOrWhiteSpace(input.ROUTE), u => u.ROUTE.Contains(input.ROUTE)) .WhereIF(!string.IsNullOrWhiteSpace(input.LineManageID), u => u.LineManageID == input.LineManageID) .WhereIF(!string.IsNullOrWhiteSpace(input.LineManage), u => u.LineManage.Contains(input.LineManage)) .WhereIF(!string.IsNullOrWhiteSpace(input.ShippingMethod), u => u.ShippingMethod.Contains(input.ShippingMethod)) .WhereIF(!string.IsNullOrWhiteSpace(input.CreatedUserName), u => u.CreatedUserName.Contains(input.CreatedUserName)) .WhereIF(!string.IsNullOrWhiteSpace(input.FREIGHTPAYER), u => u.FREIGHTPAYER.Contains(input.FREIGHTPAYER)) .WhereIF(!string.IsNullOrWhiteSpace(input.DZRemark), u => u.DZRemark.Contains(input.DZRemark)) .WhereIF(!string.IsNullOrWhiteSpace(input.CZRemark), u => u.CZRemark.Contains(input.CZRemark)) .WhereIF(!string.IsNullOrWhiteSpace(input.ZhanCangFlag), u => u.ZhanCangFlag == input.ZhanCangFlag) .WhereIF(!string.IsNullOrWhiteSpace(input.BSSTATUSNAME), u => u.BSSTATUSNAME == input.BSSTATUSNAME) .WhereIF(input.BDELETETIME != null, u => u.DeleteTime >= input.BDELETETIME) .WhereIF(input.EDELETETIME != null, u => u.DeleteTime < input.EDELETETIME.Value.AddDays(1)) .WhereIF(saleUserList != null && saleUserList.Count > 0, o => saleUserList.Contains(o.SALEID)) .WhereIF(opUserList != null && opUserList.Count > 0, o => opUserList.Contains(o.OPID)) .WhereIF(userlist != null && userlist.Count() > 0, u => userlist.Contains((long)u.CreatedUserId) || UserManager.UserId.ToString() == u.ROUTEID || UserManager.Name.ToString() == u.ROUTE || UserManager.UserId.ToString() == u.LineManageID || UserManager.Name.ToString() == u.LineManage || UserManager.UserId.ToString() == u.SALEID || UserManager.Name.ToString() == u.SALE || userlistString.Contains(u.OPID) || UserManager.Name.ToString() == u.OP || userlistString.Contains(u.DOCID) || UserManager.Name.ToString() == u.DOC || UserManager.UserId.ToString() == u.CUSTSERVICEID || UserManager.Name.ToString() == u.CUSTSERVICE); var selector = new List() { new SelectModel() { FiledName = "Id" }, new SelectModel() { FiledName = "TenantId" } }; var ordProps = typeof(BookingOrder).GetProperties(); foreach (var sc in input.ShowColumns) { var prop = ordProps.FirstOrDefault(x => x.Name.ToLower() == sc.ToLower()); if (prop != null) { selector.Add(new SelectModel() { FiledName = prop.Name }); } else { _logger.LogWarning($"找不到对象上的列:{sc}"); } } query = query.Select(selector); if (!string.IsNullOrEmpty(input.SortField) || input.MultiSort == null || input.MultiSort.Count == 0) { query = query.OrderBy(PageInputOrder.OrderBuilder(input.SortField, input.DescSort)); } else { query = query.OrderBy(PageInputOrder.MultiOrderBuilder(input.MultiSort)); } #endregion var entities = await query.ToPagedListAsync(input.PageNo, input.PageSize); //var sql = query.ToSqlString(); if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageDataNew {reqId} Stage 3 {et.TotalMilliseconds}"); } var list = entities.Adapt>(); if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageDataNew {reqId} Stage 4 {et.TotalMilliseconds}"); } var bookingidlist = list.Items.Select(x => x.Id).ToList(); var itgoodsStatus = new List(); var itconfigs = new List(); var pageColsCfg = _djyUserConfigService.Multi(new string[] { "booking_list_column" }) .GetAwaiter().GetResult().FirstOrDefault(); bool isUseGoodsStatus = true; //这里因为个人配置的不是标准的格式化数据,所以这里只做了正则匹配 if (pageColsCfg != null && !string.IsNullOrWhiteSpace(pageColsCfg.ConfigJson)) { isUseGoodsStatus = Regex.IsMatch(pageColsCfg.ConfigJson, "\\\"field\\\"\\s?\\:\\s?\\\"goodsStatusList\\\""); _logger.LogInformation("取到个人配置里是否展示 goodsStatusList(货物状态)={rlt}", (isUseGoodsStatus ? "展示" : "隐藏")); } List statusList = new List(); if (App.Configuration["ServiceStatusOpenAuto"] == "1") { if (isUseGoodsStatus) { QueryServiceProjectWithStatusBatch batchQuery = new QueryServiceProjectWithStatusBatch { BookingIds = bookingidlist.ToArray(), QueryType = TrackingQueryTypeEnum.QUERY_SERVICE_ALL, TenantId = list.Items.FirstOrDefault().TenantId.Value }; var queryRlt = _serviceWorkFlowManageService.GetEnableStatusListByBusinessBatch(batchQuery) .GetAwaiter().GetResult(); if (queryRlt.succ) { statusList = JSON.Deserialize>(JSON.Serialize(queryRlt.ext)); } } } else { //货物状态 itgoodsStatus = _goodsStatus.AsQueryable().LeftJoin(_goodsStatusConfig.AsQueryable(), (goods, config) => config.Id == goods.ConfigId && bookingidlist.Contains((long)goods.bookingId)). OrderBy((goods, config) => config.Sort). Select((goods, config) => new ITGoodsStatusDto { bookingid = goods.bookingId, ConfigId = goods.ConfigId, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = goods.FinishTime, ExtData = goods.ExtData, Remark = goods.Remark, CreatedUserId = config.CreatedUserId, Sort = config.Sort }).ToList(); var configID = itgoodsStatus.Select(x => x.ConfigId) .Distinct().ToList(); itconfigs = _goodsStatusConfig.AsQueryable() .Where(x => configID.Contains(x.Id)).Select(config => new ITConfigsDto { bookingid = "", ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = "", ExtData = "", Remark = "", CreatedUserId = config.CreatedUserId, Sort = config.Sort }).ToList(); } if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageDataNew {reqId} Stage 5 {et.TotalMilliseconds}"); } List statusloglist = null; List statuslogdetaillist = null; if (input.ShowColumns.Contains("statuslogs")) { //提箱返场 statusloglist = _repStatuslog.AsQueryable().Filter(null, true).Where(x => bookingidlist.Contains((long)x.BookingId) && (x.Status == "提箱" || x.Status == "返场") && x.IsDeleted == false).ToList(); var statuslogId = statusloglist.Select(x => x.Id).ToList(); //运踪状态详情 statuslogdetaillist = _statuslogdetail.AsQueryable().Where(x => statuslogId.Contains(x.PId)).ToList(); } //运踪状态 List BookingStatusList = null; if (input.ShowColumns.Contains("bookstatus")) { BookingStatusList = _repBookingStatus.AsQueryable().Filter(null, true).Where(x => bookingidlist.Contains((long)x.BookingId)).ToList(); } //备注 List bookingremarkList = null; if (input.ShowColumns.Contains("bookremark")) { bookingremarkList = _bookingremark.AsQueryable().Filter(null, true).Where(x => bookingidlist.Contains(x.PId)).ToList(); } if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageDataNew {reqId} Stage 6 {et.TotalMilliseconds}"); } if (input.ShowColumns.Contains("isVGM") || input.ShowColumns.Contains("isCanDan") || input.ShowColumns.Contains("isZZFX") || input.ShowColumns.Contains("goodsStatusList") || input.ShowColumns.Contains("statuslogs") || input.ShowColumns.Contains("txxp")) { foreach (var item in list.Items) { #region 查询条件 //运踪 if (input.ShowColumns.Contains("bookstatus")) { var sta = BookingStatusList.Where(x => x.BookingId == item.Id).ToList(); if (sta != null) { item.bookstatus = sta; } } //备注 if (input.ShowColumns.Contains("bookremark")) { var st = bookingremarkList.Where(x => x.PId == item.Id).ToList(); if (st != null) { item.bookremark = st; } } //变更日期类型 if (!string.IsNullOrWhiteSpace(item.ETD)) { item.ETD = Convert.ToDateTime(item.ETD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.ETA)) { item.ETA = Convert.ToDateTime(item.ETA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.YgtETD)) { item.YgtETD = Convert.ToDateTime(item.YgtETD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.ATD)) { item.ATD = Convert.ToDateTime(item.ATD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.StartETA)) { item.StartETA = Convert.ToDateTime(item.StartETA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.StartATA)) { item.StartATA = Convert.ToDateTime(item.StartATA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.MiddleETA)) { item.MiddleETA = Convert.ToDateTime(item.MiddleETA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.MiddleETD)) { item.MiddleETD = Convert.ToDateTime(item.MiddleETD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.MiddleATA)) { item.MiddleATA = Convert.ToDateTime(item.MiddleATA).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.MiddleATD)) { item.MiddleATD = Convert.ToDateTime(item.MiddleATD).ToString("yyyy-MM-dd"); } if (!string.IsNullOrWhiteSpace(item.ATA)) { item.ATA = Convert.ToDateTime(item.ATA).ToString("yyyy-MM-dd"); } #endregion if (App.Configuration["ServiceStatusOpenAuto"] == "1") { if (isUseGoodsStatus) { var currStatusList = statusList.Where(a => long.Parse(a.BusiId) == item.Id).ToList(); if (currStatusList.Count > 0) { if (currStatusList.Any(a => a.StatusSKUCode.Equals("YFVGM", StringComparison.OrdinalIgnoreCase) && a.IsYield)) { var currStus = currStatusList.FirstOrDefault(a => a.StatusSKUCode.Equals("YFVGM", StringComparison.OrdinalIgnoreCase) && a.IsYield); if (currStus != null) item.IsVGM = currStus?.ActDate.Value; } if (currStatusList.Any(a => a.StatusSKUCode.Equals("YFCD", StringComparison.OrdinalIgnoreCase) && a.IsYield)) { var currStus = currStatusList.FirstOrDefault(a => a.StatusSKUCode.Equals("YFCD", StringComparison.OrdinalIgnoreCase) && a.IsYield); if (currStus != null) item.IsCanDan = currStus?.ActDate.Value; } if (currStatusList.Any(a => a.StatusSKUCode.Equals("ZZFX", StringComparison.OrdinalIgnoreCase) && a.IsYield)) { var currStus = currStatusList.FirstOrDefault(a => a.StatusSKUCode.Equals("ZZFX", StringComparison.OrdinalIgnoreCase) && a.IsYield); if (currStus != null) item.IsZZFX = currStus?.ActDate.Value; } //货物状态列 if (input.ShowColumns.Contains("goodsStatusList")) { item.GoodsStatusList = currStatusList.OrderBy(a => a.CalcSortNo) .Select(a => new GoodsStatusList { FinishTime = a.ActDate, IsLast = a.IsEnd, Sort = a.ActSortNo, StatusName = a.ShowName, SystemCode = a.StatusSKUCode, ExtData = !string.IsNullOrWhiteSpace(a.ActVal) ? a.ActVal : string.Empty, Remark = !string.IsNullOrWhiteSpace(a.ActRemark) ? a.ActRemark : string.Empty }).ToList(); } } } } else { var itgoods = itgoodsStatus.Where(x => x.CreatedUserId == item.CreatedUserId && x.bookingid == item.Id).OrderBy(x => x.Sort). Select(x => new GoodsStatusList { ConfigId = x.ConfigId, StatusName = x.StatusName, SystemCode = x.SystemCode, FinishTime = x.FinishTime, ExtData = x.ExtData, Remark = x.Remark, Sort = x.Sort }).ToList(); var itconfig = itconfigs.Where(x => x.CreatedUserId == item.CreatedUserId).OrderBy(x => x.Sort). Select(x => new GoodsStatusList { ConfigId = x.ConfigId, StatusName = x.StatusName, SystemCode = x.SystemCode, FinishTime = null, ExtData = x.ExtData, Remark = x.Remark, Sort = x.Sort }).ToList(); foreach (var ii in itgoods) { itconfig.RemoveAll(x => x.ConfigId == ii.ConfigId); } item.IsVGM = itgoods.Where(x => x.SystemCode == "YFVGM").FirstOrDefault() == null ? null : itgoods.Where(x => x.SystemCode == "YFVGM").Select(x => x.FinishTime).FirstOrDefault(); item.IsCanDan = itgoods.Where(x => x.SystemCode == "YFCD").FirstOrDefault() == null ? null : itgoods.Where(x => x.SystemCode == "YFCD").Select(x => x.FinishTime).FirstOrDefault(); item.IsZZFX = itgoods.Where(x => x.SystemCode == "ZZFX").FirstOrDefault() == null ? null : itgoods.Where(x => x.SystemCode == "ZZFX").Select(x => x.FinishTime).FirstOrDefault(); item.GoodsStatusList = itgoods.Union(itconfig).OrderBy(x => x.Sort).ToList(); } //获取提箱返场状态 if (input.ShowColumns.Contains("statuslogs")) { var statusids = statusloglist.Where(x => x.BookingId == item.Id).Select(x => x.Id).ToList(); var dto = statuslogdetaillist.Where(x => statusids.Contains(x.PId)).ToList(); List CNTRNODtolist = new List(); foreach (var d in dto) { var ctn = CNTRNODtolist.Where(x => x.CNTRNO == d.CNTRNO).FirstOrDefault(); if (ctn == null) { if (d.Status == "提箱") { CNTRNODtolist.Add(new CNTRNODto { BookingId = item.Id, CNTRNO = d.CNTRNO, TXOPTime = d.OPTime, FCOPTime = null }); } if (d.Status == "返场") { CNTRNODtolist.Add(new CNTRNODto { BookingId = item.Id, CNTRNO = d.CNTRNO, FCOPTime = d.OPTime, TXOPTime = null }); } } else { if (d.Status == "提箱") { ctn.TXOPTime = d.OPTime; } if (d.Status == "返场") { ctn.FCOPTime = d.OPTime; } } } item.statuslogs1 = CNTRNODtolist; } //扩展表(小票相关) if (input.ShowColumns.Contains("txxp")) { var extendstate = await _repextendstate.FirstOrDefaultAsync(x => x.bookingId == item.Id); if (extendstate != null) { item.ExtendState = extendstate; } } } } if (!string.IsNullOrEmpty(reqId)) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogWarning($"PageDataNew {reqId} Stage 7 {et.TotalMilliseconds}"); } return list; } /// /// 立即返回保存信息 /// /// /// [HttpPost("/BookingOrder/Save")] public async Task Save(SaveBookingOrderInput input) { var reqId = Guid.NewGuid().ToString(); //请求id,跟踪请求耗时 if (input == null) { throw Oops.Bah("请传入正常数据!"); } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],开始:{UserManager.Name} {JsonConvert.SerializeObject(input, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore })}"); } var ms = JsonUtil.TrimFields(input); if (!string.IsNullOrEmpty(ms)) { throw Oops.Bah(ms); } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],大写转换完成"); } //转大写 JsonUtil.PropToUpper(input, "ORDNO", "BSSTATUS", "YARDID", "YardContract", "YardContractTel", "YardContractEmail", "MARKS", "DESCRIPTION", "CONSIGNEENAME", "SHIPPERNAME", "NOTIFYPARTYNAME", "DZRemark", "CZRemark"); if (input.ctnInputs != null) { var groupList = input.ctnInputs.Where(x => x.CTNNUM > 0).GroupBy(c => c.CTNALL).Select(g => $"{g.Key}*{g.Sum(gg => gg.CTNNUM)}"); input.CNTRTOTAL = string.Join(" / ", groupList); } //条件限制 重复限制 if (!string.IsNullOrWhiteSpace(input.MBLNO) && input.ParentId == 0) { var et = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.MBLNO == input.MBLNO && x.TenantId == UserManager.TENANT_ID && x.ParentId == 0 && x.Id != input.Id).FirstAsync(); if (et != null) { throw Oops.Bah("当前主提单号已存在,请勿重复录入!"); } } //if (!string.IsNullOrWhiteSpace(input.HBLNO) && !string.IsNullOrWhiteSpace(input.MBLNO) && input.ParentId != 0) //{ // var et = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.MBLNO == input.MBLNO && x.HBLNO == input.HBLNO && x.TenantId == UserManager.TENANT_ID && x.ParentId == input.ParentId && x.Id != input.Id).FirstAsync(); // if (et != null) // { // throw Oops.Bah("当前分提单号已存在,请勿重复录入!"); // } //} //input.HBLNO请求参数的分单号不为空 if (!string.IsNullOrWhiteSpace(input.HBLNO)) { //查询表中是否有当前输入的分单号 if (input.ParentId > 0) //分单 { var et = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.HBLNO == input.HBLNO && x.TenantId == UserManager.TENANT_ID && x.Id != input.Id && x.Id != input.ParentId).FirstAsync(); if (et != null) { throw Oops.Bah("当前分提单号已存在,请勿重复录入!"); } } else //主单 { var et = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.HBLNO == input.HBLNO && x.TenantId == UserManager.TENANT_ID && x.Id != input.Id && x.ParentId != input.Id).FirstAsync(); if (et != null) { throw Oops.Bah("当前分提单号已存在,请勿重复录入!"); } } } //陈冠宇提订舱编号不允许重复 if (!string.IsNullOrWhiteSpace(input.CUSTNO)) { var et = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.CUSTNO == input.CUSTNO && x.TenantId == UserManager.TENANT_ID && x.ParentId == 0 && x.Id != input.Id).FirstAsync(); if (et != null) { throw Oops.Bah("当前订舱编号已存在,请勿重复录入!"); } } //孙晓飞提PONO不允许重复 if (!string.IsNullOrWhiteSpace(input.PONO)) { var et = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.PONO == input.PONO && x.TenantId == UserManager.TENANT_ID && x.ParentId == 0 && x.Id != input.Id).FirstAsync(); if (et != null) { throw Oops.Bah("当前PONO已存在,请勿重复录入!"); } } //版本号避免多人同时操作数据错乱 //if (!string.IsNullOrWhiteSpace(input.VERSION) && input.Id != 0) //{ // var et = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.VERSION == input.VERSION && x.Id == input.Id).FirstAsync(); // if (et == null) // { // throw Oops.Bah("当前版本号不一致,请刷新后在保存单据"); // } //} if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],校验完成"); } var entity = input.Adapt(); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],转为实体对象完成"); } //存在船名航次引入船期数据 if (!string.IsNullOrEmpty(input.VESSEL) && !string.IsNullOrEmpty(input.VOYNO)) { var vesselInfo = _vesselInfo.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.TenantId == UserManager.UserId && x.Vessel == input.VESSEL && x.Voyno == input.VESSEL && x.ATD != null).ToList().FirstOrDefault(); if (vesselInfo != null) { entity.YgtETD = vesselInfo.ETD; entity.StartETA = vesselInfo.ETA; entity.ATD = vesselInfo.ATD; if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],引用船期数据完成"); } } } //判断是否订阅运踪目的港起运港标识 if (!string.IsNullOrEmpty(entity.MBLNO)) { if (!string.IsNullOrEmpty(entity.CARRIERID) && !string.IsNullOrEmpty(entity.YARDID)) { entity.IsBookingYZ = "3"; } if (!string.IsNullOrEmpty(entity.CARRIERID) && string.IsNullOrEmpty(entity.YARDID)) { entity.IsBookingYZ = "2"; } if (string.IsNullOrEmpty(entity.CARRIERID) && !string.IsNullOrEmpty(entity.YARDID)) { entity.IsBookingYZ = "1"; } } else { entity.IsBookingYZ = "0"; } if (input.Id == 0) { if (string.IsNullOrEmpty(entity.VOYNO)) { entity.VOYNO = entity.VOYNOINNER; } entity.VERSION = Guid.NewGuid().ToString(); entity.BOOKINGNO = Yitter.IdGenerator.YitIdHelper.NextId().ToString(); entity.BSDATE = DateTime.Today; entity.BSNO = null; await _rep.InsertAsync(entity); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],新增插入完成"); } if (input.ctnInputs != null) { foreach (var item in input.ctnInputs) { var ctnentity = item.Adapt(); ctnentity.BILLID = entity.Id; await _repCtn.InsertAsync(ctnentity); //这里保存有可能没有添加多品名,所有箱下没有货物信息 if (item.ctnDetailInputs != null) { foreach (var it in item.ctnDetailInputs) { var ctndetail = it.Adapt(); ctndetail.CTNID = ctnentity.Id; await _ctndetailrep.InsertAsync(ctndetail); } } } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],箱信息插入完成"); } } if (input.BookingEDIExt != null) { //写入EDI扩展 var ediExt = input.BookingEDIExt.Adapt(); ediExt.BookingId = entity.Id; await _bookingEDIExt.InsertAsync(ediExt); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],扩展数据插入完成"); } } ////添加booking日志 await _bookinglog.InsertAsync(new BookingLog { Type = "Add", BookingId = entity.Id, TenantId = Convert.ToInt64(UserManager.TENANT_ID), CreatedTime = DateTime.Now, CreatedUserId = UserManager.UserId, CreatedUserName = UserManager.Name }); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],添加订舱日志完成"); } if (!string.IsNullOrEmpty(entity.MBLNO) && !string.IsNullOrEmpty(entity.YARDID)) { await _publisher.PublishAsync(new ChannelEventSource("BillTrace:Update", new { BookingId = entity.Id, TenentId = UserManager.TENANT_ID, UserId = UserManager.UserId, UserName = UserManager.Name, DjyUserId = UserManager.DjyUserId })); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],更新运踪订阅完成"); } } } else { var mlist = await _rep.AsQueryable().Filter(null, true).Where(x => x.Id == input.Id).FirstAsync(); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],获取订舱数据完成"); } //封账处理 var extend = _repextendstate.FirstOrDefault(x => x.bookingId == input.Id); var isextendorder = await GetIsBookingLockOrder(entity, mlist); if (extend != null && extend.IsLockBooking && !isextendorder) { throw Oops.Bah("当前单据已封账,不允许修改"); } var rightlist = await _right.GetDataScopeList(MenuConst.MenuBookingOrder, true); //除现有配置权限外 创建人本人、操作、单证、客服 具有编辑权限 if (rightlist != null && !( mlist.OPID == UserManager.UserId.ToString() || mlist.OP == UserManager.Name.ToString() || mlist.DOCID == UserManager.UserId.ToString() || mlist.DOC == UserManager.Name.ToString() || mlist.CUSTSERVICEID == UserManager.UserId.ToString() || mlist.CUSTSERVICE == UserManager.Name.ToString() || UserManager.UserId == 400234750476357 || mlist.CreatedUserId.ToString() == UserManager.UserId.ToString() || rightlist.Contains((long)mlist.CreatedUserId) )) { throw Oops.Bah("您没有当前单据的操作权限!"); } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],修改权限校验完成"); } if (string.IsNullOrEmpty(entity.VOYNO)) { entity.VOYNO = entity.VOYNOINNER; } entity.VERSION = Guid.NewGuid().ToString(); //判断如果船名航次船公司变动 同步更新船期字段 if (entity.CARRIERID != mlist.CARRIERID || entity.VOYNO != mlist.VOYNO || entity.VESSEL != mlist.VESSEL) { var vess = await _vesselInfo.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.TenantId == UserManager.TENANT_ID && x.CARRIERID == entity.CARRIERID && x.Vessel == entity.VESSEL && x.Voyno == entity.VOYNO).FirstAsync(); if (vess != null) { entity.StartETA = vess.ETA; entity.ATD = vess.ATD; entity.YgtETD = vess.YgtETD; } else { entity.StartETA = null; entity.ATD = null; entity.YgtETD = null; } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],拉取船期ETD、ATD等内容完成"); } } //把前端传递的已修改字段转换为属性名称 var lstPropName = new List { "CNTRTOTAL","IsBookingYZ" }; if (input.ChangedFields != null && input.ChangedFields.Count > 0) { var propsOrder = typeof(BookingOrder).GetProperties(); input.ChangedFields.ForEach(x => { var pchg = propsOrder.FirstOrDefault(p => p.Name.ToLower() == x.ToLower()); if (pchg != null) { lstPropName.Add(pchg.Name); } }); } await _rep.AsUpdateable(entity).UpdateColumns(lstPropName.ToArray()).ExecuteCommandAsync(); //await _rep.AsUpdateable(entity).IgnoreColumns(it => new //{ // it.ParentId, // it.BSDATE, // it.BSNO, // it.TenantId, // it.CreatedTime, // it.CreatedUserId, // it.CreatedUserName, // it.TenantName, // it.IsDeleted, // it.BOOKINGNO, // it.BSSTATUSNAME, // //it.YgtETD, // it.LstShipOrderCompareId, // it.LstShipOrderCompareDate, // it.LstShipOrderCompareRlt, // it.LstShipOrderCompareRltName, // it.LstDraftCompareDate, // it.LstDraftCompareRlt, // //it.ATD, // it.ETA, // //it.StartETA, // it.StartATA, // it.MiddleETA, // it.MiddleETD, // it.MiddleATA, // it.MiddleATD, // it.ATA //}).ExecuteCommandAsync(); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],数据库更新数据完成"); } var ctnlist = await _repCtn.AsQueryable().Filter(null, true).Where(x => x.BILLID == input.Id && x.IsDeleted == false).ToListAsync(); //删除箱信息 重新插入 await _repCtn.DeleteAsync(x => x.BILLID == input.Id); await _ctndetailrep.DeleteAsync(x => ctnlist.Select(x => x.Id).Contains((long)x.CTNID)); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],删除箱信息及多品名完成"); } if (input.ctnInputs != null) { foreach (var item in input.ctnInputs) { var ctnentity = item.Adapt(); //封账处理 var oldctn = ctnlist.Where(x => x.CNTRNO == item.CNTRNO).FirstOrDefault(); if (oldctn != null) { var isextendctn = await GetIsBookingLockCtn(ctnentity, oldctn); if (extend != null && extend.IsLockBooking && !isextendorder) { throw Oops.Bah("当前单据已封账,不允许修改箱信息"); } } ctnentity.BILLID = entity.Id; await _repCtn.InsertAsync(ctnentity); if (item.ctnDetailInputs != null) { foreach (var it in item.ctnDetailInputs) { var ctndetail = it.Adapt(); ctndetail.CTNID = ctnentity.Id; await _ctndetailrep.InsertAsync(ctndetail); } } } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],重新插入箱信息和多品名完成"); } } if (input.BookingEDIExt != null) { //检索EDI扩展 var ediExt = _bookingEDIExt.AsQueryable().Filter(null, true).First(u => u.BookingId == input.Id); if (ediExt == null) { //写入EDI扩展 ediExt = input.BookingEDIExt.Adapt(); ediExt.BookingId = entity.Id; await _bookingEDIExt.InsertAsync(ediExt); } else { //更新EDI扩展 var currEdiExtEntity = input.BookingEDIExt.Adapt(); currEdiExtEntity.Id = ediExt.Id; currEdiExtEntity.BookingId = ediExt.BookingId; await _bookingEDIExt.AsUpdateable(currEdiExtEntity).IgnoreColumns(it => new { it.BookingId, it.TenantId, it.CreatedTime, it.CreatedUserId, it.CreatedUserName }).ExecuteCommandAsync(); } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],拓展数据更新完成"); } } //记录日志 await SaveLog(entity, mlist); if (!string.IsNullOrEmpty(entity.MBLNO) && !string.IsNullOrEmpty(entity.YARDID) && (entity.MBLNO != mlist.MBLNO || entity.YARDID != mlist.YARDID || entity.CARRIERID != mlist.CARRIERID)) { _logger.LogInformation($"数据有变化,更新运踪订阅"); //更改提单号重新订阅运踪 await _publisher.PublishAsync(new ChannelEventSource("BillTrace:Update", new { BookingId = entity.Id, TenentId = UserManager.TENANT_ID, UserId = UserManager.UserId, UserName = UserManager.Name, DjyUserId = UserManager.DjyUserId })); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],更新运踪完成"); } } else if (string.IsNullOrEmpty(entity.MBLNO) && !string.IsNullOrEmpty(mlist.MBLNO) && mlist.IsBookingYZ != "0") { // 在已经订阅运踪的情况下,如果操作员删除提单号,则取消订阅运踪 await UnsubscribeBillTrace(new List(1) { new BillTraceUnsubscribeList(mlist.Id.ToString(), mlist.MBLNO) }); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],退订运踪完成"); } } } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],{(input.Id == 0 ? "新增" : "更新")}数据完成"); } var Id = entity.Id; BookingOrderOutput ordOut = new BookingOrderOutput(); var main = await _rep.FirstOrDefaultAsync(u => u.Id == Id); if (!string.IsNullOrEmpty(entity.MBLNO) || !string.IsNullOrEmpty(entity.CUSTNO)) { #region 插入货运动态 if (!string.IsNullOrEmpty(entity.CUSTNO)) { await SetGoodsStatus("YDC", Id); } if (!string.IsNullOrEmpty(entity.MBLNO)) { await SetGoodsStatus("YSDBC", Id); } #endregion } if (string.IsNullOrEmpty(entity.MBLNO) || string.IsNullOrEmpty(entity.CUSTNO)) { #region 取消货运动态 //配置中所有的货物状态 var config = _goodsStatusConfig.AsQueryable().Filter(null, true).Where(config => config.CreatedUserId == main.CreatedUserId).ToList(); if (string.IsNullOrEmpty(entity.CUSTNO)) { if (App.Configuration["ServiceStatusOpenAuto"] == "1") { await SetGoodsStatusCancel("YDC", Id); //await SetBookingOrderGoodsStatus(Id); } else { var Config = config.Where(x => x.SystemCode == "YDC").FirstOrDefault(); if (Config != null) { _goodsStatus.Delete(x => x.bookingId == Id && x.ConfigId == Config.Id); //更新货物状态 await SetBookingOrderGoodsStatus(Id); } } } if (string.IsNullOrEmpty(entity.MBLNO)) { if (App.Configuration["ServiceStatusOpenAuto"] == "1") { await SetGoodsStatusCancel("YSDBC", Id); //await SetBookingOrderGoodsStatus(Id); } else { var Config = config.Where(x => x.SystemCode == "YSDBC").FirstOrDefault(); if (Config != null) { _goodsStatus.Delete(x => x.bookingId == Id && x.ConfigId == Config.Id); //更新货物状态 await SetBookingOrderGoodsStatus(Id); } } } #endregion } if (main != null) { ordOut = main.Adapt(); var ctnlist = await _repCtn.AsQueryable().Where(x => x.BILLID == Id).ToListAsync(); var ctninput = ctnlist.Adapt>(); var ctnIdlist = ctnlist.Select(x => x.Id).ToList(); var ctndetaillist = await _ctndetailrep.AsQueryable().Where(x => ctnIdlist.Contains((long)x.CTNID)).ToListAsync(); foreach (var item in ctninput) { var _ctndetaillist = ctndetaillist.Where(x => x.CTNID == item.Id).ToList(); item.ctnDetailInputs = _ctndetaillist.Adapt>(); } ordOut.ctnInputs = ctninput; var ordUrl = _repOrderUrl.FirstOrDefault(x => x.BookingId == Id); if (ordUrl != null) { ordOut.Link = new BookingOrderUrlOutput() { LinkUrlTxxp = ordUrl.UrlTxxp, LinkUrlVgm = ordUrl.UrlVgm, LinkUrlVmgSi = ordUrl.UrlVgmSi, }; } var extendstate = await _repextendstate.FirstOrDefaultAsync(x => x.bookingId == Id); if (extendstate != null) { ordOut.ExtendState = extendstate; //检索EDI扩展 } } List HbList = new List(); var _hblist = await _rep.AsQueryable().Where(x => x.ParentId == Id).ToListAsync(); if (_hblist != null) { HbList = _hblist.Adapt>(); foreach (var item in HbList) { var ctnlist = await _repCtn.AsQueryable().Where(x => x.BILLID == item.Id).ToListAsync(); var ctninput = ctnlist.Adapt>(); var ctnIdlist = ctnlist.Select(x => x.Id).ToList(); var ctndetaillist = await _ctndetailrep.AsQueryable().Where(x => ctnIdlist.Contains((long)x.CTNID)).ToListAsync(); foreach (var it in ctninput) { var _ctndetaillist = ctndetaillist.Where(x => x.CTNID == item.Id).ToList(); it.ctnDetailInputs = _ctndetaillist.Adapt>(); } item.ctnInputs = ctninput; //检索EDI扩展 var ediExt = _bookingEDIExt.FirstOrDefault(u => u.BookingId == item.Id); if (ediExt != null) { item.BookingEDIExt = ediExt.Adapt(); } } ordOut.HbList = HbList; } var ediExtEntity = _bookingEDIExt.FirstOrDefault(u => u.BookingId == Id); if (ediExtEntity != null) { ordOut.BookingEDIExt = ediExtEntity.Adapt(); } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],从数据库拉取最新数据完成"); } //推送东胜 await SendBookingOrder(new long[] { main.ParentId == 0 ? Id : (long)main.ParentId }); if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],推送东胜完成"); } //临时文件转正式 if (input.TempFiles != null && input.TempFiles.Count > 0) { var optTmp = App.GetOptions(); foreach (var tmpFile in input.TempFiles) { var fpath = Path.Combine(App.WebHostEnvironment.WebRootPath, optTmp.Path, tmpFile.TempPathName); if (File.Exists(fpath)) { var fn = Path.GetFileName(tmpFile.TempPathName); MemoryStream memStream = new MemoryStream(File.ReadAllBytes(fpath)); await AddFile(new FormFile(memStream, 0, memStream.Length, fn, fn), new BookingFileDto() { BookingId = Id, TypeCode = tmpFile.TypeCode, TypeName = tmpFile.TypeName }); } } if (!string.IsNullOrEmpty(reqId)) { _logger.LogWarning($"保存请求[{reqId}],临时文件处理完成"); } } return ordOut; } /// /// 在订舱台账保存单证备注、操作备注等功能 /// /// /// [HttpPost("/BookingOrder/SaveDataInList")] public async Task SaveDataInList(JObject obj) { if (!obj.ContainsKey("Id")) { throw Oops.Bah("参数有误,没有Id"); } var id = obj.GetLongValue("Id"); var order = await _rep.AsQueryable().Filter(null, true).FirstAsync(x => x.Id == id); if (order == null) { throw Oops.Bah("订舱数据不存在"); } //判断权限,返回null表示有全部权限 List userlist = await _right.GetDataScopeList(MenuConst.MenuBookingOrder, true); if (userlist != null && !userlist.Contains(UserManager.UserId)) { throw Oops.Bah("无权修改"); } var orderCompare = await _rep.AsQueryable().Filter(null, true).FirstAsync(x => x.Id == id); var propsOrder = typeof(BookingOrder).GetProperties(); foreach (var property in obj) { var propNameLower = property.Key.ToLower(); var propOrd = propsOrder.FirstOrDefault(p => p.Name.ToLower() == propNameLower); if (propOrd != null) { if (propOrd.PropertyType == typeof(string)) { propOrd.SetValue(order, obj.GetStringValue(property.Key)); } else if (propOrd.PropertyType == typeof(int) || propOrd.PropertyType == typeof(int?)) { propOrd.SetValue(order, obj.GetIntValue(property.Key)); } else if (propOrd.PropertyType == typeof(long) || propOrd.PropertyType == typeof(long?)) { propOrd.SetValue(order, obj.GetLongValue(property.Key)); } else if (propOrd.PropertyType == typeof(DateTime) || propOrd.PropertyType == typeof(DateTime?)) { propOrd.SetValue(order, obj.GetDateTimeValue(property.Key)); } else if (propOrd.PropertyType == typeof(bool) || propOrd.PropertyType == typeof(bool?)) { propOrd.SetValue(order, obj.GetBooleanValue(property.Key)); } else if (propOrd.PropertyType == typeof(decimal) || propOrd.PropertyType == typeof(decimal?)) { propOrd.SetValue(order, obj.GetDecimalValue(property.Key)); } } } JsonUtil.PropToUpper(order, "ORDNO", "BSSTATUS", "YARDID", "YardContract", "YardContractTel", "YardContractEmail", "MARKS", "DESCRIPTION", "CONSIGNEENAME", "SHIPPERNAME", "NOTIFYPARTYNAME", "DZRemark", "CZRemark"); order.VERSION = Guid.NewGuid().ToString(); await _rep.UpdateAsync(order); //记录修改日志 await SaveLog(order, orderCompare); //推送东胜 await SendBookingOrder(new long[] { order.Id }); } /// /// 删除订舱 /// /// /// [SqlSugarUnitOfWork] [HttpPost("/BookingOrder/Delete")] public async Task Delete(string Ids) { var arr = Ids.Split(","); if (arr.Count() > 0) { var order = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.TenantId == UserManager.TENANT_ID).ToListAsync(); var url = _cache.GetAllDictData().Result.Where(x => x.Code == "bookingorder_delete").Select(x => x.Value).FirstOrDefault(); if (string.IsNullOrEmpty(url)) { throw Oops.Bah("未获取到相关url,请联系管理员!"); } // 要取消订阅运踪的列表 List waitUnsubscribeBilltrace = new(arr.Count()); foreach (var ar in arr) { long Id = Convert.ToInt64(ar); var mblno = order.Where(x => x.Id == Id).Select(x => x.MBLNO).FirstOrDefault(); // 将待删除的订舱单id存放到Cache中。目的:使用SendBookingOrder()推送订舱单数据前通过Cache判断是否正在走删除逻辑,来决定是否推送(如果是正在处理删除逻辑的数据,则不推送) string deletingCacheKey = $"DeletingBookingOrderId_{ar}"; await _cache.SetTimeoutAsync(deletingCacheKey, null, TimeSpan.FromMinutes(1)); _logger.LogInformation("设置待删除的订舱单id到Cache中,key:" + deletingCacheKey); BookingOrderDelete bookingOrderDelete = new BookingOrderDelete(); List deletelist = new List(); deletelist.Add(new BookingOrderDeleteDetail { Id = Id, MBLNO = mblno }); bookingOrderDelete.Delete = deletelist; var stn = await url.SetBody(bookingOrderDelete).PostAsStringAsync(); var jobj = stn.ToJObject(); _logger.LogInformation(mblno + "删除单据:" + jobj); if (jobj.GetIntValue("Code") == 200) { JObject data = jobj.GetValue("Data") as JObject; JArray NoDeleted = data.GetValue("NoDeleted") as JArray; if (NoDeleted == null || NoDeleted.Count() == 0) { var ctnlist = await _repCtn.AsQueryable().Where(x => x.BILLID == Id).Select(x => x.Id).ToListAsync(); await _repCtn.UpdateAsync(x => x.BILLID == Id, x => new BookingCtn { IsDeleted = true }); await _ctndetailrep.UpdateAsync(x => ctnlist.Contains((long)x.CTNID), x => new BookingCtnDetail { IsDeleted = true }); await _rep.UpdateAsync(x => x.Id == Id, x => new BookingOrder { IsDeleted = true, DeleteTime = DateTime.Now }); await _bookingEDIExt.UpdateAsync(x => x.BookingId == Id && x.IsDeleted == false, x => new BookingEDIExt { IsDeleted = true }); _logger.LogInformation(mblno + "删除成功!"); // 取消订阅运踪 waitUnsubscribeBilltrace.Add(new BillTraceUnsubscribeList(Id.ToString(), mblno)); } else { var re = NoDeleted[0] as JObject; if (re.GetIntValue("Code") == 201) { var ctnlist = await _repCtn.AsQueryable().Where(x => x.BILLID == Id).Select(x => x.Id).ToListAsync(); await _repCtn.UpdateAsync(x => x.BILLID == Id, x => new BookingCtn { IsDeleted = true }); await _ctndetailrep.UpdateAsync(x => ctnlist.Contains((long)x.CTNID), x => new BookingCtnDetail { IsDeleted = true }); await _rep.UpdateAsync(x => x.Id == Id, x => new BookingOrder { IsDeleted = true, DeleteTime = DateTime.Now }); await _bookingEDIExt.UpdateAsync(x => x.BookingId == Id && x.IsDeleted == false, x => new BookingEDIExt { IsDeleted = true }); _logger.LogInformation(mblno + "删除成功!"); // 取消订阅运踪 waitUnsubscribeBilltrace.Add(new BillTraceUnsubscribeList(Id.ToString(), mblno)); } else { await _cache.DelAsync(deletingCacheKey); _logger.LogInformation("从Cache中移除待删除的订舱单id,key:" + deletingCacheKey); string result = re.GetStringValue("Result"); throw Oops.Bah(result); } } } else { await _cache.DelAsync(deletingCacheKey); _logger.LogInformation("从Cache中移除待删除的订舱单id,key:" + deletingCacheKey); throw Oops.Bah(mblno + "删除单据失败"); } await _cache.DelAsync(deletingCacheKey); _logger.LogInformation("从Cache中移除待删除的订舱单id,key:" + deletingCacheKey); } // 取消订阅运踪 if (waitUnsubscribeBilltrace.Count > 0) { await UnsubscribeBillTrace(waitUnsubscribeBilltrace); } #region 消息队列推送删除信息 //var itemcode = _cache.GetAllTenantParam().Result.Where(x => x.ParaCode == "BOOKING_DATA_PUSH" && x.TenantId == UserManager.TENANT_ID).Select(x => x.ItemCode).FirstOrDefault(); //if (!string.IsNullOrEmpty(itemcode)) //{ // if (itemcode == "true") // try // { // const string MqActionExchangeName = "djy.output.dingcang.ds6"; // const string MqActionQueueName = "djy.output.dingcang.ds6_delete"; // ConnectionFactory factory = new ConnectionFactory(); // factory.Uri = new Uri(_cache.GetAllDictData().Result.Where(x => x.Code == "BookingOrderMQUri").Select(x => x.Value).FirstOrDefault()); // using (IConnection conn = factory.CreateConnection()) // { // IModel mqModel = conn.CreateModel(); // mqModel.ExchangeDeclare(MqActionExchangeName, ExchangeType.Direct); // var queueName = $"{MqActionQueueName}.{UserManager.TENANT_ID}"; // mqModel.QueueDeclare(queueName, false, false, false, null); // mqModel.QueueBind(queueName, MqActionExchangeName, queueName, null); // byte[] messageBodyBytes = Encoding.UTF8.GetBytes(Ids); // IBasicProperties props = mqModel.CreateBasicProperties(); // props.DeliveryMode = 2; // mqModel.BasicPublish(MqActionExchangeName, // queueName, props, // messageBodyBytes); // conn.Close(); // _logger.LogInformation($"订舱数据删除回推,已发送数据到消息队列【{_cache.GetAllDictData().Result.Where(x => x.Code == "BookingOrderMQUri").Select(x => x.Value).FirstOrDefault()}】,数据内容:【{Ids}】"); // } // } // catch (Exception ex) // { // _logger.LogError(ex.Message); // _logger.LogError(ex.StackTrace); // } //} #endregion } else { throw Oops.Bah("请上传正确参数"); } } /// /// 恢复删除 /// /// /// [SqlSugarUnitOfWork] [HttpPost("/BookingOrder/RecoverDelete")] public async Task RecoverDelete(string Ids) { var arr = Ids.Split(","); if (arr.Count() > 0) { foreach (var ar in arr) { long Id = Convert.ToInt64(ar); var order = _rep.AsQueryable().Filter(null, true).Where(x => x.Id == Id).First(); if (!string.IsNullOrEmpty(order.MBLNO)) { var et = await _rep.AsQueryable().Filter(null, true).Where(x => x.MBLNO == order.MBLNO && x.IsDeleted == false && x.TenantId == UserManager.TENANT_ID && x.ParentId == 0 && x.Id != Id).FirstAsync(); if (et != null) { throw Oops.Bah("当前主提单号已存在,无法恢复!"); } } var ctnlist = await _repCtn.AsQueryable().Where(x => x.BILLID == Id).Select(x => x.Id).ToListAsync(); await _repCtn.UpdateAsync(x => x.BILLID == Id, x => new BookingCtn { IsDeleted = false }); await _ctndetailrep.UpdateAsync(x => ctnlist.Contains((long)x.CTNID), x => new BookingCtnDetail { IsDeleted = false }); await _rep.UpdateAsync(x => x.Id == Id, x => new BookingOrder { IsDeleted = false }); await _bookingEDIExt.UpdateAsync(x => x.BookingId == Id && x.IsDeleted == true, x => new BookingEDIExt { IsDeleted = false }); await SendBookingOrder(new long[] { Id }); _logger.LogInformation(Id + "恢复删除成功!"); } //try //{ // SendBookingOrder(Id); // const string MqActionExchangeName = "djy.output.dingcang.ds6"; // const string MqActionQueueName = "djy.output.dingcang.ds6_recoverdelete"; // ConnectionFactory factory = new ConnectionFactory(); // factory.Uri = new Uri(_cache.GetAllDictData().Result.Where(x => x.Code == "BookingOrderMQUri").Select(x => x.Value).FirstOrDefault()); // using (IConnection conn = factory.CreateConnection()) // { // IModel mqModel = conn.CreateModel(); // mqModel.ExchangeDeclare(MqActionExchangeName, ExchangeType.Direct); // var queueName = $"{MqActionQueueName}.{UserManager.TENANT_ID}"; // mqModel.QueueDeclare(queueName, false, false, false, null); // mqModel.QueueBind(queueName, MqActionExchangeName, queueName, null); // byte[] messageBodyBytes = Encoding.UTF8.GetBytes(Ids); // IBasicProperties props = mqModel.CreateBasicProperties(); // props.DeliveryMode = 2; // mqModel.BasicPublish(MqActionExchangeName, // queueName, props, // messageBodyBytes); // conn.Close(); // _logger.LogInformation($"订舱数据删除恢复回推,已发送数据到消息队列【{_cache.GetAllDictData().Result.Where(x => x.Code == "BookingOrderMQUri").Select(x => x.Value).FirstOrDefault()}】,数据内容:【{Ids}】"); // } //} //catch (Exception ex) //{ // _logger.LogError(ex.Message); // _logger.LogError(ex.StackTrace); //} } else { throw Oops.Bah("请上传正确参数"); } } /// /// 获取订舱明细 /// /// /// [HttpGet("/BookingOrder/Get")] public async Task Get(long Id) { BookingOrderOutput ordOut = new BookingOrderOutput(); var main = await _rep.FirstOrDefaultAsync(u => u.Id == Id); if (main != null) { ordOut = main.Adapt(); var ctnlist = await _repCtn.AsQueryable().Where(x => x.BILLID == Id).ToListAsync(); var ctninput = ctnlist.Adapt>(); var ctnIdlist = ctnlist.Select(x => x.Id).ToList(); var ctndetaillist = await _ctndetailrep.AsQueryable().Where(x => ctnIdlist.Contains((long)x.CTNID)).ToListAsync(); foreach (var item in ctninput) { var _ctndetaillist = ctndetaillist.Where(x => x.CTNID == item.Id).ToList(); item.ctnDetailInputs = _ctndetaillist.Adapt>(); } ordOut.ctnInputs = ctninput; var ordUrl = _repOrderUrl.FirstOrDefault(x => x.BookingId == Id); if (ordUrl != null) { ordOut.Link = new BookingOrderUrlOutput() { LinkUrlTxxp = ordUrl.UrlTxxp, LinkUrlVgm = ordUrl.UrlVgm, LinkUrlVmgSi = ordUrl.UrlVgmSi, }; } var extendstate = await _repextendstate.FirstOrDefaultAsync(x => x.bookingId == Id); if (extendstate != null) { ordOut.ExtendState = extendstate; //检索EDI扩展 } } List HbList = new List(); var _hblist = await _rep.AsQueryable().Where(x => x.ParentId == Id).ToListAsync(); if (_hblist != null) { HbList = _hblist.Adapt>(); foreach (var item in HbList) { var ctnlist = await _repCtn.AsQueryable().Where(x => x.BILLID == item.Id).ToListAsync(); var ctninput = ctnlist.Adapt>(); var ctnIdlist = ctnlist.Select(x => x.Id).ToList(); var ctndetaillist = await _ctndetailrep.AsQueryable().Where(x => ctnIdlist.Contains((long)x.CTNID)).ToListAsync(); foreach (var it in ctninput) { var _ctndetaillist = ctndetaillist.Where(x => x.CTNID == item.Id).ToList(); it.ctnDetailInputs = _ctndetaillist.Adapt>(); } item.ctnInputs = ctninput; //检索EDI扩展 var ediExt = _bookingEDIExt.FirstOrDefault(u => u.BookingId == item.Id); if (ediExt != null) { item.BookingEDIExt = ediExt.Adapt(); } } ordOut.HbList = HbList; } //检索EDI扩展 var ediExtEntity = _bookingEDIExt.FirstOrDefault(u => u.BookingId == Id); if (ediExtEntity != null) { ordOut.BookingEDIExt = ediExtEntity.Adapt(); } return ordOut; } #endregion #region 批量编辑相关 /// /// 批量编辑 /// /// [HttpPost("/BookingOrder/BachUpdate")] public async Task BachUpdate(BatchUpdate dto) { if (dto == null || dto.Id.Count == 0) { throw Oops.Bah("未提交数据"); } await _rep.UpdateAsync(x => dto.Id.Contains(x.Id), x => new BookingOrder { VERSION = Guid.NewGuid().ToString(), VESSEL = dto.VESSEL, VOYNOINNER = dto.VOYNOINNER, ETD = dto.ETD, VOYNO = dto.VOYNO, PORTDISCHARGEID = dto.PORTDISCHARGEID, PORTDISCHARGE = dto.PORTDISCHARGE, DESTINATIONID = dto.DESTINATIONID, DESTINATION = dto.DESTINATION, CLOSINGDATE = dto.CLOSINGDATE, CLOSEDOCDATE = dto.CLOSEDOCDATE }); await SendBookingOrder(dto.Id.ToArray()); } /// /// 批量修改船代 /// /// [HttpPost("/BookingOrder/BachUpdateShipagency")] public async Task BachUpdateShipagency(BatchUpdateShipagency dto) { if (dto == null || dto.Id.Count == 0) { throw Oops.Bah("未提交数据"); } await _rep.UpdateAsync(x => dto.Id.Contains(x.Id), x => new BookingOrder { SHIPAGENCY = dto.Shipagency, SHIPAGENCYID = dto.ShipagencyId }); await SendBookingOrder(dto.Id.ToArray()); } #endregion #region 日志、备注、附件、货运动态、服务项目、货物状态 等 /// /// 获取日志明细 /// /// /// [HttpGet("/BookingOrder/GetLog")] public async Task> GetLog(long Id) { List list = new List(); var main = await _bookinglog.AsQueryable().Where(u => u.BookingId == Id).ToListAsync(); list = main.Adapt>(); if (list != null) { foreach (var item in list) { var details = await _bookinglogdetail.AsQueryable().Where(x => x.PId == item.Id).ToListAsync(); item.details = details; } } return list; } /// /// 获取备注 /// /// /// [HttpGet("/BookingOrder/GetRemark")] public async Task> GetRemark(long Id) { var list = await _bookingremark.AsQueryable().Where(u => u.PId == Id).ToListAsync(); return list; } /// /// 增加备注 /// /// /// [SqlSugarUnitOfWork] [HttpPost("/BookingOrder/AddRemark")] public async Task AddRemark(BookingRemarkDto dto) { if (dto.Id == 0) { var entity = dto.Adapt(); entity.UpdatedUserId = UserManager.UserId; entity.UpdatedUserName = UserManager.Name; await _bookingremark.InsertAsync(entity); } else { var entity = _bookingremark.FirstOrDefault(x => x.Id == dto.Id); entity.Remark = dto.Remark; await _bookingremark.AsUpdateable(entity).IgnoreColumns(it => new { it.TenantId, it.CreatedTime, it.CreatedUserId, it.CreatedUserName }).ExecuteCommandAsync(); } } /// /// 删除备注 /// /// /// [SqlSugarUnitOfWork] [HttpPost("/BookingOrder/DeleteRemark")] public async Task DeleteRemark(long Id) { await _bookingremark.DeleteAsync(x => x.Id == Id); } /// /// 增加订舱附件 /// /// /// 注意,如果是新建单据,BookingId传0 /// [HttpPost("/BookingOrder/AddFile")] public async Task AddFile(IFormFile file, [FromForm] BookingFileDto dto) { //未上传文件 if (file == null || file.Length == 0) { throw Oops.Bah(BookingErrorCode.BOOK200); } var opt = App.GetOptions(); var originalFilename = file.FileName; // 文件原始名称 var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀 if (!opt.fileType.Contains(fileSuffix)) { throw Oops.Bah(BookingErrorCode.BOOK114); } var dirAbs = string.Empty; var fileRelaPath = string.Empty; var fileAbsPath = string.Empty; //2023年8月9日,增加无bookingId时可上传附件功能(放在临时目录) if (dto.BookingId == 0) { var optTmp = App.GetOptions(); dirAbs = Path.Combine(App.WebHostEnvironment.WebRootPath, optTmp.Path); var tmpPath = YitIdHelper.NextId().ToString(); fileRelaPath = Path.Combine(tmpPath, originalFilename).ToLower(); dirAbs = Path.Combine(dirAbs, tmpPath); if (!Directory.Exists(dirAbs)) Directory.CreateDirectory(dirAbs); fileAbsPath = Path.Combine(dirAbs, originalFilename).ToLower(); } else { if (string.IsNullOrEmpty(opt.basePath)) { dirAbs = Path.Combine(App.WebHostEnvironment.WebRootPath, opt.relativePath); } else { dirAbs = Path.Combine(opt.basePath, opt.relativePath); } if (!Directory.Exists(dirAbs)) Directory.CreateDirectory(dirAbs); // 先存库获取Id var id = YitIdHelper.NextId(); var fileSaveName = $"{id}{fileSuffix}".ToLower(); fileRelaPath = Path.Combine(opt.relativePath, fileSaveName).ToLower(); fileAbsPath = Path.Combine(dirAbs, fileSaveName).ToLower(); var newFile = new BookingFile { Id = id, FileName = originalFilename, FilePath = fileRelaPath, TypeCode = dto.TypeCode, TypeName = dto.TypeName, BookingId = dto.BookingId, }; await _bookingfile.InsertAsync(newFile); } using (var stream = File.Create(fileAbsPath)) { await file.CopyToAsync(stream); } return fileRelaPath; } /// /// 获取附件 /// /// /// [HttpGet("/BookingOrder/GetFile")] public async Task> GetFile(long Id) { var list = await _bookingfile.AsQueryable().Filter(null, true).Where(u => u.BookingId == Id).ToListAsync(); return list; } /// /// 获取货运动态 /// [HttpGet("/BookingOrder/GetStatusLog")] public async Task> GetBookingStatusLog(long Id) { var statuslog = await _repStatuslog.AsQueryable().Filter(null, true).Where(x => x.BookingId == Id).OrderByDescending(x => x.OpTime).ToListAsync(); var dto = statuslog.Adapt>(); foreach (var item in dto) { var detail = await _statuslogdetail.AsQueryable().Where(x => x.PId == item.Id).ToListAsync(); item.detail = detail.Adapt>(); } return dto; } /// /// 获取订舱动态 /// [HttpGet("/BookingOrder/GetStatus")] public async Task> GetBookingStatus(long Id) { var dto = await _repBookingStatus.AsQueryable().Where(x => x.BookingId == Id).ToListAsync(); return dto; } /// /// 保存服务项目 /// /// /// [HttpPost("/BookingOrder/SaveServiceItem")] [SqlSugarUnitOfWork] public async Task SaveServiceItem(BookingServiceItemList input) { if (input.BookingId == null || input.BookingId == 0) { throw Oops.Bah("未传入业务id"); } await _serviceItem.DeleteAsync(x => x.BookingId == input.BookingId); foreach (var item in input.item) { await _serviceItem.InsertAsync( new BookingServiceItem { BookingId = input.BookingId, Code = item.Code, Value = item.Value }); } } /// /// 获取服务项目 /// /// /// [HttpGet("/BookingOrder/GetServiceItemList")] public async Task GetServiceItemList(long bookingId) { return await _serviceItem.AsQueryable().Where(x => x.BookingId == bookingId).ToListAsync(); } /// /// 增加货物状态 /// /// /// [SqlSugarUnitOfWork] [HttpPost("/BookingOrder/SaveGoodsStatus")] public async Task SaveGoodsStatus(GoodsStatusDtoList input) { if (input.BookingId == null || input.BookingId == 0) { throw Oops.Bah("未传入业务id"); } await _goodsStatus.DeleteAsync(x => x.bookingId == input.BookingId); foreach (var item in input.item) { var entity = item.Adapt(); entity.bookingId = input.BookingId; if (item.FinishTime.HasValue) //2023年5月25日,王书岚:可以只填写申请箱使天数,但是没有完成申请箱使 { entity.FinishUser = UserManager.Name; entity.FinishTime = item.FinishTime; entity.FinishUserId = UserManager.UserId; } await _goodsStatus.InsertAsync(entity); } //更新货物状态 await SetBookingOrderGoodsStatus((long)input.BookingId); _logger.LogInformation("货物状态直推东胜:"); //推送东胜 await SendBookingOrder(new long[] { Convert.ToInt64(input.BookingId) }); var order = _rep.Where(x => x.Id == input.BookingId).First(); var userid = order.CreatedUserId; if (userid != null) { //获取当前用户已经录入的货物状态 var list = await _goodsStatus.AsQueryable().LeftJoin(_goodsStatusConfig.AsQueryable(), (goods, config) => config.Id == goods.ConfigId).Where((goods, config) => config.CreatedUserId == userid && goods.bookingId == input.BookingId). OrderBy((goods, config) => config.Sort). Select((goods, config) => new GoodsStatusQuery { ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = goods.FinishTime, FinishUser = goods.FinishUser, FinishUserId = goods.FinishUserId, IsPublic = goods.IsPublic, ExtData = goods.ExtData, Remark = goods.Remark, Sort = config.Sort }).ToListAsync(); //配置中所有的货物状态 var config = _goodsStatusConfig.AsQueryable().Where(config => config.CreatedUserId == userid).ToList().DistinctBy(x => x.StatusName).Select(config => new GoodsStatusQuery { ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = null, FinishUser = null, FinishUserId = null, IsPublic = false, ExtData = null, Remark = null, Sort = config.Sort }).ToList(); //去掉两个list中重复的货物状态 foreach (var item in list) { config.RemoveAll(x => x.ConfigId == item.ConfigId); } var t = list.Union(config).OrderBy(x => x.Sort).DistinctBy(x => x.StatusName).ToList(); return t; } return null; } /// /// 获取货物状态 /// /// /// [HttpGet("/BookingOrder/GetGoodsStatusList")] public async Task> GetGoodsStatusList(long bookingId) { var userid = _rep.Where(x => x.Id == bookingId).Select(x => x.CreatedUserId).First(); if (userid != null) { //获取当前用户已经录入的货物状态 var list = await _goodsStatus.AsQueryable().LeftJoin(_goodsStatusConfig.AsQueryable(), (goods, config) => config.Id == goods.ConfigId).Where((goods, config) => config.CreatedUserId == userid && goods.bookingId == bookingId). OrderBy((goods, config) => config.Sort). Select((goods, config) => new GoodsStatusQuery { ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = goods.FinishTime, FinishUser = goods.FinishUser, FinishUserId = goods.FinishUserId, IsPublic = goods.IsPublic, ExtData = goods.ExtData, Remark = goods.Remark, Sort = config.Sort }).ToListAsync(); //配置中所有的货物状态 var config = _goodsStatusConfig.AsQueryable().Where(config => config.CreatedUserId == userid).ToList().DistinctBy(x => x.StatusName).Select(config => new GoodsStatusQuery { ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = null, FinishUser = null, FinishUserId = null, IsPublic = false, ExtData = null, Remark = null, Sort = config.Sort }).ToList(); //去掉两个list中重复的货物状态 foreach (var item in list) { config.RemoveAll(x => x.ConfigId == item.ConfigId); } return list.Union(config).OrderBy(x => x.Sort).DistinctBy(x => x.StatusName).ToList(); } return null; } #endregion #region 运踪 /// /// 调用运踪接口 /// [HttpPost("/BookingOrder/SendTrace")] [SqlSugarUnitOfWork] public async Task SendTrace(List dto) { if (dto == null) { throw Oops.Bah("未传入正确参数!"); } var key = _webAccountConfig.GetAccountConfig("seae_billtraceurl", UserManager.UserId).Result; if (key == null) { throw Oops.Bah("调用运踪接口相关账号未维护!"); } var url = _cache.GetAllDictData().Result; BillTraceDto billdto = new BillTraceDto(); List billTraceList = new List(); var dicdatalist = _cache.GetAllDictData().Result; foreach (var item in dto) { if (!string.IsNullOrWhiteSpace(item.CARRIERID)) { var et = await _repBookingStatus.AsQueryable().Where(x => x.StaCode == "sta_mudigang" && x.BookingId == Convert.ToInt64(item.BusinessId)).FirstAsync(); if (et != null) { throw Oops.Bah("提单号" + item.MBLNO + "已订阅!"); } } if (!string.IsNullOrWhiteSpace(item.YardCode)) { var et = await _repBookingStatus.AsQueryable().Where(x => x.StaCode == "sta_qiyungang" && x.BookingId == Convert.ToInt64(item.BusinessId)).FirstAsync(); if (et != null) { throw Oops.Bah("提单号" + item.MBLNO + "已订阅!"); } } _logger.LogInformation("调用运踪接口提单号:" + item.MBLNO + " 调用运踪接口"); if (item.isBook && (string.IsNullOrWhiteSpace(item.CARRIERID) || string.IsNullOrWhiteSpace(item.CARRIER) || string.IsNullOrWhiteSpace(item.MBLNO))) { throw Oops.Bah("订阅目的港船公司或提单号不能为空!"); } if (!item.isBook && (string.IsNullOrWhiteSpace(item.YARD) || string.IsNullOrWhiteSpace(item.YardCode) || string.IsNullOrWhiteSpace(item.MBLNO))) { throw Oops.Bah("订阅港前数据提单号或场站不能为空!"); } var YARDID = _cache.GetAllMappingYard().Result.Where(x => x.Module == "BillTrace" && x.Code == item.YardCode).Select(x => x.MapCode).FirstOrDefault(); billTraceList.Add(new BillTraceList { BusinessId = item.BusinessId, MBLNO = item.MBLNO, YARD = item.YARD == "" ? null : item.YARD, YardCode = YARDID == "" ? null : YARDID, CARRIER = item.CARRIER == "" ? null : item.CARRIER, CARRIERID = item.CARRIERID == "" ? null : item.CARRIERID, isBook = item.isBook }); var status = string.Empty; var IsBookingYZ = String.Empty; if (!string.IsNullOrWhiteSpace(item.YardCode) && !string.IsNullOrWhiteSpace(item.CARRIERID)) { status = "订阅起运港,目的港"; IsBookingYZ = "3"; } else if (string.IsNullOrWhiteSpace(item.YardCode) && !string.IsNullOrWhiteSpace(item.CARRIERID)) { status = "订阅目的港"; IsBookingYZ = "2"; } else if (!string.IsNullOrWhiteSpace(item.YardCode) && string.IsNullOrWhiteSpace(item.CARRIERID)) { status = "订阅起运港"; IsBookingYZ = "1"; } else { IsBookingYZ = "0"; } ////添加booking日志 var bid = await _bookinglog.InsertReturnSnowflakeIdAsync(new BookingLog { Type = "Trace", BookingId = Convert.ToInt64(item.BusinessId), TenantId = Convert.ToInt64(UserManager.TENANT_ID), CreatedTime = DateTime.Now, CreatedUserId = UserManager.UserId, CreatedUserName = UserManager.Name }); await _bookinglogdetail.InsertReturnSnowflakeIdAsync(new BookingLogDetail { PId = bid, Field = "", OldValue = "", NewValue = status, }); await _rep.UpdateAsync(x => x.Id == Convert.ToInt64(item.BusinessId), x => new BookingOrder { IsBookingYZ = IsBookingYZ }); } billdto.Children = billTraceList; billdto.Key = key.Account; billdto.PWD = key.Password; billdto.url = url.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "response_seae_billtraceurl").Value; billdto.Gid = UserManager.DjyUserId; var json = billdto.ToJsonString(); _logger.LogInformation("调用运踪接口发送josn:" + json); var html = await url.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "request_seae_billtraceurl").Value.SetHttpMethod(HttpMethod.Post).SetQueries(new { msg = json }).SetRetryPolicy(3, 5000).SendAsAsync(); _logger.LogInformation("调用运踪接口返回" + html.ToJsonString()); if (html.Success != true) { _logger.LogError("调用运踪接口返回:" + html.ToJsonString()); throw Oops.Bah(html.Message); } } /// /// 即时刷新运踪 /// /// /// [HttpPost("/BookingOrder/RefreshBillTrace")] public async Task RefreshBillTrace(string Ids) { var url = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "response_seae_billtraceRefreshurl").Value; if (string.IsNullOrEmpty(url)) { throw Oops.Bah("未找到相关URL,请联系管理员配置"); } var html = await url.SetHttpMethod(HttpMethod.Post).SetQueries(new { Ids = Ids, flag = true }).SetRetryPolicy(3, 5000).SendAsAsync(); _logger.LogInformation("调用运踪刷新接口返回" + html.ToJsonString()); if (html.Success != true) { _logger.LogError("调用运踪刷新接口返回:" + html.ToJsonString()); throw Oops.Bah(html.Message); } } /// /// 更新运踪提单号或自动订阅运踪 /// /// /// [HttpPost("/BookingOrder/UpdateMblno")] [SqlSugarUnitOfWork] public async Task UpdateMblno(BookingOrder order) { var key = _webAccountConfig.GetAccountConfig("seae_billtraceurl", UserManager.UserId).Result; if (key == null) { throw Oops.Bah("调用运踪接口相关账号未维护!"); } /* * 2023-9-8,允许分单的主提单号和主单的主提单号不一致之后,操作填写的分单中的提单号可能是错误的, * 导致订阅运踪且后期回推数据,然后又推送东胜,导致分单会在东胜中生成主单信息, * 跟和川操作确认,取消分单订阅运踪 */ if (order.ParentId > 0) { _logger.LogError("分单不再订阅运踪"); return; } var url = _cache.GetAllDictData().Result; BillTraceDto billdto = new BillTraceDto(); List billTraceList = new List(); var dicdatalist = _cache.GetAllDictData().Result; _logger.LogInformation("调用运踪修改接口提单号:" + order.MBLNO + " 调用运踪接口"); var uidList = new List(); if (!string.IsNullOrEmpty(order.OPID)) { uidList.Add(Convert.ToInt64(order.OPID)); } if (!string.IsNullOrEmpty(order.CUSTSERVICEID)) { uidList.Add(Convert.ToInt64(order.CUSTSERVICEID)); } var emailList = _repUser.AsQueryable().Where(x => uidList.Contains(x.Id) && !string.IsNullOrEmpty(x.Email)).Select(x => x.Email).ToList(); billTraceList.Add(new BillTraceList { BusinessId = order.Id.ToString(), MBLNO = order.MBLNO, YARD = order.YARD == "" ? null : order.YARD, YardCode = order.YARDID == "" ? null : order.YARDID, CARRIER = order.CARRIER == "" ? null : order.CARRIER, CARRIERID = order.CARRIERID == "" ? null : order.CARRIERID, isBook = true, AlertEmail = string.Join(";", emailList) }); var status = string.Empty; if (!string.IsNullOrWhiteSpace(order.YARDID) && !string.IsNullOrWhiteSpace(order.CARRIERID)) { status = "订阅起运港,目的港"; } else if (string.IsNullOrWhiteSpace(order.YARDID) && !string.IsNullOrWhiteSpace(order.CARRIERID)) { status = "订阅目的港"; } else if (!string.IsNullOrWhiteSpace(order.YARDID) && string.IsNullOrWhiteSpace(order.CARRIERID)) { status = "订阅起运港"; } var stalogids = _repStatuslog.AsQueryable().Filter(null, true).Where(x => x.BookingId == order.Id).Select(x => x.Id).ToList(); _repBookingStatus.Delete(x => x.BookingId == order.Id); _statuslogdetail.Delete(x => stalogids.Contains(x.PId)); _repStatuslog.Delete(x => x.BookingId == order.Id); ////添加booking日志 var bid = await _bookinglog.InsertReturnSnowflakeIdAsync(new BookingLog { Type = "Trace", BookingId = order.Id, TenantId = UserManager.TENANT_ID, CreatedTime = DateTime.Now, CreatedUserId = UserManager.UserId, CreatedUserName = UserManager.Name }); await _bookinglogdetail.InsertReturnSnowflakeIdAsync(new BookingLogDetail { PId = bid, Field = "", OldValue = "", NewValue = status, }); //if (!string.IsNullOrWhiteSpace(order.CARRIERID)) //{ // BookingStatus bookingStatus = new BookingStatus(); // bookingStatus.BookingId = order.Id; // bookingStatus.StaCode = "sta_mudigang"; // bookingStatus.StaName = dicdatalist.Where(x => x.Code == "sta_mudigang").Select(x => x.Value).FirstOrDefault(); // bookingStatus.StaTime = DateTime.Now; // bookingStatus.StaCate = "book_sta_cate_billtrace"; // await _repBookingStatus.InsertAsync(bookingStatus); //} //if (!string.IsNullOrWhiteSpace(order.YARDID)) //{ // BookingStatus bookingStatus = new BookingStatus(); // bookingStatus.BookingId = order.Id; // bookingStatus.StaCode = "sta_qiyungang"; // bookingStatus.StaName = dicdatalist.Where(x => x.Code == "sta_qiyungang").Select(x => x.Value).FirstOrDefault(); // bookingStatus.StaTime = DateTime.Now; // bookingStatus.StaCate = "book_sta_cate_billtrace"; // await _repBookingStatus.InsertAsync(bookingStatus); //} billdto.Children = billTraceList; billdto.Key = key.Account; billdto.PWD = key.Password; billdto.url = url.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "response_seae_billtraceurl").Value; billdto.Gid = UserManager.DjyUserId; var json = billdto.ToJsonString(); _logger.LogInformation("调用运踪更改接口发送josn:" + json); var html = await url.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "request_seae_updatebilltraceurl").Value.SetHttpMethod(HttpMethod.Post).SetQueries(new { msg = json }).SetRetryPolicy(3, 5000).SendAsAsync(); _logger.LogInformation("调用运踪更改接口返回" + html.ToJsonString()); if (html.Success != true) { _logger.LogError("调用运踪更改接口返回:" + html.ToJsonString()); throw Oops.Bah(html.Message); } } /// /// 退订运踪 /// public async Task UnsubscribeBillTrace(List billtraces) { if (billtraces == null) { throw Oops.Bah("未传入正确参数!"); } var key = _webAccountConfig.GetAccountConfig("seae_billtraceurl", UserManager.UserId).Result; if (key == null) { throw Oops.Bah("调用运踪接口相关账号未维护!"); } var url = _cache.GetAllDictData().Result?.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "request_unsubscribe_seae_billtrace_url")?.Value; if (string.IsNullOrEmpty(url)) { throw Oops.Bah("未配置退订运踪接口地址!"); } BillTraceUnsubscribeDto reqDto = new BillTraceUnsubscribeDto() { Children = new List(), Key = key.Account, PWD = key.Password, Gid = UserManager.DjyUserId }; foreach (BillTraceUnsubscribeList item in billtraces) { _logger.LogInformation("调用退订运踪接口,提单号:" + item.MBLNO); if (string.IsNullOrEmpty(item.BusinessId)) { throw Oops.Bah("订舱记录主键不能为空!"); } reqDto.Children.Add(new BillTraceUnsubscribeList(item.BusinessId, item.MBLNO)); ////添加booking日志 var bid = await _bookinglog.InsertReturnSnowflakeIdAsync(new BookingLog { Type = "Trace", BookingId = Convert.ToInt64(item.BusinessId), TenantId = Convert.ToInt64(UserManager.TENANT_ID), CreatedTime = DateTime.Now, CreatedUserId = UserManager.UserId, CreatedUserName = UserManager.Name }); await _bookinglogdetail.InsertReturnSnowflakeIdAsync(new BookingLogDetail { PId = bid, Field = "", OldValue = "", NewValue = "退订运踪", }); await _rep.UpdateAsync(x => x.Id == Convert.ToInt64(item.BusinessId), x => new BookingOrder { IsBookingYZ = "0" }); } var json = reqDto.ToJsonString(); _logger.LogInformation("调用退订运踪接口发送json:" + json); var html = await url.SetHttpMethod(HttpMethod.Post).SetQueries(new { msg = json }).SetRetryPolicy(3, 5000).SendAsAsync(); _logger.LogInformation("调用退订运踪接口返回" + html.ToJsonString()); if (html.Success != true) { _logger.LogError("调用退订运踪接口返回:" + html.ToJsonString()); throw Oops.Bah(html.Message); } } #endregion #region 放舱(入货通知) /// /// 获取放舱信息 /// /// /// [HttpGet("/BookingOrder/LetterYard")] public async Task LetterYard(long bookingId) { var order = _rep.FirstOrDefault(x => x.Id == bookingId); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } var letterYard = await _repLetterYard.FirstOrDefaultAsync(x => x.BookingId == bookingId); if (letterYard == null) { var user = _repUser.FirstOrDefault(x => x.Id == UserManager.UserId); letterYard = new BookingLetteryard() { BookingId = bookingId, Description = order.DESCRIPTION, FromName = user.Name, FromTel = user.Tel, FromMail = user.Email, FromPhone = user.Phone, YARDID = order.YARDID, YARD = order.YARD, YARDCONTRACT = order.YARDCONTRACT, YARDCONTRACTTEL = order.YARDCONTRACTTEL, }; } var output = letterYard.Adapt(); //链接信息 var urlModel = _repOrderUrl.FirstOrDefault(x => x.BookingId == bookingId); if (urlModel != null) { output.OrderUrl = urlModel.Adapt(); } return output; } /// /// 保存(新增或修改)放舱 /// /// /// [HttpPost("/BookingLetteryard/Save")] public async Task LetteryardSave(UpdateBookingLetteryardInput input) { long rtnId = 0; if (input.Id == 0) { var entity = input.Adapt(); await _repLetterYard.InsertAsync(entity); rtnId = entity.Id; } else { var entity = _repLetterYard.AsQueryable().Filter(null, true).First(x => x.Id == input.Id); input.Adapt(entity); await _repLetterYard.UpdateAsync(entity); rtnId = entity.Id; } var order = _rep.FirstOrDefault(x => x.Id == input.BookingId); //生成提箱小票 var allowCarrier = _cache.GetAllDictData().Result.Where(x => x.TypeCode == "txxp_carrier_list").Select(x => x.Code).ToList(); if (allowCarrier.Contains(order.CARRIERID)) { try { var txxpLink = await TxxpLink(input.BookingId); } catch { } } //vgm链接 allowCarrier = _cache.GetAllDictData().Result.Where(x => x.TypeCode == "vgm_carrier_list").Select(x => x.Code).ToList(); if (allowCarrier.Contains(order.CARRIERID)) { try { await VgmLink(input.BookingId); } catch { } } await SendLetterYard(input.BookingId); return rtnId; } /// /// 放舱推送东胜 /// /// public async Task SendLetterYard(long bookingId) { var entity = _repLetterYard.AsQueryable().Filter(null, true).First(x => x.BookingId == bookingId && x.IsDeleted == false); if (entity != null) { var json = entity.ToJsonString(); try { const string MqActionExchangeName = "djy.output.dingcang.ds6"; const string MqActionQueueName = "djy.output.dingcang.ds6_fangcang"; ConnectionFactory factory = new ConnectionFactory(); factory.Uri = new Uri(_cache.GetAllDictData().Result.Where(x => x.Code == "BookingOrderMQUri").Select(x => x.Value).FirstOrDefault()); using (IConnection conn = factory.CreateConnection()) { IModel mqModel = conn.CreateModel(); mqModel.ExchangeDeclare(MqActionExchangeName, ExchangeType.Direct); var queueName = $"{MqActionQueueName}.{UserManager.TENANT_ID}"; mqModel.QueueDeclare(queueName, false, false, false, null); mqModel.QueueBind(queueName, MqActionExchangeName, queueName, null); byte[] messageBodyBytes = Encoding.UTF8.GetBytes(json); IBasicProperties props = mqModel.CreateBasicProperties(); props.DeliveryMode = 2; mqModel.BasicPublish(MqActionExchangeName, queueName, props, messageBodyBytes); conn.Close(); _logger.LogInformation($"放舱数据回推,已发送数据到消息队列【{_cache.GetAllDictData().Result.Where(x => x.Code == "BookingOrderMQUri").Select(x => x.Value).FirstOrDefault()}】,数据内容:【{json}】"); } } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); } } return null; } /// /// 获取放舱历史信息(曾经删除的) /// /// /// [HttpGet("/BookingLetteryard/LetterYardHis")] public async Task> LetterYardHis(long bookingId) { var list = await _repLetterYard.AsQueryable() .Filter(null, true) .Where(x => x.BookingId == bookingId && x.TenantId == UserManager.TENANT_ID) .OrderBy(x => x.CreatedTime) .ToListAsync(); return list.Adapt>(); } /// /// 删除放舱 /// /// /// [SqlSugarUnitOfWork] [HttpPost("/BookingLetteryard/LetterYardDelete")] public async Task LetterYardDelete(long Id) { var entity = _repLetterYard.FirstOrDefault(x => x.BookingId == Id); entity.IsDeleted = true; string json = entity.ToJsonString(); try { const string MqActionExchangeName = "djy.output.dingcang.ds6"; const string MqActionQueueName = "djy.output.dingcang.ds6_fangcangdelete"; ConnectionFactory factory = new ConnectionFactory(); factory.Uri = new Uri(_cache.GetAllDictData().Result.Where(x => x.Code == "BookingOrderMQUri").Select(x => x.Value).FirstOrDefault()); using (IConnection conn = factory.CreateConnection()) { IModel mqModel = conn.CreateModel(); mqModel.ExchangeDeclare(MqActionExchangeName, ExchangeType.Direct); var queueName = $"{MqActionQueueName}.{UserManager.TENANT_ID}"; mqModel.QueueDeclare(queueName, false, false, false, null); mqModel.QueueBind(queueName, MqActionExchangeName, queueName, null); byte[] messageBodyBytes = Encoding.UTF8.GetBytes(json); IBasicProperties props = mqModel.CreateBasicProperties(); props.DeliveryMode = 2; mqModel.BasicPublish(MqActionExchangeName, queueName, props, messageBodyBytes); conn.Close(); _logger.LogInformation($"删除放舱,已发送数据到消息队列【{_cache.GetAllDictData().Result.Where(x => x.Code == "BookingOrderMQUri").Select(x => x.Value).FirstOrDefault()}】,数据内容:【{json}】"); } } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); } await _repLetterYard.UpdateAsync(entity); _logger.LogInformation(Id + "放舱删除成功!"); } /// /// 放舱发送 /// /// 订舱ID /// 打印模板ID /// [HttpPost("/BookingLetteryard/SendLetterYard")] public async Task SendLetterYard(long bookingId, long templateId) { var order = _rep.FirstOrDefault(x => x.Id == bookingId); var user = await _repUser.FirstOrDefaultAsync(u => u.Id == order.CreatedUserId); var tenant = await _repTenant.FirstOrDefaultAsync(t => t.Id == order.TenantId); var letterYard = await _repLetterYard.FirstOrDefaultAsync(x => x.BookingId == bookingId); if (letterYard == null) { throw Oops.Bah("放舱信息未找到,请先保存数据"); } if (string.IsNullOrEmpty(letterYard.AttnMail)) { throw Oops.Bah("ATTN MAIL未正确填写"); } if (string.IsNullOrEmpty(letterYard.FromMail)) { throw Oops.Bah("FROM MAIL未正确填写"); } var mailAcc = await _repUserMail.FirstOrDefaultAsync(x => x.CreatedUserId == user.Id && x.MailAccount == letterYard.FromMail && x.SmtpPort > 0 && x.SmtpServer != null && x.SmtpServer != ""); if (mailAcc == null) { throw Oops.Bah("用户邮箱未设置或smtp未正确配置"); } var orderUrl = await _repOrderUrl.FirstOrDefaultAsync(u => u.BookingId == bookingId); //if (orderUrl == null) //{ // throw Oops.Bah("未生成链接信息,请重新保存数据"); //} #region 保存放舱文件,并挂载到订舱附件 var printTemplate = await _repPrintTemplate.AsQueryable().Filter(null, true).FirstAsync(x => x.Id == templateId); if (printTemplate == null) { throw Oops.Bah(BookingErrorCode.BOOK115); } var bs = await GenPrintFile(bookingId, printTemplate); var opt = App.GetOptions(); var fileSaveName = $"放舱_{order.MBLNO}_{DateTime.Now.Ticks}.pdf"; // 文件原始名称 var dirAbs = string.Empty; if (string.IsNullOrEmpty(opt.basePath)) { dirAbs = Path.Combine(App.WebHostEnvironment.WebRootPath, opt.relativePath); } else { dirAbs = Path.Combine(opt.basePath, opt.relativePath); } if (!Directory.Exists(dirAbs)) Directory.CreateDirectory(dirAbs); var fileRelaPath = Path.Combine(opt.relativePath, fileSaveName).ToLower(); var fileAbsPath = Path.Combine(dirAbs, fileSaveName).ToLower(); File.WriteAllBytes(fileAbsPath, bs); var newFile = new BookingFile { FileName = fileSaveName, FilePath = fileRelaPath, TypeCode = "ruhuotongzhi", TypeName = ".pdf", }; await _bookingfile.InsertAsync(newFile); #endregion //货运动态 var bsl = new BookingStatusLog(); bsl.BookingId = bookingId; bsl.Status = $"放舱给客户"; bsl.OpTime = DateTime.Now; bsl.Category = "ship"; bsl.MBLNO = order.MBLNO; await _repStatuslog.InsertAsync(bsl); //订舱状态 await SaveBookingStatus(bookingId, "sta_letter_yard", "放舱"); #region 发送邮件 var mailSubject = $"放舱信息:{order.MBLNO}/{order.CARRIERID}/{order.VESSEL}/{order.VOYNO}/PO:{order.PONO}/{order.TenantName}"; var extContent = string.Empty; if (order.CARGOID == "R") //冻柜 { extContent = $"温度:{order.TEMPSET}{order.TEMPID}
通风:{order.REEFERF}
湿度:{order.HUMIDITY}
"; } else if (order.CARGOID == "D") //危险品 { extContent = $"危险品等级:{order.DCLASS}
危险品编号:{order.DUNNO}
"; } var linkContent = string.Empty; if (orderUrl != null) { linkContent = $@"提箱小票链接:{orderUrl.UrlTxxp}
提交VGM链接:{orderUrl.UrlVgm}
"; } var mailContent = $@"TO:{order.CUSTOMERNAME} 贵司委托我司代理订舱出口的货物信息如下,详情请见附件,谢谢!
提单号:{order.MBLNO}
船名航次:{order.VESSEL}/{order.VOYNO}
目的港:{order.PORTDISCHARGE}
预计船期:{(order.ETD.HasValue ? order.ETD.Value.Date.ToString("yyyy-MM-dd") : "")}
场站:{order.YARD}
船代:{order.SHIPAGENCY}
预计截港时间:{order.CLOSINGDATE}
预计截单时间:{order.CLOSEDOCDATE}
截VGM时间:{order.CLOSEVGMDATE}
{extContent} 备注:{order.YARDREMARK}
{linkContent}
温馨提示:
如果分票报关,请回箱前通知场站及我司。
开船及截港时间以码头具体计划为准。
若贵司自输VGM,请不要通过VGM链接提交数据,否则我司收取相关VGM申报费用。

订舱代理联系人:{UserManager.Name}
电话:{user.Tel} 手机:{user.Phone}
邮箱:{user.Email}
"; var sendResult = await MailSendHelper.SendMail(mailAcc, mailSubject, mailContent, letterYard.AttnMail, new KeyValuePair(fileSaveName, bs)); if (!sendResult.Key) { _logger.LogError($"放舱邮件发送失败:从{mailAcc.MailAccount}到{letterYard.AttnMail},主题 {mailSubject}"); throw Oops.Bah($"邮件发送失败:{sendResult.Value}"); } #endregion //设置货物状态-放舱 await SetGoodsStatus("YFC", bookingId); await SendBookingOrder(new long[] { bookingId }); } /// /// 获取放舱pdf(准备作废,后期使用打印相关接口) /// /// /// 类型,1:pdf、2:xlsx、3:docx /// [HttpGet("/BookingOrder/LetterYardPdf")] public async Task LetterYardPdf(long bookingId, int type = 1) { var letterYard = await _repLetterYard.FirstOrDefaultAsync(x => x.BookingId == bookingId); if (letterYard == null) { throw Oops.Bah("放舱信息未找到,请先保存数据"); } var fileType = ""; if (type == 1) { fileType = ".pdf"; } else if (type == 2) { fileType = ".xlsx"; } else if (type == 3) { fileType = ".docx"; } else { throw Oops.Bah("类型参数不正确"); } var bs = await GetReportFile(bookingId, "fangcang", type); var fileName = HttpUtility.UrlEncode($"{bookingId}_{DateTime.Now.Ticks}{fileType}", Encoding.GetEncoding("UTF-8")); var result = new FileContentResult(bs, "application/octet-stream") { FileDownloadName = fileName }; return result; } /// /// 获取放舱excel(准备作废,后期使用打印相关接口) /// /// /// [HttpGet("/BookingOrder/LetterYardXlsx")] public async Task LetterYardXlsx(long bookingId) { var letterYard = await _repLetterYard.FirstOrDefaultAsync(x => x.BookingId == bookingId); if (letterYard == null) { throw Oops.Bah("放舱信息未找到,请先保存数据"); } var bs = await GetReportFile(bookingId, "fangcang", 2); var fileName = HttpUtility.UrlEncode($"{bookingId}_{DateTime.Now.Ticks}.xlsx", Encoding.GetEncoding("UTF-8")); var result = new FileContentResult(bs, "application/octet-stream") { FileDownloadName = fileName }; return result; } /// /// 生成报表文件(准备作废) /// /// /// 类型,1:pdf、2:xlsx、3:docx /// 报表类型代码,例如fangcang、samplebill等 /// [NonAction] private async Task GetReportFile(long bookingId, string typeCode, int type = 1) { //打印报表服务地址 var reportUrl = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "url_report_generate").Value; if (!reportUrl.EndsWith("/")) { reportUrl += "/"; } //订舱数据 var order = _rep.FirstOrDefault(x => x.Id == bookingId); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } _logger.LogInformation($"查找模板:bookingId-{bookingId} TenantId-{order.TenantId}"); var printTemplate = await _repPrintTemplate.AsQueryable().Filter(null, true).FirstAsync(x => x.TenantId == order.TenantId && x.TypeCode == typeCode); if (printTemplate == null) { throw Oops.Bah(BookingErrorCode.BOOK115); } var opt = App.GetOptions(); var dirAbs = opt.basePath; if (string.IsNullOrEmpty(dirAbs)) { dirAbs = App.WebHostEnvironment.WebRootPath; } var fileAbsPath = Path.Combine(dirAbs, printTemplate.FilePath); _logger.LogInformation($"查找模板文件:{fileAbsPath}"); if (!File.Exists(fileAbsPath)) { throw Oops.Bah(BookingErrorCode.BOOK115); } _logger.LogInformation($"准备调用报表生成:id:{bookingId},文件:{printTemplate.FileName}"); var genUrl = $"{reportUrl}Report/BookingReport?bookingId={bookingId}&type={type}"; var rtn = await genUrl .SetContentType("multipart/form-data") .SetBodyBytes(("file", File.ReadAllBytes(fileAbsPath), HttpUtility.UrlEncode(printTemplate.FileName, Encoding.GetEncoding("UTF-8")))) .PostAsStringAsync(); var jobjRtn = JObject.Parse(rtn); _logger.LogInformation($"调用报表生成返回:{rtn}"); if (jobjRtn.GetBooleanValue("Success")) { //调用读取文件 var fn = jobjRtn.GetStringValue("Data"); _logger.LogInformation($"准备调用读取报表文件:id:{bookingId},文件名:{fn}"); var readFileUrl = $"{reportUrl}Report/GetFile?fileName={fn}"; var bs = await readFileUrl.GetAsByteArrayAsync(); _logger.LogInformation($"调用读取报表文件返回:{bs.Length}"); return bs; } else { throw Oops.Bah($"生成报表文件失败:{jobjRtn.GetStringValue("Message")}"); } } /// /// 生成打印报表文件 /// /// 订舱ID /// 打印模板 /// 类型,1:pdf、2:xlsx、3:docx /// [NonAction] private async Task GenPrintFile(long bookingId, BookingPrintTemplate printTemplate, int type = 1) { //打印报表服务地址 var reportUrl = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "url_report_generate").Value; if (!reportUrl.EndsWith("/")) { reportUrl += "/"; } //订舱数据 var order = _rep.FirstOrDefault(x => x.Id == bookingId); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } var opt = App.GetOptions(); var dirAbs = opt.basePath; if (string.IsNullOrEmpty(dirAbs)) { dirAbs = App.WebHostEnvironment.WebRootPath; } var fileAbsPath = Path.Combine(dirAbs, printTemplate.FilePath); _logger.LogInformation($"查找模板文件:{fileAbsPath}"); if (!File.Exists(fileAbsPath)) { throw Oops.Bah(BookingErrorCode.BOOK115); } _logger.LogInformation($"准备调用报表生成:id:{bookingId},文件:{printTemplate.FileName}"); var genUrl = $"{reportUrl}Report/BookingReport?bookingId={bookingId}&type={type}"; var rtn = await genUrl .SetContentType("multipart/form-data") .SetBodyBytes(("file", File.ReadAllBytes(fileAbsPath), HttpUtility.UrlEncode(printTemplate.FileName, Encoding.GetEncoding("UTF-8")))) .PostAsStringAsync(); var jobjRtn = JObject.Parse(rtn); _logger.LogInformation($"调用报表生成返回:{rtn}"); if (jobjRtn.GetBooleanValue("Success")) { //调用读取文件 var fn = jobjRtn.GetStringValue("Data"); _logger.LogInformation($"准备调用读取报表文件:id:{bookingId},文件名:{fn}"); var readFileUrl = $"{reportUrl}Report/GetFile?fileName={fn}"; var bs = await readFileUrl.GetAsByteArrayAsync(); _logger.LogInformation($"调用读取报表文件返回:{bs.Length}"); return bs; } else { throw Oops.Bah($"生成报表文件失败:{jobjRtn.GetStringValue("Message")}"); } } /// /// 查询历史放舱数据(用于历史引入) /// /// /// [HttpPost("/BookingOrder/LetterYardHis")] public async Task> LetterYardHis(BookingLetteryardHisInput input) { var list = await _repLetterYard.AsQueryable() .InnerJoin((ly, ord) => ly.BookingId == ord.Id) .Where(ly => ly.CreatedUserId == UserManager.UserId) .WhereIF(!string.IsNullOrEmpty(input.MBLNO), (ly, ord) => ord.MBLNO.Contains(input.MBLNO)) .WhereIF(!string.IsNullOrEmpty(input.HBLNO), (ly, ord) => ord.HBLNO.Contains(input.HBLNO)) .WhereIF(!string.IsNullOrEmpty(input.BOOKINGNO), (ly, ord) => ord.BOOKINGNO.Contains(input.BOOKINGNO)) .WhereIF(!string.IsNullOrEmpty(input.CUSTOMERNAME), (ly, ord) => ord.CUSTOMERNAME.Contains(input.CUSTOMERNAME)) .WhereIF(input.BETD.HasValue, (ly, ord) => ord.ETD > input.BETD.Value) .WhereIF(input.EETD.HasValue, (ly, ord) => ord.ETD < input.EETD.Value.AddDays(1)) .OrderByDescending((ly, ord) => ly.CreatedTime) .Select((ly, ord) => new BookingLetteryardHisOutput() { MBLNO = ord.MBLNO, HBLNO = ord.HBLNO, BOOKINGNO = ord.BOOKINGNO, ETD = ord.ETD.Value.ToString("yyyy-MM-dd"), CUSTOMERNAME = ord.CUSTOMERNAME, ToName = ly.ToName, Attn = ly.Attn, AttnMail = ly.AttnMail, AttnPhone = ly.AttnPhone, AttnTel = ly.AttnTel, FromMail = ly.FromMail, FromName = ly.FromName, FromPhone = ly.FromPhone, FromTel = ly.FromTel, Description = ly.Description, CloseDocTime = ly.CloseDocTime, ClosingTime = ly.ClosingTime, VgmTime = ly.VgmTime, YARD = ly.YARD, YARDCONTRACT = ly.YARDCONTRACT, YARDCONTRACTTEL = ly.YARDCONTRACTTEL, YARDID = ly.YARDID, Remark = ly.Remark, }) .ToPagedListAsync(input.PageNo, input.PageSize); ; return list; } #endregion #region 打印 /// /// 下载打印文件 /// /// 文件名 /// [HttpGet("/BookingOrder/DownloadPrint"), AllowAnonymous] public IActionResult DownloadPrint(string fileName) { var opt = App.GetOptions().Path; var fileFullPath = Path.Combine(App.WebHostEnvironment.WebRootPath, opt);//服务器路径 var result = new FileStreamResult(new FileStream(Path.Combine(fileFullPath, fileName), FileMode.Open), "application/octet-stream") { FileDownloadName = fileName }; return result; } /// /// 订舱打印(返回文件名) /// /// 订舱Id /// 打印模板ID /// 分类代码(使用字典【booking_template_category】中的代码) /// 类型,1:pdf、2:xlsx、3:docx /// 打印类型,10:FastReport、20:Excel模板 /// [HttpGet("/BookingOrder/PrintOrder")] public async Task PrintOrder(long bookingId, long templateId, string cateCode, int type = 1, BookingPrintTemplateType printType = BookingPrintTemplateType.FastReport) { var printTemplate = await _repPrintTemplate.AsQueryable().Filter(null, true).FirstAsync(x => x.Id == templateId); if (printTemplate == null) { throw Oops.Bah(BookingErrorCode.BOOK115); } var order = await _rep.FirstOrDefaultAsync(x => x.Id == bookingId); var edi = await _bookingEDIExt.FirstOrDefaultAsync(x => x.BookingId == bookingId); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } var fileName = string.Empty; var dicCate = (await _cache.GetAllDictData()).FirstOrDefault(x => x.Code == cateCode && x.TypeCode == "booking_template_category"); if (dicCate == null) { throw Oops.Bah("分类代码参数不正确"); } #region FastReport打印 if (printType == BookingPrintTemplateType.FastReport) { var bs = await GenPrintFile(bookingId, printTemplate, type); var fileType = ""; if (type == 1) { fileType = ".pdf"; } else if (type == 2) { fileType = ".xlsx"; } else if (type == 3) { fileType = ".docx"; } else { throw Oops.Bah("类型参数不正确"); } //2023-4-3,根据河川操作要求,文件名只带提单号 if (!string.IsNullOrEmpty(order.MBLNO)) { fileName = $"{order.MBLNO}{fileType}";//名称 } else { fileName = $"{order.Id}_{DateTime.Now.Ticks}{fileType}";//名称 } var opt = App.GetOptions().Path; var serverpath = Path.Combine(App.WebHostEnvironment.WebRootPath, opt);//服务器路径 if (!Directory.Exists(serverpath)) { Directory.CreateDirectory(serverpath); } var fullPath = Path.Combine(serverpath, fileName); await File.WriteAllBytesAsync(fullPath, bs); } #endregion #region Excel模板打印 else if (printType == BookingPrintTemplateType.ExcelTemplate) { var opt = App.GetOptions(); var dirAbs = opt.basePath; if (string.IsNullOrEmpty(dirAbs)) { dirAbs = App.WebHostEnvironment.WebRootPath; } var fileAbsPath = Path.Combine(dirAbs, printTemplate.FilePath); _logger.LogInformation($"准备调用EXCEL生成:id:{bookingId},文件:{printTemplate.FileName}"); var result = new FileStream(fileAbsPath, FileMode.Open); var excelwork = new HSSFWorkbook(result); var sheet = excelwork.GetSheetAt(0); var entity = await _excelrep.AsQueryable().Where(x => x.PId == templateId).OrderBy(x => x.Row).ToListAsync(); if (entity == null) { throw Oops.Bah("当前模板未设置"); } for (int _row = 1; _row <= entity.Max(x => x.Row); _row++) { if (entity.Where(x => x.Row == _row).Count() > 0) { ////获取行 var row = sheet.GetRow(_row - 1); if (row != null) { for (int _cellNum = 1; _cellNum <= entity.Max(x => x.Column); _cellNum++) { if (entity.Where(x => x.Row == _row && x.Column == _cellNum).Count() > 0) { var name = entity.Where(x => x.Row == _row && x.Column == _cellNum).Select(x => x.Field).FirstOrDefault(); if (name.Split('.')[0].ToLower() == "order") { foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(order)) { var _name = descriptor.Name.ToLower(); if (name.Split('.')[0].ToLower() == "order" && name.Split('.')[1].ToLower() == _name) { var value = descriptor.GetValue(order) != null ? descriptor.GetValue(order).ToString() : ""; ICell cell = row.GetCell(_cellNum - 1); if (descriptor.PropertyType.FullName.Contains("DateTime")) { value = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : ""; } if (cell != null) { row.Cells[_cellNum - 1].SetCellValue(value); } else { row.CreateCell(_cellNum - 1).SetCellValue(value); } } if (name.Split('.')[0].ToLower() == "order" && name.Split('.')[1].ToLower() == "_pkgs" && _name == "pkgs") { var value = string.Empty; if (order.PKGS != null) { if (order.PKGS.ToString().Split('.').Count() > 1 && Convert.ToInt32(order.PKGS.ToString().Split('.')[1]) > 0) { value = string.Format("{0:F3}", order.PKGS); } else { value = order.PKGS.ToString().Split('.')[0]; } } ICell cell = row.GetCell(_cellNum - 1); if (cell != null) { row.Cells[_cellNum - 1].SetCellValue(value + order.KINDPKGS); } else { row.CreateCell(_cellNum - 1).SetCellValue(value + order.KINDPKGS); } } if (name.Split('.')[0].ToLower() == "order" && name.Split('.')[1].ToLower() == "_kgs" && _name == "kgs") { var value = string.Empty; if (order.KGS != null) { if (order.KGS.ToString().Split('.').Count() > 1 && Convert.ToInt32(order.KGS.ToString().Split('.')[1]) > 0) { value = string.Format("{0:F3}", order.KGS); } else { value = order.KGS.ToString().Split('.')[0]; } } ICell cell = row.GetCell(_cellNum - 1); if (cell != null) { row.Cells[_cellNum - 1].SetCellValue(value + "KGS"); } else { row.CreateCell(_cellNum - 1).SetCellValue(value + "KGS"); } } if (name.Split('.')[0].ToLower() == "order" && name.Split('.')[1].ToLower() == "_cbm" && _name == "cbm") { var value = string.Empty; if (order.CBM != null) { if (order.CBM.ToString().Split('.').Count() > 1 && Convert.ToInt32(order.CBM.ToString().Split('.')[1]) > 0) { value = string.Format("{0:F3}", order.CBM); } else { value = order.CBM.ToString().Split('.')[0]; } } ICell cell = row.GetCell(_cellNum - 1); if (cell != null) { row.Cells[_cellNum - 1].SetCellValue(value + "CBM"); } else { row.CreateCell(_cellNum - 1).SetCellValue(value + "CBM"); } } } } if (name.Split('.')[0].ToLower() == "edi") { foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(edi)) { var _name = descriptor.Name.ToLower(); if (name.Split('.')[0].ToLower() == "edi" && name.Split('.')[1].ToLower() == _name) { var value = descriptor.GetValue(edi) != null ? descriptor.GetValue(edi).ToString() : ""; ICell cell = row.GetCell(_cellNum - 1); if (descriptor.PropertyType.FullName.Contains("DateTime")) { value = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : ""; } if (cell != null) { row.Cells[_cellNum - 1].SetCellValue(value); } else { row.CreateCell(_cellNum - 1).SetCellValue(value); } } } } if (name.Split('.')[0].ToLower() == "userinfo") { ICell cell = row.GetCell(_cellNum - 1); var value = string.Empty; if (name.Split('.')[1].ToLower() == "username") { value = UserManager.Name; } if (name.Split('.')[1].ToLower() == "usertel") { value = UserManager.TEl; } if (name.Split('.')[1].ToLower() == "usermobile") { value = UserManager.Phone; } if (name.Split('.')[1].ToLower() == "useremail") { value = UserManager.Email; } if (name.Split('.')[1].ToLower() == "usertenant") { value = UserManager.TENANT_NAME; } if (cell != null) { row.Cells[_cellNum - 1].SetCellValue(value); } else { row.CreateCell(_cellNum - 1).SetCellValue(value); } } } } } else { ////创建行 var srow = NpoiExcelExportHelper._.CreateRow(sheet, _row - 1); for (int _cellNum = 1; _cellNum <= entity.Max(x => x.Column); _cellNum++) { if (entity.Where(x => x.Row == _row && x.Column == _cellNum).Count() > 0) { var name = entity.Where(x => x.Row == _row && x.Column == _cellNum).Select(x => x.Field).FirstOrDefault(); if (name.Split('.')[0].ToLower() == "order") { foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(order)) { var _name = descriptor.Name.ToLower(); if (name.Split('.')[1].ToLower() == _name && name.Split('.')[0].ToLower() == "order") { var value = descriptor.GetValue(order) != null ? descriptor.GetValue(order).ToString() : ""; if (descriptor.PropertyType.FullName.Contains("DateTime")) { value = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : ""; } srow.CreateCell(_cellNum - 1).SetCellValue(value); } } } if (name.Split('.')[0].ToLower() == "edi") { foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(edi)) { var _name = descriptor.Name.ToLower(); if (name.Split('.')[1].ToLower() == _name && name.Split('.')[0].ToLower() == "edi") { var value = descriptor.GetValue(edi) != null ? descriptor.GetValue(edi).ToString() : ""; if (descriptor.PropertyType.FullName.Contains("DateTime")) { value = value != "" ? Convert.ToDateTime(value).ToString("yyyy-MM-dd") : ""; } srow.CreateCell(_cellNum - 1).SetCellValue(value); } } } if (name.Split('.')[0].ToLower() == "userinfo") { var value = string.Empty; if (name.Split('.')[1].ToLower() == "username") { value = UserManager.Name; } if (name.Split('.')[1].ToLower() == "usertel") { value = UserManager.TEl; } if (name.Split('.')[1].ToLower() == "usermobile") { value = UserManager.Phone; } if (name.Split('.')[1].ToLower() == "useremail") { value = UserManager.Email; } if (name.Split('.')[1].ToLower() == "usertenant") { value = UserManager.TENANT_NAME; } srow.CreateCell(_cellNum - 1).SetCellValue(value); } } } } } } var fileFullPath = Path.Combine(App.WebHostEnvironment.WebRootPath, App.GetOptions().Path);//服务器路径 if (!Directory.Exists(fileFullPath)) { Directory.CreateDirectory(fileFullPath); } //2023-4-3,根据河川操作要求,文件名只带提单号 if (!string.IsNullOrEmpty(order.MBLNO)) { fileName = $"{order.MBLNO}.xls";//名称 } else { fileName = $"{order.Id}_{DateTime.Now.Ticks}.xls";//名称 } _logger.LogInformation("导出excel:" + Path.Combine(fileFullPath, fileName)); var filestream = new FileStream(Path.Combine(fileFullPath, fileName), FileMode.OpenOrCreate, FileAccess.ReadWrite); excelwork.Write(filestream); } #endregion //记录打印次数和时间,用于前端动态展示常用的打印类型 var printRecentListKey = $"{PrintRecentListTypeKey}_{cateCode}_{printType}"; var usrCfg = _repUserConfig.AsQueryable().First(x => x.CreatedUserId == UserManager.UserId && x.Type == printRecentListKey); if (usrCfg == null) { usrCfg = new DjyUserConfig(); usrCfg.Type = printRecentListKey; usrCfg.ConfigJson = (new long[] { templateId }).ToJson(); await _repUserConfig.InsertAsync(usrCfg); } else { var arr = JArray.Parse(usrCfg.ConfigJson).Select(x => Convert.ToInt64(x)).Where(x => x != templateId).ToList(); arr.Insert(0, templateId); usrCfg.ConfigJson = arr.ToArray().ToJson(); await _repUserConfig.UpdateAsync(usrCfg); } return HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8")); } /// /// 预览模板生成的pdf文件 /// /// 文件名称 /// [HttpGet("/BookingOrder/ViewPrintPdf/{fn}"), AllowAnonymous] public void ViewPrintPdf(string fn) { var opt = App.GetOptions().Path; var fileFullPath = Path.Combine(App.WebHostEnvironment.WebRootPath, opt); var fileFullName = Path.Combine(fileFullPath, fn); if (File.Exists(fileFullName)) { _logger.LogInformation($"预览pdf文件:{fileFullName}"); var sysConfig = _cache.GetAllSysConfig().Result; var viewUrl = sysConfig.FirstOrDefault(x => x.Code == "booking_print_view_pdf_url"); //var readMem = new ReadOnlyMemory(File.ReadAllBytes(fileFullName)); //_httpContextAccessor.HttpContext.Response.BodyWriter.WriteAsync(readMem); _httpContextAccessor.HttpContext.Response.StatusCode = 302; _httpContextAccessor.HttpContext.Response.Headers["Location"] = $"{viewUrl.Value}{fn}"; } else { _logger.LogInformation($"未找到预览pdf文件:{fileFullName}"); _httpContextAccessor.HttpContext.Response.StatusCode = 404; } } /// /// 获取订舱打印模板列表(带有当前用户打印历史排序) /// /// 分类代码(使用字典【booking_template_category】中的代码) /// 打印分类,10:FastReport、20:Excel模板 /// [HttpGet("/BookingOrder/PrintTemplateWithHistoryList")] public async Task PrintTemplateWithHistoryList(string cateCode, BookingPrintTemplateType printType) { var typeCode = printType.ToString(); //当前公司所有已配置的模板 var allList = await _repPrintTemplate.AsQueryable() .Filter(null, true).InnerJoin((d, t) => d.Id == t.PrintTemplateId && t.SysUserId == UserManager.UserId) .Where(d => d.TenantId == UserManager.TENANT_ID && d.CateCode.Contains(cateCode) && d.Type == typeCode) .Select(d => new { d.Id, d.CateCode, d.CateName, d.DisplayName }) .ToListAsync(); var listReult = new List(); //当前用户打印历史数据 var printRecentListKey = $"{PrintRecentListTypeKey}_{cateCode}_{printType}"; var usrCfg = await _repUserConfig.AsQueryable().FirstAsync(x => x.CreatedUserId == UserManager.UserId && x.Type == printRecentListKey); if (usrCfg != null) { var arr = JArray.Parse(usrCfg.ConfigJson).Select(x => Convert.ToInt64(x)).ToList(); //按顺序加入到结果 arr.ForEach(x => { var find = allList.FirstOrDefault(y => y.Id == x); if (find != null) { listReult.Add(find); } }); var listOut = allList.Where(x => !arr.Contains(x.Id)).ToList(); listReult.AddRange(listOut); return listReult; } else { return allList; } } /// /// 下载文件 /// /// [HttpGet("/BookingOrder/Download")] public async Task Download(long id) { var printFile = await _bookingfile.FirstOrDefaultAsync(u => u.Id == id); if (printFile == null) { throw Oops.Oh(BookingErrorCode.BOOK200); } var opt = App.GetOptions(); var dirAbs = opt.basePath; if (string.IsNullOrEmpty(dirAbs)) { dirAbs = App.WebHostEnvironment.WebRootPath; } var fileFullPath = Path.Combine(dirAbs, printFile.FilePath); if (!File.Exists(fileFullPath)) { throw Oops.Oh(BookingErrorCode.BOOK115); } var fileName = HttpUtility.UrlEncode(printFile.FileName, Encoding.GetEncoding("UTF-8")); var result = new FileStreamResult(new FileStream(fileFullPath, FileMode.Open), "application/octet-stream") { FileDownloadName = fileName }; return result; } #endregion #region 下货纸 /// /// 发送下货纸 /// /// /// [HttpPost("/BookingOrder/SendXHZ")] public async Task SendXHZ(long bookingId) { var rtn = await XiahuozhiHelpler.Send(bookingId, "9"); if (!rtn.Key) { throw Oops.Bah($"发送失败:{rtn.Value}"); } //订舱状态 await SaveBookingStatus(bookingId, "sta_xhz", "下货纸"); //设置货物状态:已发下货纸,并回传东胜 await SetGoodsStatus("YFXHZ", bookingId); await SendBookingOrder(new long[] { bookingId }); } #endregion #region 样单(提单确认) /// /// 样单 /// /// /// [HttpGet("/BookingOrder/SampleBill")] public async Task SampleBill(long bookingId) { var order = _rep.FirstOrDefault(x => x.Id == bookingId); var samp = await _repSampleBill.FirstOrDefaultAsync(x => x.BookingId == bookingId); if (samp == null) { var user = _repUser.FirstOrDefault(x => x.Id == UserManager.UserId); samp = new BookingSampleBill() { BookingId = bookingId, Description = order.DESCRIPTION, FromName = user.Name, FromTel = user.Tel, FromMail = user.Email, }; } var output = samp.Adapt(); return output; } /// /// 保存(新增或修改)样单 /// /// /// [HttpPost("/BookingSampleBill/Save")] public async Task SampleBillSave(UpdateBookingSampleBillInput input) { BookingSampleBill entity = null; if (input.Id == 0) { entity = input.Adapt(); await _repSampleBill.InsertAsync(entity); } else { entity = _repSampleBill.FirstOrDefault(x => x.BookingId == input.Id); entity = input.Adapt(entity); await _repSampleBill.UpdateAsync(entity); } return entity.Id; } /// /// 获取样单pdf(准备作废,后期使用打印相关api) /// /// /// [HttpGet("/BookingOrder/SampleBillPdf")] public async Task SampleBillPdf(long bookingId) { var samp = await _repSampleBill.FirstOrDefaultAsync(x => x.BookingId == bookingId); if (samp == null) { throw Oops.Bah("请先保存提单确认数据后再继续"); } var bs = await GetReportFile(bookingId, "tidanqueren"); var fileName = HttpUtility.UrlEncode($"{bookingId}_{DateTime.Now.Ticks}.xlsx", Encoding.GetEncoding("UTF-8")); var result = new FileContentResult(bs, "application/octet-stream") { FileDownloadName = fileName }; return result; } #endregion #region 小票链接 /// /// 获取提箱小票链接 /// /// /// [HttpGet("/BookingOrder/TxxpLink")] public async Task TxxpLink(long bookingId) { var order = _rep.FirstOrDefault(x => x.Id == bookingId); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } var ordUrl = _repOrderUrl.FirstOrDefault(x => x.BookingId == bookingId); if (ordUrl == null) { ordUrl = new BookingOrderUrl(); ordUrl.BookingId = bookingId; await _repOrderUrl.InsertAsync(ordUrl); } //if (!string.IsNullOrEmpty(ordUrl.UrlTxxp)) //{ // return ordUrl.UrlTxxp; //} var dictData = await _cache.GetAllDictData(); //校验船公司 if (string.IsNullOrEmpty(order.CARRIERID)) { throw Oops.Bah(BookingErrorCode.BOOK118); } //判断船公司是否支持 var allowCarrier = dictData.Where(x => x.TypeCode == "txxp_carrier_list").Select(x => x.Code).ToList(); if (!allowCarrier.Contains(order.CARRIERID)) { throw Oops.Bah(BookingErrorCode.BOOK117); } var carrCode = order.CARRIERID; var carrMap = _cache.GetAllMappingCarrier().Result.Where(y => y.Code == order.CARRIERID && y.Module == "BookingTxxp").FirstOrDefault(); if (carrMap != null) { carrCode = carrMap.MapCode; } //根据订舱代理获取账号类型 var ytMapList = dictData.Where(x => x.TypeCode == "txxp_yitong_forwarder_map").ToList(); var ytmap = ytMapList.FirstOrDefault(x => x.Value == order.FORWARDER); if (ytmap == null) { throw Oops.Bah($"订舱代理 {order.FORWARDER} 对应的网站账号类型未配置"); } //亿通账号 var ytAcc = _webAccountConfig.GetAccountConfig(ytmap.Code, UserManager.UserId).Result; if (ytAcc == null) { throw Oops.Bah(BookingErrorCode.BOOK119); } //场站转换 var yardsetList = _cache.GetAllMappingYard().Result.Where(y => y.Code == order.YARDID && y.Module == "BookingTxxp" && (y.CarrierCode == null || y.CarrierCode == "" || y.CarrierCode == order.CARRIERID)).ToList(); if (yardsetList.Count == 0) { throw Oops.Bah(BookingErrorCode.BOOK120, $"{order.YARD} {order.CARRIER}(提箱小票)"); } var yardset = yardsetList.FirstOrDefault(x => x.CarrierCode == order.CARRIERID); if (yardset == null) { yardset = yardsetList.FirstOrDefault(x => x.CarrierCode == null || x.CarrierCode == ""); } var ctns = await _repCtn.Where(x => x.BILLID == bookingId).ToListAsync(); //校验箱子数据录入 if (ctns.Where(c => string.IsNullOrEmpty(c.CTNALL) || !c.CTNNUM.HasValue).Count() > 0) { throw Oops.Bah(BookingErrorCode.BOOK121); } //箱型映射 var ctnMapping = await _cache.GetAllMappingCtn(); ctnMapping = ctnMapping.Where(x => x.Module == "BookingTxxp").ToList(); //if (ctnMapping.Count == 0) //{ // throw Oops.Bah(BookingErrorCode.BOOK122); //} var expCode = ctns.Select(x => x.CTNCODE).Distinct().Except(ctnMapping.Select(y => y.Code)).ToList(); if (expCode.Count > 0) { var expName = ctns.Where(x => expCode.Contains(x.CTNCODE)).Select(x => x.CTNALL).Distinct().ToList(); throw Oops.Bah(BookingErrorCode.BOOK123, $"{string.Join(',', expName)}(提箱小票)"); } var user = await _repUser.FirstOrDefaultAsync(x => x.Id == UserManager.UserId); //调用小票服务 var dicUrlTxxp = dictData.First(x => x.TypeCode == "url_set" && x.Code == "txxp_service"); var postObj = new { SystemCode = "djy_hechuan", CarrierCode = carrCode, billOrderId = order.Id.ToString(), sendOrderCode = order.MBLNO, userId = UserManager.DjyUserId, customerId = order.CUSTOMERID.ToString(), // userName = currUser.CODENAME, //userPassword = currUser.PASSWORD, operatorName = UserManager.Name, depotCode = yardset.MapCode, depotName = yardset.MapName, AgentName = UserManager.TENANT_NAME, linkName = UserManager.Name, linkMobile = user.Tel, CustomerName = $"{UserManager.TENANT_NAME}+{UserManager.Name}", //公司名称+用户姓名 memo = string.Empty, boxInfo = ctns.Select(c => { var mapCtn = ctnMapping.First(x => x.Code == c.CTNCODE); return new { boxType = mapCtn == null ? c.CTNALL : mapCtn.MapCode, boxCount = c.CTNNUM.Value }; }), sysLoginName = ytAcc.Account, sysPsssword = ytAcc.Password }; string strPostObj = postObj.ToJsonString(); _logger.LogInformation($"调用提箱小票接口传递数据:{strPostObj}"); var strResp = await dicUrlTxxp.Value.SetBody(postObj).PostAsStringAsync(); _logger.LogInformation($"调用提箱小票接口返回:{strResp}"); var jobjResp = JObject.Parse(strResp); int respCode = jobjResp.GetIntValue("code"); if (respCode != 200) { throw Oops.Bah(BookingErrorCode.BOOK124, jobjResp.GetStringValue("message")); } var addUrlFlag = string.IsNullOrEmpty(ordUrl.UrlTxxp) ? true : false; //新生成还是更新链接 //保存url var txxpUrl = jobjResp.GetStringValue("data"); ordUrl.UrlTxxp = txxpUrl; await _repOrderUrl.UpdateAsync(ordUrl); //货运动态 var bsl = new BookingStatusLog(); bsl.BookingId = bookingId; bsl.Status = $"{(addUrlFlag ? "生成" : "更新")}提箱小票链接"; bsl.OpTime = DateTime.Now; bsl.Category = "ship"; bsl.MBLNO = order.MBLNO; await _repStatuslog.InsertAsync(bsl); return txxpUrl; } #endregion #region VGM及VMG链接 /// /// 获取VGM、VGM SI链接 /// /// /// [HttpGet("/BookingOrder/VgmLink")] public async Task VgmLink(long bookingId) { var order = _rep.FirstOrDefault(x => x.Id == bookingId); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } var ordUrl = _repOrderUrl.FirstOrDefault(x => x.BookingId == bookingId); if (ordUrl == null) { ordUrl = new BookingOrderUrl(); ordUrl.BookingId = bookingId; await _repOrderUrl.InsertAsync(ordUrl); } if (!string.IsNullOrEmpty(ordUrl.UrlVgm)) { return new string[] { ordUrl.UrlVgm, ordUrl.UrlVgmSi }; } //校验船公司 if (string.IsNullOrEmpty(order.CARRIERID)) { throw Oops.Bah(BookingErrorCode.BOOK118); } var ctns = await _repCtn.Where(x => x.BILLID == bookingId).ToListAsync(); //判断船公司是否支持 var allowCarrier = _cache.GetAllDictData().Result.Where(x => x.TypeCode == "vgm_carrier_list").Select(x => x.Code).ToList(); if (!allowCarrier.Contains(order.CARRIERID)) { throw Oops.Bah(BookingErrorCode.BOOK117); } //船公司网站账号 var carrWebAccMap = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "carrier_web_account_mapping" && x.Code == order.CARRIERID); var webacc = _webAccountConfig.GetAccountConfig(carrWebAccMap.Value, UserManager.UserId).Result; if (webacc == null) { throw Oops.Bah(BookingErrorCode.BOOK125); } //场站转换 var yardset = _cache.GetAllMappingYard().Result.FirstOrDefault(y => y.Code == order.YARDID && y.Module == "BookingVgm"); if (yardset == null) { throw Oops.Bah(BookingErrorCode.BOOK120, $"{order.YARDID}(VGM)"); } //校验箱子数据录入 if (ctns.Where(c => string.IsNullOrEmpty(c.CTNALL) || !c.CTNNUM.HasValue).Count() > 0) { throw Oops.Bah(BookingErrorCode.BOOK121); } //箱型映射 var ctnMapping = await _cache.GetAllMappingCtn(); ctnMapping = ctnMapping.Where(x => x.Module == "BookingVgm").ToList(); //if (ctnMapping.Count == 0) //{ // throw Oops.Bah(BookingErrorCode.BOOK122); //} var expCode = ctns.Select(x => x.CTNCODE).Distinct().Except(ctnMapping.Select(y => y.Code)).ToList(); if (expCode.Count > 0) { throw Oops.Bah(BookingErrorCode.BOOK123, $"{string.Join(',', expCode)}(VGM)"); } //接收反馈地址 var dicUrlVgmResp = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "url_reponse" && x.Code == "vgm_si_post_reponse"); var dicUrlSiResp = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "url_reponse" && x.Code == "si_post_response"); var user = await _repUser.FirstOrDefaultAsync(x => x.Id == UserManager.UserId); //调用vgm链接服务 var dicUrl = _cache.GetAllDictData().Result.First(x => x.TypeCode == "url_set" && x.Code == "vgm_link_service"); var postObj = new { SystemCode = "djy_hechuan", billOrderId = order.Id.ToString(), sendOrderCode = order.MBLNO, customerName = $"{UserManager.TENANT_NAME}+{UserManager.Name}", //公司名称+用户姓名 customerId = order.CUSTOMERID.ToString(), agentName = string.IsNullOrEmpty(order.FORWARDER) ? UserManager.TENANT_NAME : order.FORWARDER, carrierCode = order.CARRIERID, userName = webacc.Account, userPassword = webacc.Password, depotCode = yardset.MapCode, depotName = order.YARD, linkName = UserManager.Name, linkMobile = user.Tel, linkEmail = user.Email, userId = UserManager.DjyUserId, returnUrl = dicUrlVgmResp?.Value, shipName = order.VESSEL, voyNo = order.VOYNO, etdstr = order.ETD.HasValue ? order.ETD.Value.ToString("yyyy-MM-dd") : string.Empty, potrSend = order.PORTLOAD, potrGoal = order.PORTDISCHARGE, boxinfoStr = order.CNTRTOTAL, vgmEndTimeStr = order.CLOSEVGMDATE.HasValue ? order.CLOSEVGMDATE.Value.ToString("yyyy-MM-dd") : string.Empty, returnOkUrl = "", SiReturnUrl = dicUrlSiResp?.Value, DataInfoJson = new { order.SHIPPER, order.CONSIGNEE, order.NOTIFYPARTY, order.MARKS, order.DESCRIPTION, order.BLFRT, order.SERVICE, order.ISSUETYPE, order.TRANSPORT, order.TRANSPORTID, order.DESTINATION, order.DESTINATIONID, order.KINDPKGS, order.THIRDPAYADDR, order.PORTLOAD, order.PORTLOADID, order.PORTDISCHARGE, order.PORTDISCHARGEID } }; string strPostObj = postObj.ToJsonString(); _logger.LogInformation($"调用VGM链接接口 {dicUrl.Value} 传递数据:{strPostObj}"); var strResp = await dicUrl.Value.SetBody(postObj).PostAsStringAsync(); _logger.LogInformation($"调用VGM链接接口返回:{strResp}"); var jobjResp = JObject.Parse(strResp); int respCode = jobjResp.GetIntValue("code"); if (respCode != 200) { throw Oops.Bah(BookingErrorCode.BOOK126, jobjResp.GetStringValue("message")); } //保存url var memoData = jobjResp.GetJObjectValue("memoData"); ordUrl.UrlVgm = memoData.GetStringValue("vgmUrl"); ordUrl.UrlVgmSi = memoData.GetStringValue("vgmAndSiUrl"); await _repOrderUrl.UpdateAsync(ordUrl); //货运动态 var bsl = new BookingStatusLog(); bsl.BookingId = bookingId; bsl.Status = $"生成VGM链接"; bsl.OpTime = DateTime.Now; bsl.Category = "ship"; bsl.MBLNO = order.MBLNO; await _repStatuslog.InsertAsync(bsl); return new string[] { ordUrl.UrlVgm, ordUrl.UrlVgmSi }; } /// /// 直发VGM(单票) /// /// /// [HttpPost("/BookingOrder/VgmSend")] public async Task VgmSend(long bookingId) { var order = _rep.FirstOrDefault(x => x.Id == bookingId); var ctns = _repCtn.Where(x => x.BILLID == bookingId).ToList(); //船公司 if (string.IsNullOrEmpty(order.CARRIERID)) { throw Oops.Bah(BookingErrorCode.BOOK118); } //提单号不能为空 if (string.IsNullOrEmpty(order.MBLNO)) { throw Oops.Bah(BookingErrorCode.BOOK127); } var config = _cache.GetAllTenantParam().Result.FirstOrDefault(x => x.TenantId == UserManager.TENANT_ID && x.ParaCode == "VgmDirectSendCarrierId"); var arrCarr = config.ItemCode.Split(",", StringSplitOptions.RemoveEmptyEntries); if (!arrCarr.Contains(order.CARRIERID)) //使用大简云发送vgm { //ETD不能为空 if (!order.ETD.HasValue) { throw Oops.Bah("ETD不能为空"); } //重量不能为空 if (!order.KGS.HasValue) { throw Oops.Bah("重量不能为空"); } var sysconfig = await _cache.GetAllSysConfig(); var urlConfig = sysconfig.FirstOrDefault(x => x.GroupCode == "DJY_CONST" && x.Code == "DjyVgmApiMyshpping"); var accConfig = await _webAccountConfig.GetAccountConfig("DjyVgm", UserManager.UserId); if (accConfig == null) { throw Oops.Bah("请在网站账号中维护VGM接口的用户id和秘钥"); } var objMdata = new { MBLNO = order.MBLNO, CARRIER = order.CARRIERID, ChuanMing = order.VESSEL, HangCi = order.VOYNOINNER, ETD = order.ETD.Value.ToString("yyyy-MM-dd HH:mm:ss"), ZongZhongLiang = order.KGS.ToString(), BeiZhu = "", ORDERNO = order.CUSTNO, VGMCLOSETIME = order.CLOSEVGMDATE.HasValue ? order.CLOSEVGMDATE.Value.ToString("yyyy-MM-dd HH:mm:ss") : "" }; var listCtn = new List(); foreach (var ctn in ctns) { if (string.IsNullOrEmpty(ctn.CTNALL) || string.IsNullOrEmpty(ctn.CNTRNO) || string.IsNullOrEmpty(ctn.SEALNO) || !ctn.WEIGHKGS.HasValue || string.IsNullOrEmpty(ctn.WEIGHDATE)) { throw Oops.Bah("所有箱子的箱型、箱号、封号、称重重量和称重时间都不能为空"); } listCtn.Add(new { ChengZhongZhongLiang = ctn.WEIGHKGS.Value.ToString(), ChengZhongShiJian = ctn.WEIGHDATE, CTNALL = ctn.CTNALL.Replace("'", ""), CNTRNO = ctn.CNTRNO, SEALNO = ctn.SEALNO }); } var dictParam = new Dictionary { { "ac", "vgm" }, { "uid", accConfig.Account}, { "skey", accConfig.Password}, { "optype", "9"}, { "mdata", JsonConvert.SerializeObject(objMdata)}, { "ctndata", JsonConvert.SerializeObject(listCtn)} }; _logger.LogInformation($"调用vgm发送接口:{urlConfig.Value},参数:{JsonConvert.SerializeObject(dictParam)}"); var rtn = await urlConfig.Value .SetBody(dictParam, "application/x-www-form-urlencoded") .PostAsStringAsync(); _logger.LogInformation($"调用vgm发送接口:{urlConfig.Value},返回:{rtn}"); var jobjRtn = JObject.Parse(rtn); if (jobjRtn.GetBooleanValue("Success")) { //货运动态 var bsl = new BookingStatusLog(); bsl.BookingId = bookingId; bsl.Status = $"发送VGM"; bsl.OpTime = DateTime.Now; bsl.Category = "ship"; bsl.MBLNO = order.MBLNO; await _repStatuslog.InsertAsync(bsl); } else { throw Oops.Bah(jobjRtn.GetStringValue("Message")); } } else //直接调用vgm接口直发 { //判断船公司是否支持 var allowCarrier = _cache.GetAllDictData().Result.Where(x => x.TypeCode == "vgm_carrier_list").Select(x => x.Code).ToList(); if (!allowCarrier.Contains(order.CARRIERID)) { throw Oops.Bah(BookingErrorCode.BOOK117); } //船公司网站账号 var carrWebAccMap = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "carrier_web_account_mapping" && x.Code == order.CARRIERID); if (carrWebAccMap == null) { throw Oops.Bah("不支持的船公司或账号映射未配置"); } var webacc = _webAccountConfig.GetAccountConfig(carrWebAccMap.Value, UserManager.UserId).Result; if (webacc == null) { throw Oops.Bah(BookingErrorCode.BOOK125); } ////箱型映射 //var ctnMapping = await _cache.GetAllMappingCtn(); //ctnMapping = ctnMapping.Where(x => x.Module == "BookingVgm").ToList(); //if (ctnMapping.Count == 0) //{ // throw Oops.Bah(BookingErrorCode.BOOK122); //} //var expCode = ctns.Select(x => x.CTNCODE).Distinct().Except(ctnMapping.Select(y => y.Code)).ToList(); //if (expCode.Count > 0) //{ // throw Oops.Bah(BookingErrorCode.BOOK123, string.Join(',', expCode)); //} #region 箱信息校验,2022-7-1修改:【累加】的必须有重量、皮重和称重重量;【总重】的只需要称重重量不为空 if (ctns.Where(c => c.WEIGHTYPE == "累加" && ( string.IsNullOrEmpty(c.CNTRNO) || !c.WEIGHKGS.HasValue || c.WEIGHKGS == 0 || !c.TAREWEIGHT.HasValue || c.TAREWEIGHT == 0 || !c.KGS.HasValue || c.KGS == 0) ).Count() > 0) { throw Oops.Bah("称重方式为累加时,箱号、重量、箱皮重以及称重重量都不能为空"); } if (ctns.Where(c => c.WEIGHTYPE == "总重" && ( string.IsNullOrEmpty(c.CNTRNO) || !c.WEIGHKGS.HasValue || c.WEIGHKGS == 0) ).Count() > 0) { throw Oops.Bah("称重方式为总重时,箱号和称重重量都不能为空"); } #endregion ////场站转换 //var yardset = _cache.GetAllMappingYard().Result.FirstOrDefault(y => y.Code == order.YARDID && y.Module == "BookingVgm"); //if (yardset == null) //{ // throw Oops.Bah(BookingErrorCode.BOOK120, order.YARDID); //} if (string.IsNullOrEmpty(order.YARD) || string.IsNullOrEmpty(order.YARDID)) { throw Oops.Bah("场站未正确选择"); } var user = await _repUser.FirstOrDefaultAsync(x => x.Id == UserManager.UserId); int idx = 1; //调用接口 var dicUrl = _cache.GetAllDictData().Result.First(x => x.TypeCode == "url_set" && x.Code == "vgm_service_single"); var sendObj = new { SystemCode = "djy_hechuan", billOrderId = order.Id.ToString(), sendOrderCode = order.MBLNO, customerName = $"{UserManager.TENANT_NAME}+{UserManager.Name}", //公司名称+用户姓名 customerId = order.CUSTOMERID.ToString(), agentName = string.IsNullOrEmpty(order.FORWARDER) ? UserManager.TENANT_NAME : order.FORWARDER, carrierCode = order.CARRIERID, userName = webacc.Account, userPassword = webacc.Password, depotCode = order.YARDID, depotName = order.YARD, linkName = UserManager.Name, linkMobile = user.Phone, linkEmail = user.Email, userId = user.DjyUserId, signatory = user.NickName, //2023年8月28日,董怡含:把用户昵称当做vgm上传人 returnUrl = "", shipName = order.VESSEL, voyNo = order.VOYNO, etdstr = order.ETD.HasValue ? order.ETD.Value.ToString("yyyy-MM-dd") : string.Empty, potrSend = order.PORTLOAD, potrGoal = order.PORTDISCHARGE, boxinfoStr = order.CNTRTOTAL.Replace("'", ""), vgmEndTimeStr = order.CLOSEVGMDATE.HasValue ? order.CLOSEVGMDATE.Value.ToString("yyyy-MM-dd") : string.Empty, BoxInfo = ctns.Select(c => new { index = idx++, boxType = c.CTNALL.Replace("'", ""), boxcount = c.CTNNUM.HasValue ? c.CTNNUM.Value : 0, code = c.CNTRNO, sealCode = c.SEALNO, weigth = c.KGS, weigthTare = c.TAREWEIGHT, weigthTotal = c.WEIGHKGS, weigthType = c.WEIGHTYPE == "累加" ? "SM2" : "SM1" }).ToList(), returnOkUrl = "" }; string strPostObj = sendObj.ToJsonString(); _logger.LogInformation($"调用VGM直发接口 {dicUrl.Value} 传递数据:{strPostObj}"); var strResp = await dicUrl.Value.SetBody(sendObj).PostAsStringAsync(); _logger.LogInformation($"调用VGM直发接口返回:{strResp}"); var jobjResp = JObject.Parse(strResp); int respCode = jobjResp.GetIntValue("code"); if (respCode != 200) { throw Oops.Bah(BookingErrorCode.BOOK128, jobjResp.GetStringValue("message")); } //货运动态 var bsl = new BookingStatusLog(); bsl.BookingId = bookingId; bsl.Status = $"直发VGM"; bsl.OpTime = DateTime.Now; bsl.Category = "ship"; bsl.MBLNO = order.MBLNO; await _repStatuslog.InsertAsync(bsl); } //设置货物状态:已发VGM,并回传东胜 await SetGoodsStatus("YFVGM", bookingId); await SendBookingOrder(new long[] { bookingId }); } /// /// 批量编辑vgm /// /// 业务id 逗号拼接 /// [HttpGet("/BookingOrder/GetVmgDataList")] public async Task> GetVmgDataList(string ids) { var arr = ids.Split(','); if (arr.Length == 0) { throw Oops.Bah("请传入正确数据"); } var main = await _rep.AsQueryable().Where(x => x.ParentId == 0).ToListAsync(); List batchVGMs = new List(); foreach (var item in arr) { BatchVGM batchVGM = new BatchVGM(); batchVGM.Id = Convert.ToInt64(item); batchVGM.MBLNO = main.Where(x => x.Id == batchVGM.Id).Select(x => x.MBLNO).FirstOrDefault(); batchVGM.ctnlist = await _repCtn.Where(x => x.BILLID == batchVGM.Id).Select(x => new BatchVGMList { Id = x.Id, CTNCODE = x.CTNCODE, CTNALL = x.CTNALL, CNTRNO = x.CNTRNO, KGS = x.KGS, TAREWEIGHT = x.TAREWEIGHT, WEIGHTYPE = x.WEIGHTYPE, WEIGHKGS = x.WEIGHKGS }).ToListAsync(); batchVGMs.Add(batchVGM); } return batchVGMs; } /// /// 批量保存vgm /// /// /// [HttpPost("/BookingOrder/SaveBatchVgm")] public async Task SaveBatchVgm(List dto) { if (dto == null) { throw Oops.Bah("未提交数据"); } foreach (var item in dto) { await _repCtn.UpdateAsync(x => x.Id == item.Id, x => new BookingCtn { CTNCODE = item.CTNCODE, CTNALL = item.CTNALL, CNTRNO = item.CNTRNO, KGS = item.KGS, TAREWEIGHT = item.TAREWEIGHT, WEIGHTYPE = item.WEIGHTYPE, WEIGHKGS = item.WEIGHKGS }); } } #endregion #region 订舱、截单EDI /// /// 发送订舱、截单EDI /// /// 订舱、截单EDI请求 /// 返回回执 [HttpPost("/BookingOrder/SendBookingOrClosingEDI")] public async Task SendBookingOrClosingEDI(BookingOrClosingEDIOrderDto model) { var dictvalue = _cache.GetAllDictData().Result.Where(x => x.Code == "XiangManCang").Select(x => x.Value).FirstOrDefault(); var order = _rep.FirstOrDefault(x => x.Id == model.Id); var FORWARDER = order.FORWARDER; if (!string.IsNullOrEmpty(FORWARDER) && dictvalue == FORWARDER) { #region //var edi = _bookingEDIExt.FirstOrDefault(x => x.BookingId == model.Id); //var ctn = _repCtn.AsQueryable().Where(x => x.BILLID == model.Id).ToList(); //#region 箱满仓生成excel文件 //string fileName = String.Empty; //var opt = App.GetOptions(); //var dirAbs = opt.basePath; //if (string.IsNullOrEmpty(dirAbs)) //{ // dirAbs = App.WebHostEnvironment.WebRootPath; //} //var fPath = "upload/printtemplate/箱满舱上传Excel模板.xls"; //var fileAbsPath = Path.Combine(dirAbs, fPath); //_logger.LogInformation($"准备调用EXCEL"); //var file = new FileStream(fileAbsPath, FileMode.Open); //var excelwork = new HSSFWorkbook(file); //var sheet = excelwork.GetSheetAt(0); //for (int i = 0; i < sheet.LastRowNum; i++) //{ // ////获取行 // var row = sheet.GetRow(i); // if (i == 0) // { // //委托编号 // ICell cell = row.GetCell(5); // if (cell != null) // { // row.Cells[5].SetCellValue(order.CUSTNO); // } // else // { // row.CreateCell(5).SetCellValue(order.CUSTNO); // } // } // if (i == 1) // { // //场站 // var yardid = order.YARDID; // if (!string.IsNullOrEmpty(yardid)) // { // ICell cell = row.GetCell(5); // var yard = _cache.GetAllMappingYard().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == yardid).Select(x => x.MapCode).First(); // if (cell != null) // { // row.Cells[5].SetCellValue(yard); // } // else // { // row.CreateCell(5).SetCellValue(yard); // } // } // } // if (i == 2) // { // //指定业务员 // ICell cell = row.GetCell(5); // if (cell != null) // { // row.Cells[5].SetCellValue(edi.XMCYWY); // } // else // { // row.CreateCell(5).SetCellValue(edi.XMCYWY); // } // } // if (i == 3) // { // //提单号 // ICell cell = row.GetCell(5); // if (cell != null) // { // row.Cells[5].SetCellValue(order.MBLNO); // } // else // { // row.CreateCell(5).SetCellValue(order.MBLNO); // } // } // if (i == 8) // { // //发货人 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.SHIPPER); // } // else // { // row.CreateCell(1).SetCellValue(order.SHIPPER); // } // } // if (i == 10) // { // //发货人代码 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.SHIPPERID); // } // else // { // row.CreateCell(1).SetCellValue(order.SHIPPERID); // } // } // if (i == 11) // { // //收货人 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.CONSIGNEE); // } // else // { // row.CreateCell(1).SetCellValue(order.CONSIGNEE); // } // } // if (i == 14) // { // //通知人 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.NOTIFYPARTY); // } // else // { // row.CreateCell(1).SetCellValue(order.NOTIFYPARTY); // } // } // if (i == 17) // { // //第二通知人 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.NOTIFYPARTY2); // } // else // { // row.CreateCell(1).SetCellValue(order.NOTIFYPARTY2); // } // } // if (i == 18) // { // //起运港国际五字代码 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PORTLOADID); // } // else // { // row.CreateCell(1).SetCellValue(order.PORTLOADID); // } // var service = order.SERVICE; // //运输方式 // ICell cell5 = row.GetCell(5); // if (cell5 != null) // { // row.Cells[5].SetCellValue(_cache.GetAllMappingService().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == service).Select(x => x.MapCode).First()); // } // else // { // row.CreateCell(5).SetCellValue(_cache.GetAllMappingService().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == service).Select(x => x.MapCode).First()); // } // } // if (i == 19) // { // //卸货港国际五字代码 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PORTDISCHARGEID); // } // else // { // row.CreateCell(1).SetCellValue(order.PORTDISCHARGEID); // } // } // if (i == 20) // { // //交货地国际五字代码 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PLACEDELIVERYID); // } // else // { // row.CreateCell(1).SetCellValue(order.PLACEDELIVERYID); // } // } // if (i == 21) // { // //ETD // if (order.ETD != null) // { // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(Convert.ToDateTime(order.ETD).ToString("yyyy-MM-dd")); // } // else // { // row.CreateCell(1).SetCellValue(Convert.ToDateTime(order.ETD).ToString("yyyy-MM-dd")); // } // } // //船名 // ICell cell4 = row.GetCell(4); // if (cell4 != null) // { // row.Cells[4].SetCellValue(order.VESSEL); // } // else // { // row.CreateCell(4).SetCellValue(order.VESSEL); // } // } // if (i == 22) // { // //客户协约号 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.CONTRACTNO); // } // else // { // row.CreateCell(1).SetCellValue(order.CONTRACTNO); // } // } // if (i == 23) // { // //航次 // ICell cell = row.GetCell(4); // if (cell != null) // { // row.Cells[4].SetCellValue(order.VOYNO); // } // else // { // row.CreateCell(4).SetCellValue(order.VOYNO); // } // } // if (i == 26) // { // //唛头 // ICell cell = row.GetCell(0); // if (cell != null) // { // row.Cells[0].SetCellValue(order.MARKS); // } // else // { // row.CreateCell(0).SetCellValue(order.MARKS); // } // if (order.PKGS != null) // { // //件数 // ICell cell1 = row.GetCell(1); // if (cell1 != null) // { // row.Cells[1].SetCellValue(order.PKGS.ToString()); // } // else // { // row.CreateCell(1).SetCellValue(order.PKGS.ToString()); // } // } // //包装 // ICell cell2 = row.GetCell(2); // if (cell2 != null) // { // row.Cells[2].SetCellValue(order.KINDPKGS); // } // else // { // row.CreateCell(2).SetCellValue(order.KINDPKGS); // } // //品名 // ICell cell3 = row.GetCell(3); // if (cell3 != null) // { // row.Cells[3].SetCellValue(order.DESCRIPTION); // } // else // { // row.CreateCell(3).SetCellValue(order.DESCRIPTION); // } // if (order.KGS != null) // { // //重量 // ICell cell4 = row.GetCell(4); // if (cell3 != null) // { // row.Cells[4].SetCellValue(order.KGS.ToString()); // } // else // { // row.CreateCell(4).SetCellValue(order.KGS.ToString()); // } // } // if (order.CBM != null) // { // //尺码 // ICell cell5 = row.GetCell(5); // if (cell5 != null) // { // row.Cells[5].SetCellValue(order.CBM.ToString()); // } // else // { // row.CreateCell(5).SetCellValue(order.CBM.ToString()); // } // } // } // if (i == 39) // { // var c = ctn.DistinctBy(x => x.CTNALL).ToList(); // var ctnAll = string.Empty; // foreach (var item in c) // { // ctnAll += $"{ctn.Where(x => x.CTNALL == item.CTNALL).Count()}*{_cache.GetAllMappingCtn().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == item.CTNCODE).Select(x => x.MapCode).First()}+"; // } // ctnAll = ctnAll.Substring(0, ctnAll.Length - 1); // //箱型箱量 // ICell cell = row.GetCell(0); // if (cell != null) // { // row.Cells[0].SetCellValue(ctnAll); // } // else // { // row.CreateCell(0).SetCellValue(ctnAll); // } // } // if (i == 42) // { // //运费支付方式 // var BLFRTCode = _cache.GetAllCodeFrt().Result.Where(x => x.EnName == order.BLFRT).Select(x => x.Code).First(); // var bl = string.Empty; // if (!string.IsNullOrEmpty(BLFRTCode)) // { // bl = _cache.GetAllMappingFrt().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == BLFRTCode).Select(x => x.MapCode).First(); // } // ICell cell = row.GetCell(0); // if (cell != null) // { // row.Cells[0].SetCellValue(bl); // } // else // { // row.CreateCell(0).SetCellValue(bl); // } // } // if (i == 43) // { // //hscode // ICell cell = row.GetCell(3); // if (cell != null) // { // row.Cells[3].SetCellValue(order.HSCODE); // } // else // { // row.CreateCell(3).SetCellValue(order.HSCODE); // } // } // if (i == 44) // { // var BLFRTCode = _cache.GetAllCodeFrt().Result.Where(x => x.EnName == order.BLFRT).Select(x => x.Code).First(); // var bl = string.Empty; // if (!string.IsNullOrEmpty(BLFRTCode)) // { // bl = _cache.GetAllMappingFrt().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == BLFRTCode).Select(x => x.MapCode).First(); // } // if (bl == "预付") // { // //预付地点 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PREPARDATID); // } // else // { // row.CreateCell(1).SetCellValue(order.PREPARDATID); // } // } // else if((bl == "到付")) // { // //预付地点 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PAYABLEATID); // } // else // { // row.CreateCell(1).SetCellValue(order.PAYABLEATID); // } // } // } // if (i == 45) // { // //Name accout // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(edi.EmcNameAccount); // } // else // { // row.CreateCell(1).SetCellValue(edi.EmcNameAccount); // } // } // if (i == 47) // { // //Name accout // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.TEMPSET); // } // else // { // row.CreateCell(1).SetCellValue(order.TEMPSET); // } // //温度 // ICell cell2 = row.GetCell(2); // if (cell2 != null) // { // row.Cells[2].SetCellValue(order.TEMPSET); // } // else // { // row.CreateCell(2).SetCellValue(order.TEMPSET); // } // //湿度 // ICell cell3 = row.GetCell(3); // if (cell2 != null) // { // row.Cells[3].SetCellValue(order.HUMIDITY); // } // else // { // row.CreateCell(3).SetCellValue(order.HUMIDITY); // } // } // if (i == 49) // { // //危险品编号 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.DUNNO); // } // else // { // row.CreateCell(1).SetCellValue(order.DUNNO); // } // } // if (i == 50) // { // //订舱备注 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.SOREMARK); // } // else // { // row.CreateCell(1).SetCellValue(order.SOREMARK); // } // } //} //var fileFullPath = Path.Combine(App.WebHostEnvironment.WebRootPath, App.GetOptions().Path);//服务器路径 //if (!Directory.Exists(fileFullPath)) //{ // Directory.CreateDirectory(fileFullPath); //} ////2023-4-3,根据合川操作要求,文件名只带提单号 //if (!string.IsNullOrEmpty(order.MBLNO)) //{ // fileName = $"{DateTime.Now.Ticks}_{order.MBLNO}.xls";//名称 //} //else //{ // fileName = $"{DateTime.Now.Ticks}_{order.MBLNO}.xls";//名称 //} //_logger.LogInformation("导出excel:" + Path.Combine(fileFullPath, fileName)); //var filestream = new FileStream(Path.Combine(fileFullPath, fileName), FileMode.OpenOrCreate, FileAccess.ReadWrite); //excelwork.Write(filestream); //#endregion //#region 调用爬虫接口 //var url = _cache.GetAllDictData().Result.Where(x => x.Code == "xiangManCangPostUrl").Select(x => x.Value).FirstOrDefault(); //var account = _webAccountConfig.GetAccountConfig("XiangManCang", UserManager.UserId).Result; //var key = _cache.GetAllSysConfig().Result.Where(x => x.Code == "billTraceNewUserKey").Select(x => x.Value).FirstOrDefault(); //if (string.IsNullOrEmpty(key)) //{ // throw Oops.Bah("未获取到相关KEY,请联系管理员!"); //} //var secret = _cache.GetAllSysConfig().Result.Where(x => x.Code == "billTraceNewUserSecret").Select(x => x.Value).FirstOrDefault(); //if (string.IsNullOrEmpty(secret)) //{ // throw Oops.Bah("未获取到相关SECRET,请联系管理员!"); //} //////使用HttpClient方式上传文件 //var carrier_code = _cache.GetAllMappingCarrier().Result.Where(x => x.Module == "HeChuan" && x.MapCode == order.CARRIERID).Select(x => x.Code).First(); //string fn = string.Empty; //using (var httpClient = new HttpClient()) //{ // using (var request = new HttpRequestMessage(new HttpMethod("Post"), url)) // { // request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded"); // var multipartContent = new MultipartFormDataContent(); // multipartContent.Add(new StringContent("user_key"), key); // multipartContent.Add(new StringContent("user_secret"), secret); // multipartContent.Add(new StringContent("web_user"), account.Account); // multipartContent.Add(new StringContent("web_psw"), account.Password); // multipartContent.Add(new StringContent("carrier_code"), carrier_code); // multipartContent.Add(new StreamContent(filestream, (int)filestream.Length), "file", fileName); // request.Content = multipartContent; // var response = await httpClient.SendAsync(request); // if (response.IsSuccessStatusCode) // { // var strRtn = response.Content.ReadAsStringAsync().Result; // var jobj = strRtn.ToJObject(); // if (jobj.GetIntValue("code") == 200) // { // fn = jobj.GetStringValue("msg"); // } // else // { // throw Oops.Bah(jobj.GetStringValue("msg")); // } // } // } //} //return fn; //#endregion #endregion return await XMCEXCEL(model.Id); } else { return await InnerBookingOrClosingEDI(model); } } [NonAction] public async Task XMCEXCEL(long Id, bool flag = false) { var order = _rep.FirstOrDefault(x => x.Id == Id); var edi = _bookingEDIExt.FirstOrDefault(x => x.BookingId == Id); var ctn = _repCtn.AsQueryable().Where(x => x.BILLID == Id).ToList(); #region 箱满仓生成excel文件 string fileName = String.Empty; var opt = App.GetOptions(); var dirAbs = opt.basePath; if (string.IsNullOrEmpty(dirAbs)) { dirAbs = App.WebHostEnvironment.WebRootPath; } var fPath = "upload/printtemplate/箱满舱上传Excel模板.xls"; var fileAbsPath = Path.Combine(dirAbs, fPath); _logger.LogInformation($"准备调用EXCEL"); var file = new FileStream(fileAbsPath, FileMode.Open); var excelwork = new HSSFWorkbook(file); var sheet = excelwork.GetSheetAt(0); for (int i = 0; i < sheet.LastRowNum; i++) { ////获取行 var row = sheet.GetRow(i); if (i == 0) { //委托编号 ICell cell = row.GetCell(5); if (cell != null) { row.Cells[5].SetCellValue(order.CUSTNO); } else { row.CreateCell(5).SetCellValue(order.CUSTNO); } } if (i == 1) { //场站 var yardid = order.YARDID; if (!string.IsNullOrEmpty(yardid)) { ICell cell = row.GetCell(5); var yard = _cache.GetAllMappingYard().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == yardid).Select(x => x.MapCode).FirstOrDefault(); if (cell != null) { row.Cells[5].SetCellValue(yard); } else { row.CreateCell(5).SetCellValue(yard); } } } if (i == 2) { //指定业务员 ICell cell = row.GetCell(5); if (cell != null) { row.Cells[5].SetCellValue(edi.XMCYWY); } else { row.CreateCell(5).SetCellValue(edi.XMCYWY); } } if (i == 3) { //提单号 ICell cell = row.GetCell(5); if (cell != null) { if (string.IsNullOrEmpty(order.MBLNO)) { row.Cells[5].SetCellValue(order.CUSTNO); } else { row.Cells[5].SetCellValue(order.MBLNO); } } else { if (string.IsNullOrEmpty(order.MBLNO)) { row.CreateCell(5).SetCellValue(order.CUSTNO); } else { row.CreateCell(5).SetCellValue(order.MBLNO); } } } if (i == 8) { //发货人 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.SHIPPER); } else { row.CreateCell(1).SetCellValue(order.SHIPPER); } } if (i == 10) { //发货人代码 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.SHIPPERID); } else { row.CreateCell(1).SetCellValue(order.SHIPPERID); } } if (i == 11) { //收货人 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.CONSIGNEE); } else { row.CreateCell(1).SetCellValue(order.CONSIGNEE); } } if (i == 14) { //通知人 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.NOTIFYPARTY); } else { row.CreateCell(1).SetCellValue(order.NOTIFYPARTY); } } if (i == 17) { //第二通知人 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.NOTIFYPARTY2); } else { row.CreateCell(1).SetCellValue(order.NOTIFYPARTY2); } } if (i == 18) { //起运港国际五字代码 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.PORTLOADID); } else { row.CreateCell(1).SetCellValue(order.PORTLOADID); } var service = order.SERVICE; //运输方式 ICell cell5 = row.GetCell(5); if (cell5 != null) { row.Cells[5].SetCellValue(_cache.GetAllMappingService().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == service).Select(x => x.MapCode).FirstOrDefault()); } else { row.CreateCell(5).SetCellValue(_cache.GetAllMappingService().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == service).Select(x => x.MapCode).FirstOrDefault()); } } if (i == 19) { //卸货港国际五字代码 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.PORTDISCHARGEID); } else { row.CreateCell(1).SetCellValue(order.PORTDISCHARGEID); } } if (i == 20) { //交货地国际五字代码 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.DESTINATIONID); } else { row.CreateCell(1).SetCellValue(order.DESTINATIONID); } } if (i == 21) { //ETD if (order.ETD != null) { ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(Convert.ToDateTime(order.ETD).ToString("yyyy-MM-dd")); } else { row.CreateCell(1).SetCellValue(Convert.ToDateTime(order.ETD).ToString("yyyy-MM-dd")); } } //船名 ICell cell4 = row.GetCell(4); if (cell4 != null) { row.Cells[4].SetCellValue(order.VESSEL); } else { row.CreateCell(4).SetCellValue(order.VESSEL); } } if (i == 22) { //客户协约号 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.CONTRACTNO); } else { row.CreateCell(1).SetCellValue(order.CONTRACTNO); } } if (i == 23) { //航次 ICell cell = row.GetCell(4); if (cell != null) { row.Cells[4].SetCellValue(order.VOYNO); } else { row.CreateCell(4).SetCellValue(order.VOYNO); } } if (i == 26) { //唛头 ICell cell = row.GetCell(0); if (cell != null) { row.Cells[0].SetCellValue(order.MARKS); } else { row.CreateCell(0).SetCellValue(order.MARKS); } if (order.PKGS != null) { //件数 ICell cell1 = row.GetCell(1); if (cell1 != null) { row.Cells[1].SetCellValue(order.PKGS.ToString()); } else { row.CreateCell(1).SetCellValue(order.PKGS.ToString()); } } //包装 ICell cell2 = row.GetCell(2); if (cell2 != null) { row.Cells[2].SetCellValue(order.KINDPKGS); } else { row.CreateCell(2).SetCellValue(order.KINDPKGS); } //品名 ICell cell3 = row.GetCell(3); if (cell3 != null) { row.Cells[3].SetCellValue(order.DESCRIPTION); } else { row.CreateCell(3).SetCellValue(order.DESCRIPTION); } if (order.KGS != null) { //重量 ICell cell4 = row.GetCell(4); if (cell3 != null) { row.Cells[4].SetCellValue(order.KGS.ToString()); } else { row.CreateCell(4).SetCellValue(order.KGS.ToString()); } } if (order.CBM != null) { //尺码 ICell cell5 = row.GetCell(5); if (cell5 != null) { row.Cells[5].SetCellValue(order.CBM.ToString()); } else { row.CreateCell(5).SetCellValue(order.CBM.ToString()); } } } if (i == 39) { var c = ctn.DistinctBy(x => x.CTNALL).ToList(); var ctnAll = string.Empty; foreach (var item in c) { ctnAll += $"{ctn.Where(x => x.CTNALL == item.CTNALL).Count()}*{_cache.GetAllMappingCtn().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == item.CTNCODE).Select(x => x.MapCode).First()}+"; } ctnAll = ctnAll.Substring(0, ctnAll.Length - 1); //箱型箱量 ICell cell = row.GetCell(0); if (cell != null) { row.Cells[0].SetCellValue(ctnAll); } else { row.CreateCell(0).SetCellValue(ctnAll); } } if (i == 42) { //运费支付方式 var BLFRTCode = _cache.GetAllCodeFrt().Result.Where(x => x.EnName == order.BLFRT).Select(x => x.Code).FirstOrDefault(); var bl = string.Empty; if (!string.IsNullOrEmpty(BLFRTCode)) { bl = _cache.GetAllMappingFrt().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == BLFRTCode).Select(x => x.MapCode).FirstOrDefault(); } ICell cell = row.GetCell(0); if (cell != null) { row.Cells[0].SetCellValue(bl); } else { row.CreateCell(0).SetCellValue(bl); } } if (i == 43) { //hscode ICell cell = row.GetCell(3); if (cell != null) { row.Cells[3].SetCellValue(order.HSCODE); } else { row.CreateCell(3).SetCellValue(order.HSCODE); } } if (i == 44) { var BLFRTCode = _cache.GetAllCodeFrt().Result.Where(x => x.EnName == order.BLFRT).Select(x => x.Code).FirstOrDefault(); var bl = string.Empty; if (!string.IsNullOrEmpty(BLFRTCode)) { bl = _cache.GetAllMappingFrt().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == BLFRTCode).Select(x => x.MapCode).FirstOrDefault(); } if (bl == "预付") { //预付地点 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.PREPARDATID); } else { row.CreateCell(1).SetCellValue(order.PREPARDATID); } } else if ((bl == "到付")) { //预付地点 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.PAYABLEATID); } else { row.CreateCell(1).SetCellValue(order.PAYABLEATID); } } } if (i == 45) { //Name accout ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(edi.EmcNameAccount); } else { row.CreateCell(1).SetCellValue(edi.EmcNameAccount); } } if (i == 47) { //Name accout ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.TEMPSET); } else { row.CreateCell(1).SetCellValue(order.TEMPSET); } //温度 ICell cell2 = row.GetCell(2); if (cell2 != null) { row.Cells[2].SetCellValue(order.REEFERF); } else { row.CreateCell(2).SetCellValue(order.REEFERF); } //湿度 ICell cell3 = row.GetCell(3); if (cell2 != null) { row.Cells[3].SetCellValue(order.HUMIDITY); } else { row.CreateCell(3).SetCellValue(order.HUMIDITY); } } if (i == 49) { //危险品编号 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.DUNNO); } else { row.CreateCell(1).SetCellValue(order.DUNNO); } } if (i == 50) { //订舱备注 ICell cell = row.GetCell(1); if (cell != null) { row.Cells[1].SetCellValue(order.SOREMARK); } else { row.CreateCell(1).SetCellValue(order.SOREMARK); } } } var fileFullPath = Path.Combine(App.WebHostEnvironment.WebRootPath, App.GetOptions().Path);//服务器路径 if (!Directory.Exists(fileFullPath)) { Directory.CreateDirectory(fileFullPath); } //2023-4-3,根据合川操作要求,文件名只带提单号 if (!string.IsNullOrEmpty(order.MBLNO)) { fileName = $"{DateTime.Now.Ticks}_{order.MBLNO}.xls";//名称 } else { fileName = $"{DateTime.Now.Ticks}_{order.MBLNO}.xls";//名称 } _logger.LogInformation("导出excel:" + Path.Combine(fileFullPath, fileName)); var filestream = new FileStream(Path.Combine(fileFullPath, fileName), FileMode.OpenOrCreate, FileAccess.ReadWrite); excelwork.Write(filestream); #endregion if (flag) { filestream.Close(); filestream.Dispose(); var fpath = Path.Combine(fileFullPath, fileName); var fInfo = new FileInfo(fpath); _logger.LogInformation("箱满仓文件地址:" + fpath + " " + fInfo); return new FileStreamResult(new FileStream(fpath, FileMode.Open), "application/octet-stream") { FileDownloadName = fInfo.Name }; } #region 调用爬虫接口 var url = _cache.GetAllDictData().Result.Where(x => x.Code == "xiangManCangPostUrl").Select(x => x.Value).FirstOrDefault(); var account = _webAccountConfig.GetAccountConfig("XiangManCang", UserManager.UserId).Result; if (account == null) { throw Oops.Bah("未配置箱满仓账号!"); } var key = _cache.GetAllSysConfig().Result.Where(x => x.Code == "billTraceNewUserKey").Select(x => x.Value).FirstOrDefault(); if (string.IsNullOrEmpty(key)) { throw Oops.Bah("未获取到相关KEY,请联系管理员!"); } var secret = _cache.GetAllSysConfig().Result.Where(x => x.Code == "billTraceNewUserSecret").Select(x => x.Value).FirstOrDefault(); if (string.IsNullOrEmpty(secret)) { throw Oops.Bah("未获取到相关SECRET,请联系管理员!"); } ////使用HttpClient方式上传文件 var carrier_code = _cache.GetAllMappingCarrier().Result.Where(x => x.Module == "HeChuan" && x.MapCode == order.CARRIERID).Select(x => x.Code).First(); string fn = string.Empty; using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage(new HttpMethod("Post"), url)) { //request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded"); var multipartContent = new MultipartFormDataContent(); multipartContent.Add(new StringContent("user_key"), key); multipartContent.Add(new StringContent("user_secret"), secret); multipartContent.Add(new StringContent("web_user"), account.Account); multipartContent.Add(new StringContent("web_psw"), account.Password); multipartContent.Add(new StringContent("carrier_code"), carrier_code); multipartContent.Add(new StreamContent(filestream, (int)filestream.Length), "file", fileName); request.Content = multipartContent; var response = await httpClient.SendAsync(request); if (response.IsSuccessStatusCode) { var strRtn = response.Content.ReadAsStringAsync().Result; var jobj = strRtn.ToJObject(); if (jobj.GetIntValue("code") == 200) { fn = jobj.GetStringValue("msg"); } else { throw Oops.Bah(jobj.GetStringValue("msg")); } } } } return fn; #endregion } [NonAction] public async Task InnerBookingOrClosingEDI(BookingOrClosingEDIOrderDto model) { string batchNo = IDGen.NextID().ToString(); _logger.LogInformation("批次={no}获取请求订舱、截单EDI {msg}", batchNo, JSON.Serialize(model)); /* 发送订舱和截单EDI的流程 1、通过订单号获取订单信息。 2、检查订单的必填信息。 3、根据船公司ID获取对应的路由枚举。 4、获取EDI转换参数。(集装箱型号、包装方式) 5、读取EDI的配置信息,获取船公司相关的EDI配置。 6、检查详细信息。 7、生成订舱或者截单EDI报文,并返回文件保存绝对路径。 */ if (model.Id == 0) throw Oops.Bah("订单Id不能为空"); var order = _rep.FirstOrDefault(a => a.Id == model.Id); if (order == null) throw Oops.Bah($"获取订单信息失败"); if (order.ParentId.HasValue && order.ParentId.Value > 0) throw Oops.Bah($"获取当前订单为分单不能生成EDI信息"); _logger.LogInformation("批次={no}提取订单信息完成", batchNo); var ediExtModel = _bookingEDIExt.FirstOrDefault(a => a.BookingId == model.Id); if (ediExtModel == null) throw Oops.Bah($"获取EDI信息失败"); _logger.LogInformation("批次={no}提取订单EDI信息完成", batchNo); //箱信息 var contaList = _repCtn.AsQueryable().Where(t => t.BILLID == order.Id).ToList(); CheckBookingOrClosingEDI(order, contaList); EDIRouteEnum ediRouteEnum = GetEDIRoute(order.CARRIERID); if (ediRouteEnum == EDIRouteEnum.YT) { if (string.IsNullOrWhiteSpace(order.NOBILL)) { throw Oops.Bah($"当前船公司{order.CARRIERID} EDI={ediRouteEnum.ToString()} 提单份数必填"); } } //部分船公司EDI需要填写操作英文名称,这里预先预警,其他船公司如果也需要可以再此追加 if (ediRouteEnum == EDIRouteEnum.TSL) { if (string.IsNullOrWhiteSpace(ediExtModel.OpEName)) throw Oops.Bah("未填写(EDI并补充信息)操作英文名称"); } _logger.LogInformation("批次={no} 获取EDI路由完成 路由={route}", batchNo, ediRouteEnum.ToString()); if (ediRouteEnum == EDIRouteEnum.NULL) throw Oops.Bah($"当前船公司没有对应的请求路由配置"); //这里船公司VOL的单子不能走此通道发送 if (ediRouteEnum == EDIRouteEnum.VOL) throw Oops.Bah($"当前船公司VOL不能执行标准发送"); //集装箱型 var ediCtnList = _cache.GetAllMappingCtn().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(t.CarrierCode) && t.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)).ToList(); //包装 var ediPkgsList = _cache.GetAllMappingPackage().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(t.CarrierCode) && t.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)).ToList(); //包装基础数据 var basePkgsList = _cache.GetAllCodePackage().GetAwaiter().GetResult(); //EDI SO\SI代码 var ediSOSICfg = _cache.GetAllMappingCarrier().GetAwaiter().GetResult() .FirstOrDefault(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase) && t.Code.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)); if (ediSOSICfg == null || string.IsNullOrWhiteSpace(ediSOSICfg.MapCode)) throw Oops.Bah($"CARRIERID={order.CARRIERID} 发送SO(SI)的船公司EDI代码未找到"); string postSpiderUrl = string.Empty; DjyWebsiteAccountConfig userWebAccountConfig = null; if (ediRouteEnum == EDIRouteEnum.TSL && model.send) { if (model.sendType.Equals("E", StringComparison.OrdinalIgnoreCase)) throw Oops.Oh($"暂未提供TSL的截单发送"); postSpiderUrl = _cache.GetAllDictData().GetAwaiter().GetResult() .FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == CONST_TSL_EDI_URL)?.Value; if (string.IsNullOrWhiteSpace(postSpiderUrl)) throw Oops.Bah($"字典未配置 url_set->{CONST_TSL_EDI_URL} 请联系管理员"); //获取个人对应的账户,这里GetAccountConfig逻辑优先取个人,个人没有配置取公司对应配置 userWebAccountConfig = await _webAccountConfig.GetAccountConfig(CONST_TSL_TYPE_CODE, UserManager.UserId); _logger.LogInformation("批次={no} 获取获取网站的账户完成,result={Num}", batchNo, JSON.Serialize(userWebAccountConfig)); if (userWebAccountConfig == null) throw Oops.Oh($" 未配置个人或公司网站账户,网站{CONST_TSL_TYPE_CODE}"); } var ediModel = new EDIBaseModel(); //2023-03-06 修改读取EDI配置方法,所有提取配置必须是已启用的EnableFlag=true,并且要根据SendType匹配发送类型,SendType=""表示使用订舱和截单,SO-订舱 SI-截单 var ftpSet = _cache.GetAllEdiSetting().GetAwaiter().GetResult() .FirstOrDefault(a => a.EDICODE.Equals(ediRouteEnum.ToString(), StringComparison.OrdinalIgnoreCase) && a.TenantId == order.TenantId && !string.IsNullOrWhiteSpace(a.CARRIERID) && a.CARRIERID.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase) && a.EnableFlag && (string.IsNullOrWhiteSpace(a.SendType) || (!string.IsNullOrWhiteSpace(a.SendType) && ((model.sendType == "B" && a.SendType == "SO") || (model.sendType == "E" && a.SendType == "SI"))))); if (ftpSet == null) throw Oops.Bah($"获取EDICODE={ediRouteEnum.ToString()}的EDI参数设置失败"); _logger.LogInformation("批次={no} 获取EDI配置完成 路由={set}", batchNo, JSON.Serialize(ftpSet)); ediModel.SENDCODE = ftpSet.SENDCODE; ediModel.SENDNAME = ftpSet.SENDNAME; ediModel.RECEIVECODE = ftpSet.RECEIVECODE; ediModel.SENDCOMPANYCODE = ftpSet.SENDCOMPANYCODE; ediModel.SENDSUBCOMPANYCODE = ftpSet.SENDSUBCOMPANYCODE; ediModel.ALIASSENDCODE = ftpSet.ALIASSENDCODE; ediModel.SENDSHIPPERCODE = ftpSet.SENDSHIPPERCODE; ediModel.filetype = model.sendType; //订舱 ediModel.filerole = model.fileRole; //读取文件配置 var fileCfg = App.GetOptions(); string filePath = String.Empty; string relativePath = string.Empty; if (!model.send) { var opt = App.GetOptions().Path; filePath = $"{Path.Combine(App.WebHostEnvironment.WebRootPath, opt)}\\{order.BOOKINGNO}";//服务器路径 } else { relativePath = $"{fileCfg.relativePath}\\edifiles\\{order.BOOKINGNO}"; filePath = $"{(!string.IsNullOrWhiteSpace(fileCfg.basePath) ? fileCfg.basePath : App.WebHostEnvironment.WebRootPath)}\\{relativePath}"; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { relativePath = relativePath.Replace("\\", "/"); filePath = filePath.Replace("\\", "/"); } _logger.LogInformation("批次={no} 生成文件保存路径完成 路由={filePath} 服务器系统={system}", batchNo, filePath, RuntimeInformation.OSDescription); //预先创建目录 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } ediModel.filerpath = filePath; /* * 2023-03-08 这里根据最新的要求,不通过前台读取了,直接从配置读取 ediModel.UseForWarderCode = model.useForwarderCode; ediModel.ForWarderCode = model.forwarderCode; ediModel.ForWarderName = model.forwarderName; */ ediModel.ForWarderCode = ftpSet.SENDCODE; ediModel.ForWarderName = ftpSet.SENDNAME; ediModel.BSLIST = new List(); var primaryModel = order.Adapt(); //航次取内部航次号 2023-04-03 合川操作确认这样调整 primaryModel.VOYNO = order.VOYNOINNER; //航线信息直接取的航司航线(ESL用) primaryModel.ESLLINECODE = order.LANENAME; //起始港映射 var ediLoadPortList = _cache.GetAllMappingPortLoad().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(t.CarrierCode) && t.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)).ToList(); //收货地 if (!string.IsNullOrWhiteSpace(primaryModel.PLACERECEIPTID)) { var currPortInfo = ediLoadPortList.FirstOrDefault(a => a.Code.Equals(primaryModel.PLACERECEIPTID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) throw Oops.Bah($"收货地{primaryModel.PLACERECEIPTID}的EDI代码未找到"); primaryModel.PLACERECEIPTID = currPortInfo.MapCode?.Trim(); } //装货港 if (!string.IsNullOrWhiteSpace(primaryModel.PORTLOADID)) { var currPortInfo = ediLoadPortList.FirstOrDefault(a => a.Code.Equals(primaryModel.PORTLOADID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) throw Oops.Bah($"装货港{primaryModel.PORTLOADID}的EDI代码未找到"); primaryModel.PORTLOADID = currPortInfo.MapCode?.Trim(); } //签单地点 if (!string.IsNullOrWhiteSpace(primaryModel.ISSUEPLACEID)) { var currPortInfo = ediLoadPortList.FirstOrDefault(a => a.Code.Equals(primaryModel.ISSUEPLACEID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) throw Oops.Bah($"签单地点{primaryModel.ISSUEPLACEID}的EDI代码未找到"); primaryModel.ISSUEPLACEID = currPortInfo.MapCode?.Trim(); } //预付地点 if (!string.IsNullOrWhiteSpace(primaryModel.PREPARDATID)) { var currPortInfo = ediLoadPortList.FirstOrDefault(a => a.Code.Equals(primaryModel.PREPARDATID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) throw Oops.Bah($"预付地点{primaryModel.PREPARDATID}的EDI代码未找到"); primaryModel.PREPARDATID = currPortInfo.MapCode?.Trim(); } //目的港基础 var portList = _cache.GetAllCodePort().GetAwaiter().GetResult(); //目的港映射 var ediPortList = _cache.GetAllMappingPort().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase) && (string.IsNullOrWhiteSpace(t.CarrierCode) || (!string.IsNullOrWhiteSpace(t.CarrierCode) && t.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase))) ).ToList(); //卸货港 if (!string.IsNullOrWhiteSpace(primaryModel.PORTDISCHARGEID)) { var sameList = portList.Where(a => !string.IsNullOrWhiteSpace(a.EdiCode) && a.EdiCode.Equals(primaryModel.PORTDISCHARGEID, StringComparison.OrdinalIgnoreCase)) .Select(a => a.Code).ToList(); if (sameList == null || sameList.Count == 0) throw Oops.Bah($"卸货港{primaryModel.PORTDISCHARGEID}基础港口代码未找到"); var currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code) && !string.IsNullOrWhiteSpace(a.CarrierCode) && a.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) { currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code)); } if (currPortInfo == null) throw Oops.Bah($"卸货港{primaryModel.PORTDISCHARGEID}的EDI代码未找到"); primaryModel.PORTDISCHARGEID = currPortInfo.MapCode?.Trim(); } //中转港 if (!string.IsNullOrWhiteSpace(primaryModel.TRANSPORTID)) { var sameList = portList.Where(a => !string.IsNullOrWhiteSpace(a.EdiCode) && a.EdiCode.Equals(primaryModel.TRANSPORTID, StringComparison.OrdinalIgnoreCase)) .Select(a => a.Code).ToList(); if (sameList == null || sameList.Count == 0) throw Oops.Bah($"中转港{primaryModel.TRANSPORTID}基础港口代码未找到"); var currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code) && !string.IsNullOrWhiteSpace(a.CarrierCode) && a.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) { currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code)); } if (currPortInfo == null) throw Oops.Bah($"中转港{primaryModel.TRANSPORTID}的EDI代码未找到"); primaryModel.TRANSPORTID = currPortInfo.MapCode?.Trim(); } //目的地 if (!string.IsNullOrWhiteSpace(primaryModel.DESTINATIONID)) { var sameList = portList.Where(a => !string.IsNullOrWhiteSpace(a.EdiCode) && a.EdiCode.Equals(primaryModel.DESTINATIONID, StringComparison.OrdinalIgnoreCase)) .Select(a => a.Code?.Trim()).ToList(); if (sameList == null || sameList.Count == 0) throw Oops.Bah($"目的地{primaryModel.DESTINATIONID}基础港口代码未找到"); var currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code) && !string.IsNullOrWhiteSpace(a.CarrierCode) && a.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) { currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code)); } if (currPortInfo == null) throw Oops.Bah($"目的地{primaryModel.DESTINATIONID}的EDI代码未找到"); primaryModel.DESTINATIONID = currPortInfo.MapCode?.Trim(); } //交货地 if (!string.IsNullOrWhiteSpace(primaryModel.PLACEDELIVERYID)) { var sameList = portList.Where(a => !string.IsNullOrWhiteSpace(a.EdiCode) && a.EdiCode.Equals(primaryModel.PLACEDELIVERYID, StringComparison.OrdinalIgnoreCase)) .Select(a => a.Code).ToList(); if (sameList == null || sameList.Count == 0) throw Oops.Bah($"交货地{primaryModel.PLACEDELIVERYID}基础港口代码未找到"); var currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code) && !string.IsNullOrWhiteSpace(a.CarrierCode) && a.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) { currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code)); } if (currPortInfo == null) throw Oops.Bah($"交货地{primaryModel.PLACEDELIVERYID}的EDI代码未找到"); primaryModel.PLACEDELIVERYID = currPortInfo.MapCode?.Trim(); } //到付地点 if (!string.IsNullOrWhiteSpace(primaryModel.PAYABLEATID)) { var sameList = portList.Where(a => !string.IsNullOrWhiteSpace(a.EdiCode) && a.EdiCode.Equals(primaryModel.PAYABLEATID, StringComparison.OrdinalIgnoreCase)) .Select(a => a.Code).ToList(); if (sameList == null || sameList.Count == 0) throw Oops.Bah($"到付地点{primaryModel.PAYABLEATID}基础港口代码未找到"); var currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code) && !string.IsNullOrWhiteSpace(a.CarrierCode) && a.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)); if (currPortInfo == null) { currPortInfo = ediPortList.FirstOrDefault(a => sameList.Contains(a.Code)); } if (currPortInfo == null) throw Oops.Bah($"到付地点{primaryModel.PAYABLEATID}的EDI代码未找到"); primaryModel.PAYABLEATID = currPortInfo.MapCode?.Trim(); } //起运港是CNTAO并且船公司是太平需要判断场站EDI if (ediRouteEnum == EDIRouteEnum.WY) { //场站 var ediYardList = _cache.GetAllMappingYard().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase)).ToList(); if (!string.IsNullOrWhiteSpace(order.YARDID)) { var currYardInfo = ediYardList.FirstOrDefault(t => t.Code.Equals(order.YARDID, StringComparison.OrdinalIgnoreCase)); if (currYardInfo == null) throw Oops.Bah($"场站{order.YARDID}的EDI代码未找到"); primaryModel.YARDEDICODE = currYardInfo.MapCode?.Trim(); primaryModel.YARD = currYardInfo.MapName?.Trim(); } } //ESL、PIL、WY、YML、YT 需要付费方式映射EDI代码 if (ediRouteEnum == EDIRouteEnum.ESL || ediRouteEnum == EDIRouteEnum.PIL || ediRouteEnum == EDIRouteEnum.WY || ediRouteEnum == EDIRouteEnum.YML || ediRouteEnum == EDIRouteEnum.YT) { //付费方式基础数据 var baseFrtList = _cache.GetAllCodeFrt().GetAwaiter().GetResult(); var baseFrtInfo = baseFrtList.FirstOrDefault(t => t.EnName.Equals(order.BLFRT, StringComparison.OrdinalIgnoreCase)); if (baseFrtInfo == null) throw Oops.Bah($"付费方式{order.BLFRT}的基础代码未找到"); //付费方式映射 var ediFrtList = _cache.GetAllMappingFrt().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(t.CarrierCode) && t.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase) ).ToList(); if (!string.IsNullOrWhiteSpace(order.BLFRT)) { var currFrtInfo = ediFrtList.FirstOrDefault(t => t.Code.Equals(baseFrtInfo.Code, StringComparison.OrdinalIgnoreCase)); if (currFrtInfo == null) throw Oops.Bah($"付费方式{order.BLFRT}的EDI代码未找到"); primaryModel.BLFRTEDICODE = currFrtInfo.MapCode?.Trim(); } } if (!string.IsNullOrWhiteSpace(order.SERVICE)) { //运输条款EDI var baseServiceList = _cache.GetAllCodeService().GetAwaiter().GetResult(); var baseServiceInfo = baseServiceList.FirstOrDefault(t => t.Name.Equals(order.SERVICE, StringComparison.OrdinalIgnoreCase)); if (baseServiceInfo == null) throw Oops.Bah($"运输条款{order.SERVICE}的基础代码未找到"); //运输条款映射 var ediServiceList = _cache.GetAllMappingService().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(t.CarrierCode) && t.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase) ).ToList(); var currServiceInfo = ediServiceList.FirstOrDefault(t => t.Code.Equals(baseServiceInfo.Code, StringComparison.OrdinalIgnoreCase)); if (currServiceInfo == null) throw Oops.Bah($"运输条款{order.SERVICE}的EDI代码未找到"); primaryModel.SERVICEEDICODE = currServiceInfo.MapCode?.Trim(); } if (!string.IsNullOrWhiteSpace(order.ISSUETYPE)) { //签单方式EDI var baseIssueTypeList = _cache.GetAllCodeIssueType().GetAwaiter().GetResult(); var baseIssueTypeInfo = baseIssueTypeList.FirstOrDefault(t => t.EnName.Equals(order.ISSUETYPE, StringComparison.OrdinalIgnoreCase)); if (baseIssueTypeInfo == null) throw Oops.Bah($"签单方式{order.ISSUETYPE}的基础代码未找到"); //签单方式映射 var ediIssueTypeList = _cache.GetAllMappingIssueType().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE, StringComparison.OrdinalIgnoreCase) ).ToList(); var currIssueTypeInfo = ediIssueTypeList.FirstOrDefault(t => !string.IsNullOrWhiteSpace(t.CarrierCode) && t.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase) && t.Code.Equals(baseIssueTypeInfo.Code, StringComparison.OrdinalIgnoreCase)); if (currIssueTypeInfo == null) { //如果没有对应的船司记录,则取默认的第一个代码对应的记录 currIssueTypeInfo = ediIssueTypeList.FirstOrDefault(t => t.Code.Equals(baseIssueTypeInfo.Code, StringComparison.OrdinalIgnoreCase)); } if (currIssueTypeInfo == null) throw Oops.Bah($"签单方式{order.ISSUETYPE}的EDI代码未找到"); primaryModel.ISSUETYPE = currIssueTypeInfo.MapCode?.Trim().ToUpper(); } primaryModel.CARRIEREDICODE = ediSOSICfg.MapCode; //这里除了TSL,订舱编号默认都对应到业务编号(订舱保存时自动生成) if (ediRouteEnum == EDIRouteEnum.TSL) { if (string.IsNullOrWhiteSpace(order.CUSTNO)) throw Oops.Bah($"船公司是{order.CARRIERID} 订舱编号不能为空"); primaryModel.ORDERNO = order.CUSTNO; } else { primaryModel.ORDERNO = order.BOOKINGNO; } //2023-06-15 按照沟通要求,如果主提单号为空,并且订舱编号不为空,可以去订舱编号填入主提单号 if (string.IsNullOrWhiteSpace(primaryModel.MBLNO)) { if (!string.IsNullOrWhiteSpace(order.CUSTNO)) { _logger.LogInformation("批次={no} 主题单号为空 MBLNO={mblno} 取订舱编号补到主提单号 custno={custno}", batchNo, primaryModel.MBLNO, order.CUSTNO); primaryModel.MBLNO = order.CUSTNO; } } var curBasePkgs = basePkgsList.FirstOrDefault(p => p.Name.Equals(order.KINDPKGS, StringComparison.OrdinalIgnoreCase)); if (curBasePkgs == null) throw Oops.Bah($"包装{order.KINDPKGS}的基础数据代码未找到"); var ediPkgs = ediPkgsList.FirstOrDefault(x => x.Code.Equals(curBasePkgs.Code, StringComparison.OrdinalIgnoreCase)); if (ediPkgs == null || string.IsNullOrWhiteSpace(ediPkgs.MapCode)) throw Oops.Bah($"包装{order.KINDPKGS}的EDI代码未找到"); primaryModel.KINDPKGS_EDI_CODE = ediPkgs.MapCode?.Trim(); //这里是订舱时,默认取SOREMARK赋值到EDIREMARK if (model.sendType == "B") { primaryModel.EDIREMARK = order.SOREMARK; } primaryModel.S0CC0C = ediExtModel.S0CC0C; primaryModel.ACIHBL = ediExtModel.ACIHBL; primaryModel.MasterBOLIndicator = ediExtModel.MasterBolIndicator; primaryModel.ConsigneeEdiCode = ediExtModel.ConsigneeEdiCode; primaryModel.ShipperEdiCode = ediExtModel.ShipperEdiCode; primaryModel.SalesRepCode = ediExtModel.SalerCode; primaryModel.CNPTNo = ediExtModel.CNPTNo; //优先取订舱的EDI附属信息,为空取FTP配置 primaryModel.EDIATTN = ediExtModel.EDIAttn; if (string.IsNullOrWhiteSpace(primaryModel.EDIATTN)) { primaryModel.EDIATTN = ftpSet.SENDATTN; } primaryModel.EDIATTNTEL = ediExtModel.EDIAttnTel; if (string.IsNullOrWhiteSpace(primaryModel.EDIATTNTEL)) { primaryModel.EDIATTNTEL = ftpSet.SENDTEL; } primaryModel.EDIATTNEMAIL = ediExtModel.EDIAttnMail; if (string.IsNullOrWhiteSpace(primaryModel.EDIATTNEMAIL)) { primaryModel.EDIATTNEMAIL = ftpSet.SENDEMAIL; } primaryModel.AMSCONSIGNEE = ediExtModel.AMSConsignee; primaryModel.AMSNOTIFYPARTY = ediExtModel.AMSNotifyParty; primaryModel.OpEName = ediExtModel.OpEName; primaryModel.OpTel = ediExtModel.OpTel; primaryModel.OpEmail = ediExtModel.OpEmail; /* 2023-04-14 确认东胜流程后,这里调整商品名称取值,不从EDI扩展信息取,改为从主表的GOODS_CODE取代码经过品名翻译英文填写 注:仅限PIL //primaryModel.GOODSNAME = ediExtModel.GoodsName; */ if (ediRouteEnum == EDIRouteEnum.PIL) { if (model.sendType.Equals("E", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrWhiteSpace(order.GOODSCODE)) { var pGoods = _paraGoodsInfoRepository.AsQueryable().First(x => x.GOODS_CODE == order.GOODSCODE); if (pGoods == null) { _logger.LogInformation("批次={no} 提取商品名称失败 GOODSCODE={code}", batchNo, order.GOODSCODE); throw Oops.Bah($"商品分类编码{order.GOODSCODE}对应商品名称未找到"); } else { primaryModel.GOODSNAME = pGoods.GOODS_NAME_EN; _logger.LogInformation("批次={no} 提取商品名称失败 code={code} name={name}", batchNo, order.GOODSCODE, pGoods.GOODS_NAME_EN); } } } else if (model.sendType.Equals("B", StringComparison.OrdinalIgnoreCase)) { //2023-05-17 PIL订舱时不提供GOODSNAME,这里默认赋空 primaryModel.GOODSNAME = string.Empty; } } primaryModel.cKHI = ediExtModel.CKHI; primaryModel.cNCM = ediExtModel.CNCM; primaryModel.wNCM = ediExtModel.WNCM; primaryModel.ORDERREMARK = ediExtModel.OrderRemark; //2023-05-10 (PIL)订舱的预抵日期不提供输入框,按照和川操作要求取开船日期填写到预抵日期 if (string.IsNullOrWhiteSpace(primaryModel.ETA) && !string.IsNullOrWhiteSpace(primaryModel.ETD) && ediRouteEnum == EDIRouteEnum.PIL) { primaryModel.ETA = primaryModel.ETD; } primaryModel.KINGTAREWEIGHT = ediExtModel.KingTareweight.HasValue ? ediExtModel.KingTareweight.Value : 0; _logger.LogInformation("批次={no} 提取箱完成 数量={total}", batchNo, contaList.Count); primaryModel.CTNLIST = new List(); //集装箱 foreach (var conta in contaList) { var contaModel = conta.Adapt(); //EDI箱型 var currConta = ediCtnList.FirstOrDefault(x => x.Code.Equals(conta.CTNCODE, StringComparison.OrdinalIgnoreCase)); if (currConta == null) throw Oops.Oh($"箱型{conta.CTNCODE}的EDI代码未找到"); contaModel.CTNALLCODE = currConta.MapCode; if (string.IsNullOrWhiteSpace(conta.KINDPKGS)) throw Oops.Oh($"集装箱包装不能为空"); var curContaBasePkgs = basePkgsList.FirstOrDefault(p => p.Name.Equals(conta.KINDPKGS, StringComparison.OrdinalIgnoreCase)); if (curContaBasePkgs == null) throw Oops.Bah($"包装{conta.KINDPKGS}的基础数据代码未找到"); //EDI包装 var ediContaPkgs = ediPkgsList.FirstOrDefault(x => x.Code.Equals(curContaBasePkgs.Code, StringComparison.OrdinalIgnoreCase)); if (currConta == null) throw Oops.Oh($"集装箱包装{conta.KINDPKGS}的EDI代码未找到"); contaModel.KINDPKGS_EDI_CODE = ediContaPkgs.MapCode?.Trim(); primaryModel.CTNLIST.Add(contaModel); } //多品名 var cargoList = _ctndetailrep.AsQueryable().Where(t => contaList.Select(a => a.Id).ToArray().Contains(t.CTNID.Value)).ToList(); _logger.LogInformation("批次={no} 提取多品名完成 数量={total}", batchNo, cargoList.Count); primaryModel.CTNGOODSLIST = new List(); foreach (var cargo in cargoList) { MsOpSeaeCtnDetailEDIBaseModel cargoModel = cargo.Adapt(); cargoModel.CNTRNO = contaList.FirstOrDefault(a => a.Id == cargo.CTNID.Value).CNTRNO; if (string.IsNullOrWhiteSpace(cargo.KINDPKGS)) throw Oops.Oh($"多品名包装不能为空"); var curCargoBasePkgs = basePkgsList.FirstOrDefault(p => p.Name.Equals(cargo.KINDPKGS, StringComparison.OrdinalIgnoreCase)); if (curCargoBasePkgs == null) throw Oops.Bah($"包装{cargo.KINDPKGS}的基础数据代码未找到"); var ediDetailPkgs = ediPkgsList.FirstOrDefault(x => x.Code.Equals(curCargoBasePkgs.Code, StringComparison.OrdinalIgnoreCase)); if (ediDetailPkgs == null) throw Oops.Oh($"货明细的包装{cargo.KINDPKGS}的EDI代码未找到"); cargoModel.KINDPKGS_EDI_CODE = ediDetailPkgs.MapCode?.Trim(); primaryModel.CTNGOODSLIST.Add(cargoModel); } ediModel.BSLIST.Add(primaryModel); var result = await InnerSendBookingOrClosingEDI(model, ediModel, ediRouteEnum); _logger.LogInformation("批次={no} 生成EDI文件完成 结果={result}", batchNo, JSON.Serialize(result)); if (!result.succ) { throw Oops.Bah(result.msg); } if (order.CARRIERID.Equals("ONE", StringComparison.OrdinalIgnoreCase)) { await PrintCarrierOneSOFileAsync(order); } if (model.send) { /* 2023-05-24 这里新增TSL的判断,如果是走TSL则默认走吴广的外挂,需要提供个人账户 */ string currFilePath = string.Empty; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { currFilePath = System.Text.RegularExpressions.Regex.Match(result.extra.ToString(), relativePath.Replace("/", "\\/") + ".*").Value; } else { currFilePath = System.Text.RegularExpressions.Regex.Match(result.extra.ToString(), relativePath.Replace("\\", "\\\\") + ".*").Value; } string fileTypeCode = "edi"; string fileTypeName = "EDI文件"; if (model.sendType.Equals("E", StringComparison.OrdinalIgnoreCase)) { fileTypeCode = "esi"; fileTypeName = "ESI文件"; } //这里先写入附件表 await SaveEDIFile(model.Id, currFilePath, new System.IO.FileInfo(currFilePath).Name, fileTypeCode, fileTypeName); _logger.LogInformation("批次={no} 直接发送FTP 文件访问地址={filepath}", batchNo, result.extra.ToString()); DateTime bDate = DateTime.Now; //是否发送邮件,EDI这里主要分2种通道发送 默认是FTP,如果配置里指定了接收接收邮箱,就需要推送邮件 bool isSendEmail = false; //上传FTP CommonWebApiResult sendStatus = null; //TSL单独走接口 if (ediRouteEnum == EDIRouteEnum.TSL) { sendStatus = await InnerSendBookingOrClosingEDIToPOST(result.extra.ToString(), postSpiderUrl, userWebAccountConfig); } else { //是订舱并且FTP配置了订舱接收邮箱则触发邮箱发送 if (ftpSet.SendType.Equals("SO", StringComparison.OrdinalIgnoreCase) && model.sendType.Equals("B", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(ftpSet.RECEIVEEMAIL)) { isSendEmail = true; } else if (ftpSet.SendType.Equals("SI", StringComparison.OrdinalIgnoreCase) && model.sendType.Equals("E", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(ftpSet.RECEIVEEMAIL)) { isSendEmail = true; } else if (string.IsNullOrWhiteSpace(ftpSet.SendType) && !string.IsNullOrWhiteSpace(ftpSet.RECEIVEEMAIL)) { isSendEmail = true; } if (isSendEmail) { //推送订舱邮件 sendStatus = await InnerSendBookingOrClosingEDIToEmail(order, result.extra.ToString(), model.sendType, result.extra2.ToString(), ftpSet); } else { sendStatus = await InnerSendBookingOrClosingEDIToFTP(result.extra.ToString(), ftpSet); } } DateTime eDate = DateTime.Now; TimeSpan ts = eDate.Subtract(bDate); var timeDiff = ts.TotalMilliseconds; _logger.LogInformation("批次={no} 发送完成,耗时:{timeDiff}ms. 结果{msg}", batchNo, timeDiff, sendStatus.succ ? "成功" : "失败"); var logId = await _bookinglog.InsertReturnSnowflakeIdAsync(new BookingLog { Type = "Trace", BookingId = model.Id, TenantId = Convert.ToInt64(UserManager.TENANT_ID), CreatedTime = DateTime.Now, CreatedUserId = UserManager.UserId, CreatedUserName = UserManager.Name }); string sendTypeName = "FTP"; if (isSendEmail) { sendTypeName = "邮件"; } else if (ediRouteEnum == EDIRouteEnum.TSL) { sendTypeName = "POST"; } await _bookinglogdetail.InsertReturnSnowflakeIdAsync(new BookingLogDetail { PId = logId, Field = String.Empty, OldValue = String.Empty, NewValue = $"发送 {order.CARRIERID} EDI 类型={model.sendType} 通过{sendTypeName} {(sendStatus.succ ? "成功" : "失败")}", }); if (!sendStatus.succ) { throw Oops.Bah($"发送失败,原因:{sendStatus.msg}"); } //截单 if (model.sendType.Equals("E", StringComparison.OrdinalIgnoreCase)) { //如果是截单需最后推送货物状态 await SetGoodsStatus("JD", model.Id); await SendBookingOrder(new long[] { model.Id }); } } return result.extra.ToString(); } [NonAction] private async Task SaveEDIFile(long boookId, string FilePath, string fileName, string fileTypeCode = "edi", string fileTypeName = "EDI文件") { /* 直接将附件信息写入附件表 */ //EDI文件 var bookFile = new BookingFile { Id = YitIdHelper.NextId(), FileName = fileName, FilePath = FilePath, TypeCode = fileTypeCode, TypeName = fileTypeName, BookingId = boookId, }; await _bookingfile.InsertAsync(bookFile); } #endregion #region 下载订舱、截单EDI /// /// 下载订舱、截单EDI /// /// 订单主键 /// 订单号 /// 是否使用货代代码 /// 货代代码 /// 货代称呼 /// 文件功能 (9原始,1 更新,5 退舱 ) /// 发送类型 B-订舱 E-截单 /// [HttpGet("/BookingOrder/DownloadBookingOrClosingEDI")] public async Task DownloadBookingOrClosingEDI([FromQuery] long id, [FromQuery] string orderNo, [FromQuery] bool useForwarderCode, [FromQuery] string forwarderCode, [FromQuery] string forwarderName, [FromQuery] string fileRole, [FromQuery] string sendType) { var order = _rep.FirstOrDefault(x => x.Id == id); var FORWARDER = order.FORWARDER; var dictvalue = _cache.GetAllDictData().Result.Where(x => x.Code == "XiangManCang").Select(x => x.Value).FirstOrDefault(); _logger.LogInformation("FORWARDER:" + FORWARDER + "dictvalue:" + dictvalue); if (!string.IsNullOrEmpty(FORWARDER) && dictvalue == FORWARDER) { #region //#region 箱满仓生成excel文件 //string fileName = String.Empty; //var opt = App.GetOptions(); //var dirAbs = opt.basePath; //if (string.IsNullOrEmpty(dirAbs)) //{ // dirAbs = App.WebHostEnvironment.WebRootPath; //} //var fPath = "upload/printtemplate/箱满舱上传Excel模板.xls"; //var fileAbsPath = Path.Combine(dirAbs, fPath); //_logger.LogInformation($"准备调用EXCEL"); //var file = new FileStream(fileAbsPath, FileMode.Open); //var excelwork = new HSSFWorkbook(file); //var sheet = excelwork.GetSheetAt(0); //for (int i = 0; i < sheet.LastRowNum; i++) //{ // ////获取行 // var row = sheet.GetRow(i); // if (i == 0) // { // //委托编号 // ICell cell = row.GetCell(5); // if (cell != null) // { // row.Cells[5].SetCellValue(order.CUSTNO); // } // else // { // row.CreateCell(5).SetCellValue(order.CUSTNO); // } // } // if (i == 1) // { // //场站 // var yardid = order.YARDID; // if (!string.IsNullOrEmpty(yardid)) // { // ICell cell = row.GetCell(5); // var yard = _cache.GetAllMappingYard().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == yardid).Select(x => x.MapCode).First(); // if (cell != null) // { // row.Cells[5].SetCellValue(yard); // } // else // { // row.CreateCell(5).SetCellValue(yard); // } // } // } // if (i == 2) // { // //指定业务员 // ICell cell = row.GetCell(5); // if (cell != null) // { // row.Cells[5].SetCellValue(edi.XMCYWY); // } // else // { // row.CreateCell(5).SetCellValue(edi.XMCYWY); // } // } // if (i == 3) // { // //提单号 // ICell cell = row.GetCell(5); // if (cell != null) // { // row.Cells[5].SetCellValue(order.MBLNO); // } // else // { // row.CreateCell(5).SetCellValue(order.MBLNO); // } // } // if (i == 8) // { // //发货人 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.SHIPPER); // } // else // { // row.CreateCell(1).SetCellValue(order.SHIPPER); // } // } // if (i == 10) // { // //发货人代码 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.SHIPPERID); // } // else // { // row.CreateCell(1).SetCellValue(order.SHIPPERID); // } // } // if (i == 11) // { // //收货人 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.CONSIGNEE); // } // else // { // row.CreateCell(1).SetCellValue(order.CONSIGNEE); // } // } // if (i == 14) // { // //通知人 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.NOTIFYPARTY); // } // else // { // row.CreateCell(1).SetCellValue(order.NOTIFYPARTY); // } // } // if (i == 17) // { // //第二通知人 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.NOTIFYPARTY2); // } // else // { // row.CreateCell(1).SetCellValue(order.NOTIFYPARTY2); // } // } // if (i == 18) // { // //起运港国际五字代码 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PORTLOADID); // } // else // { // row.CreateCell(1).SetCellValue(order.PORTLOADID); // } // var service = order.SERVICE; // //运输方式 // ICell cell5 = row.GetCell(5); // if (cell5 != null) // { // row.Cells[5].SetCellValue(_cache.GetAllMappingService().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == service).Select(x => x.MapCode).First()); // } // else // { // row.CreateCell(5).SetCellValue(_cache.GetAllMappingService().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == service).Select(x => x.MapCode).First()); // } // } // if (i == 19) // { // //卸货港国际五字代码 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PORTDISCHARGEID); // } // else // { // row.CreateCell(1).SetCellValue(order.PORTDISCHARGEID); // } // } // if (i == 20) // { // //交货地国际五字代码 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PLACEDELIVERYID); // } // else // { // row.CreateCell(1).SetCellValue(order.PLACEDELIVERYID); // } // } // if (i == 21) // { // //ETD // if (order.ETD != null) // { // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(Convert.ToDateTime(order.ETD).ToString("yyyy-MM-dd")); // } // else // { // row.CreateCell(1).SetCellValue(Convert.ToDateTime(order.ETD).ToString("yyyy-MM-dd")); // } // } // //船名 // ICell cell4 = row.GetCell(4); // if (cell4 != null) // { // row.Cells[4].SetCellValue(order.VESSEL); // } // else // { // row.CreateCell(4).SetCellValue(order.VESSEL); // } // } // if (i == 22) // { // //客户协约号 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.CONTRACTNO); // } // else // { // row.CreateCell(1).SetCellValue(order.CONTRACTNO); // } // } // if (i == 23) // { // //航次 // ICell cell = row.GetCell(4); // if (cell != null) // { // row.Cells[4].SetCellValue(order.VOYNO); // } // else // { // row.CreateCell(4).SetCellValue(order.VOYNO); // } // } // if (i == 26) // { // //唛头 // ICell cell = row.GetCell(0); // if (cell != null) // { // row.Cells[0].SetCellValue(order.MARKS); // } // else // { // row.CreateCell(0).SetCellValue(order.MARKS); // } // if (order.PKGS != null) // { // //件数 // ICell cell1 = row.GetCell(1); // if (cell1 != null) // { // row.Cells[1].SetCellValue(order.PKGS.ToString()); // } // else // { // row.CreateCell(1).SetCellValue(order.PKGS.ToString()); // } // } // //包装 // ICell cell2 = row.GetCell(2); // if (cell2 != null) // { // row.Cells[2].SetCellValue(order.KINDPKGS); // } // else // { // row.CreateCell(2).SetCellValue(order.KINDPKGS); // } // //品名 // ICell cell3 = row.GetCell(3); // if (cell3 != null) // { // row.Cells[3].SetCellValue(order.DESCRIPTION); // } // else // { // row.CreateCell(3).SetCellValue(order.DESCRIPTION); // } // if (order.KGS != null) // { // //重量 // ICell cell4 = row.GetCell(4); // if (cell3 != null) // { // row.Cells[4].SetCellValue(order.KGS.ToString()); // } // else // { // row.CreateCell(4).SetCellValue(order.KGS.ToString()); // } // } // if (order.CBM != null) // { // //尺码 // ICell cell5 = row.GetCell(5); // if (cell5 != null) // { // row.Cells[5].SetCellValue(order.CBM.ToString()); // } // else // { // row.CreateCell(5).SetCellValue(order.CBM.ToString()); // } // } // } // if (i == 39) // { // var c = ctn.DistinctBy(x => x.CTNALL).ToList(); // var ctnAll = string.Empty; // foreach (var item in c) // { // ctnAll += $"{ctn.Where(x => x.CTNALL == item.CTNALL).Count()}*{_cache.GetAllMappingCtn().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == item.CTNCODE).Select(x => x.MapCode).First()}+"; // } // ctnAll = ctnAll.Substring(0, ctnAll.Length - 1); // //箱型箱量 // ICell cell = row.GetCell(0); // if (cell != null) // { // row.Cells[0].SetCellValue(ctnAll); // } // else // { // row.CreateCell(0).SetCellValue(ctnAll); // } // } // if (i == 42) // { // //运费支付方式 // var BLFRTCode = _cache.GetAllCodeFrt().Result.Where(x => x.EnName == order.BLFRT).Select(x => x.Code).First(); // var bl = string.Empty; // if (!string.IsNullOrEmpty(BLFRTCode)) // { // bl = _cache.GetAllMappingFrt().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == BLFRTCode).Select(x => x.MapCode).First(); // } // ICell cell = row.GetCell(0); // if (cell != null) // { // row.Cells[0].SetCellValue(bl); // } // else // { // row.CreateCell(0).SetCellValue(bl); // } // } // if (i == 43) // { // //hscode // ICell cell = row.GetCell(3); // if (cell != null) // { // row.Cells[3].SetCellValue(order.HSCODE); // } // else // { // row.CreateCell(3).SetCellValue(order.HSCODE); // } // } // if (i == 44) // { // var BLFRTCode = _cache.GetAllCodeFrt().Result.Where(x => x.EnName == order.BLFRT).Select(x => x.Code).First(); // var bl = string.Empty; // if (!string.IsNullOrEmpty(BLFRTCode)) // { // bl = _cache.GetAllMappingFrt().Result.Where(x => x.Module == "XiangManCangEDI" && x.Code == BLFRTCode).Select(x => x.MapCode).First(); // } // if (bl == "预付") // { // //预付地点 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PREPARDATID); // } // else // { // row.CreateCell(1).SetCellValue(order.PREPARDATID); // } // } // else if ((bl == "到付")) // { // //预付地点 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.PAYABLEATID); // } // else // { // row.CreateCell(1).SetCellValue(order.PAYABLEATID); // } // } // } // if (i == 45) // { // //Name accout // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(edi.EmcNameAccount); // } // else // { // row.CreateCell(1).SetCellValue(edi.EmcNameAccount); // } // } // if (i == 47) // { // //Name accout // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.TEMPSET); // } // else // { // row.CreateCell(1).SetCellValue(order.TEMPSET); // } // //温度 // ICell cell2 = row.GetCell(2); // if (cell2 != null) // { // row.Cells[2].SetCellValue(order.TEMPSET); // } // else // { // row.CreateCell(2).SetCellValue(order.TEMPSET); // } // //湿度 // ICell cell3 = row.GetCell(3); // if (cell2 != null) // { // row.Cells[3].SetCellValue(order.HUMIDITY); // } // else // { // row.CreateCell(3).SetCellValue(order.HUMIDITY); // } // } // if (i == 49) // { // //危险品编号 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.DUNNO); // } // else // { // row.CreateCell(1).SetCellValue(order.DUNNO); // } // } // if (i == 50) // { // //订舱备注 // ICell cell = row.GetCell(1); // if (cell != null) // { // row.Cells[1].SetCellValue(order.SOREMARK); // } // else // { // row.CreateCell(1).SetCellValue(order.SOREMARK); // } // } //} //var fileFullPath = Path.Combine(App.WebHostEnvironment.WebRootPath, App.GetOptions().Path);//服务器路径 //if (!Directory.Exists(fileFullPath)) //{ // Directory.CreateDirectory(fileFullPath); //} //if (!string.IsNullOrEmpty(order.MBLNO)) //{ // fileName = $"{DateTime.Now.Ticks}_{order.MBLNO}.xls";//名称 //} //else //{ // fileName = $"{DateTime.Now.Ticks}_{order.MBLNO}.xls";//名称 //} //_logger.LogInformation("导出excel:" + Path.Combine(fileFullPath, fileName)); //var filestream = new FileStream(Path.Combine(fileFullPath, fileName), FileMode.OpenOrCreate, FileAccess.ReadWrite); //excelwork.Write(filestream); //filestream.Close(); //filestream.Dispose(); //#endregion ////return new FileStreamResult( filestream, "application/octet-stream") { FileDownloadName = fileName }; //var fpath = Path.Combine(fileFullPath, fileName); //var fInfo = new FileInfo(fpath); //_logger.LogInformation("箱满仓文件地址:" + fpath + " " + fInfo); //return new FileStreamResult(new FileStream(fpath, FileMode.Open), "application/octet-stream") { FileDownloadName = fInfo.Name }; #endregion return await XMCEXCEL(id, true); } var model = new BookingOrClosingEDIOrderDto { Id = id, orderNo = orderNo, useForwarderCode = useForwarderCode, forwarderCode = forwarderCode, forwarderName = forwarderName, fileRole = fileRole, send = false, sendType = sendType }; var filePath = InnerBookingOrClosingEDI(model).GetAwaiter().GetResult(); var fileInfo = new FileInfo(filePath); var result = new FileStreamResult(new FileStream(filePath, FileMode.Open), "application/octet-stream") { FileDownloadName = fileInfo.Name }; return result; } #endregion #region 上传FTP /// /// 上传FTP /// /// EDI文件路径 /// FTP配置 /// 返回回执 private async Task InnerSendBookingOrClosingEDIToFTP(string filePath, DjyEdiSetting ediCfg) { CommonWebApiResult result = new CommonWebApiResult { succ = true }; CancellationTokenSource cts = new CancellationTokenSource(); string host = string.Empty; string port = string.Empty; if (ediCfg.SERVERIP.IndexOf(":") >= 0) { host = ediCfg.SERVERIP.Split(new char[] { ':' }).FirstOrDefault().Trim(); port = ediCfg.SERVERIP.Split(new char[] { ':' }).Last()?.Trim(); } NameValueCollection par = new NameValueCollection(); par.Add("host", host); //这里如果配置没有指定端口号默认是21端口 par.Add("port", string.IsNullOrWhiteSpace(port) ? "21" : port); par.Add("username", ediCfg.USERNAME); par.Add("pwd", ediCfg.PASSWORD); par.Add("path", ediCfg.FOLDERNAME); var ftpSpiderUrl = _cache.GetAllDictData().GetAwaiter().GetResult() .FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "booking_edi_ftp_server")?.Value; if (ftpSpiderUrl == null) throw Oops.Bah("字典未配置 url_set->booking_edi_ftp_server 请联系管理员"); //var fileInfo = new FileInfo(filePath); _logger.LogInformation($"准备请求发送ftp:{ftpSpiderUrl} ,参数:{JSON.Serialize(par)},文件:{filePath}"); System.IO.FileStream file = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read); int SplitSize = 5242880;//5M分片长度 int index = 1; //序号 第几片 long StartPosition = 5242880 * (index - 1); long lastLens = file.Length - StartPosition;//真不知道怎么起命了,就这样吧 if (lastLens < 5242880) { SplitSize = (int)lastLens; } byte[] heByte = new byte[SplitSize]; file.Seek(StartPosition, SeekOrigin.Begin); //第一个参数是 起始位置 file.Read(heByte, 0, SplitSize); //第三个参数是 读取长度(剩余长度) file.Close(); string strJoin = System.IO.File.ReadAllText(filePath); DateTime bDate = DateTime.Now; _logger.LogInformation("FTP 开始上传"); var res = FTPHelper.TransmitFtpFile(ftpSpiderUrl, par, new { file = "file", fileName = Path.GetFileName(filePath), fileBytes = heByte }); DateTime eDate = DateTime.Now; TimeSpan ts = eDate.Subtract(bDate); var timeDiff = ts.TotalMilliseconds; _logger.LogInformation($"FTP 上传完成 上传文件大小:{heByte.Length} 用时:{timeDiff}ms.,{strJoin}"); _logger.LogInformation($"发送ftp返回:{res}"); var jobjRetn = JObject.Parse(res); if (jobjRetn.GetStringValue("status") != "1") { result.succ = false; result.msg = jobjRetn.GetStringValue("message"); } return result; } #endregion /// /// EDI发送POST请求 /// /// 文件路径 /// 请求URL /// 配置账户 /// 返回回执 private async Task InnerSendBookingOrClosingEDIToPOST(string filePath, string url, DjyWebsiteAccountConfig accountConfig) { CommonWebApiResult result = new CommonWebApiResult { succ = true }; CancellationTokenSource cts = new CancellationTokenSource(); NameValueCollection par = new NameValueCollection(); par.Add("user_key", App.Configuration["BCOrDraftUserKey"]); par.Add("user_secret", App.Configuration["BCOrDraftUserSecret"]); par.Add("web_user", accountConfig.Account?.Trim()); par.Add("web_psw", accountConfig.Password?.Trim()); _logger.LogInformation($"准备请求发送POST:{url} ,参数:{JSON.Serialize(par)},文件:{filePath}"); System.IO.FileStream file = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read); int SplitSize = 5242880;//5M分片长度 int index = 1; //序号 第几片 long StartPosition = 5242880 * (index - 1); long lastLens = file.Length - StartPosition;//真不知道怎么起命了,就这样吧 if (lastLens < 5242880) { SplitSize = (int)lastLens; } byte[] heByte = new byte[SplitSize]; file.Seek(StartPosition, SeekOrigin.Begin); //第一个参数是 起始位置 file.Read(heByte, 0, SplitSize); //第三个参数是 读取长度(剩余长度) file.Close(); string strJoin = System.IO.File.ReadAllText(filePath); DateTime bDate = DateTime.Now; _logger.LogInformation("POST 开始上传"); var res = FTPHelper.TransmitFtpFile(url, par, new { file = "file", fileName = Path.GetFileName(filePath), fileBytes = heByte }); DateTime eDate = DateTime.Now; TimeSpan ts = eDate.Subtract(bDate); var timeDiff = ts.TotalMilliseconds; _logger.LogInformation($"请求POST 上传完成 上传文件大小:{heByte.Length} 用时:{timeDiff}ms.,{strJoin}"); _logger.LogInformation($"发送POST返回:{res}"); var jobjRetn = JObject.Parse(res); if (jobjRetn.GetStringValue("code") != "200") { result.succ = false; result.msg = jobjRetn.GetStringValue("msg"); } return result; } #region 上传邮件 /// /// 上传邮件 /// /// 订舱详情 /// 文件路径 /// 请求类型 /// EDI配置 /// 返回回执 private async Task InnerSendBookingOrClosingEDIToEmail(BookingOrder bookingOrder, string filePath, string sendType, string emailTopic, DjyEdiSetting ediCfg) { CommonWebApiResult result = new CommonWebApiResult { succ = true }; var emailUrl = _cache.GetAllDictData().GetAwaiter().GetResult() .FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "email_api_url")?.Value; if (emailUrl == null) throw Oops.Bah("字典未配置 url_set->email_api_url 请联系管理员"); List emailList = new List(); EmailApiDto emailApiDto = new EmailApiDto { SendTo = ediCfg.RECEIVEEMAIL, Title = emailTopic, Attaches = new List(), Body = emailTopic, }; System.IO.FileStream file = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read); int SplitSize = 5242880;//5M分片长度 int index = 1; //序号 第几片 long StartPosition = 5242880 * (index - 1); long lastLens = file.Length - StartPosition;//真不知道怎么起命了,就这样吧 if (lastLens < 5242880) { SplitSize = (int)lastLens; } byte[] heByte = new byte[SplitSize]; file.Seek(StartPosition, SeekOrigin.Begin); //第一个参数是 起始位置 file.Read(heByte, 0, SplitSize); //第三个参数是 读取长度(剩余长度) file.Close(); string base64Str = Convert.ToBase64String(heByte); emailApiDto.Attaches.Add(new AttachesInfo { AttachName = Path.GetFileName(filePath), AttachContent = base64Str }); emailList.Add(emailApiDto); string strJoin = System.IO.File.ReadAllText(filePath); DateTime bDate = DateTime.Now; HttpResponseMessage res = null; try { res = await emailUrl.SetBody(emailList, "application/json").PostAsync(); } catch (Exception ex) { _logger.LogInformation($"发送邮件异常:{ex.Message}"); } DateTime eDate = DateTime.Now; TimeSpan ts = eDate.Subtract(bDate); var timeDiff = ts.TotalMilliseconds; _logger.LogInformation($"邮件上传完成 上传文件大小:{heByte.Length} 用时:{timeDiff}ms.,{strJoin}"); _logger.LogInformation($"发送邮件返回:{JSON.Serialize(res)}"); if (res != null && res.StatusCode == System.Net.HttpStatusCode.OK) { var userResult = await res.Content.ReadAsStringAsync(); var respObj = JsonConvert.DeserializeAnonymousType(userResult, new { Success = false, Message = string.Empty, Code = -9999, }); result.succ = respObj.Success; result.msg = respObj.Message; } return result; } #endregion #region /// /// 转发EDI内部方法 /// /// 请求接口地址 /// 键值对参数 /// 文件信息 /// 默认 application/json /// 返回结果 private static string TransmitFtpFile(string requestUrl, NameValueCollection nameValueCollection, dynamic fileInfo, string contentType = "application/json") { var result = string.Empty; using (var httpClient = new HttpClient()) { try { using (var reduceAttach = new MultipartFormDataContent()) { string[] allKeys = nameValueCollection.AllKeys; foreach (string key in allKeys) { var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key])); dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue($"form-data") { Name = key }; reduceAttach.Add(dataContent); } #region 文件参数 if (fileInfo != null) { var Content = new ByteArrayContent(fileInfo.fileBytes); //Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") //{ // Name = fileInfo.file.ToString(), // FileName = fileInfo.fileName.ToString(), //}; Content.Headers.Add("Content-Type", contentType); reduceAttach.Add(Content, fileInfo.file.ToString(), HttpUtility.UrlEncode(fileInfo.fileName.ToString())); } #endregion //请求 var response = httpClient.PostAsync(requestUrl, reduceAttach).Result; result = response.Content.ReadAsStringAsync().Result; } } catch (Exception ex) { result = JSON.Serialize(new { message = $"{nameof(TransmitFtpFile)} 转发EDI内部方法异常,原因:{ex.Message}", status = 0 }); } } return result; } #endregion #region 触发订舱 /// /// 触发订舱 /// /// /// /// /// [NonAction] private async Task InnerSendBookingOrClosingEDI(BookingOrClosingEDIOrderDto model, EDIBaseModel ediModel, EDIRouteEnum ediRouteEnum) { CommonWebApiResult result = new CommonWebApiResult(); try { if (ediRouteEnum == EDIRouteEnum.PIL) { #region PIL string strCheck = PILEdiHelper.IsCreatePILEDI(ediModel); _logger.LogInformation($"调用SO(SI),校验:{strCheck},数据对象:{JsonConvert.SerializeObject(ediModel)}"); if (!string.IsNullOrWhiteSpace(strCheck)) { if (Regex.IsMatch(strCheck, "\\")) { strCheck = Regex.Replace(strCheck, "\\", "\n"); } throw Oops.Bah($"发送{EDIRouteEnum.PIL.ToString()}校验失败,{strCheck}"); } var currRlt = PILEdiHelper.CreateEdiPIL(ediModel); #endregion result.succ = currRlt.succ; result.extra = currRlt.succ ? currRlt.extra.ToString() : ""; result.extra2 = currRlt.succ ? currRlt.extra2.ToString() : ""; } else if (ediRouteEnum == EDIRouteEnum.TSL) { #region TSL string strCheck = TSLEdiHelper.IsCreateTSL(ediModel); _logger.LogInformation($"调用SO(SI),校验:{strCheck},数据对象:{JsonConvert.SerializeObject(ediModel)}"); if (!string.IsNullOrWhiteSpace(strCheck)) { if (Regex.IsMatch(strCheck, "\\")) { strCheck = Regex.Replace(strCheck, "\\", "\n"); } throw Oops.Bah($"发送{EDIRouteEnum.TSL.ToString()}校验失败,{strCheck}"); } CommonWebApiResult currRlt = new CommonWebApiResult(); if (model.sendType == "B") { currRlt = TSLEdiHelper.CreateEdiTSL(ediModel); } else if (model.sendType == "E") { currRlt = TSLEdiHelper.CreateEdiTSLSI(ediModel); } #endregion result.succ = currRlt.succ; result.extra = currRlt.succ ? currRlt.extra.ToString() : ""; } else if (ediRouteEnum == EDIRouteEnum.WY) { #region WY string strCheck = WYEdiHelper.IsCreateWYEDI(ediModel); _logger.LogInformation($"调用SO(SI),校验:{strCheck},数据对象:{JsonConvert.SerializeObject(ediModel)}"); if (!string.IsNullOrWhiteSpace(strCheck)) { if (Regex.IsMatch(strCheck, "\\")) { strCheck = Regex.Replace(strCheck, "\\", "\n"); } throw Oops.Bah($"发送{EDIRouteEnum.WY.ToString()}校验失败,{strCheck}"); } var currRlt = WYEdiHelper.CreateEdiWY(ediModel); #endregion result.succ = currRlt.succ; result.extra = currRlt.succ ? currRlt.extra.ToString() : ""; } else if (ediRouteEnum == EDIRouteEnum.YML) { #region YML string strCheck = YMLEdiHelper.IsCreateYMLEDI(ediModel); _logger.LogInformation($"调用SO(SI),校验:{strCheck},数据对象:{JsonConvert.SerializeObject(ediModel)}"); if (!string.IsNullOrWhiteSpace(strCheck)) { if (Regex.IsMatch(strCheck, "\\")) { strCheck = Regex.Replace(strCheck, "\\", "\n"); } throw Oops.Bah($"发送{EDIRouteEnum.YML.ToString()}校验失败,{strCheck}"); } CommonWebApiResult currRlt = new CommonWebApiResult(); if (model.sendType == "B") { currRlt = YMLEdiHelper.CreateEdiYML(ediModel); } else if (model.sendType == "E") { currRlt = YMLEdiHelper.CreateEdiYMLSI(ediModel); } #endregion result.succ = currRlt.succ; result.extra = currRlt.succ ? currRlt.extra.ToString() : ""; } else if (ediRouteEnum == EDIRouteEnum.YT) { #region YT string strCheck = YTEdiHelper.IsCreateYTEDI(ediModel); _logger.LogInformation($"调用SO(SI),校验:{strCheck},数据对象:{JsonConvert.SerializeObject(ediModel)}"); if (!string.IsNullOrWhiteSpace(strCheck)) { if (Regex.IsMatch(strCheck, "\\")) { strCheck = Regex.Replace(strCheck, "\\", "\n"); } throw Oops.Bah($"发送{EDIRouteEnum.YT.ToString()}校验失败,{strCheck}"); } CommonWebApiResult currRlt = YTEdiHelper.CreateEdiYT(ediModel); #endregion result.succ = currRlt.succ; result.extra = currRlt.succ ? currRlt.extra.ToString() : ""; } else if (ediRouteEnum == EDIRouteEnum.ESL) { #region ESL string strCheck = ESLEdiHelper.IsCreateESLEDI(ediModel); _logger.LogInformation($"调用SO(SI),校验:{strCheck},数据对象:{JsonConvert.SerializeObject(ediModel)}"); if (!string.IsNullOrWhiteSpace(strCheck)) { if (Regex.IsMatch(strCheck, "\\")) { strCheck = Regex.Replace(strCheck, "\\", "\n"); } throw Oops.Bah($"发送{EDIRouteEnum.ESL.ToString()}校验失败,{strCheck}"); } CommonWebApiResult currRlt = ESLEdiHelper.CreateEdiESL(ediModel); #endregion result.succ = currRlt.succ; result.extra = currRlt.succ ? currRlt.extra.ToString() : ""; } else if (ediRouteEnum == EDIRouteEnum.MELL) { #region MELL string strCheck = MellEdiHelper.IsCreatePILMELL(ediModel); _logger.LogInformation($"调用SO(SI),校验:{strCheck},数据对象:{JsonConvert.SerializeObject(ediModel)}"); if (!string.IsNullOrWhiteSpace(strCheck)) { if (Regex.IsMatch(strCheck, "\\")) { strCheck = Regex.Replace(strCheck, "\\", "\n"); } throw Oops.Bah($"发送{EDIRouteEnum.MELL.ToString()}校验失败,{strCheck}"); } var currRlt = MellEdiHelper.CreateEdiPILMELL(ediModel); #endregion result.succ = currRlt.succ; result.extra = currRlt.succ ? currRlt.extra.ToString() : ""; result.extra2 = currRlt.succ ? currRlt.extra2.ToString() : ""; } } catch (Exception ex) { result.succ = false; result.msg = ex.Message; } return result; } #endregion #region 检查订舱、截单EDI订单信息 /// /// 检查订舱、截单EDI订单信息 /// /// [NonAction] private void CheckBookingOrClosingEDI(BookingOrder order, List ctnList) { if (string.IsNullOrWhiteSpace(order.CARRIERID)) throw Oops.Bah("船公司必须填写"); //if (string.IsNullOrWhiteSpace(order.OPID)) // throw Oops.Bah("未填写操作人"); if (string.IsNullOrWhiteSpace(order.KINDPKGS)) throw Oops.Bah("包装种类未填写"); //增加箱包装和主信息的包装是否一致校验 if (ctnList.Any(a => a.KINDPKGS != order.KINDPKGS)) { throw Oops.Bah("集装箱包装和订舱包装不一致,请修改"); } //如果合同协议号不为空需要判断是否字符前、后有空格,不允许字符前后有空格,需要提示修改 if (!string.IsNullOrWhiteSpace(order.CONTRACTNO)) { if (order.CONTRACTNO.StartsWith(" ")) throw Oops.Bah("运费协议号前含有空格,请修改"); if (order.CONTRACTNO.EndsWith(" ")) throw Oops.Bah("运费协议号后含有空格,请修改"); } //增加件、重、尺比对 if (ctnList != null && ctnList.Count > 0) { if (ctnList.Sum(a => a.PKGS.HasValue ? a.PKGS.Value : 0) != (order.PKGS.HasValue ? order.PKGS.Value : 0)) { throw Oops.Bah("集装箱件数合计和订舱件数不一致,请修改"); } if (ctnList.Sum(a => a.KGS.HasValue ? a.KGS.Value : 0) != (order.KGS.HasValue ? order.KGS.Value : 0)) { throw Oops.Bah("集装箱重量合计和订舱重量不一致,请修改"); } if (ctnList.Sum(a => a.CBM.HasValue ? a.CBM.Value : 0) != (order.CBM.HasValue ? order.CBM.Value : 0)) { throw Oops.Bah("集装箱尺码合计和订舱尺码不一致,请修改"); } } } #endregion #region 根据船公司ID获取EDI的路由枚举 /// /// 根据船公司ID获取EDI的路由枚举 /// /// 船公司ID /// 返回适用的路由枚举 [NonAction] private EDIRouteEnum GetEDIRoute(string carrierId) { EDIRouteEnum routeEnum = EDIRouteEnum.NULL; var ediRouteCfg = _cache.GetAllMappingCarrier().GetAwaiter().GetResult() .FirstOrDefault(t => t.Module.Equals(CONST_MAPPING_MODULE_ROUTE, StringComparison.OrdinalIgnoreCase) && t.Code.Equals(carrierId, StringComparison.OrdinalIgnoreCase)); if (ediRouteCfg != null && !string.IsNullOrWhiteSpace(ediRouteCfg.MapCode)) routeEnum = (EDIRouteEnum)System.Enum.Parse(typeof(EDIRouteEnum), ediRouteCfg.MapCode); //switch (carrierId.ToUpper()) //{ // case "PIL": // routeEnum = EDIRouteEnum.PIL; // break; // case "ONE": // routeEnum = EDIRouteEnum.YT; // break; // case "TSL": // routeEnum = EDIRouteEnum.TSL; // break; // case "YML": // routeEnum = EDIRouteEnum.YML; // break; // case "WY": // routeEnum = EDIRouteEnum.WY; // break; //} return routeEnum; } #endregion #region ocr /// /// 上传ocr文件 /// /// /// 订舱id(新建的单据传0) /// [HttpPost("/BookingOrder/OcrUpFile")] public async Task OcrUpFile(IFormFile file, long bookingId) { var output = new OcrUploadOutputDto(); //未上传文件 if (file == null || file.Length == 0) { throw Oops.Bah("未上传文件"); } //保存到订舱 output.UploadFileName = await AddFile(file, new BookingFileDto() { BookingId = bookingId, TypeCode = "other", TypeName = "其他" }); var originalFilename = file.FileName; // 文件原始名称 var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀 var serverUrl = (await _cache.GetAllDictData()).FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "ocr_api_url").Value; if (!serverUrl.EndsWith("/")) { serverUrl += "/"; } var ms = new MemoryStream(); await file.CopyToAsync(ms); _logger.LogInformation($"调用ocr处理文件{originalFilename}"); //Furion框架上传文件名称带有双引号,导致上传失败 //var strRtn = await $"{serverUrl}pdf/upload" // .SetContentType("multipart/form-data") // .SetContentEncoding(Encoding.UTF8) // .SetBodyBytes(("file", ms.GetBuffer(), "test.pdf")) // .PostAsStringAsync(); //var jobj = strRtn.ToJObject(); //if (jobj.GetIntValue("code") == 0) //{ // var fn = jobj.GetStringValue("data"); // return fn; //} //else //{ // throw Oops.Bah(jobj.GetStringValue("message")); //} //使用HttpClient方式上传文件 ms.Position = 0; var formData = new MultipartFormDataContent(); formData.Add(new StreamContent(ms, (int)ms.Length), "file", originalFilename); var _httpclient = new HttpClient(); var response = await _httpclient.PostAsync($"{serverUrl}pdf/upload", formData); if (response.IsSuccessStatusCode) { var strRtn = response.Content.ReadAsStringAsync().Result; var jobj = strRtn.ToJObject(); if (jobj.GetIntValue("code") == 0) { output.OcrFileName = jobj.GetStringValue("data"); return output; } else { throw Oops.Bah(jobj.GetStringValue("message")); } } throw Oops.Bah("文件上传失败"); } /// /// 获取图片 /// /// 文件名称 /// 缩放比例,默认为1.5 /// [HttpPost("/BookingOrder/OcrGetImg")] public async Task OcrGetImg(string fileName, float scale = 1.5f) { var serverUrl = (await _cache.GetAllDictData()).FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "ocr_api_url").Value; if (!serverUrl.EndsWith("/")) { serverUrl += "/"; } var bs = await $"{serverUrl}pdf/getCanvasImage?fileName={fileName}&scale={scale}" .GetAsByteArrayAsync(); var result = new FileContentResult(bs, "application/octet-stream") { FileDownloadName = "ocr.jpg" }; return result; } /// /// 获取文字 /// /// 文件名称 /// 缩放比例 /// x坐标 /// y坐标 /// 宽度 /// 高度 /// [HttpPost("/BookingOrder/OcrGetText")] public async Task OcrGetText(string fileName, float scale, int x, int y, int w, int h) { var serverUrl = (await _cache.GetAllDictData()).FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "ocr_api_url").Value; if (!serverUrl.EndsWith("/")) { serverUrl += "/"; } var str = await $"{serverUrl}pdf/getRegionText?fileName={fileName}&scale={scale}&x={x}&y={y}&w={w}&h={h}" .PostAsStringAsync(); return str; } #endregion #region 其他 /// /// 获取用户报表的json /// /// [HttpGet("/BookingOrder/GenReportJson")] public async Task GenReportJson(long id) { var jsonUrl = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "url_report_generate").Value; if (!jsonUrl.EndsWith("/")) { jsonUrl += "/"; } jsonUrl += "Report/BookingReportJson?bookingId=" + id; var rtn = await jsonUrl.SetHttpMethod(HttpMethod.Get).GetAsStringAsync(); var fileName = HttpUtility.UrlEncode($"{id}.json", Encoding.GetEncoding("UTF-8")); var result = new FileContentResult(Encoding.UTF8.GetBytes(rtn), "application/octet-stream") { FileDownloadName = fileName }; return result; } /// /// 生成报表文件 /// /// /// 类型,对应字典中的【订舱打印模板类型】 /// [HttpGet("/BookingOrder/GenReportFile")] public async Task GenReportFile(long id, string type) { //打印报表服务地址 var reportUrl = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "url_report_generate").Value; if (!reportUrl.EndsWith("/")) { reportUrl += "/"; } //订舱数据 var order = _rep.FirstOrDefault(x => x.Id == id); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } //打印模板 var printTemplate = _repPrint.FirstOrDefault(x => x.TenantId == order.TenantId && x.TypeCode == type); if (printTemplate == null) { throw Oops.Bah(BookingErrorCode.BOOK112); } //读取配置路劲 var opt = App.GetOptions(); var dirAbs = opt.basePath; if (string.IsNullOrEmpty(dirAbs)) { dirAbs = App.WebHostEnvironment.WebRootPath; } //读取模板并调用接口 var fileAbsPath = Path.Combine(dirAbs, printTemplate.FilePath).ToLower(); if (!File.Exists(fileAbsPath)) { throw Oops.Bah(BookingErrorCode.BOOK112); } _logger.LogInformation($"准备调用报表生成:id:{id},文件:{printTemplate.FileName}"); var genUrl = reportUrl + "Report/BookingReport?bookingId=" + id; var rtn = await genUrl .SetContentType("multipart/form-data") .SetBodyBytes(("file", File.ReadAllBytes(fileAbsPath), HttpUtility.UrlEncode(printTemplate.FileName, Encoding.GetEncoding("UTF-8")))) .PostAsStringAsync(); var jobjRtn = JObject.Parse(rtn); _logger.LogInformation($"调用报表生成返回:{rtn}"); if (jobjRtn.GetBooleanValue("Success")) { //调用读取文件 var fn = jobjRtn.GetStringValue("Data"); _logger.LogInformation($"准备调用读取文件:id:{id},文件名:{fn}"); var readFileUrl = reportUrl + "Report/GetFile?fileName=" + fn; var bs = await readFileUrl.GetAsByteArrayAsync(); _logger.LogInformation($"调用读取文件返回:{bs.Length}"); var fileName = HttpUtility.UrlEncode($"{id}_{type}_{DateTime.Now.Ticks}.pdf", Encoding.GetEncoding("UTF-8")); var result = new FileContentResult(bs, "application/octet-stream") { FileDownloadName = fileName }; return result; } else { throw Oops.Bah($"生成报表文件失败:{jobjRtn.GetStringValue("Message")}"); } } /// /// 自动引入场站数据消息已读 /// /// [HttpGet("/BookingOrder/ReadAutoYardImport")] public async Task ReadAutoYardImport(long bookId) { var model = _repAutoYard.FirstOrDefault(x => x.Id == bookId); if (model != null) { model.IsRead = true; model.ReadTime = DateTime.Now; model.ReadUser = UserManager.Name; await _repAutoYard.UpdateAsync(model); } } /// /// 获取场站数据 /// /// /// /// [HttpGet("/BookingOrder/GetYardData")] public async Task GetYardData(long bookingId, bool isWeb = false) { //订舱数据 var order = _rep.FirstOrDefault(x => x.Id == bookingId); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } if (string.IsNullOrEmpty(order.YARDID)) { throw Oops.Bah("请先选择场站"); } var listRtn = await GetYardDataAndMappingSystem(order, isWeb); return listRtn.ToJsonString(); } /// /// 获取订舱记录在指定网站的HTML数据 /// /// 订舱记录主键 /// 网站编码;值为YARD或HLW_CD或YGT;YARD:获取订舱记录所属场站的网页数据;HLW_CD:获取互联网+的网页数据;YGT:获取云港通的网页数据 [HttpGet("/BookingOrder/GetWebData")] public async Task GetWebData(long bookingId, string webCode) { //订舱数据 var order = _rep.FirstOrDefault(x => x.Id == bookingId); if (order == null) { throw Oops.Bah(BookingErrorCode.BOOK001); } if (string.IsNullOrEmpty(order.YARDID)) { throw Oops.Bah("请先选择场站"); } WebCodeEnum codeEnum = webCode switch { "YARD" => WebCodeEnum.YARD, "HLW_CD" => WebCodeEnum.HLW_CD, "YGT" => WebCodeEnum.YGT, _ => throw Oops.Bah("webCode参数错误") }; var rtn = await WebDataHelper.GetWebData(App.User.FindFirst(ClaimConst.CLAINM_USERID) == null ? order.CreatedUserId.Value : UserManager.UserId, order.TenantId.Value, order.TenantName, order.MBLNO, codeEnum, order.YARDID); if (!rtn.Key) { throw Oops.Bah(rtn.Value); } return rtn.Value; } /// /// 从爬虫获取场站数据,并映射为系统中的箱型 /// /// private async Task> GetYardDataAndMappingSystem(BookingOrder order, bool isWeb = false) { var rtn = await YardDataHelper.GetYardData(App.User.FindFirst(ClaimConst.CLAINM_USERID) == null ? order.CreatedUserId.Value : UserManager.UserId, order.TenantId.Value, order.TenantName, order.MBLNO, order.YARDID, isWeb); if (!rtn.Key) { throw Oops.Bah(rtn.Value); } //场站引入的数据,转换为订舱箱型,且带上箱型代码 var ctnList = await _cache.GetAllCodeCtn(); var mapCtn = await _cache.GetAllMappingCtn(); var listRtn = JsonConvert.DeserializeObject>(rtn.Value); foreach (var item in listRtn) { var ctnall = item.CTNALL; var findMap = mapCtn.FirstOrDefault(x => x.Module == "YardData" && x.MapCode == ctnall); var findCtn = ctnList.FirstOrDefault(x => x.Name == ctnall); if (findMap != null) { item.CtnCode = findMap.Code; findCtn = ctnList.First(c => c.Code == findMap.Code); item.CTNALL = findCtn.Name; //名称显示维护的箱型 } else if (findCtn != null) { item.CtnCode = findCtn.Code; item.CTNALL = findCtn.Name; //名称显示维护的箱型 } else { throw Oops.Bah($"未找到箱型{ctnall}的场站引入配置"); } } return listRtn; } /// /// 自动引入场站箱型箱量数据 /// /// /// public async Task AutoYardData(long bookId) { var order = _rep.AsQueryable().Filter(null, true).First(x => x.Id == bookId); var paraAuto = _cache.GetAllTenantParam().Result.FirstOrDefault(x => x.TenantId == order.TenantId && x.ParaCode == "AUTO_CNTRNO_SEALNO_IMPORT"); if (paraAuto == null || paraAuto.ItemCode != "YES") { _logger.LogInformation($"{order.TenantName}未开启自动箱号引入"); return; } var ctns = _repCtn.AsQueryable().Filter(null, true).Where(x => x.BILLID == bookId).ToList(); if (ctns.Count(x => !string.IsNullOrEmpty(x.CNTRNO) || !string.IsNullOrEmpty(x.SEALNO)) > 0) //有数据填写了箱封号,不再处理 { _logger.LogInformation($"{bookId}({order.MBLNO})的数据已填写过箱封号,不再处理自动引入"); //写入提示 await SaveAutoYardData(bookId, false, $"已有箱封号,不再处理自动引入", ctns.ToJson(), ""); return; } var ctnAllMulti = ctns.GroupBy(x => x.CTNALL).Select(x => new { CTNALL = x.Key, COUNT = x.Count() }).Count(x => x.COUNT > 1); if (ctnAllMulti > 0) //有箱型填写超过1行,展开过箱量,不再处理 { //写入提示 await SaveAutoYardData(bookId, false, $"箱量已展开,无法处理数据引入", ctns.ToJson(), ""); return; } /* 孙晓菲: HLCUTA12307DPXJ3 以这票为例 6个柜 录单的时候件重尺就没填 是0 所以展开箱量的时候件重尺也都会是0 在引入场站数据的时候,件重尺直接覆盖即可 另一种情况,录单的时候件重尺有填写,所以展开箱量的时候件重尺也会自动均分且有数字 在引入场站数据的时候,件重尺可以直接覆盖或者不覆盖 但要给操作提醒 此处件重尺不一致 */ /* 分析: 单行20GP*6这种,无件重尺,场站箱数和填写箱数一致,则自动展开覆盖 单行20GP*6这种,件重尺任意一个填写过,场站箱数一致,且均分后的件重尺匹配填写的件重尺,则自动展开覆盖 */ var match = true; var rtn = await GetYardDataAndMappingSystem(order, false); //拉取场站的数据 //2023-8-31,调用此方法的时并未判断全部提箱,因此,这里内部判断一下 if (rtn[0].XiangLiang > rtn.Count) { _logger.LogInformation($"{order.MBLNO}({order.Id})未全部提箱,暂不处理"); return; } var groupYardList = rtn.GroupBy(x => x.CTNALL).Select(x => new { CTNALL = x.Key, COUNT = x.Count() }).ToList(); //按箱型分组计算箱量(场站) var groupCtnDist = ctns.Select(x => x.CTNALL).Distinct().ToList(); if (groupYardList.Count != groupCtnDist.Count) { //箱型不匹配 match = false; //写入提示 await SaveAutoYardData(bookId, false, $"箱型不匹配,场站:{string.Join("、", groupCtnDist)},填写:{string.Join("、", groupYardList.Select(x => x.CTNALL))}", ctns.ToJson(), rtn.ToJson()); } else { foreach (var item in groupYardList) { var find = ctns.FirstOrDefault(x => x.CTNALL == item.CTNALL); if (find == null) { //箱型不匹配 match = false; //写入提示 await SaveAutoYardData(bookId, false, $"箱型不匹配,场站:{item.CTNALL},填写:未找到", ctns.ToJson(), rtn.ToJson()); break; } if (find.CTNNUM.Value != item.COUNT) { //item.CTNALL 箱数不匹配 match = false; //写入提示 await SaveAutoYardData(bookId, false, $"箱型箱量不匹配,场站:{item.CTNALL}*{item.COUNT},填写:{find.CTNALL}*{find.CTNNUM}", ctns.ToJson(), rtn.ToJson()); break; } } } //箱型 箱量都校验过了,校验件重尺 if (match) { var listPKGS = ctns.Where(x => x.PKGS > 0).ToList(); //填写了件数 foreach (var item in listPKGS) { var sumPkgs = rtn.Where(x => x.CTNALL == item.CTNALL).Sum(x => x.PKGS); if (sumPkgs != item.PKGS) { //件数不一致 match = false; //写入提示 await SaveAutoYardData(bookId, false, $"件数不一致,场站:{sumPkgs},填写:{item.PKGS}", ctns.ToJson(), rtn.ToJson()); break; } } var listKGS = ctns.Where(x => x.KGS > 0).ToList(); //填写了重量 foreach (var item in listKGS) { var sumKgs = rtn.Where(x => x.CTNALL == item.CTNALL).Sum(x => x.KGS); if (Convert.ToDecimal(sumKgs.Value) != item.KGS.Value) { //重量不一致 match = false; //写入提示 await SaveAutoYardData(bookId, false, $"重量不一致,场站:{sumKgs},填写:{item.KGS}", ctns.ToJson(), rtn.ToJson()); break; } } var listCBM = ctns.Where(x => x.CBM > 0).ToList(); //填写了尺码 foreach (var item in listCBM) { var sumCBM = rtn.Where(x => x.CTNALL == item.CTNALL).Sum(x => x.CBM); if (Convert.ToDecimal(sumCBM.Value) != item.CBM.Value) { //尺码不一致 match = false; //写入提示 await SaveAutoYardData(bookId, false, $"尺码不一致,场站:{sumCBM},填写:{item.CBM}", ctns.ToJson(), rtn.ToJson()); break; } } } if (match) { var cfgDevSwitch = (await _cache.GetAllSysConfig()).FirstOrDefault(x => x.Code == "AutoYardDataDevOpId"); if (cfgDevSwitch != null && (cfgDevSwitch.Value == "all" || (!string.IsNullOrEmpty(order.OPID) && cfgDevSwitch.Value.Contains(order.OPID.ToString())))) { await _repCtn.DeleteAsync(x => x.BILLID == bookId); _logger.LogInformation($"{bookId}({order.MBLNO})的箱封号自动引入获取场站数据:{rtn.ToJsonString()}"); //场站数据的包装经常为空,因此取场站数据时,如果包装为空,从主信息或填写过的箱信息的包装中获取 var ctnKindPkg = ctns.FirstOrDefault(x => !string.IsNullOrEmpty(x.KINDPKGS)); var kindPkg = order.KINDPKGS; if (string.IsNullOrEmpty(kindPkg) && ctnKindPkg != null) { kindPkg = ctnKindPkg.KINDPKGS; } foreach (var item in rtn) { var ctn = new BookingCtn(); ctn.BILLID = order.Id; ctn.CTNCODE = item.CtnCode; ctn.CTNALL = item.CTNALL; ctn.CTNNUM = 1; ctn.CNTRNO = item.CNTRNO; ctn.SEALNO = item.SEALNO; ctn.KINDPKGS = string.IsNullOrEmpty(item.KINDPKGS) ? kindPkg : item.KINDPKGS; ctn.PKGS = item.PKGS; ctn.KGS = Convert.ToDecimal(item.KGS); ctn.CBM = Convert.ToDecimal(item.CBM); ctn.TAREWEIGHT = Convert.ToDecimal(item.TAREWEIGHT); ctn.TenantId = order.TenantId; ctn.CreatedUserId = order.CreatedUserId; ctn.CreatedUserName = "系统"; await _repCtn.InsertAsync(ctn); } _logger.LogInformation($"{bookId}({order.MBLNO})的箱封号自动引入完成"); //写入提示 await SaveAutoYardData(bookId, true, $"已自动引入", ctns.ToJson(), rtn.ToJson()); } else { //写入提示 await SaveAutoYardData(bookId, true, $"已自动引入", ctns.ToJson(), rtn.ToJson(), read: true); } } } /// /// 写入自动引入场站数据信息数据 /// /// [NonAction] private async Task SaveAutoYardData(long bookId, bool success, string content, string ctnJson, string yardJson, bool read = false) { await _repAutoYard.DeleteAsync(x => x.Id == bookId); //写入提示 var autoYard = new BookingAutoYardImport(); autoYard.Id = bookId; autoYard.Status = success ? "已导入" : "未导入"; autoYard.Content = content; autoYard.CtnJson = ctnJson; autoYard.YardJson = yardJson; if (read) //未开启自动写入的用户,自动已读 { autoYard.IsRead = true; autoYard.ReadTime = DateTime.Now; autoYard.ReadUser = "系统"; } await _repAutoYard.InsertAsync(autoYard); } /// /// 记录或更新订舱状态 /// /// /// /// /// [NonAction] public async Task SaveBookingStatus(long bookingId, string code, string name) { var bookSta = _repBookingStatus.FirstOrDefault(x => x.BookingId == bookingId && x.StaCode == code); if (bookSta == null) { //记录状态 bookSta = new BookingStatus(); bookSta.BookingId = bookingId; bookSta.StaCode = code; bookSta.StaName = name; bookSta.StaTime = DateTime.Now; await _repBookingStatus.InsertAsync(bookSta); } else { bookSta.StaTime = DateTime.Now; await _repBookingStatus.UpdateAsync(bookSta); } } /// /// 下拉获取字段名称 /// /// [HttpGet("/BookingOrder/GetFieldName")] public async Task GetFieldName() { BookingOrder order = new BookingOrder(); BookingCtn ctn = new BookingCtn(); BookingEDIExt edi = new BookingEDIExt(); Dictionary dic = new Dictionary(); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(order)) { string name = descriptor.Name; if (name == "TenantId" || name == "CreatedTime" || name == "UpdatedTime" || name == "CreatedUserId" || name == "CreatedUserName") { continue; } if (!string.IsNullOrWhiteSpace(descriptor.Description)) { dic.Add("order." + descriptor.Name, descriptor.Description); } } dic.Add("order._PKGS", "件数(包装)"); dic.Add("order._KGS", "毛重(KGS)"); dic.Add("order._CBM", "尺码(CBM)"); Dictionary dic1 = new Dictionary(); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(ctn)) { string name = descriptor.Name; if (name == "TenantId" || name == "CreatedTime" || name == "UpdatedTime" || name == "CreatedUserId" || name == "CreatedUserName") { continue; } if (!string.IsNullOrWhiteSpace(descriptor.Description)) { dic1.Add("ctn." + descriptor.Name, descriptor.Description); } } Dictionary dic2 = new Dictionary(); foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(edi)) { string name = descriptor.Name; if (name == "TenantId" || name == "CreatedTime" || name == "UpdatedTime" || name == "CreatedUserId" || name == "CreatedUserName") { continue; } if (!string.IsNullOrWhiteSpace(descriptor.Description)) { dic2.Add("edi." + descriptor.Name, descriptor.Description); } } Dictionary dic3 = new Dictionary(); dic3.Add("userinfo.username", "当前登录人"); dic3.Add("userinfo.usertel", "当前登录人电话"); dic3.Add("userinfo.usermobile", "当前登录人手机"); dic3.Add("userinfo.useremail", "当前登录人邮箱"); dic3.Add("userinfo.usertenant", "当前登录人所在公司"); var dynamic = new { order = dic, ctn = dic1, edi = dic2, userinfo = dic3 }; return dynamic; } /// /// 获取订舱数据接口 备注 、 文件 、日志、服务项目、状态日志 /// /// [HttpGet("/BookingOrder/GetAllData")] public async Task GetAllData(long bookingId) { var traceTime = false; var ticks = DateTime.Now; if (traceTime) { _logger.LogInformation($"{bookingId} GetAllData Stage 0 "); } BookingAllData allData = new BookingAllData(); if (bookingId == 0) { return allData; } //服务项目 var itemlist = await _serviceItem.AsQueryable().Where(x => x.BookingId == bookingId).ToListAsync(); allData.item = itemlist; //备注 var remarklist = await _bookingremark.AsQueryable().Where(u => u.PId == bookingId).ToListAsync(); allData.remark = remarklist; //附件 var filelist = await _bookingfile.AsQueryable().Filter(null, true).Where(u => u.BookingId == bookingId).ToListAsync(); allData.file = filelist; if (traceTime) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogInformation($"GetAllData Stage 1 {et.TotalMilliseconds}"); } //日志 var statuslog = await _repStatuslog.AsQueryable().Filter(null, true).Where(x => x.BookingId == bookingId).OrderByDescending(x => x.OpTime).ToListAsync(); var dto = statuslog.Adapt>(); //状态日志 var statuslogdetail = await _statuslogdetail.AsQueryable().ToListAsync(); foreach (var item in dto) { var detail = statuslogdetail.Where(x => x.PId == item.Id).ToList(); item.detail = detail.Adapt>(); } allData.statuslog = dto; if (traceTime) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogInformation($"GetAllData Stage 2 {et.TotalMilliseconds}"); } List list = new List(); var main = await _bookinglog.AsQueryable().Where(u => u.BookingId == bookingId).ToListAsync(); var mailidlist = main.Select(x => x.Id).ToList(); list = main.Adapt>(); if (list != null) { var bookinglogdetail = await _bookinglogdetail.AsQueryable().Where(x => mailidlist.Contains(x.PId)).ToListAsync(); foreach (var item in list) { var details = bookinglogdetail.Where(x => x.PId == item.Id).ToList(); item.details = details; } } allData.log = list; if (traceTime) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogInformation($"GetAllData Stage 3 {et.TotalMilliseconds}"); } var order = _rep.Where(x => x.Id == bookingId).First(); var userid = order.CreatedUserId; var username = order.CreatedUserName; //货物状态 if (userid != null) { _GoodsConfig.InitGoodsStatusConfig(Convert.ToInt64(userid), username); if (traceTime) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogInformation($"GetAllData Stage 4 {et.TotalMilliseconds}"); } var GoodsStatus = await _goodsStatus.AsQueryable().LeftJoin(_goodsStatusConfig.AsQueryable(), (goods, config) => config.Id == goods.ConfigId).Where((goods, config) => config.CreatedUserId == userid && goods.bookingId == bookingId). OrderBy((goods, config) => config.Sort). Select((goods, config) => new GoodsStatusQuery { ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = goods.FinishTime, FinishUser = goods.FinishUser, FinishUserId = goods.FinishUserId, IsPublic = goods.IsPublic, ExtData = goods.ExtData, Remark = goods.Remark, Sort = config.Sort }).ToListAsync(); if (traceTime) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogInformation($"GetAllData Stage 5 {et.TotalMilliseconds}"); } var config = _goodsStatusConfig.AsQueryable().Where(config => config.CreatedUserId == userid).ToList().Select(config => new GoodsStatusQuery { ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = null, FinishUser = null, FinishUserId = null, IsPublic = false, ExtData = null, Remark = null, Sort = config.Sort }).ToList(); if (traceTime) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogInformation($"GetAllData Stage 6 {et.TotalMilliseconds}"); } foreach (var item in GoodsStatus) { config.RemoveAll(x => x.ConfigId == item.ConfigId); } allData.GoodsStatus = GoodsStatus.Union(config).OrderBy(x => x.Sort).DistinctBy(x => x.StatusName).ToList(); if (traceTime) { var et = DateTime.Now - ticks; ticks = DateTime.Now; _logger.LogInformation($"GetAllData Stage 7 {et.TotalMilliseconds}"); } } //自动引入场站记录信息 allData.AutoYardImport = _repAutoYard.FirstOrDefault(x => x.Id == bookingId && !x.IsRead); return allData; } /// ///获取下拉前10条接口 /// /// [HttpGet("/BookingOrder/GetAllSelectData")] public async Task GetAllSelectData() { ////报关行 var BGH = _djycustomer.Where(x => x.PropString.Contains("customs_broker") && x.TenantId == UserManager.TENANT_ID).Take(10).ToList(); //车队 var CD = _djycustomer.Where(x => x.PropString.Contains("fleet") && x.TenantId == UserManager.TENANT_ID).Take(10).ToList(); //国外代理 var GWDL = _djycustomer.Where(x => x.PropString.Contains("out_agent") && x.TenantId == UserManager.TENANT_ID).Take(10).ToList(); //仓库 var CK = _djycustomer.Where(x => x.PropString.Contains("warehouse") && x.TenantId == UserManager.TENANT_ID).Take(10).ToList(); var Portload = _cache.GetAllCodePortLoad().Result.Take(10).ToList(); List list = await _cache.GetAllCodePort(); var listLineRela = await _cache.GetAllRelaPortCarrierLane(); var listLine = await _cache.GetAllCodeLane(); List result = null; result = list.Take(10).ToList(); result.ForEach(x => { var query = from line in listLine join lineRel in listLineRela on line.Code equals lineRel.LaneCode where lineRel.PortCode == x.Code select new { line, lineRel }; x.LineName = query.Select(x => new { x.line.CnName, x.lineRel.CarrierCode }).Take(10).ToList(); }); //收发通 var TemplateIds = _repPrintTemplateShare.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.ShareToId == UserManager.UserId).Select(x => x.TemplateId).ToList(); var STemplate = _bookingTemplate.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && (TemplateIds.Contains(x.Id) || x.CreatedUserId == UserManager.UserId) && x.Type == "10" && x.CreatedUserId == UserManager.UserId).Take(10).ToList(); var FTemplate = _bookingTemplate.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && (TemplateIds.Contains(x.Id) || x.CreatedUserId == UserManager.UserId) && x.Type == "20" && x.CreatedUserId == UserManager.UserId).Take(10).ToList(); var TTemplate = _bookingTemplate.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && (TemplateIds.Contains(x.Id) || x.CreatedUserId == UserManager.UserId) && x.Type == "30" && x.CreatedUserId == UserManager.UserId).Take(10).ToList(); //委托单位 var WTDW = _djycustomer.Where(x => x.PropString.Contains("consignor") && x.TenantId == UserManager.TENANT_ID).Take(10).ToList(); //订舱代理 var DCDL = _djycustomer.Where(x => x.PropString.Contains("booking_agent") && x.TenantId == UserManager.TENANT_ID).Take(10).ToList(); //船代 var Forwarder = _cache.GetAllCodeForwarder().Result.Take(10).ToList(); //货物品名 var GoodsName = _paraGoodsInfoRepository.AsQueryable().OrderBy("GOODS_CODE asc").Take(50).ToList().Select(t => t.Adapt()).ToList(); var YFXY = _paraContractNoInfoRepository.AsQueryable().OrderBy("CONTRACT_NO asc").Take(10).ToList().Select(t => t.Adapt()).ToList(); ; var User = await _repUser.AsQueryable().Filter(null, true).Where(x => x.TenantId == UserManager.TENANT_ID && x.Status == CommonStatus.ENABLE && x.IsDeleted == false).OrderBy(x => x.Name).ToListAsync(); //服务项目 var Service = _cache.GetAllCodeService().Result.Take(10).ToList(); dynamic obj = new { BGH = BGH, CD = CD, GWDL = GWDL, CK = CK, Portload = Portload, Port = result, STemplate = STemplate, FTemplate = FTemplate, TTemplate = TTemplate, WTDW = WTDW, DCDL = DCDL, GoodsName = GoodsName, User = User, Forwarder = Forwarder, Service = Service, contractno = YFXY, }; return obj; } /// /// 推送东胜 /// /// /// [NonAction] public async Task SendBookingOrder(long[] ids) { _logger.LogInformation("开始同步订舱数据"); var itemcode = App.Configuration["ITEMCODE"].ToString(); var BookingOrderMQUri = App.Configuration["SendBookingOrderMQUri"]; _logger.LogInformation("订舱数据回推地址:" + BookingOrderMQUri + itemcode); if (!string.IsNullOrEmpty(itemcode) && itemcode == "True") { if (ids.Count() == 0) { throw Oops.Bah("请上传正确数据"); } var order = await _rep.AsQueryable().Filter(null, true).Where(x => ids.Contains(x.Id) && x.TenantId == UserManager.TENANT_ID && x.IsDeleted == false).ToListAsync(); foreach (var item in order) { //2023-9-8,增加校验,分单不能单独推送东胜,只能随主单推送 if (item.ParentId > 0) { continue; } //2023-9-26,添加校验:推送前通过Cache判断一下待推送的数据是否正在走删除逻辑 if (await _cache.ExistsAsync($"DeletingBookingOrderId_{item.Id}")) { continue; } var dto = item.Adapt(); List statusList = new List(); if (App.Configuration["ServiceStatusOpenAuto"] == "1") { QueryServiceProjectWithStatus queryInfo = new QueryServiceProjectWithStatus { BookingId = item.Id, QueryType = TrackingQueryTypeEnum.QUERY_SERVICE_PROJECT, TenantId = item.TenantId.Value }; var queryRlt = await _serviceWorkFlowManageService.GetEnableStatusListByBusiness(queryInfo); if (queryRlt.succ) { statusList = JSON.Deserialize>(JSON.Serialize(queryRlt.ext)); } } if (App.Configuration["ServiceStatusOpenAuto"] == "1") { if (statusList != null && statusList.Any(x => x.StatusSKUCode == "SQXS" && x.IsYield)) { dto.CtnDayNum = statusList.FirstOrDefault(x => x.StatusSKUCode == "SQXS" && x.IsYield)?.ActVal; } } else { //箱使 var CtnDayNumlist = await GetGoodsStatusList(item.Id); if (CtnDayNumlist != null) { dto.CtnDayNum = CtnDayNumlist.Where(x => x.StatusName == "申请箱使").Select(x => x.ExtData).FirstOrDefault(); } } var ctn = await _repCtn.AsQueryable().Filter(null, true).Where(x => x.BILLID == item.Id && x.IsDeleted == false).ToListAsync(); dto.ctnInputs = ctn.Adapt>(); foreach (var it in dto.ctnInputs) { var ctnDetailInputs = await _ctndetailrep.AsQueryable().Filter(null, true).Where(x => x.CTNID == it.Id && x.IsDeleted == false).ToListAsync(); it.ctnDetailInputs = ctnDetailInputs.Adapt>(); } //EDI var BookingEDIExt = await _bookingEDIExt.AsQueryable().Filter(null, true).Where(x => x.BookingId == item.Id && x.IsDeleted == false).FirstAsync(); if (BookingEDIExt != null) { dto.BookingEDIExt = BookingEDIExt.Adapt(); } if (App.Configuration["ServiceStatusOpenAuto"] == "1") { if (statusList != null && statusList.Any(x => x.IsYield)) { dto.GoodsStatus = statusList.Where(x => x.IsYield).OrderBy(x => x.SortNo).Select(x => new BookingGoodsStatusDto { StatusName = x.ShowName, FinishTime = x.ActDate, Remark = x.ActRemark, ExtData = x.ActVal }).ToList(); } else { dto.GoodsStatus = new List(); } } else { //货物状态 dto.GoodsStatus = await _goodsStatus.AsQueryable().Filter(null, true).Where(x => x.bookingId == item.Id).InnerJoin((t, d) => t.ConfigId == d.Id).Select((t, d) => new BookingGoodsStatusDto { StatusName = d.StatusName, FinishTime = t.FinishTime, Remark = t.Remark, ExtData = t.ExtData }).Distinct().ToListAsync(); } var childrens = await _rep.AsQueryable().Filter(null, true).Where(x => x.ParentId == item.Id && x.TenantId == UserManager.TENANT_ID && x.IsDeleted == false).ToListAsync(); dto.childrens = childrens.Adapt>(); foreach (var childitem in dto.childrens) { var ctnInputs = await _repCtn.AsQueryable().Filter(null, true).Where(x => x.BILLID == childitem.Id && x.IsDeleted == false).ToListAsync(); childitem.ctnInputs = ctnInputs.Adapt>(); foreach (var it in childitem.ctnInputs) { var ctnDetailInputs = await _ctndetailrep.AsQueryable().Filter(null, true).Where(x => x.CTNID == it.Id && x.IsDeleted == false).ToListAsync(); it.ctnDetailInputs = ctnDetailInputs.Adapt>(); } var childBookingEDIExt = await _bookingEDIExt.AsQueryable().Filter(null, true).Where(x => x.BookingId == childitem.Id && x.IsDeleted == false).FirstAsync(); if (childBookingEDIExt != null) { childitem.BookingEDIExt = childBookingEDIExt.Adapt(); } } var json = dto.ToJsonString(); json = $"[{json}]"; _logger.LogInformation("订舱数据回推:" + json); try { const string MqActionExchangeName = "djy.output.dingcang.ds6"; const string MqActionQueueName = "djy.output.dingcang.ds6"; ConnectionFactory factory = new ConnectionFactory(); factory.Uri = new Uri(BookingOrderMQUri); using (IConnection conn = factory.CreateConnection()) { IModel mqModel = conn.CreateModel(); mqModel.ExchangeDeclare(MqActionExchangeName, ExchangeType.Direct); var queueName = $"{MqActionQueueName}.{UserManager.TENANT_ID}"; mqModel.QueueDeclare(queueName, false, false, false, null); mqModel.QueueBind(queueName, MqActionExchangeName, queueName, null); byte[] messageBodyBytes = Encoding.UTF8.GetBytes(SharpZipLib.Compress(json)); IBasicProperties props = mqModel.CreateBasicProperties(); props.DeliveryMode = 2; mqModel.BasicPublish(MqActionExchangeName, queueName, props, messageBodyBytes); conn.Close(); _logger.LogInformation($"订舱数据回推,已发送数据到消息队列【{BookingOrderMQUri}】,数据内容:【{json}】"); } } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); } await SendLetterYard(item.Id); } return order; } return null; } /// /// 即时刷新船期 /// /// [HttpPost("/BookingOrder/RefreshSailingDate")] public async Task RefreshSailingDate(long Id) { var order = _rep.FirstOrDefault(x => x.Id == Id); if (string.IsNullOrEmpty(order.MBLNO)) { throw Oops.Bah("提单号为空"); } var url = _cache.GetAllDictData().Result.Where(x => x.Code == "billTraceYgtUrl").Select(x => x.Value).FirstOrDefault(); if (string.IsNullOrEmpty(url)) { throw Oops.Bah("未获取到请求URL,请联系管理员!"); } var key = _cache.GetAllSysConfig().Result.Where(x => x.Code == "billTraceNewUserKey").Select(x => x.Value).FirstOrDefault(); if (string.IsNullOrEmpty(key)) { throw Oops.Bah("未获取到相关KEY,请联系管理员!"); } var secret = _cache.GetAllSysConfig().Result.Where(x => x.Code == "billTraceNewUserSecret").Select(x => x.Value).FirstOrDefault(); if (string.IsNullOrEmpty(secret)) { throw Oops.Bah("未获取到相关SECRET,请联系管理员!"); } JObject jobjSend = new JObject(); jobjSend.Add("user_key", new JValue(key)); jobjSend.Add("user_secret", new JValue(secret)); jobjSend.Add("customer_id", new JValue(order.TenantId)); jobjSend.Add("customer_name", new JValue(order.TenantName)); JArray jarrTemps = new JArray(); JObject jobjTemp = new JObject(); jobjTemp.Add("bno", new JValue(order.MBLNO)); jobjTemp.Add("web_code", new JValue("YGT_YZ")); jarrTemps.Add(jobjTemp); jobjSend.Add("data_list", jarrTemps); var rtn = await url.SetHttpMethod(HttpMethod.Post).SetBody(jobjSend.ToJsonString()).PostAsStringAsync(); _logger.LogInformation("刷新船期:" + rtn); JObject jobjRtn = JObject.Parse(rtn); var code = jobjRtn.GetValue("code").ToString(); var msg = jobjRtn.GetValue("msg").ToString(); if (code != "200") { throw Oops.Bah($"请求爬虫获取【云港通】出错:{msg}"); } JArray jarrData = jobjRtn.GetValue("data") as JArray; if (jarrData == null || jarrData.Count == 0) { throw Oops.Bah($"单号信息不存在"); } JObject it = jarrData[0] as JObject; JArray array = it.GetValue("data") as JArray; if (array == null || array.Count == 0) { throw Oops.Bah($"单号信息不存在"); } JObject item = array[0] as JObject; var yjdk_time = item.GetDateTimeValue("yjdk_time");//预计到港时间 var yjlk_time = item.GetDateTimeValue("yjlk_time");//预计离港时间 var sjdk_time = item.GetDateTimeValue("sjdk_time");//实际到港时间 var sjlg_time = item.GetDateTimeValue("sjlg_time");//实际离港时间 _logger.LogInformation("船期:" + yjdk_time + yjlk_time + sjdk_time + sjlg_time); bool flag = false; if (order.StartETA != yjdk_time && yjdk_time != null) { order.StartETA = yjdk_time; flag = true; } if (order.YgtETD != yjlk_time && yjlk_time != null) { order.YgtETD = yjlk_time; flag = true; } if (order.StartATA != sjdk_time && sjdk_time != null) { order.StartATA = sjdk_time; flag = true; } if (order.ATD != sjlg_time && sjlg_time != null) { order.ATD = sjlg_time; flag = true; } //同步船期 if (flag) { await _rep.AsUpdateable(order).IgnoreColumns().ExecuteCommandAsync(); await SendBookingOrder(new long[] { Id }); if (!string.IsNullOrEmpty(order.VESSEL) && !string.IsNullOrEmpty(order.VOYNO)) { //2023年8月24日,邹文坤:如果云港通的船名航次和操作填写的不一致,则需要提示,并且不能批量更新数据 var ywcm = item.GetStringValue("ywcm"); var ckhc = item.GetStringValue("ckhc"); if (order.VOYNO != ckhc) { throw Oops.Bah($"船名不匹配,云港通:{ywcm},填写:{order.VESSEL}"); } if (order.VOYNO != ckhc) { throw Oops.Bah($"航次不匹配,云港通:{ckhc},填写:{order.VOYNO}"); } var orderlist = await _rep.AsQueryable().Filter(null, true).Where(x => x.IsDeleted == false && x.TenantId == UserManager.TENANT_ID && x.CARRIERID == order.CARRIERID && x.VESSEL == order.VESSEL && x.VOYNO == order.VOYNO && x.Id != order.Id) .WhereIF(!string.IsNullOrEmpty(order.VOYNOINNER), x => x.VOYNOINNER == order.VOYNOINNER).ToListAsync(); foreach (var i in orderlist) { i.StartETA = yjdk_time; i.YgtETD = yjlk_time; i.StartATA = sjdk_time; i.ATD = sjlg_time; await _rep.AsUpdateable(i).IgnoreColumns().ExecuteCommandAsync(); await SendBookingOrder(new long[] { i.Id }); } } } return order; } /// /// 设置货物状态完成 /// /// /// /// public async Task SetGoodsStatus(string code, long bookingId) { if (App.Configuration["ServiceStatusOpenAuto"] == "1") { await SetGoodsStatusPush(code, bookingId); return; } var CreatedUserId = _rep.AsQueryable().Filter(null, true).Where(x => x.Id == bookingId).Select(x => x.CreatedUserId).First(); if (CreatedUserId != null) { var gsCfg = _goodsStatusConfig.FirstOrDefault(x => x.SystemCode == code && x.CreatedUserId == (long)CreatedUserId); if (gsCfg != null) { _logger.LogInformation($"检查{code}货物状态:{bookingId}"); var gs = _goodsStatus.FirstOrDefault(x => x.ConfigId == gsCfg.Id && x.bookingId == bookingId); if (gs == null) { gs = new BookingGoodsStatus(); gs.bookingId = bookingId; gs.ConfigId = gsCfg.Id; gs.FinishUser = UserManager.Name; gs.FinishTime = DateTime.Now; gs.FinishUserId = UserManager.UserId; await _goodsStatus.InsertAsync(gs); _logger.LogInformation($"发送{code}后自动完成货物状态,Id:{bookingId}"); //更新货物状态 await SetBookingOrderGoodsStatus(bookingId); } } } } /// /// 更新主单货物状态 /// /// /// public async Task SetBookingOrderGoodsStatus(long bookingId) { var order = _rep.AsQueryable().Filter(null, true).First(x => x.Id == bookingId); var createUserid = order.CreatedUserId; //获取当前用户已经录入的货物状态 var list = await _goodsStatus.AsQueryable().LeftJoin(_goodsStatusConfig.AsQueryable(), (goods, config) => config.Id == goods.ConfigId).Where((goods, config) => config.CreatedUserId == createUserid && goods.bookingId == bookingId). OrderBy((goods, config) => config.Sort). Select((goods, config) => new GoodsStatusQuery { ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = goods.FinishTime, FinishUser = goods.FinishUser, FinishUserId = goods.FinishUserId, IsPublic = goods.IsPublic, ExtData = goods.ExtData, Remark = goods.Remark, Sort = config.Sort }).ToListAsync(); if (list != null) { ///回写主单状态 var StatusName = list.Where(x => x.FinishTime.HasValue).OrderByDescending(x => x.Sort).Select(x => x.StatusName).FirstOrDefault(); if (StatusName == null) { StatusName = ""; } //order.BSSTATUSNAME = StatusName; //await _rep.AsUpdateable(order).IgnoreColumns(it => new //{ // it.ParentId, // it.TenantId, // it.CreatedTime, // it.CreatedUserId, // it.CreatedUserName, // it.TenantName, // it.IsDeleted, // it.BOOKINGNO //}).ExecuteCommandAsync(); await _rep.UpdateAsync(x => x.Id == bookingId, x => new BookingOrder { BSSTATUSNAME = StatusName }); } } /// /// 记录日志 /// /// [NonAction] public async Task SaveLog(BookingOrder newOrder, BookingOrder oldOrder) { bool flag = true; long bid = 0; foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(newOrder)) { //基础字段不记录 string name = descriptor.Name; if (name == "TenantId" || name == "CreatedTime" || name == "UpdatedTime" || name == "CreatedUserId" || name == "CreatedUserName") { continue; } object value = descriptor.GetValue(newOrder); var oldvalue = oldOrder.GetType().GetProperty(name).GetValue(oldOrder, null); //数值类型转换比较 if (name == "KGS" || name == "CBM") { if (Convert.ToDecimal(value) == Convert.ToDecimal(oldvalue)) { continue; } } string _oldvalue = oldvalue != null ? oldvalue.ToString() : ""; string _value = value != null ? value.ToString() : ""; if (_oldvalue != _value && !string.IsNullOrWhiteSpace(descriptor.Description)) { if (flag) { ////添加booking日志 bid = await _bookinglog.InsertReturnSnowflakeIdAsync(new BookingLog { Type = "Edit", BookingId = newOrder.Id, TenantId = Convert.ToInt64(UserManager.TENANT_ID), CreatedTime = DateTime.Now, CreatedUserId = UserManager.UserId, CreatedUserName = UserManager.Name }); flag = false; } await _bookinglogdetail.InsertReturnSnowflakeIdAsync(new BookingLogDetail { PId = bid, Field = descriptor.Description, OldValue = _oldvalue, NewValue = _value, }); } } } /// /// 判断是否可以编辑主单 True可以 /// /// /// /// public async Task GetIsBookingLockOrder(BookingOrder newOrder, BookingOrder oldOrder) { var list = _cache.GetAllDictData().Result.Where(x => x.TypeCode == "BookingLockOrder").ToList(); foreach (var item in list) { foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(newOrder)) { string name = descriptor.Name; if (name.ToUpper() == item.Code.ToUpper())//转换大写 字典录入不在区分大小写 { object value = descriptor.GetValue(newOrder); var oldvalue = oldOrder.GetType().GetProperty(name).GetValue(oldOrder, null); string _oldvalue = oldvalue != null ? oldvalue.ToString() : ""; string _value = value != null ? value.ToString() : ""; if (_oldvalue != _value) { return false; } } } } return true; } /// /// 判断是否可以编辑箱信息 True可以 /// /// /// /// public async Task GetIsBookingLockCtn(BookingCtn newOrder, BookingCtn oldOrder) { var list = _cache.GetAllDictData().Result.Where(x => x.TypeCode == "BookingLockCtn").ToList(); foreach (var item in list) { foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(newOrder)) { string name = descriptor.Name; if (name.ToUpper() == item.Code.ToUpper())//转换大写 字典录入不在区分大小写 { object value = descriptor.GetValue(newOrder); var oldvalue = oldOrder.GetType().GetProperty(name).GetValue(oldOrder, null); string _oldvalue = oldvalue != null ? oldvalue.ToString() : ""; string _value = value != null ? value.ToString() : ""; if (_oldvalue != _value) { return false; } } } } return true; } #endregion #region 临时测试使用 /// /// 恢复场站数据临时使用 /// /// [HttpGet("/BookingOrder/DataRepire"), AllowAnonymous] public async Task DataRepire() { var basePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "DataRepire"); if (Directory.Exists(basePath)) { var files = Directory.GetFiles(basePath, "*.txt"); foreach (var f in files) { try { var jobj = JObject.Parse(File.ReadAllText(f)); var jinput = jobj.GetJObjectValue("input"); var bookId = Convert.ToInt64(Path.GetFileNameWithoutExtension(f)); var bookOrd = _rep.AsQueryable().Filter(null, true).First(x => x.Id == bookId); var dbCtns = _repCtn.AsQueryable().Filter(null, true).Where(x => x.BILLID == bookId).ToList(); foreach (var dbCtn in dbCtns) { dbCtn.IsDeleted = true; dbCtn.REMARK = "系统恢复删除"; _repCtn.Update(dbCtn); } var jarrCtn = jinput.GetJArrayValue("ctnInputs"); foreach (JObject jc in jarrCtn) { var ctnentity = new BookingCtn(); ctnentity.Id = YitIdHelper.NextId(); ctnentity.CTNCODE = jc.GetStringValue("ctncode"); ctnentity.CTNALL = jc.GetStringValue("ctnall"); ctnentity.CTNNUM = jc.GetIntValue("ctnnum"); ctnentity.CNTRNO = jc.GetStringValue("cntrno"); ctnentity.SEALNO = jc.GetStringValue("sealno"); ctnentity.PKGS = jc.GetIntValue("pkgs"); ctnentity.KINDPKGS = jc.GetStringValue("kindpkgs"); ctnentity.KGS = jc.GetDecimalValue("kgs"); ctnentity.CBM = jc.GetDecimalValue("cbm"); ctnentity.WEIGHTYPE = jc.GetStringValue("weightype"); ctnentity.WEIGHKGS = jc.GetDecimalValue("weighkgs"); ctnentity.BILLID = bookId; ctnentity.CreatedUserName = "系统恢复"; ctnentity.REMARK = "系统恢复"; ctnentity.TEU = 0; ctnentity.TAREWEIGHT = jc.GetDecimalValue("tareweight"); ctnentity.CreatedUserId = bookOrd.CreatedUserId; ctnentity.TenantId = bookOrd.TenantId; await _repCtn.InsertAsync(ctnentity); } File.Delete(f); } catch { } } } } #endregion #region 打印船公司ONE的订舱附件 /// /// 打印船公司ONE的订舱附件(生成后自动写入订舱附件) /// /// 订舱详情 /// private async Task PrintCarrierOneSOFileAsync(BookingOrder model) { string batchNo = IDGen.NextID().ToString(); /* 1、提取默认的ONE订舱附件打印模板。 2、生成打印文件。 3、将文件写入订舱附件。 */ try { var printTemplate = await _repPrintTemplate.AsQueryable() .Filter(null, true) .InnerJoin((d, t) => d.Id == t.PrintTemplateId && t.SysUserId == UserManager.UserId) .Where(d => d.TenantId == UserManager.TENANT_ID && d.CateCode.Contains(CONST_ONE_SOFILE_CATE_CODE) && d.Type == BookingPrintTemplateType.FastReport.ToString()) .FirstAsync(); //取到打印模板文件 if (printTemplate == null) { _logger.LogInformation("打印船公司ONE的订舱附件 batchNo={batchno} 获取模板文件失败", batchNo); throw Oops.Bah("获取模板文件失败"); } _logger.LogInformation("打印船公司ONE的订舱附件 batchNo={batchno} 获取模板文件成功", batchNo); //打印报表服务地址 var reportUrl = _cache.GetAllDictData().Result.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "url_report_generate").Value; if (string.IsNullOrWhiteSpace(reportUrl)) { _logger.LogInformation("打印船公司ONE的订舱附件 batchNo={batchno} 获取打印报表服务地址失败", batchNo); throw Oops.Bah("获取打印报表服务地址失败"); } if (!reportUrl.EndsWith("/")) { reportUrl += "/"; } var ctns = await _repCtn.AsQueryable().Where(x => x.BILLID == model.Id).ToListAsync(); var bookingEdi = await _bookingEDIExt.AsQueryable().FirstAsync(x => x.BookingId == model.Id); var letterYard = await _repLetterYard.AsQueryable().FirstAsync(x => x.BookingId == model.Id); DjyCustomer customer = null; if (!string.IsNullOrEmpty(model.AGENTID)) //根据国外代理,获取客户的提单信息 { customer = await _djycustomer.AsQueryable().FirstAsync(x => x.CodeName == model.AGENTID && x.TenantId == model.TenantId); } var printOrderModel = model.Adapt(); printOrderModel.senderName = UserManager.Name; printOrderModel.senderTel = UserManager.TEl; printOrderModel.senderMobile = UserManager.Phone; printOrderModel.senderEmail = UserManager.Email; var requestJson = JsonConvert.SerializeObject(new { order = printOrderModel, ctns = ctns, letterYard, agentCustomer = customer, ediExt = bookingEdi, }); //调取生成打印二进制流 var bs = await PrintHelper.GeneratePrintFile(requestJson, reportUrl, PRINT_DATASOURCE_KEY, PrintFileTypeEnum.PDF, printTemplate); //保存文件 var bookFilePath = await FileAttachHelper.SaveFile(model.Id.ToString(), bs, batchNo, "", PrintFileTypeEnum.PDF, "sofile", true); _logger.LogInformation("打印船公司ONE的订舱附件 批次={no} id={id} 完成文件保存 {filepath}", batchNo , model.Id, bookFilePath); //写入订舱随附单据 string fileTypeCode = "sofile"; string fileTypeName = "订舱附件"; //将BC引入的文件写入订舱的附件 await SaveEDIFile(model.Id, bookFilePath, new System.IO.FileInfo(bookFilePath).Name, fileTypeCode, fileTypeName); _logger.LogInformation("打印船公司ONE的订舱附件 批次={no} id={id} 完成写入附件表 {filepath}", batchNo , model.Id, bookFilePath); } catch (Exception ex) { _logger.LogInformation("打印船公司ONE的订舱附件失败 batchNo={batchno} 原因={reason}", batchNo, ex.GetMessage()); } } #endregion #region 航线操作和航线管理 /// /// 航线操作和航线管理列表 /// /// [HttpPost("/BookingOrder/LineOpMgrConfigList")] public async Task> LineOpMgrConfigList(LineOpMgrConfigQueryInput input) { var query = _repLineOpMgrConfig.AsQueryable() .WhereIF(string.IsNullOrEmpty(input.CARRIERID), x => x.CARRIERID == input.CARRIERID) .WhereIF(string.IsNullOrEmpty(input.CARRIER), x => x.CARRIER.Contains(input.CARRIER)) .WhereIF(input.DeptId.HasValue, x => x.DeptId == input.DeptId) .WhereIF(string.IsNullOrEmpty(input.DeptName), x => x.DeptName.Contains(input.DeptName)) .WhereIF(input.StartDateBegin.HasValue, x => x.StartDate > input.StartDateBegin); if (!string.IsNullOrEmpty(input.SortField) || input.MultiSort == null || input.MultiSort.Count == 0) { query = query.OrderBy(PageInputOrder.OrderBuilder(input.SortField, input.DescSort)); } else { query = query.OrderBy(PageInputOrder.MultiOrderBuilder(input.MultiSort)); } var entities = await query.ToPagedListAsync(input.PageNo, input.PageSize); var list = entities.Adapt>(); return list; } /// /// 航线操作和航线管理配置保存 /// /// [HttpPost("/BookingOrder/LineOpMgrConfigSave")] public async Task LineOpMgrConfigSave(LineOpMgrConfigSaveModel input) { BookingLineOpMgrConfig model = null; if (input.Id > 0) { model = _repLineOpMgrConfig.FirstOrDefault(x => x.Id == input.Id); if (model == null) throw Oops.Bah("未找到数据"); input.Adapt(model); await _repLineOpMgrConfig.UpdateAsync(model); } else { model = input.Adapt(); await _repLineOpMgrConfig.InsertAsync(model); } return model.Adapt(); } ///// ///// 根据条件(船司、航线、当前登录人部门)查询匹配的航线操作和航线管理 ///// ///// 船司ID ///// 航线名称 ///// //[HttpGet("/BookingOrder/LineOpMgrConfigSearch")] //public async Task LineOpMgrConfigSearch(string carrierId, string line) //{ // var emp = _repSysEmp.FirstOrDefault(x => x.Id == UserManager.UserId); // if (emp == null || emp.OrgId > 0 || string.IsNullOrEmpty(emp.OrgName)) // throw Oops.Bah("未找到用户部门"); // var list = _repLineOpMgrConfig.AsQueryable() // .Where(x => x.StartDate <= DateTime.Today && x.EndDate >= DateTime.Today) // .WhereIF(!string.IsNullOrEmpty(carrierId), x => x.CARRIERID == carrierId) // .WhereIF(!string.IsNullOrEmpty(line), x => x.LineName == line) // .ToList(); //} #endregion #region 同步东胜 /// /// 批量提单号同步东胜 /// /// /// [HttpPost("/BookingOrder/TestSendDS")] public async Task TestSendDS(string MBLNO) { var orderlist = _rep.AsQueryable().Filter(null, true). Where(x => x.TenantId == UserManager.TENANT_ID). WhereIF(!string.IsNullOrWhiteSpace(MBLNO) && !MBLNO.Contains(','), u => u.MBLNO.Contains(MBLNO.Trim())). WhereIF(!string.IsNullOrWhiteSpace(MBLNO) && MBLNO.Contains(','), u => MBLNO.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Contains(u.MBLNO.Trim())). Select(x => x.Id).ToList(); _logger.LogInformation("批量提单号同步东胜:" + orderlist.ToString()); await SendBookingOrder(orderlist.ToArray()); } /// /// /批量ID同步东胜 /// /// /// [HttpPost("/BookingOrder/TestSendDSID")] public async Task TestSendDSID(string Id) { var orderlist = _rep.AsQueryable().Filter(null, true). Where(x => x.TenantId == UserManager.TENANT_ID). WhereIF(!string.IsNullOrWhiteSpace(Id) && !Id.Contains(','), u => u.Id.ToString() == Id). WhereIF(!string.IsNullOrWhiteSpace(Id) && Id.Contains(','), u => Id.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Contains(u.Id.ToString())). Select(x => x.Id).ToList(); _logger.LogInformation("批量提单号同步东胜:" + orderlist.ToString()); await SendBookingOrder(orderlist.ToArray()); } #endregion #region 推送服务状态 /// /// 推送服务状态 /// /// 服务状态代码 /// 订舱ID /// 是否默认同步东胜 true-自动同步 false-不自动同步 /// public async Task SetGoodsStatusPush(string code, long bookingId, bool isAutoSyncDS = false) { string batchNo = IDGen.NextID().ToString(); /* 1、调取推送服务状态。 2、获取单票的服务状态排序值最大状态。写入订舱的状态(BSSTATUSNAME) 3、调取同步订舱同步东胜。 */ if (string.IsNullOrWhiteSpace(code)) { _logger.LogInformation("批次={no} 调取{name} 服务状态代码不能为空", batchNo, nameof(SetGoodsStatusPush)); throw Oops.Oh($"服务状态代码不能为空"); } if (bookingId == 0) { _logger.LogInformation("批次={no} 调取{name} 订舱ID不能为空", batchNo, nameof(SetGoodsStatusPush)); throw Oops.Oh($"订舱ID不能为空"); } var saveStatusRlt = await _serviceWorkFlowManageService.SaveServiceStatus(new ModifyServiceProjectStatusDto { BookingId = bookingId, SourceType = TrackingSourceTypeEnum.AUTO, StatusCodes = new List { new ModifyServiceProjectStatusDetailDto { StatusCode = code } } }); _logger.LogInformation("批次={no} 异步推送状态完成,结果={rlt}", batchNo, JSON.Serialize(saveStatusRlt)); if (saveStatusRlt.succ) { //拉取最新的状态数据,并取已完成的排序最大的状态写入订舱的字段 BSSTATUSNAME var bookingOrder = _rep.AsQueryable().Filter(null, true) .First(a => a.Id == bookingId); QueryServiceProjectWithStatus queryInfo = new QueryServiceProjectWithStatus { BookingId = bookingId, QueryType = TrackingQueryTypeEnum.QUERY_SERVICE_PROJECT, TenantId = bookingOrder.TenantId.Value }; var queryRlt = await _serviceWorkFlowManageService.GetEnableStatusListByBusiness(queryInfo); if (queryRlt.succ) { var statusList = JSON.Deserialize>(JSON.Serialize(queryRlt.ext)); if (statusList != null) { var maxStatus = statusList.Where(a => a.IsYield) .OrderByDescending(a => a.SortNo) .FirstOrDefault(); if (maxStatus != null) { var model = _rep.AsQueryable().Filter(null, true) .First(a => a.Id == bookingId); model.BSSTATUSNAME = maxStatus.ShowName; //model.VERSION = IDGen.NextID().ToString().Replace("-", ""); //更新订舱 _rep.AsUpdateable(model) .UpdateColumns(it => new { it.BSSTATUSNAME, //it.VERSION }).ExecuteCommand(); //推送东胜 if (isAutoSyncDS) await SendBookingOrder(new long[] { bookingId }); } } } } } #endregion #region 取消服务状态 /// /// 取消服务状态 /// /// 服务状态代码 /// 订舱编号 /// 是否默认同步东胜 true-自动同步 false-不自动同步 /// public async Task SetGoodsStatusCancel(string code, long bookingId, bool isAutoSyncDS = false) { string batchNo = IDGen.NextID().ToString(); /* 1、调取推送服务状态。 2、获取单票的服务状态排序值最大状态。写入订舱的状态(BSSTATUSNAME) 3、调取同步订舱同步东胜。 */ if (string.IsNullOrWhiteSpace(code)) { _logger.LogInformation("批次={no} 调取{name} 服务状态代码不能为空", batchNo, nameof(SetGoodsStatusPush)); throw Oops.Oh($"服务状态代码不能为空"); } if (bookingId == 0) { _logger.LogInformation("批次={no} 调取{name} 订舱ID不能为空", batchNo, nameof(SetGoodsStatusPush)); throw Oops.Oh($"订舱ID不能为空"); } var saveStatusRlt = await _serviceWorkFlowManageService.CancelServiceStatus(new ModifyServiceProjectStatusDto { BookingId = bookingId, SourceType = TrackingSourceTypeEnum.AUTO, StatusCodes = new List { new ModifyServiceProjectStatusDetailDto { StatusCode = code } } }); _logger.LogInformation("批次={no} 异步取消状态完成,结果={rlt}", batchNo, JSON.Serialize(saveStatusRlt)); if (saveStatusRlt.succ) { //拉取最新的状态数据,并取已完成的排序最大的状态写入订舱的字段 BSSTATUSNAME var bookingOrder = _rep.AsQueryable().Filter(null, true) .First(a => a.Id == bookingId); QueryServiceProjectWithStatus queryInfo = new QueryServiceProjectWithStatus { BookingId = bookingId, QueryType = TrackingQueryTypeEnum.QUERY_SERVICE_PROJECT, TenantId = bookingOrder.TenantId.Value }; var queryRlt = await _serviceWorkFlowManageService.GetEnableStatusListByBusiness(queryInfo); if (queryRlt.succ) { var statusList = JSON.Deserialize>(JSON.Serialize(queryRlt.ext)); if (statusList != null) { var maxStatus = statusList.Where(a => a.IsYield) .OrderByDescending(a => a.SortNo) .FirstOrDefault(); var model = _rep.AsQueryable().Filter(null, true) .First(a => a.Id == bookingId); if (maxStatus != null) { model.BSSTATUSNAME = maxStatus.ShowName; } else { model.BSSTATUSNAME = string.Empty; } //model.VERSION = IDGen.NextID().ToString().Replace("-", ""); //更新订舱 _rep.AsUpdateable(model) .UpdateColumns(it => new { it.BSSTATUSNAME, //it.VERSION }).ExecuteCommand(); //推送东胜 if (isAutoSyncDS) //推送东胜 await SendBookingOrder(new long[] { bookingId }); } } } } /// /// 设定保存订舱的货物状态并同步东胜 /// /// /// 是否默认同步东胜 true-自动同步 false-不自动同步 /// public async Task SetBookingGoodsStatus(long bookingId, bool isAutoSyncDS = false) { var bookingOrder = _rep.AsQueryable().Filter(null, true) .First(a => a.Id == bookingId); QueryServiceProjectWithStatus queryInfo = new QueryServiceProjectWithStatus { BookingId = bookingId, QueryType = TrackingQueryTypeEnum.QUERY_SERVICE_PROJECT, TenantId = bookingOrder.TenantId.Value }; var queryRlt = await _serviceWorkFlowManageService.GetEnableStatusListByBusiness(queryInfo); if (queryRlt.succ) { var statusList = JSON.Deserialize>(JSON.Serialize(queryRlt.ext)); if (statusList != null) { var maxStatus = statusList.Where(a => a.IsYield) .OrderByDescending(a => a.SortNo) .FirstOrDefault(); var model = _rep.AsQueryable().Filter(null, true) .First(a => a.Id == bookingId); if (maxStatus != null) { model.BSSTATUSNAME = maxStatus.ShowName; } else { model.BSSTATUSNAME = string.Empty; } //model.VERSION = IDGen.NextID().ToString().Replace("-", ""); //更新订舱 _rep.AsUpdateable(model) .UpdateColumns(it => new { it.BSSTATUSNAME, //it.VERSION }).ExecuteCommand(); //推送东胜 if (isAutoSyncDS) //推送东胜 await SendBookingOrder(new long[] { bookingId }); } } } #endregion #region 提箱小票CMA /// /// 提箱小票CMA /// /// /// [HttpPost("/BookingOrder/SaveBookingTxxp")] public async Task SaveBookingTxxp(long Id) { //获取url var url = _cache.GetAllDictData().Result.Where(x => x.Code == "bookingTxxpUrl").Select(x => x.Value).FirstOrDefault(); _logger.LogInformation("提箱小票CMAurl:" + url); //亿通账号 var ytAcc = _webAccountConfig.GetAccountConfig("YitongWeb", UserManager.UserId).Result; if (ytAcc == null) { throw Oops.Bah(BookingErrorCode.BOOK119); } _logger.LogInformation("提箱小票CMA:" + ytAcc.ToJsonString()); var order = _rep.FirstOrDefault(x => x.Id == Id); //条件判断 目前只支持CMA 的数据 var CARRIERID = _cache.GetAllMappingCarrier().Result.Where(x => order.CARRIERID == x.Code && x.Module == "BookingTxxp").Select(x => x.MapCode).FirstOrDefault(); if (CARRIERID != "CMA") { throw Oops.Bah("船公司目前只支持CMA"); } if (string.IsNullOrEmpty(order.VESSEL)) { throw Oops.Bah("船名不能为空"); } if (string.IsNullOrEmpty(order.MBLNO)) { throw Oops.Bah("提单号不能为空"); } var json = new { custname = "DJY", custpsw = "123", username = ytAcc.Account, password = ytAcc.Password, company = "CMA", vessel = order.VESSEL }; BookingExtendState extends = new BookingExtendState(); var rtn = await url.SetBody(json).PostAsStringAsync(); JObject jobjRtn = JObject.Parse(rtn); var status = jobjRtn.GetValue("status").ToString(); if (status != "1") { //不等于1 返回结果错误 throw Oops.Bah(jobjRtn.GetValue("message").ToString()); } else { var jarrData = jobjRtn.GetValue("message") as JArray; foreach (JObject item in jarrData) { //订舱号(单号) var mb = item.GetStringValue("bookingno"); //提单号 if (mb == order.MBLNO) { var noApply = item.GetIntValue("noApply"); //未申请 var applyNoPrint = item.GetIntValue("applyNoPrint"); //已申请未打印 var print = item.GetIntValue("print"); //已打印 extends = _repextendstate.FirstOrDefault(x => x.bookingId == Id); if (extends == null) { extends.bookingId = Id; extends.noApply = noApply; extends.applyNoPrint = applyNoPrint; extends.print = print; extends.IsLockBooking = false; await _repextendstate.InsertAsync(extends); } else { extends.noApply = noApply; extends.applyNoPrint = applyNoPrint; extends.print = print; await _repextendstate.AsUpdateable(extends).IgnoreColumns().ExecuteCommandAsync(); } } } } return extends; } #endregion #region 检查是否VOLTA并返回初始数据 /// /// 检查是否VOLTA并返回初始数据 /// /// 请求参数 /// 返回回执 [HttpPost("/BookingOrder/CheckAndInitVOLTAEdi")] public dynamic CheckAndInitVOLTAEdi(BookingOrClosingEDIOrderDto model) { CommonWebApiResult result = new CommonWebApiResult(); /* 判断当前单子是否满足执行VOLTA截单流程 1、是截单请求 2、船公司是VOL。 3、提单号开头是(VOL、FCS、REL) */ string batchNo = IDGen.NextID().ToString(); _logger.LogInformation("批次={no}获取请求VOLTA截单详情 {msg}", batchNo, JSON.Serialize(model)); if (!model.sendType.Equals("E", StringComparison.OrdinalIgnoreCase)) { throw Oops.Bah("只接受发送类型截单(E)"); } if (model.Id == 0) throw Oops.Bah("订单Id不能为空"); var order = _rep.FirstOrDefault(a => a.Id == model.Id); if (order == null) throw Oops.Bah($"获取订单信息失败"); if (order.ParentId.HasValue && order.ParentId.Value > 0) throw Oops.Bah($"获取当前订单为分单不能生成EDI信息"); _logger.LogInformation("批次={no}提取订单信息完成", batchNo); if (!order.CARRIERID.Equals("VOL", StringComparison.OrdinalIgnoreCase)) { throw Oops.Bah("当前订单的船公司不是VOL(沃尔塔航运)不能发送VOLTA截单EDI"); } if (string.IsNullOrWhiteSpace(order.MBLNO)) throw Oops.Bah($"提单号不能为空"); if (!order.MBLNO.StartsWith("VOL") && !order.MBLNO.StartsWith("FCS") && !order.MBLNO.StartsWith("REL")) { throw Oops.Bah($"只支持提单号开头是(VOL、FCS、REL)发送截单"); } //箱信息 var contaList = _repCtn.AsQueryable().Where(t => t.BILLID == order.Id).ToList(); VOLTAEDIBaseModel voltaModel = order.Adapt(); #region 拆分收、发、通(名称、地址拆分) if (!string.IsNullOrWhiteSpace(voltaModel.ShpperName)) { string name = voltaModel.ShpperName; voltaModel.ShpperName = GetShipCneeNotifyDetail(name); voltaModel.ShpperAddr = GetShipCneeNotifyDetail(name, "addr"); } if (!string.IsNullOrWhiteSpace(voltaModel.ConsigneeName)) { string name = voltaModel.ConsigneeName; voltaModel.ConsigneeName = GetShipCneeNotifyDetail(name); voltaModel.ConsigneeAddr = GetShipCneeNotifyDetail(name, "addr"); } if (!string.IsNullOrWhiteSpace(voltaModel.NotifyName)) { string name = voltaModel.NotifyName; voltaModel.NotifyName = GetShipCneeNotifyDetail(name); voltaModel.NotifyAddr = GetShipCneeNotifyDetail(name, "addr"); } #endregion if (voltaModel.CargoDescription.EndsWith("\n")) voltaModel.CargoDescription = voltaModel.CargoDescription.Substring(0, voltaModel.CargoDescription.Length - 1); if (voltaModel != null) voltaModel.ContaList = contaList.Adapt>(); StringBuilder pkgsBuilder = new StringBuilder(); //还需要翻译箱明细的包装 if (voltaModel.ContaList != null && voltaModel.ContaList.Count > 0) { List origPkgsList = voltaModel.ContaList.Select(x => x.Pkgs).Distinct().ToList(); //包装基础数据 var basePkgsList = _cache.GetAllCodePackage().GetAwaiter().GetResult(); var ediPkgsList = _cache.GetAllMappingPackage().GetAwaiter().GetResult() .Where(t => t.Module.Equals(CONST_MAPPING_MODULE_VOLTA, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(t.CarrierCode) && t.CarrierCode.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase)) .ToList(); int startNo = 1; voltaModel.ContaList.ForEach(x => { x.SNo = startNo; var curBasePkgs = basePkgsList.FirstOrDefault(p => p.Name.Equals(x.Pkgs, StringComparison.OrdinalIgnoreCase)); if (curBasePkgs == null) pkgsBuilder.Append($"包装{x.Pkgs}的基础数据代码未找到"); if (curBasePkgs != null) { var ediPkgs = ediPkgsList.FirstOrDefault(x => x.Code.Equals(curBasePkgs.Code, StringComparison.OrdinalIgnoreCase)); if (ediPkgs == null || string.IsNullOrWhiteSpace(ediPkgs.MapCode)) pkgsBuilder.AppendLine($"包装{x.Pkgs}的EDI代码未找到"); if (ediPkgs != null) { x.EdiPkgs = ediPkgs.MapCode?.Trim(); } } if (string.IsNullOrWhiteSpace(x.EdiPkgs)) x.EdiPkgs = string.Empty; startNo++; }); } if (pkgsBuilder.Length > 0) { _logger.LogInformation("批次={no}获取请求VOLTA截单详情有错误 {msg}", batchNo, JSON.Serialize(model)); result.msg = pkgsBuilder.ToString(); } result.succ = true; result.extra = voltaModel; return result; } #endregion #region 发送VOLTA截单请求 /// /// 发送VOLTA截单请求 /// /// 请求截单详情 /// 返回回执 [HttpPost("/BookingOrder/SendVOLTAEdiSI")] public async Task SendVOLTAEdiSI(VOLTAEDIBaseModel model) { return await InnerVOLTAEDI(model, true); } #endregion #region 下载VOLTA截单请求报文 /// /// 下载VOLTA截单请求报文 /// /// 请求截单详情 /// 返回回执 [HttpPost("/BookingOrder/DownloadVOLTAEdiSI")] public async Task DownloadVOLTAEdiSI(VOLTAEDIBaseModel model) { var filePath = InnerVOLTAEDI(model).GetAwaiter().GetResult(); var fileInfo = new FileInfo(filePath); var result = new FileStreamResult(new FileStream(filePath, FileMode.Open), "application/octet-stream") { FileDownloadName = fileInfo.Name }; return result; } #endregion #region 生成VOLTA报文(内部方法) /// /// 生成VOLTA报文(内部方法) /// /// 请求截单详情 /// 是否直接发送VOLTA申报截单 /// 返回回执 [NonAction] public async Task InnerVOLTAEDI(VOLTAEDIBaseModel model, bool isSend = false) { CommonWebApiResult result = new CommonWebApiResult(); string batchNo = IDGen.NextID().ToString(); _logger.LogInformation("批次={no}获取请求VOLTA截单EDI {msg}", batchNo, JSON.Serialize(model)); if (model.id == 0) throw Oops.Bah("订单Id不能为空"); var order = _rep.FirstOrDefault(a => a.Id == model.id); if (order == null) throw Oops.Bah($"获取订单信息失败"); if (order.ParentId.HasValue && order.ParentId.Value > 0) throw Oops.Bah($"获取当前订单为分单不能生成EDI信息"); _logger.LogInformation("批次={no}提取订单信息完成", batchNo); //箱信息 var contaList = _repCtn.AsQueryable().Where(t => t.BILLID == order.Id).ToList(); EDIRouteEnum ediRouteEnum = GetEDIRoute(order.CARRIERID); _logger.LogInformation("批次={no} 获取EDI路由完成 路由={route}", batchNo, ediRouteEnum.ToString()); if (ediRouteEnum == EDIRouteEnum.NULL) throw Oops.Bah($"当前船公司没有对应的请求路由配置"); //读取文件配置 var fileCfg = App.GetOptions(); string filePath = String.Empty; string relativePath = string.Empty; if (!isSend) { var opt = App.GetOptions().Path; filePath = $"{Path.Combine(App.WebHostEnvironment.WebRootPath, opt)}\\{order.BOOKINGNO}";//服务器路径 } else { relativePath = $"{fileCfg.relativePath}\\edifiles\\{order.BOOKINGNO}"; filePath = $"{(!string.IsNullOrWhiteSpace(fileCfg.basePath) ? fileCfg.basePath : App.WebHostEnvironment.WebRootPath)}\\{relativePath}"; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { relativePath = relativePath.Replace("\\", "/"); filePath = filePath.Replace("\\", "/"); } _logger.LogInformation("批次={no} 生成文件保存路径完成 路由={filePath} 服务器系统={system}", batchNo, filePath, RuntimeInformation.OSDescription); //预先创建目录 if (!Directory.Exists(filePath)) { Directory.CreateDirectory(filePath); } model.FilePath = filePath; //调用帮助类 result = VOLTAEdiHelper.CreateEdiVOLTA(model); _logger.LogInformation("批次={no} 生成EDI文件完成 结果={result}", batchNo, JSON.Serialize(result)); if (!result.succ) { throw Oops.Bah(result.msg); } if (isSend) { //这里发送配置通过提单号的前3个英文字母判断 string ediCode = order.MBLNO.Substring(0, 3).ToUpper(); var ftpSet = _cache.GetAllEdiSetting().GetAwaiter().GetResult() .FirstOrDefault(a => a.EDICODE.Equals(ediCode, StringComparison.OrdinalIgnoreCase) && a.TenantId == order.TenantId && !string.IsNullOrWhiteSpace(a.CARRIERID) && a.CARRIERID.Equals(order.CARRIERID, StringComparison.OrdinalIgnoreCase) && a.EnableFlag && (string.IsNullOrWhiteSpace(a.SendType) || (!string.IsNullOrWhiteSpace(a.SendType) && a.SendType == "SI"))); if (ftpSet == null) throw Oops.Bah($"获取EDICODE={ediCode}的EDI参数设置失败"); string currFilePath = string.Empty; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { currFilePath = System.Text.RegularExpressions.Regex.Match(result.extra.ToString(), relativePath.Replace("/", "\\/") + ".*").Value; } else { currFilePath = System.Text.RegularExpressions.Regex.Match(result.extra.ToString(), relativePath.Replace("\\", "\\\\") + ".*").Value; } string fileTypeCode = "esi"; string fileTypeName = "ESI文件"; //这里先写入附件表 await SaveEDIFile(model.id, currFilePath, new System.IO.FileInfo(currFilePath).Name, fileTypeCode, fileTypeName); _logger.LogInformation("批次={no} 直接发送FTP 文件访问地址={filepath}", batchNo, result.extra.ToString()); DateTime bDate = DateTime.Now; bool isSendEmail = false; if (ftpSet.SendType.Equals("SI", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(ftpSet.RECEIVEEMAIL)) { isSendEmail = true; } CommonWebApiResult sendStatus = null; if (isSendEmail) { var mailAcc = await _repUserMail.FirstOrDefaultAsync(x => x.CreatedUserId == UserManager.UserId && x.SmtpPort > 0 && x.SmtpServer != null && x.SmtpServer != ""); //推送订舱邮件 sendStatus = await InnerSendToEmailByUserEmail(mailAcc, result.extra.ToString(), result.extra2.ToString(), ftpSet); } DateTime eDate = DateTime.Now; TimeSpan ts = eDate.Subtract(bDate); var timeDiff = ts.TotalMilliseconds; _logger.LogInformation("批次={no} 发送完成,耗时:{timeDiff}ms. 结果{msg}", batchNo, timeDiff, sendStatus.succ ? "成功" : "失败"); var logId = await _bookinglog.InsertReturnSnowflakeIdAsync(new BookingLog { Type = "Trace", BookingId = model.id, TenantId = Convert.ToInt64(UserManager.TENANT_ID), CreatedTime = DateTime.Now, CreatedUserId = UserManager.UserId, CreatedUserName = UserManager.Name }); string sendTypeName = "邮件"; await _bookinglogdetail.InsertReturnSnowflakeIdAsync(new BookingLogDetail { PId = logId, Field = String.Empty, OldValue = String.Empty, NewValue = $"发送 {order.CARRIERID} EDI 类型=E 通过{sendTypeName} {(sendStatus.succ ? "成功" : "失败")}", }); if (!sendStatus.succ) { throw Oops.Bah($"发送失败,原因:{sendStatus.msg}"); } //如果是截单需最后推送货物状态 await SetGoodsStatus("JD", model.id); await SendBookingOrder(new long[] { model.id }); } return result.extra.ToString(); } #endregion #region 提取收、发、通详情 /// /// 提取收、发、通详情 /// /// 收、发、通信息 /// 内容定位(name-名称;addr-地址) /// 返回截取字符 [NonAction] private string GetShipCneeNotifyDetail(string name, string location = "name") { string result = string.Empty; try { if (location == "name") { result = Regex.Match(name, ".*(?=\\n)").Value; } else if (location == "addr") { string s = Regex.Match(name, ".*(?=\\n)").Value; result = name.Replace(s, ""); if (Regex.IsMatch(result, "^\\n")) { result = Regex.Replace(result, "^\\n", ""); } //result = Regex.Match(name, $"(?<={s}).*").Value; } } catch (Exception ex) { _logger.LogInformation($"{nameof(GetShipCneeNotifyDetail)} 提取收、发、通详情异常,原因:{ex.Message}"); } return result; } #endregion #region 上传邮件 /// /// 上传邮件 /// /// 发送人邮箱信息 /// 文件路径 /// 邮件标题 /// EDI配置 /// 返回回执 private async Task InnerSendToEmailByUserEmail(DjyUserMailAccount userEmailAccount, string filePath, string emailTopic, DjyEdiSetting ediCfg) { CommonWebApiResult result = new CommonWebApiResult { succ = true }; if (userEmailAccount == null) throw Oops.Bah("当前操作人未预设邮箱账户,请进入用户邮箱账户管理"); System.IO.FileStream file = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read); int SplitSize = 5242880;//5M分片长度 int index = 1; //序号 第几片 long StartPosition = 5242880 * (index - 1); long lastLens = file.Length - StartPosition;//真不知道怎么起命了,就这样吧 if (lastLens < 5242880) { SplitSize = (int)lastLens; } byte[] heByte = new byte[SplitSize]; file.Seek(StartPosition, SeekOrigin.Begin); //第一个参数是 起始位置 file.Read(heByte, 0, SplitSize); //第三个参数是 读取长度(剩余长度) file.Close(); string strJoin = System.IO.File.ReadAllText(filePath); DateTime bDate = DateTime.Now; bool isSendRlt = false; string fileName = Path.GetFileName(filePath); try { var sendResult = await MailSendHelper.SendMail(userEmailAccount, emailTopic, emailTopic, ediCfg.RECEIVEEMAIL, new KeyValuePair(fileName, heByte)); _logger.LogInformation($"发送邮件返回:{JSON.Serialize(sendResult)}"); isSendRlt = sendResult.Key; result.succ = isSendRlt; if (!sendResult.Key) { _logger.LogError($"放舱邮件发送失败:从{userEmailAccount.MailAccount}到{ediCfg.RECEIVEEMAIL},主题 {emailTopic}"); result.msg = sendResult.Value; } } catch (Exception ex) { _logger.LogInformation($"发送邮件异常:{ex.Message}"); } DateTime eDate = DateTime.Now; TimeSpan ts = eDate.Subtract(bDate); var timeDiff = ts.TotalMilliseconds; _logger.LogInformation($"邮件上传完成 上传文件大小:{heByte.Length} 用时:{timeDiff}ms.,{strJoin}"); return result; } #endregion #region 临时 /// /// 临时 /// /// /// [HttpGet("/BookingOrder/TestGenUserCode")] public async Task TestGenUserCode(long id) { var usr = await _repUser.AsQueryable().FirstAsync(x => x.Id == id); if (usr == null) { throw Oops.Bah("未找到用户"); } usr.UserCode = PinyinHelper.GetPinyinInitials(usr.Name); await _repUser.AsUpdateable(usr).UpdateColumns(x => new { x.UserCode }).ExecuteCommandAsync(); } /// /// 临时 /// /// /// [HttpGet("/BookingOrder/TestGenUserCodeTenant")] public async Task TestGenUserCodeTenant(long id) { var users = await _repUser.AsQueryable().Where(u => u.TenantId == id && !string.IsNullOrEmpty(u.Name)).ToListAsync(); foreach (var user in users) { if (string.IsNullOrEmpty(user.UserCode)) { user.UserCode = PinyinHelper.GetPinyinInitials(user.Name); await _repUser.AsUpdateable(user).UpdateColumns(x => new { x.UserCode }).ExecuteCommandAsync(); } } } #endregion } }