using Amazon.S3.Model; using DS.Module.Core; using DS.Module.Core.Extensions; using DS.Module.SqlSugar; using DS.Module.UserModule; using DS.WMS.Core.Code.Entity; using DS.WMS.Core.Info.Entity; using DS.WMS.Core.Map.Entity; using DS.WMS.Core.Op.Dtos; using DS.WMS.Core.Op.EDI; using DS.WMS.Core.Op.Entity; using DS.WMS.Core.Op.Interface; using DS.WMS.Core.Sys.Dtos; using DS.WMS.Core.Sys.Entity; using DS.WMS.Core.Sys.Interface; using LanguageExt.Pipes; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json.Linq; using NLog; using NPOI.HSSF.UserModel; using NPOI.SS.Formula.Functions; using SqlSugar; using System.Collections.Specialized; using System.Text; using System.Text.RegularExpressions; using Logger = NLog.Logger; namespace DS.WMS.Core.Op.Method { public class SeaExportCommonService : ISeaExportCommonService { private static readonly string EdiFilePath = "XHZ"; private readonly IServiceProvider _serviceProvider; private readonly ISqlSugarClient db; private readonly IUser user; private readonly ISaasDbService saasService; private readonly ICommonService commonService; private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); private readonly IWebHostEnvironment _environment; /// /// /// /// public SeaExportCommonService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; db = _serviceProvider.GetRequiredService(); user = _serviceProvider.GetRequiredService(); saasService = _serviceProvider.GetRequiredService(); commonService = _serviceProvider.GetRequiredService(); _environment = _serviceProvider.GetRequiredService(); } #region 获取客户结算方式及结算日期 public DataResult GetCustomerStlInfo(CustomerStlReq req) { DateTime? stlDate; DateTime etd; var tenantDb = saasService.GetBizDbScopeById(user.TenantId); if (req.ETD.IsNull()) { return DataResult.Failed("开船日期不能为空!"); } if (DateTime.TryParse(req.ETD.Value.ToString("yyyy-MM-dd"), out DateTime result)) { // 转换成功,赋值给Nullable etd = result; } else { return DataResult.Failed("开船日期格式不正确!"); } var accDate = tenantDb.Queryable().First(x=>x.ClientId == req.CustomerId && etd >= x.BeginDate && etd <= x.EndDate); if (accDate.IsNull()) { return DataResult.Success(new CustomerStlRes() { StlName ="票结", StlDate = req.ETD }); } if (accDate.AccountType == "月结") { stlDate = etd.AddMonths((int)accDate.AccountMonth); if (accDate.AccountDays > 28) { var tmpYear = stlDate.Value.Year.ToString(); var tmpMonth = stlDate.Value.Month.ToString(); var tmpDay = stlDate.Value.Day.ToString(); var tmpStr = tmpYear + "-" + tmpMonth + "-01"; var tmpDate = DateTime.Parse(tmpStr).AddMonths(1); stlDate = tmpDate.AddDays(-1); return DataResult.Success(new CustomerStlRes() { StlName = accDate.AccountType, StlDate = stlDate }); } else { if (accDate.AccountDays == 0) { return DataResult.Success(new CustomerStlRes() { StlName = accDate.AccountType, StlDate = stlDate }); } else { var tmpYear = stlDate.Value.Year.ToString(); var tmpMonth = stlDate.Value.Month.ToString(); var tmpStr = tmpYear + "-" + tmpMonth + "-" + accDate.AccountDays.ToString(); stlDate = DateTime.Parse(tmpStr); return DataResult.Success(new CustomerStlRes() { StlName = accDate.AccountType, StlDate = stlDate }); } } } else if (accDate.AccountType == "约定天数") { stlDate = etd.AddDays((int)accDate.AccountDays); return DataResult.Success(new CustomerStlRes() { StlName = accDate.AccountType, StlDate = stlDate }); } else if (accDate.AccountType == "旬结") { stlDate = etd.AddDays(10); return DataResult.Success(new CustomerStlRes() { StlName = accDate.AccountType, StlDate = stlDate }); } else if (accDate.AccountType == "半月结") { var tmpYear = etd.Year; var tmpMonth = etd.Month; var tmpDay = etd.Day; if (tmpDay < 16) { tmpDay = (int)accDate.AccountDays; if ((int)accDate.AccountDays > 28) { var tmpStr = tmpYear.ToString() + "-" + tmpMonth.ToString() + "-1"; var tmpDate = DateTime.Parse(tmpStr).AddMonths(1).AddDays(-1); var tmpDay2 = tmpDate.Day; if (tmpDay2 < (int)accDate.AccountDays) { tmpDay = tmpDay2; } } stlDate = DateTime.Parse(tmpYear.ToString() + "-" + tmpMonth.ToString() + "-" + tmpDay.ToString()); } else { tmpDay = (int)accDate.AccountMonth; if ((int)accDate.AccountMonth > 28) { var tmpStr = tmpYear.ToString() + "-" + tmpMonth.ToString() + "-1"; var tmpDate = DateTime.Parse(tmpStr).AddMonths(2).AddDays(-1); var tmpDay2 = tmpDate.Day; if (tmpDay2 < (int)accDate.AccountMonth) { tmpDay = tmpDay2; } } stlDate = DateTime.Parse(tmpYear.ToString() + "-" + tmpMonth.ToString() + "-" + accDate.AccountMonth.ToString()).AddMonths(1); } return DataResult.Success(new CustomerStlRes() { StlName = accDate.AccountType, StlDate = stlDate }); } else if (accDate.AccountType == "季结") { stlDate = etd.AddDays((int)accDate.AccountMonth*90); return DataResult.Success(new CustomerStlRes() { StlName = accDate.AccountType, StlDate = stlDate }); } else { return DataResult.Failed("非法结算方式!"); } } #endregion #region 通用方法 /// /// 获取所有字典数据 /// /// public List GetAllDictData() { var data = db.Queryable() .InnerJoin((a, b) => a.TypeId == b.Id) .Select((a, b) => new DictDataListRes { Id = a.Id, TypeId = b.Id, TypeCode = b.Code, Name = a.Name, EnName = a.EnName, ExpandValue = a.ExpandValue }).ToList(); return data; } /// /// 获取所有Edi配置 /// /// public List GetAllEdiSet() { var data = db.Queryable().Where(x => x.Status == StatusEnum.Enable).ToList(); return data; } public BusinessEntityDto GetYardInfo(long Id) { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var yard = tenantDb.Queryable().First(v => v.Id == Id && v.Status == StatusEnum.Enable.ToEnumInt()); var data = new BusinessEntityDto(); if (yard.IsNotNull()) { data = new BusinessEntityDto() { EdiCode = yard.EDICode, Name = yard.ShortName }; } return data; } /// /// 获取第三方账户 /// /// /// /// /// /// public CodeThirdParty GetCodeThirdParty(string type,string userId, SqlSugarScopeProvider tenantDb,long customerId =0) { //var account = new CodeThirdParty(); if (userId.IsNull()) { return tenantDb.Queryable().First(x => x.AccountType == type) ; } var uId = long.Parse(userId); if (customerId == 0) { if (tenantDb.Queryable().Where(x => x.AccountType == type && x.CreateBy == uId).Any()) { return tenantDb.Queryable().Where(x => x.AccountType == type && x.CreateBy == uId).First(); } else { return tenantDb.Queryable().First(x => x.AccountType == type); } } else { if (tenantDb.Queryable().Where(x => x.AccountType == type && x.CreateBy == uId && x.CustomerId == customerId).Any()) { return tenantDb.Queryable().Where(x => x.AccountType == type && x.CreateBy == uId && x.CustomerId == customerId).First(); } else if(tenantDb.Queryable().Where(x => x.AccountType == type && x.CreateBy == uId).Any()) { return tenantDb.Queryable().First(x => x.AccountType == type && x.CreateBy == uId); } else { return tenantDb.Queryable().First(x => x.AccountType == type); } } //return account; } /// /// 获取往来单位代码 有EDICode返 无返回CodeName /// /// /// /// /// public string GetClientCode(long Id, SqlSugarScopeProvider tenantDb, bool isEDI = true) { if (Id == 0) return ""; var client = tenantDb.Queryable().First(v => v.Id == Id && v.Status == StatusEnum.Enable.ToEnumInt()); if (client.IsNull()) { throw new Exception("请检查往来单位信息"); } if (isEDI) { return client.EDICode.IsNotEmptyOrNull() ? client.EDICode : client.CodeName; } else { return client.CodeName; } } /// /// 获取场站代码 /// /// /// /// public string GetYardCode(long Id, SqlSugarScopeProvider tenantDb) { if (Id == 0) return ""; var yard = tenantDb.Queryable().First(v => v.Id == Id && v.Status == StatusEnum.Enable.ToEnumInt()); if (yard.IsNull()) { throw new Exception("请检查场站信息"); } return yard.EDICode.IsNull() ? yard.CodeName : yard.EDICode; } /// /// 获取船公司代码 /// /// /// /// public string GetCarrierCode(long Id, SqlSugarScopeProvider tenantDb) { if (Id == 0) return ""; var client = tenantDb.Queryable().First(v => v.Id == Id && v.Status == StatusEnum.Enable.ToEnumInt()); if (client.IsNull()) { throw new Exception("请检查船公司信息"); } return client.EDICode.IsNull() ? client.CodeName : client.EDICode; } /// /// 获取港口代码 /// /// /// /// public string GetPortCode(long Id, SqlSugarScopeProvider tenantDb) { if (Id == 0) return ""; var port = tenantDb.Queryable().First(v => v.Id == Id && v.Status == StatusEnum.Enable); if (port.IsNull()) { throw new Exception("请检查港口信息"); } return port.EdiCode.IsNull() ? port.PortName : port.EdiCode; } /// /// 获取船名EDI代码 /// /// /// /// public string GetVesselEDICode(long Id, string module = "") { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); string ediCode = string.Empty; var codeVesselEdi = tenantDb.Queryable().Where(v => v.LinkId == Id && v.Status == StatusEnum.Enable).WhereIF(module.IsNotEmptyOrNull(), v => v.Module == module).First(); if (codeVesselEdi != null) { ediCode = codeVesselEdi.MapCode.Trim(); } if (string.IsNullOrEmpty(ediCode)) { var codeVessel = tenantDb.Queryable().First(v => v.Id == Id); if (codeVessel != null && !string.IsNullOrEmpty(codeVessel.EdiCode)) { ediCode = codeVessel.EdiCode.Trim(); } else { ediCode = ""; } } return ediCode; } /// /// 获取港口代码 /// /// /// /// public string GetPortEDICode(long Id, string module = "") { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); string ediCode = string.Empty; var codeEdi = tenantDb.Queryable().Where(v => v.LinkId == Id && v.Status == StatusEnum.Enable).WhereIF(module.IsNotEmptyOrNull(), v => v.Module == module).First(); if (codeEdi != null) { ediCode = codeEdi.MapCode.Trim(); } if (string.IsNullOrEmpty(ediCode)) { var codeEntity = tenantDb.Queryable().First(v => v.Id == Id); if (codeEntity != null && !string.IsNullOrEmpty(codeEntity.EdiCode)) { ediCode = codeEntity.EdiCode.Trim(); } else { ediCode = ""; } } return ediCode; } /// /// 获取船公司EDI代码 /// /// /// /// public string GetCarrierEDICode(long Id, string module = "") { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); string ediCode = string.Empty; var mapEdi = tenantDb.Queryable().Where(v => v.LinkId == Id && v.Status == StatusEnum.Enable).WhereIF(module.IsNotEmptyOrNull(), v => v.Module == module).First(); if (mapEdi != null) { ediCode = mapEdi.MapCode.Trim(); } if (string.IsNullOrEmpty(ediCode)) { var entity = tenantDb.Queryable().First(v => v.Id == Id); if (entity != null && !string.IsNullOrEmpty(entity.EDICode)) { ediCode = entity.EDICode.Trim(); } else { ediCode = ""; } } return ediCode; } /// /// 获取箱型EDI代码 /// /// /// /// public string GetCtnEDICode(long Id, string module = "") { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); string ediCode = string.Empty; var mapEdi = tenantDb.Queryable().Where(v => v.LinkId == Id && v.Status == StatusEnum.Enable).WhereIF(module.IsNotEmptyOrNull(), v => v.Module == module).First(); if (mapEdi != null) { ediCode = mapEdi.MapCode.Trim(); } if (string.IsNullOrEmpty(ediCode)) { var entity = tenantDb.Queryable().First(v => v.Id == Id); if (entity != null && !string.IsNullOrEmpty(entity.EdiCode)) { ediCode = entity.EdiCode.Trim(); } else { ediCode = ""; } } return ediCode; } /// /// /// /// /// /// public string GetCtnEDICodeByCode(string code, string module = "") { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); string ediCode = string.Empty; var mapEdi = tenantDb.Queryable().Where(v => v.Code == code && v.Status == StatusEnum.Enable).WhereIF(module.IsNotEmptyOrNull(), v => v.Module == module).First(); if (mapEdi != null) { ediCode = mapEdi.MapCode.Trim(); } if (string.IsNullOrEmpty(ediCode)) { var entity = tenantDb.Queryable().First(v => v.EdiCode == code); if (entity != null && !string.IsNullOrEmpty(entity.EdiCode)) { ediCode = entity.EdiCode.Trim(); } else { ediCode = ""; } } return ediCode; } /// /// 获取箱属船司代码 /// /// /// /// public string GetCtnForCarrier(long carrierId, string module = "") { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); string ediCode = string.Empty; var codeCarrier = tenantDb.Queryable().First(v => v.Id == carrierId); var dictList = db.Queryable().InnerJoin((a, b) => a.TypeId == b.Id) .Where((a, b) => b.Code == "XiaHuoZhiCarrierBelongMapping").OrderBy((a, b) => a.OrderNo) .Select((a, b) => new { a.Name, a.Value }).ToList(); var map = dictList.FirstOrDefault(x => x.Name == codeCarrier.EDICode); if (map != null) { return map.Value; } else { return GetCarrierEDICode(carrierId, module); } } /// /// 根据订舱中的卸货港代码查找映射代码 /// /// /// /// public string GetDischargePortEDICode(long Id, string module = "") { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); string ediCode = string.Empty; var mapEdi = tenantDb.Queryable().Where(v => v.LinkId == Id && v.Status == StatusEnum.Enable).WhereIF(module.IsNotEmptyOrNull(), v => v.Module == module).First(); if (mapEdi != null) { ediCode = mapEdi.MapCode.Trim(); } if (string.IsNullOrEmpty(ediCode)) { var entity = tenantDb.Queryable().First(v => v.Id == Id); if (entity != null && !string.IsNullOrEmpty(entity.EdiCode)) { ediCode = entity.EdiCode.Trim(); } else { ediCode = ""; } } return ediCode; } /// /// 获取付费方式EDI代码 /// /// /// public string GetFrtEDICode(string frt) { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); string ediCode = "P"; var mapEdi = tenantDb.Queryable().First(v => v.Code == frt && v.Status == StatusEnum.Enable); if (mapEdi != null) { ediCode = mapEdi.MapCode.Trim(); } return ediCode; } /// /// 获取第三方账号- TODO后期使用缓存 /// /// public async Task> GetAllCodeThirdParty() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable).ToListAsync(); return data; } /// /// 获取所有箱型- TODO后期使用缓存 /// /// public async Task> GetAllCodeCtn() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable).ToListAsync(); return data; } /// /// 获取所有船司- TODO后期使用缓存 /// /// public async Task> GetAllCodeCarrier() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable.ToEnumInt()) .Select(v => new BusinessEntityDto() { EdiCode = v.EDICode, Name = v.ShortName }).ToListAsync(); return data; } /// /// 获取所有箱型映射- TODO后期使用缓存 /// /// public async Task> GetAllMappingCtn() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable).ToListAsync(); return data; } /// /// 获取所有船司映射- TODO后期使用缓存 /// /// public async Task> GetAllMappingCarrier() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable).ToListAsync(); return data; } /// /// 获取所有付费方式- TODO后期使用缓存 /// /// public async Task> GetAllCodeFrt() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable).ToListAsync(); return data; } /// /// 获取所有付费方式映射- TODO后期使用缓存 /// /// public async Task> GetAllMappingFrt() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable).ToListAsync(); return data; } /// /// 获取所有船名映射- TODO后期使用缓存 /// /// public async Task> GetAllMappingVessel() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable).ToListAsync(); return data; } /// /// 获取所有船名- TODO后期使用缓存 /// /// public async Task> GetAllCodeVessel() { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var data = await tenantDb.Queryable().Where(v => v.Status == StatusEnum.Enable) .Select(v => new BusinessEntityDto() { EdiCode = v.EdiCode, Name = v.VesselName }).ToListAsync(); return data; } #endregion #region 设置货物状态 /// /// 设置货物状态完成 /// /// /// /// public async Task SetGoodsStatus(string code, long bookingId) { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var CreatedUserId = tenantDb.Queryable().Filter(null, true).Where(x => x.Id == bookingId).Select(x => x.CreateBy).First(); if (CreatedUserId != null) { var gsCfg = tenantDb.Queryable().First(x => x.SystemCode == code && x.CreateBy == (long)CreatedUserId); if (gsCfg != null) { _logger.Info($"检查{code}货物状态:{bookingId}"); var gs = tenantDb.Queryable().First(x => x.ConfigId == gsCfg.Id && x.BusinessId == bookingId); if (gs == null) { gs = new BookingGoodsStatus() { BusinessId = bookingId, ConfigId = gsCfg.Id, FinishTime = DateTime.Now, FinishUserName = user.UserId.IsNull() ? "超级管理员" : user.UserName, FinishBy = user.UserId.IsNull() ? 0 : long.Parse(user.UserId), StatusCode = gsCfg.SystemCode, StatusName = gsCfg.StatusName, }; await tenantDb.Insertable(gs).ExecuteCommandAsync(); _logger.Info($"发送{code}后自动完成货物状态,Id:{bookingId}"); //更新货物状态 await SetBookingOrderGoodsStatus(bookingId); } } } } /// /// 更新主单货物状态 /// /// /// public async Task SetBookingOrderGoodsStatus(long bookingId) { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var order = tenantDb.Queryable().Filter(null, true).First(x => x.Id == bookingId); var createUserid = order.CreateBy; //获取当前用户已经录入的货物状态 var list = await tenantDb.Queryable().LeftJoin(tenantDb.Queryable(), (goods, config) => config.Id == goods.ConfigId).Where((goods, config) => config.CreateBy == createUserid && goods.BusinessId == bookingId). OrderBy((goods, config) => config.OrderNo). Select((goods, config) => new { ConfigId = config.Id, SystemCode = config.SystemCode, StatusName = config.StatusName, FinishTime = goods.FinishTime, FinishUser = goods.FinishUserName, FinishUserId = goods.FinishBy, IsPublic = goods.IsPublic, ExtData = goods.ExtData, Remark = goods.Note, OrderNo = config.OrderNo }).ToListAsync(); if (list != null) { //回写主单状态 var StatusName = list.Where(x => x.FinishTime.HasValue).OrderByDescending(x => x.OrderNo).Select(x => x.StatusName).FirstOrDefault(); if (StatusName == null) { StatusName = ""; } order.BusinessStatusName = StatusName; await tenantDb.Updateable(order).EnableDiffLogEvent().ExecuteCommandAsync(); // 记录日志 //var newOrder = order.Adapt(); //newOrder.BSSTATUSNAME = StatusName; //await SaveLog(newOrder, order, "自动更新货物状态"); } } #endregion #region 更新订舱的状态 /// /// 更新订舱的状态 /// /// 订舱主键 /// 状态代码 /// 状态名称 /// public async Task SaveBookingStatus(long bookingId, string code, string name) { var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var bookStatus = tenantDb.Queryable().First(x => x.BusinessId == bookingId && x.StatusCode == code); if (bookStatus == null) { //记录状态 var bookingStatus = new BookingStatus() { BusinessId = bookingId, StatusCode = code, StatusName = name, StatusTime = DateTime.Now, }; await tenantDb.Insertable(bookingStatus).ExecuteCommandAsync(); } else { bookStatus.StatusTime = DateTime.Now; await tenantDb.Updateable(bookStatus).ExecuteCommandAsync(); } } #endregion //#region 设定保存订舱的货物状态 ///// ///// 设定保存订舱的货物状态并同步东胜 ///// ///// ///// 是否默认同步东胜 true-自动同步 false-不自动同步 ///// 调用方模块名 ///// //public async Task SetBookingGoodsStatus(long bookingId, bool isAutoSyncDS = false, string fromFunc = null) //{ // 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); // var oldModel = model.Adapt(); // 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(); // // 保存日志 // await SaveLog(model, oldModel, fromFunc); // //推送东胜 // if (isAutoSyncDS) // //推送东胜 // await SendBookingOrder(new long[] { bookingId }); // } // } //} //#endregion #region 发送XHZ /// /// 发送XHZ /// /// /// /// public async Task XHZSend( long bookingId, string filerole) { //var repUser = App.GetService>(); //var repOrder = App.GetService>(); //var repCtn = App.GetService>(); //var repBookingFile = App.GetService>(); //var repUserMail = App.GetService>(); var tenantDb = saasService.GetBizDbScopeById(user.TenantId); var order = tenantDb.Queryable().First(o => o.Id == bookingId); if (order == null) { return DataResult.Failed("订舱信息未找到"); } var yardCode = GetYardCode(order.YardId, tenantDb); var carrierCode = GetCarrierCode(order.YardId, tenantDb); var tenantName = db.Queryable().Filter(null, true).Where(u => u.Id == long.Parse(user.TenantId)).Select(u => u.Name).First(); var checkRlt = XiahuozhiHelpler.CheckGoodsDescriptionWithInput(order); var issuePlaceCode = GetPortCode(order.IssuePlaceId, tenantDb); var dischargePortCode = GetPortCode(order.DischargePortId, tenantDb); var loadPortCode = GetPortCode(order.LoadPortId, tenantDb); var deliveryPlaceCode = GetPortCode(order.DeliveryPlaceId, tenantDb); var destinationCode = GetPortCode(order.DestinationId, tenantDb); //var destinationCode = GetPortCode(order.TR, tenantDb); //var loadPortCode = GetPortCode(order.tr, tenantDb); if (!checkRlt.Succeeded) { return checkRlt; } var ctns = tenantDb.Queryable().Where(c => c.BSNO == bookingId.ToString()).ToList(); var yardCodeSetList = db.Queryable().InnerJoin((a, b) => a.TypeId == b.Id) .Where((a, b) => b.Code == "XiaHuoZhiYardCodeSet").OrderBy((a, b) => a.OrderNo) .Select().ToList(); //dictData.Where(x => x.TypeCode == "XiaHuoZhiYardCodeSet").ToList(); //所有支持下货纸的场站代码配置 .Select((a, b) => a.Value) var gljEdiCarrierSetList = db.Queryable().InnerJoin((a, b) => a.TypeId == b.Id) .Where((a, b) => b.Code == "XiaHuoZhiGLJEdiCarrierSet").OrderBy((a, b) => a.OrderNo).Select().ToList();//港联捷通过EDI发送下货纸船司配置 var gljExcelMailCarrierSetList = db.Queryable().InnerJoin((a, b) => a.TypeId == b.Id) .Where((a, b) => b.Code == "XiaHuoZhiGLJExcelMailCarrierSet").OrderBy((a, b) => a.OrderNo).Select().ToList();//港联捷通过邮件Excel下货纸船司配置 var mappingCarrierAll = tenantDb.Queryable().Where(x => x.Status == StatusEnum.Enable).ToList(); var mappingCarrierLetterYard = mappingCarrierAll.Where(x => x.Module == "LetterYardCarrier").ToList(); //针对和川这种公共库不同的船司代码,需要匹配 var yardArr = yardCodeSetList.Select(x => x.Value).ToArray(); if (!yardArr.Contains(yardCode)) { return DataResult.Failed("不支持的场站"); } if (string.IsNullOrEmpty(order.MBLNO)) { return DataResult.Failed("主提单号不能为空"); } if (string.IsNullOrEmpty(order.Vessel)) { return DataResult.Failed("船名不能为空"); } if (string.IsNullOrEmpty(order.Voyno)) { return DataResult.Failed("海关航次不能为空"); } if (order.CargoId == "R") { //2023年10月11日,下货纸“货物标志”为“冻柜”时,对部分字段做校验 Regex regexSign = new Regex("^[-+]?([1-9][0-9]*|0)(\\.[0-9]+)?$"); if (!regexSign.IsMatch(order.TemperatureSet)) { return DataResult.Failed("冻柜的【设置温度】校验不通过,要求:必填、数字格式、可包含+或-"); } if (!string.IsNullOrEmpty(order.TemperatureMin) && !regexSign.IsMatch(order.TemperatureMin)) { return DataResult.Failed("冻柜的【最低温度】校验不通过,要求:非必填、数字格式、可包含+或-"); } if (!string.IsNullOrEmpty(order.TemperatureMax) && !regexSign.IsMatch(order.TemperatureMax)) { return DataResult.Failed("冻柜的【最高温度】校验不通过,要求:非必填、数字格式、可包含+或-"); } Regex regex = new Regex("^([1-9][0-9]*|0)(\\.[0-9]+)?$"); if (!regex.IsMatch(order.Humidity)) { return DataResult.Failed("冻柜的【湿度】校验不通过,要求:必填(无要求可以填0)、数字格式、不能含有+或-"); } if (!regex.IsMatch(order.ReeferQuantity)) { return DataResult.Failed("冻柜的【冷藏通风量】校验不通过,要求:必填、数字格式、不能含有+或-"); } //增加货描里的温度、湿度、通风与单个填写项的比对,必需一致才能提交 2024-04-17 JHQ } //2023年7月12日,下货纸为危险品时,需填写等级和编号 if (order.CargoId == "D" && (string.IsNullOrEmpty(order.DangerNo) || string.IsNullOrEmpty(order.DangerClass))) { return DataResult.Failed("危险品的等级和编号必须填写"); } var basePath = AppSetting.app(new string[] { "FileSettings", "BasePath" }); string filePath = String.Empty; string relativePath = AppSetting.app(new string[] { "FileSettings", "RelativePath" }); if (string.IsNullOrEmpty(basePath)) { basePath = _environment.WebRootPath; } var yardCodeGLJ = yardCodeSetList.FirstOrDefault(x => x.Name == "YardGLJ"); if (yardCodeGLJ == null) { return DataResult.Failed("港联捷场站代码未配置"); } var yardCodeGJF = yardCodeSetList.FirstOrDefault(x => x.Name == "YardGJF"); if (yardCodeGJF == null) { return DataResult.Failed("港捷丰场站代码未配置"); } var yardCodeJieFeng = yardCodeSetList.FirstOrDefault(x => x.Name == "YardJieFeng"); if (yardCodeJieFeng == null) { return DataResult.Failed("捷丰场站代码未配置"); } var yardCodeGLX = yardCodeSetList.FirstOrDefault(x => x.Name == "YardGLX"); if (yardCodeGLX == null) { return DataResult.Failed("港联欣站代码未配置"); } var yardCodeZhongChuang = yardCodeSetList.FirstOrDefault(x => x.Name == "YardZhongChuang"); if (yardCodeZhongChuang == null) { return DataResult.Failed("中创站代码未配置"); } //针对和川这种公共库不同的船司代码,需要匹配转换为当前的船司代码才能逻辑判断 var hlcCode = "HLC"; var mapCodeHLC = mappingCarrierLetterYard.FirstOrDefault(x => x.MapCode == "HLC"); if (mapCodeHLC != null) { hlcCode = mapCodeHLC.Code; } //var carrCode = seaComService.GetClientCode(order.CarrierId, tenantDb); #region 港联捷场站 if (yardCode == yardCodeGLJ.Value) { var ediPathAbs = Path.Combine(basePath, relativePath, EdiFilePath); if (!Directory.Exists(ediPathAbs)) { Directory.CreateDirectory(ediPathAbs); } //通过EDI发送下货纸的船司 if (gljEdiCarrierSetList.Select(x => x.Value).ToList().Contains(carrierCode)) { //租户参数-港联捷下货纸代号 var paraXHZ = db.Queryable().Where(v => v.Status == StatusEnum.Enable && v.TenantId == long.Parse(user.TenantId) && v.Code == "CODE_GLJ_XHZ").First(); if (paraXHZ == null || string.IsNullOrEmpty(paraXHZ.Value)) { return DataResult.Failed($"港联捷场站 下货纸代号[CODE_GLJ_XHZ]未找到或配置有误"); } var ediFileName = $"{paraXHZ.Value}_{order.MBLNO}_{DateTime.Now.Ticks}.txt"; var ediFileRela = Path.Combine(relativePath, EdiFilePath, ediFileName); var ediFileAbs = Path.Combine(ediPathAbs, ediFileName); var ediSettints = GetAllEdiSet(); var dicData = GetAllDictData(); //港联捷所有用户使用一个ftp用户名和密码发送报文,使用文件名中的下货纸代号进行区分 var paraServer = dicData.FirstOrDefault(x => x.TypeCode == "booking_ftp_setting_glj" && x.Name == "ftp_server"); var paraUser = dicData.FirstOrDefault(x => x.TypeCode == "booking_ftp_setting_glj" && x.Name == "username"); var paraPwd = dicData.FirstOrDefault(x => x.TypeCode == "booking_ftp_setting_glj" && x.Name == "pwd"); if (paraServer == null || paraUser == null || paraPwd == null) { return DataResult.Failed($"港联捷下货纸FTP服务地址参数未配置"); } StringBuilder sbData = new StringBuilder(); sbData.AppendLine($"01:{order.Vessel}:{order.Voyno}"); //船名 航次 // 12:提单号:中转港:目的港:货代代码:船公司:HPL参考号:特殊说明 sbData.AppendLine($"12:{order.MBLNO}:{order.TransPort}:{GetDischargePortEDICode(order.DischargePortId, "XHZ_GLJ")}:{paraXHZ.Value}:{GetCarrierEDICode(order.CarrierId, "XHZ_GLJ")}:{(GetCarrierEDICode(order.CarrierId) == hlcCode ? order.CustomerNo : "")}:{XiahuozhiHelpler.ExchangeStr(order.YardRemark)}"); //主提单 中转港代码 目的港代码 货代代码 船公司 HPL参考号 备注: //2021-8-17,报文中不能体现英文字符①【:】②【,】,以空格代替 /* * 表象:QDAC064651 客户毛重28600 EDI进来28  港联捷回复:是前面货名太长,后面内容截断了,每行不超过255字符就行 解决方案:每行不超过255,品名只取前100就行 */ var despStr = XiahuozhiHelpler.ExchangeStr(order.Description.Replace(":", " ").Replace(",", " ")).Replace("\r\n", " ").Replace("\n", " "); if (despStr.Length > 100) { despStr = despStr.Substring(0, 100); } //22:货名:件数:包装:重量:体积:危品标志:危品等级:危规号:副危品等级:副危规号:海污:温度:通风:湿度 sbData.AppendLine($"22:{despStr}:{order.PKGS}:{order.KindPkgs}:{order.KGS}:{order.CBM}:{(order.CargoId == "D" ? "Y" : "N")}:{order.DangerClass}:{order.DangerNo}::::{order.TemperatureSet}:{order.ReeferQuantity}:{order.Humidity}");//货名 件数 包装代码 总重量 总体积 危品标志 危品等级 危规号 副危品等级 副危规号 温度 通风度 湿度 var ctnCodes = (await GetAllCodeCtn()).Select(x => new { x.EdiCode, x.CtnSize }).ToList(); var ctnEdiList = (await GetAllMappingCtn()).AsQueryable().Where(x => x.Module == "XHZ_GLJ").ToList(); foreach (var ctn in ctns) { var ctnFind = ctnCodes.FirstOrDefault(c => c.EdiCode == ctn.CtnCode); if (ctnFind == null) { return DataResult.Failed($"未找到箱型 {ctn.CtnAll},请联系管理员"); } var ctnEdi = ctnEdiList.FirstOrDefault(cc => cc.Code == ctn.CtnCode); if (ctnEdi == null) { return DataResult.Failed($"箱型({ctn.CtnAll})不匹配(EDI类型:XHZ_GLJ),无法发送下货纸,请联系管理员"); } sbData.AppendLine($"13:{(order.IsContainerSoc.HasValue && order.IsContainerSoc.Value ? "SOC" : GetCtnForCarrier(order.CarrierId, "XHZ_GLJ"))}:{ctnFind.CtnSize}:{ctnEdi.MapCode}:{ctn.CtnNum}:{XiahuozhiHelpler.ExchangeStr(ctn.Note)}:N");//箱经营人代码 尺寸 箱型 箱数 备注 加重箱 } _logger.Info($"生成下货纸报文:{sbData.ToString()}"); File.WriteAllText(ediFileAbs, sbData.ToString()); //挂载附件 var bookFile = new OpFile { FileName = ediFileName, FilePath = ediFileRela, TypeCode = "xiahuozhi", TypeName = "下货纸", LinkId = order.Id, }; await tenantDb.Insertable(bookFile).ExecuteCommandAsync(); //发送ftp XiahuozhiHelpler.SplitFtpServerAndPort(paraServer.Value, out string server, out int port); var ftpSpiderUrl = db.Queryable().Filter(null, true).Where(x => x.Code == "booking_edi_ftp_server" && x.TenantId == 1288018625843826688).First().Value; //dicData.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "booking_edi_ftp_server").Value; NameValueCollection par = new NameValueCollection(); par.Add("host", server); par.Add("port", port.ToString()); par.Add("username", paraUser.Value); par.Add("pwd", paraPwd.Value); par.Add("path", "/"); _logger.Info($"准备请求发送ftp:{ftpSpiderUrl} ,参数:{par.ToJsonString()},文件:{ediFileName}"); var res = FTPHelper.TransmitFtpFile(ftpSpiderUrl, par, new { file = "file", fileName = Path.GetFileName(ediFileName), fileBytes = Encoding.UTF8.GetBytes(sbData.ToString()) }); _logger.Info($"发送ftp返回:{res}"); var jobjRetn = JObject.Parse(res); if (jobjRetn.GetStringValue("status") != "1") { return DataResult.Failed($"ftp发送失败:{jobjRetn.GetStringValue("message")}"); } return DataResult.Successed($"已发送"); } //通过邮件发送Excel的船司 else if (gljExcelMailCarrierSetList.Select(x => x.Value).ToList().Contains(carrierCode)) { var ediFileName = $"{carrierCode}_{order.Vessel}_{order.Voyno}_{DateTime.Now.Ticks}.xls"; var ediFileRela = Path.Combine(relativePath, EdiFilePath, ediFileName); var ediFileAbs = Path.Combine(ediPathAbs, ediFileName); var templateFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "XhzGljTemplate.xls"); if (!File.Exists(templateFile)) { return DataResult.Failed($"模板EXCEL文件未找到,请联系管理员"); } if (order.YardId == 0) { return DataResult.Failed("请选择场站"); } var yardContact = tenantDb.Queryable().First(x => x.BusinessId == order.Id && x.CustomerId == order.YardId); if (yardContact.IsNull()) { return DataResult.Failed("场站关系人不存在"); } if (string.IsNullOrEmpty(yardContact.Email)) { return DataResult.Failed($"场站联系人邮箱未填写"); } var userMail = tenantDb.Queryable().First(x => x.CreateBy == order.CreateBy); if (userMail == null || string.IsNullOrEmpty(userMail.SmtpServer) || userMail.SmtpPort == 0) { return DataResult.Failed($"发件邮箱未配置"); } MemoryStream ms = new MemoryStream(File.ReadAllBytes(templateFile)); var workbook = new HSSFWorkbook(ms); var sheet = workbook.GetSheetAt(0); #region 拼Excel //第一行标题 var title = $"下货纸清单-{order.Lane} SERVICE"; sheet.GetRow(0).GetCell(0).SetCellValue(title); //船期B2 sheet.GetRow(1).GetCell(1).SetCellValue(order.ETD.HasValue ? order.ETD.Value.ToString("yyyy.MM.dd") : ""); //船名B3 sheet.GetRow(2).GetCell(1).SetCellValue(order.Vessel); //航次F3 sheet.GetRow(2).GetCell(5).SetCellValue(order.Voyno); //代理B4 //sheet.GetRow(3).GetCell(1).SetCellValue(order.TenantName); sheet.GetRow(3).GetCell(1).SetCellValue(tenantName); //联系电话F4 var usr = db.Queryable().Filter(null, true).First(u => u.Id == order.CreateBy); //if (!string.IsNullOrEmpty(usr.Tel)) //{ // sheet.GetRow(3).GetCell(5).SetCellValue(usr.Tel); //} //else if (!string.IsNullOrEmpty(usr.Phone)) { sheet.GetRow(3).GetCell(5).SetCellValue(usr.Phone); } else { sheet.GetRow(3).GetCell(5).SetCellValue(""); } //订舱号B7 sheet.GetRow(6).GetCell(1).SetCellValue(order.CustomerNo); //目的港C7 sheet.GetRow(6).GetCell(2).SetCellValue(order.DischargePort); //中转港D7 sheet.GetRow(6).GetCell(3).SetCellValue(order.TransPortCode); //货名E7 sheet.GetRow(6).GetCell(4).SetCellValue(order.Description); //件数F7 sheet.GetRow(6).GetCell(5).SetCellValue(order.PKGS.Value.ToString()); //重量G7 sheet.GetRow(6).GetCell(6).SetCellValue(Convert.ToDouble(order.KGS.Value).ToString()); //尺码H7 sheet.GetRow(6).GetCell(7).SetCellValue(Convert.ToDouble(order.CBM.Value).ToString()); //冻柜信息 温度C I7 if (order.CargoId == "R") { sheet.GetRow(6).GetCell(8).SetCellValue(order.TemperatureSet); } else { sheet.GetRow(6).GetCell(8).SetCellValue(""); } //冻柜信息 通风CBM/H J7 if (order.CargoId == "R") { sheet.GetRow(6).GetCell(9).SetCellValue(order.ReeferQuantity); } else { sheet.GetRow(6).GetCell(9).SetCellValue(""); } //冻柜信息 湿度% K7 if (order.CargoId == "R") { sheet.GetRow(6).GetCell(10).SetCellValue(order.Humidity); } else { sheet.GetRow(6).GetCell(10).SetCellValue(""); } //整理箱型箱量 var groupList = ctns.Where(x => x.CtnNum > 0).GroupBy(c => c.CtnAll).Select(g => new { CTNALL = g.Key.Replace("'", ""), CTNNUM = g.Sum(gg => gg.CtnNum) }); //箱量 20GP L7 var findCtn = groupList.FirstOrDefault(x => x.CTNALL == "20GP"); if (findCtn != null) { sheet.GetRow(6).GetCell(11).SetCellValue(findCtn.CTNNUM.Value.ToString()); } else { sheet.GetRow(6).GetCell(11).SetCellValue(""); } //箱量 40GP M7 findCtn = groupList.FirstOrDefault(x => x.CTNALL == "40GP"); if (findCtn != null) { sheet.GetRow(6).GetCell(12).SetCellValue(findCtn.CTNNUM.Value.ToString()); } else { sheet.GetRow(6).GetCell(12).SetCellValue(""); } //箱量 40HC N7 findCtn = groupList.FirstOrDefault(x => x.CTNALL == "40HC"); if (findCtn != null) { sheet.GetRow(6).GetCell(13).SetCellValue(findCtn.CTNNUM.Value.ToString()); } else { sheet.GetRow(6).GetCell(13).SetCellValue(""); } //箱量 20RF O7 findCtn = groupList.FirstOrDefault(x => x.CTNALL == "20RF"); if (findCtn != null) { sheet.GetRow(6).GetCell(14).SetCellValue(findCtn.CTNNUM.Value.ToString()); } else { sheet.GetRow(6).GetCell(14).SetCellValue(""); } //箱量 40RH P7 findCtn = groupList.FirstOrDefault(x => x.CTNALL == "40RH"); if (findCtn != null) { sheet.GetRow(6).GetCell(15).SetCellValue(findCtn.CTNNUM.Value.ToString()); } else { sheet.GetRow(6).GetCell(15).SetCellValue(""); } //备注 场站/特殊要求 Q7 sheet.GetRow(6).GetCell(16).SetCellValue(order.YardRemark); #endregion MemoryStream msResult = new MemoryStream(); workbook.Write(msResult); File.WriteAllBytes(ediFileAbs, msResult.GetBuffer()); //挂载附件 var bookFile = new OpFile { FileName = ediFileName, FilePath = ediFileRela, TypeCode = "xiahuozhi", TypeName = "下货纸", LinkId = order.Id, }; await tenantDb.Insertable(bookFile).ExecuteCommandAsync(); //发送邮件 var sendResult = await MailSendHelper.SendMail(userMail, title, "", yardContact.Email, new KeyValuePair(ediFileName, msResult.GetBuffer())); if (!sendResult.Succeeded) { return DataResult.Failed(sendResult.Message); } return DataResult.Successed($"已发送"); } else { return DataResult.Failed("该船司不支持发送港联捷下货纸"); } } #endregion #region 港捷丰场站 捷丰场站 NOTE:港捷丰场站和捷丰场站下货纸功能,根据东胜7同功能模块代码翻译而来 else if (yardCode == yardCodeGJF.Value || yardCode == yardCodeJieFeng.Value) { if (!order.PKGS.HasValue || order.PKGS.Value == 0) { return DataResult.Failed($"件数不能为空"); } if (string.IsNullOrEmpty(order.KindPkgs)) { return DataResult.Failed($"件数包装不能为空"); } if (!order.KGS.HasValue || order.KGS.Value == 0) { return DataResult.Failed($"重量不能为空"); } if (!order.CBM.HasValue || order.CBM.Value == 0) { return DataResult.Failed($"尺码不能为空"); } var ediFileName = $"{order.Vessel}_{order.Voyno}_{order.MBLNO}_{DateTime.Now.Ticks}.txt"; var ediFileRela = Path.Combine(relativePath, EdiFilePath, ediFileName); var ediPathAbs = Path.Combine(basePath, relativePath, EdiFilePath); var ediFileAbs = Path.Combine(ediPathAbs, ediFileName); if (!Directory.Exists(ediPathAbs)) { Directory.CreateDirectory(ediPathAbs); } CodeEdiSet ftpset = null; if (yardCode == yardCodeGJF.Value) { ftpset = tenantDb.Queryable().First(f => f.EdiTypeCode == "XHZ_GJF"); } else if (yardCode == yardCodeJieFeng.Value) { ftpset = tenantDb.Queryable().First(f => f.EdiTypeCode == "XHZ_JIEFENG"); } var yardContact = tenantDb.Queryable().First(x => x.BusinessId == order.Id && x.CustomerId == order.YardId); if (yardContact.IsNull()) { return DataResult.Failed("场站关系人不存在"); } if (string.IsNullOrEmpty(yardContact.Email)) { return DataResult.Failed($"场站联系人邮箱未填写"); } if (ftpset == null) { return DataResult.Failed($"ftp设置未找到"); } var ediParaName = "XHZ_GJF"; if (yardCode == yardCodeJieFeng.Value) { ediParaName = "XHZ_JIEFENG"; } List listJoinStr = new List(); listJoinStr.Add("00:IFCSUM:BK:" + filerole + ":" + ftpset.SendCode + ":" + ftpset.ReceiveCode + ":" + DateTime.Now.ToString("yyyyMMddHHmm") + ":2.1'"); //提单号 listJoinStr.Add("02:" + order.Id.ToString() + ":" + order.MBLNO.Trim() + ":" + order.Service + ":" + ftpset.SendName + ":" + ftpset.ReceiveCode + "::::::::::" + order.ContractNo + ":" + (carrierCode == hlcCode ? order.CustomerNo : "") + ":'"); //提单地址 var ISSUETYPE = ""; if (order.IssueType == "正本") { ISSUETYPE = "ORI"; } else { ISSUETYPE = "EXP"; } listJoinStr.Add("03:" + ISSUETYPE + ":" + issuePlaceCode + ":" + order.IssuePlace + ":" + XiahuozhiHelpler.GetDateStr(order.IssueDate, "yyyyMMdd") + ":" + XiahuozhiHelpler.GetBillNum2(order.NoBill) + ":" + loadPortCode + ":" + order.PrepareAt + ":" + order.PayableAt + "::'");//美国AMS标志、加拿大AMS标志 //船 listJoinStr.Add("11:" + GetVesselEDICode(order.VesselId, ediParaName) + ":" + order.Vessel + ":" + order.Voyno + ":::" + GetCarrierEDICode(order.CarrierId, ediParaName) + "::" + XiahuozhiHelpler.GetDateStr(order.ETD, "yyyyMMdd") + "::::::" + yardContact.Name + ":" + XiahuozhiHelpler.formatEdiStr("txt", order.YardRemark) + ":'"); //港口 listJoinStr.Add("12:" + order.ReceiptPlace + ":" + order.ReceiptPlace + ":" + loadPortCode + ":" + order.LoadPort + ":" + GetDischargePortEDICode(order.DischargePortId, ediParaName) + ":" + order.DischargePort + ":::" + deliveryPlaceCode + ":" + order.DeliveryPlace + ":" + destinationCode + ":" + order.Destination + "'"); //付费方式 var frtstr = GetFrtEDICode(order.MBLFrt); if (frtstr != "") { listJoinStr.Add("14:" + frtstr + ":" + order.MBLFrt + "'"); listJoinStr.Add("15:::" + frtstr + ":::::::'"); } else { listJoinStr.Add("14:P:" + order.MBLFrt + "'"); listJoinStr.Add("15:::P:::::::'"); } var Shipping = ""; List ShippingList = null; //2021年9月1日修改,17行取消,放到11行原FAX位置(于斐) ////EDI备注 //if (!string.IsNullOrWhiteSpace(order.YardRemark)) //{ // Shipping = formatEdiStr("txt", order.YardRemark); // ShippingList = formatlengthStr(Shipping, 70); // if (Shipping != "") // { // listJoinStr.Add("17:" + formatListStr(ShippingList, 5) + "'"); // } //} //发货人 Shipping = XiahuozhiHelpler.formatEdiStr("txt", order.ShipperContent); ShippingList = XiahuozhiHelpler.formatlengthStr(Shipping, 35); if (ShippingList.Count != 0 && Shipping.Length > 0) { listJoinStr.Add("18::" + XiahuozhiHelpler.formatListStr(ShippingList, 6) + "'"); } //收货人 Shipping = XiahuozhiHelpler.formatEdiStr("txt", order.ConsigneeContent); ShippingList = XiahuozhiHelpler.formatlengthStr(Shipping, 35); if (ShippingList.Count != 0 && Shipping.Length > 0) { listJoinStr.Add("19::" + XiahuozhiHelpler.formatListStr(ShippingList, 6) + "'"); } //通知人 Shipping = XiahuozhiHelpler.formatEdiStr("txt", order.NotifyPartyContent); ShippingList = XiahuozhiHelpler.formatlengthStr(Shipping, 35); if (ShippingList.Count != 0 && Shipping.Length > 0) { listJoinStr.Add("20::" + XiahuozhiHelpler.formatListStr(ShippingList, 6) + "'"); } //货物标识 var cargoid = order.CargoId; if (string.IsNullOrWhiteSpace(cargoid)) { cargoid = "S"; } listJoinStr.Add("41:1::" + cargoid + ":" + order.PKGS.ToString() + ":" + order.KindPkgs + ":" + order.KindPkgs + ":" + order.KGS.ToString() + ":" + order.CBM.ToString() + "::::::" + order.KGS.ToString() + ":::'");//bill.HSCODE if (cargoid == "R") { listJoinStr.Add("43:::::::::::" + order.ReeferQuantity + ":C:" + order.TemperatureSet + ":" + order.TemperatureMin + ":" + order.TemperatureMax + "::::::" + order.Humidity + "::::'"); } else if (cargoid == "D") { listJoinStr.Add("43:" + order.DangerClass + ":" + order.DangerPage + ":" + order.DangerNo + ":" + order.DangerLabel + "::::::::::::::::::::'"); } //唛头 Shipping = XiahuozhiHelpler.formatEdiStr("txt", order.Marks); ShippingList = XiahuozhiHelpler.formatlengthStr(Shipping, 35); for (var i = 0; i < Math.Ceiling(Convert.ToDecimal(Convert.ToDecimal(ShippingList.Count) / Convert.ToDecimal(9))); i++) { var tempstr = "44:"; for (var z = 0; z < 9; z++) { if ((i * 9 + z) < ShippingList.Count) tempstr = tempstr + ShippingList[i * 9 + z]; if (z < 8) tempstr = tempstr + ":"; } if (tempstr != "44:") { listJoinStr.Add(tempstr + "'"); } } //货物描述 Shipping = XiahuozhiHelpler.formatEdiStr("txt", order.Description); ShippingList = XiahuozhiHelpler.formatlengthStr(Shipping, 70); var m = 1; var strtemp = ""; if (ShippingList.Count != 0 && Shipping.Length > 0) { for (var i = 0; i < ShippingList.Count; i++) { if (m <= 5) { if (m == 1) strtemp = "47:" + ShippingList[i] + ":"; else { if (m == 5) strtemp = strtemp + ShippingList[i]; else strtemp = strtemp + ShippingList[i] + ":"; } } else { m = 1; listJoinStr.Add(strtemp + "'"); strtemp = "47:" + ShippingList[i] + ":"; } m = m + 1; } } if (strtemp != "") { listJoinStr.Add(strtemp + "'"); } //集装箱 var groupList = ctns.Where(c => c.CtnNum.HasValue).GroupBy(c => c.CtnCode).Select(c => new { c.Key, CTNNUM = c.Sum(cc => cc.CtnNum) }).ToList(); foreach (var g in groupList) { listJoinStr.Add("48:" + GetCtnEDICodeByCode(g.Key, ediParaName) + ":" + g.CTNNUM + $":F:::::{(order.IsContainerSoc.HasValue && order.IsContainerSoc.Value ? "Y" : "N")}'"); } foreach (var ctn in ctns) { if (ctn.CntrNo != "") { listJoinStr.Add("51:" + ctn.CntrNo + ":" + GetCtnEDICodeByCode(ctn.CtnCode, ediParaName) + ":" + ctn.SealNo + ":M:CA:F:" + ctn.PKGS.ToString() + ":" + ctn.KGS.ToString() + "::" + ctn.CBM + "'"); } } listJoinStr.Add("99:" + listJoinStr.Count + 1 + "'"); var strJoin = string.Join(Environment.NewLine, listJoinStr); _logger.Info($"生成下货纸报文:{strJoin}"); File.WriteAllText(ediFileAbs, strJoin, Encoding.Default); //挂载附件 var bookFile = new OpFile { FileName = ediFileName, FilePath = ediFileRela, TypeCode = "xiahuozhi", TypeName = "下货纸", LinkId = order.Id, }; await tenantDb.Insertable(bookFile).ExecuteCommandAsync(); //发送ftp XiahuozhiHelpler.SplitFtpServerAndPort(ftpset.ServerIp, out string server, out int port); var ftpSpiderUrl = db.Queryable().Filter(null, true).Where(x => x.Code == "booking_edi_ftp_server" && x.TenantId == 1288018625843826688).First().Value; //(await cacheService.GetAllDictData()).FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "booking_edi_ftp_server").Value; NameValueCollection par = new NameValueCollection(); par.Add("host", server); par.Add("port", port.ToString()); par.Add("username", ftpset.UserName); par.Add("pwd", ftpset.Password); par.Add("path", ftpset.FolderName); par.Add("pasv", (!ftpset.FtpModeActive).ToString()); _logger.Info($"准备请求发送ftp:{ftpSpiderUrl} ,参数:{par.ToJsonString()},文件:{ediFileName}"); var res = FTPHelper.TransmitFtpFile(ftpSpiderUrl, par, new { file = "file", fileName = Path.GetFileName(ediFileName), fileBytes = Encoding.UTF8.GetBytes(strJoin) }); _logger.Info($"发送ftp返回:{res}"); var jobjRetn = JObject.Parse(res); if (jobjRetn.GetStringValue("status") != "1") { return DataResult.Failed($"ftp发送失败:{jobjRetn.GetStringValue("message")}"); } return DataResult.Successed($"完成"); } #endregion #region 港联欣场站 else if (yardCode == yardCodeGLX.Value || yardCode == yardCodeZhongChuang.Value) { //2022年6月15日增加:港联欣场站若配置了通过港联捷EDI发送,则使用港联捷报文格式 //var tenantParam = await cacheService.GetAllTenantParam(); var pGlxEdi = db.Queryable().Where(x => x.Code == "XIAHUOZHI_GLX_SEND_TYPE").First(); //tenantParam.FirstOrDefault(p => p.TenantId == order.TenantId && p.ParaCode == "XIAHUOZHI_GLX_SEND_TYPE"); if (yardCode == yardCodeGLX.Value && pGlxEdi != null && pGlxEdi.Value == "EDI_GLX") { var glxCarrierList = GetAllDictData().Where(x => x.TypeCode == "XiaHuoZhiGLXCarrierConfig").Select(x => x.Value).ToList();//港联欣支持的船司 if (!glxCarrierList.Contains(carrierCode)) { return DataResult.Failed($"港联欣下货纸当前不支持此船公司"); } var ftpset = db.Queryable().Where(x => x.EdiTypeCode == "CODE_GLX_XHZ").First(); //(await cacheService.GetAllEdiSetting()).FirstOrDefault(f => f.EDICODE == "XHZ_GLX" && f.TenantId == order.TenantId); if (ftpset == null) { return DataResult.Failed($"港联欣下货纸ftp设置未找到"); } var paraXHZ = db.Queryable().Where(x => x.Code == "CODE_GLX_XHZ").First(); //tenantParam.FirstOrDefault(p => p.TenantId == order.TenantId && p.ParaCode == "CODE_GLX_XHZ"); if (paraXHZ == null || string.IsNullOrEmpty(paraXHZ.Value)) { return DataResult.Failed($"下货纸代号[CODE_GLX_XHZ]未找到或配置有误"); } var ediFileName = $"{paraXHZ.Value}_{order.MBLNO}_{DateTime.Now.Ticks}.txt"; var ediFileRela = Path.Combine(relativePath, EdiFilePath, ediFileName); var ediPathAbs = Path.Combine(basePath, relativePath, EdiFilePath); var ediFileAbs = Path.Combine(ediPathAbs, ediFileName); if (!Directory.Exists(ediPathAbs)) { Directory.CreateDirectory(ediPathAbs); } StringBuilder sbData = new StringBuilder(); sbData.AppendLine($"01:{order.Vessel}:{order.Voyno}"); //船名 航次 sbData.AppendLine($"12:{order.MBLNO}:{order.TransPortCode}:{GetDischargePortEDICode(order.DischargePortId, "XHZ_GLX")}:{paraXHZ.Value}:{GetCarrierEDICode(order.CarrierId, "XHZ_GLX")}:{(carrierCode == hlcCode ? order.CustomerNo : "")}:{order.DischargePort}"); //主提单 中转港代码 目的港代码 货代代码 船公司 HPL参考号 备注 var despStr = XiahuozhiHelpler.ExchangeStr(order.Destination.Replace(":", " ").Replace(",", " ")).Replace("\r\n", " ").Replace("\n", " "); if (despStr.Length > 100) { despStr = despStr.Substring(0, 100); } /* “22” 2 字符 货物信息开始 货名 20 字符 必填 件数 10 字符 必填 包装代码 6 字符 必填 总重量 11 字符 公斤 必填 总体积 6 字符 立方米 必填 危品标志 1 字符 Y/N 必填 危品等级 5 字符 危规号 5 字符 副危品等级 5 字符 副危规号 5 字符 温度 5 字符 不带单位,默认C 通风度 5 字符 不带单位,默认CBM/H 湿度 5 字符 不带单位,默认% 回车换行 2 ASC码 ASC码“0D”“0A” */ sbData.AppendLine($"22:{despStr}:{order.PKGS}:{order.KindPkgs}:{order.KGS}:{order.CBM}:{(order.CargoId == "D" ? "Y" : "N")}:{order.DangerClass}:{order.DangerNo}:::{order.TemperatureSet}:{order.ReeferQuantity}:{order.Humidity}");//货名 件数 包装代码 总重量 总体积 危品标志 危品等级 危规号 副危品等级 副危规号 温度 通风度 湿度 var ctnCodes = tenantDb.Queryable().Select(x => new { x.EdiCode, x.CtnSize }).ToList(); var ctnEdiList = tenantDb.Queryable().Where(x => x.Module == "XHZ_GLX").ToList(); var groupList = ctns.GroupBy(x => new { x.CtnAll, x.CtnCode }).Select(x => new { CTNCODE = x.Key.CtnCode, CTNALL = x.Key.CtnAll, COUNT = x.Sum(y => y.CtnNum) }).ToList(); foreach (var ctn in groupList) { var ctnFind = ctnCodes.FirstOrDefault(c => c.EdiCode == ctn.CTNCODE); if (ctnFind == null) { return DataResult.Failed($"未找到箱型 {ctn.CTNALL},请联系管理员"); } var ctnEdi = ctnEdiList.FirstOrDefault(cc => cc.Code == ctn.CTNCODE); if (ctnEdi == null) { return DataResult.Failed($"箱型({ctn.CTNALL})不匹配(EDI类型:XHZ_GLX),无法发送下货纸,请联系管理员"); } sbData.AppendLine($"13:{(order.IsContainerSoc.HasValue && order.IsContainerSoc.Value ? "SOC" : GetCtnForCarrier(order.CarrierId, "XHZ_GLJ"))}:{ctnFind.CtnSize}:{ctnEdi.MapCode}:{ctn.COUNT}::N");//箱经营人代码 尺寸 箱型 箱数 备注 加重箱 } _logger.Info($"生成下货纸报文:{sbData.ToString()}"); File.WriteAllText(ediFileAbs, sbData.ToString()); //挂载附件 var bookFile = new OpFile { FileName = ediFileName, FilePath = ediFileRela, TypeCode = "xiahuozhi", TypeName = "下货纸", LinkId = order.Id, }; await tenantDb.Insertable(bookFile).ExecuteCommandAsync(); //发送ftp XiahuozhiHelpler.SplitFtpServerAndPort(ftpset.ServerIp, out string server, out int port); var ftpSpiderUrl = db.Queryable().Filter(null, true).Where(x => x.Code == "booking_edi_ftp_server" && x.TenantId == 1288018625843826688).First().Value; //(await cacheService.GetAllDictData()).FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "booking_edi_ftp_server").Value; NameValueCollection par = new NameValueCollection(); par.Add("host", server); par.Add("port", port.ToString()); par.Add("username", ftpset.UserName); par.Add("pwd", ftpset.Password); par.Add("path", ftpset.FolderName); par.Add("pasv", (!ftpset.FtpModeActive).ToString()); _logger.Info($"准备请求发送ftp:{ftpSpiderUrl} ,参数:{par.ToJsonString()},文件:{ediFileName}"); var res = FTPHelper.TransmitFtpFile(ftpSpiderUrl, par, new { file = "file", fileName = Path.GetFileName(ediFileName), fileBytes = Encoding.UTF8.GetBytes(sbData.ToString()) }); _logger.Info($"发送ftp返回:{res}"); var jobjRetn = JObject.Parse(res); if (jobjRetn.GetStringValue("status") != "1") { return DataResult.Failed($"ftp发送失败:{jobjRetn.GetStringValue("message")}"); } } else //邮件方式 { if (order.YardId == 0) { return DataResult.Failed("请选择场站"); } var yardContact = tenantDb.Queryable().First(x => x.BusinessId == order.Id && x.CustomerId == order.YardId); if (yardContact.IsNull()) { return DataResult.Failed("场站关系人不存在"); } if (string.IsNullOrEmpty(yardContact.Email)) { return DataResult.Failed($"场站联系人邮箱未填写"); } var userMail = tenantDb.Queryable().First(x => x.CreateBy == order.CreateBy); if (userMail == null || string.IsNullOrEmpty(userMail.SmtpServer) || userMail.SmtpPort == 0) { return DataResult.Failed($"发件邮箱未配置"); } var usr = db.Queryable().Filter(null, true).First(u => u.Id == order.CreateBy); var title = $"下货纸:{order.MBLNO}/{order.Carrier}/{order.Vessel}/{order.Voyno}/{tenantName}"; var bodyExt = string.Empty; if (order.CargoId == "R") { bodyExt = $@"温度:{order.TemperatureSet}{order.TemperatureUnit}
通风:{order.ReeferQuantity}
湿度:{order.Humidity}
"; } else if (order.CargoId == "D") { bodyExt = $@"危险品等级:{order.DangerClass}
危险品编号:{order.DangerNo}
危险品联系方式:{order.LinkMan}
"; } var body = $@"提单号:{order.MBLNO}
船名航次:{order.Vessel}/{order.Voyno}
起运港:{order.LoadPort},{loadPortCode}
目的港:{order.DischargePort},{GetDischargePortEDICode(order.DischargePortId, "XHZ_GLX")}
目的地:{order.Destination},{destinationCode}
预计船期:{(order.ETD.HasValue ? order.ETD.Value.ToString("yyyy-MM-dd") : "")}
箱型箱量:{order.CntrTotal}
件重尺:{order.PKGS} {order.KindPkgs}/{order.KGS}KGS/{order.CBM}CBM
货物描述:{order.Description}
{bodyExt} 备注:{order.YardRemark}

订舱代理:{tenantName}
联系人:{usr.UserName}
电话:{usr.Phone} 手机:{usr.Phone}
邮箱:{usr.Email}
"; var sendResult = await MailSendHelper.SendMail(userMail, title, body, yardContact.Email); if (!sendResult.Succeeded) { return DataResult.Failed(sendResult.Message); } } return DataResult.Successed("已发送"); } #endregion else { return DataResult.Failed("不支持的场站"); } } #endregion /// /// /// /// /// public async Task> GetConfigData(string code) { var config = await db.Queryable().Filter(null, true).Where(x => x.Code == code && x.Status == StatusEnum.Enable).FirstAsync(); if (config.IsNull()) { return await Task.FromResult(DataResult.Failed("OCR接口地址未配置!")); } return await Task.FromResult(DataResult.Success(config.Value)); } } }