You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1812 lines
81 KiB
C#

using Amazon.S3.Model;
using DS.Module.Core;
using DS.Module.Core.Extensions;
using DS.Module.SqlSugar;
7 months ago
using DS.Module.UserModule;
using DS.WMS.Core.Code.Entity;
using DS.WMS.Core.Info.Entity;
using DS.WMS.Core.Map.Entity;
7 months ago
using DS.WMS.Core.Op.Dtos;
using DS.WMS.Core.Op.EDI;
7 months ago
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 Microsoft.AspNetCore.Hosting;
7 months ago
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
7 months ago
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;
7 months ago
namespace DS.WMS.Core.Op.Method
{
public class SeaExportCommonService : ISeaExportCommonService
7 months ago
{
6 months ago
private static readonly string EdiFilePath = "XHZ";
7 months ago
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;
7 months ago
/// <summary>
///
/// </summary>
/// <param name="serviceProvider"></param>
public SeaExportCommonService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
saasService = _serviceProvider.GetRequiredService<ISaasDbService>();
commonService = _serviceProvider.GetRequiredService<ICommonService>();
_environment = _serviceProvider.GetRequiredService<IWebHostEnvironment>();
7 months ago
}
#region 获取客户结算方式及结算日期
public DataResult<CustomerStlRes> GetCustomerStlInfo(CustomerStlReq req)
{
DateTime? stlDate;
DateTime etd;
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
if (req.ETD.IsNull())
{
return DataResult<CustomerStlRes>.Failed("开船日期不能为空!");
}
if (DateTime.TryParse(req.ETD.Value.ToString("yyyy-MM-dd"), out DateTime result))
{
// 转换成功赋值给Nullable<DateTime>
etd = result;
}
else
{
return DataResult<CustomerStlRes>.Failed("开船日期格式不正确!");
}
var accDate = tenantDb.Queryable<InfoClientAccountDate>().First(x=>x.ClientId == req.CustomerId && etd >= x.BeginDate && etd <= x.EndDate);
if (accDate.IsNull())
{
return DataResult<CustomerStlRes>.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<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate
});
}
else
{
if (accDate.AccountDays == 0)
{
return DataResult<CustomerStlRes>.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<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate
});
}
}
}
else if (accDate.AccountType == "约定天数")
{
stlDate = etd.AddDays((int)accDate.AccountDays);
return DataResult<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate
});
}
else if (accDate.AccountType == "旬结")
{
stlDate = etd.AddDays(10);
return DataResult<CustomerStlRes>.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<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate
});
}
else if (accDate.AccountType == "季结")
{
stlDate = etd.AddDays((int)accDate.AccountMonth*90);
return DataResult<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate
});
}
else
{
return DataResult<CustomerStlRes>.Failed("非法结算方式!");
}
}
#endregion
#region 通用方法
/// <summary>
/// 获取所有字典数据
/// </summary>
/// <returns></returns>
public List<DictDataListRes> GetAllDictData()
{
var data = db.Queryable<SysDictData>()
.InnerJoin<SysDictType>((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;
}
/// <summary>
/// 获取所有Edi配置
/// </summary>
/// <returns></returns>
public List<CodeEdiSet> GetAllEdiSet()
{
var data = db.Queryable<CodeEdiSet>().Where(x => x.Status == StatusEnum.Enable).ToList();
return data;
}
public BusinessEntityDto GetYardInfo(long Id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var yard = tenantDb.Queryable<InfoClient>().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;
}
/// <summary>
/// 获取场站代码
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public string GetYardCode(long Id, SqlSugarScopeProvider tenantDb)
{
var yard = tenantDb.Queryable<InfoClient>().First(v => v.Id == Id && v.Status == StatusEnum.Enable.ToEnumInt());
return yard.EDICode;
}
/// <summary>
/// 获取船公司代码
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public string GetCarrierCode(long Id, SqlSugarScopeProvider tenantDb)
{
var yard = tenantDb.Queryable<InfoClient>().First(v => v.Id == Id && v.Status == StatusEnum.Enable.ToEnumInt());
return yard.EDICode;
}
/// <summary>
/// 获取港口代码
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public string GetPortCode(long Id, SqlSugarScopeProvider tenantDb)
{
var yard = tenantDb.Queryable<CodePort>().First(v => v.Id == Id && v.Status == StatusEnum.Enable);
return yard.EdiCode;
}
/// <summary>
/// 获取船名EDI代码
/// </summary>
/// <param name="Id"></param>
/// <param name="module"></param>
/// <returns></returns>
public string GetVesselEDICode(long Id, string module = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
string ediCode = string.Empty;
var codeVesselEdi = tenantDb.Queryable<MappingVessel>().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<CodeVessel>().First(v => v.Id == Id);
if (codeVessel != null && !string.IsNullOrEmpty(codeVessel.EdiCode))
{
ediCode = codeVessel.EdiCode.Trim();
}
else
{
ediCode = "";
}
}
return ediCode;
}
/// <summary>
6 months ago
/// 获取港口代码
/// </summary>
/// <param name="Id"></param>
/// <param name="module"></param>
/// <returns></returns>
public string GetPortEDICode(long Id, string module = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
string ediCode = string.Empty;
var codeEdi = tenantDb.Queryable<MappingPort>().Where(v => v.LinkId == Id && v.Status == StatusEnum.Enable).WhereIF(module.IsNotEmptyOrNull(), v => v.Module == module).First();
6 months ago
if (codeEdi != null)
{
ediCode = codeEdi.MapCode.Trim();
}
if (string.IsNullOrEmpty(ediCode))
{
var codeEntity = tenantDb.Queryable<CodePort>().First(v => v.Id == Id);
if (codeEntity != null && !string.IsNullOrEmpty(codeEntity.EdiCode))
{
ediCode = codeEntity.EdiCode.Trim();
}
else
{
ediCode = "";
}
}
return ediCode;
}
/// <summary>
/// 获取船公司EDI代码
/// </summary>
/// <param name="Id"></param>
/// <param name="module"></param>
/// <returns></returns>
public string GetCarrierEDICode(long Id, string module = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
string ediCode = string.Empty;
var mapEdi = tenantDb.Queryable<MappingCarrier>().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<InfoClient>().First(v => v.Id == Id);
if (entity != null && !string.IsNullOrEmpty(entity.EDICode))
{
ediCode = entity.EDICode.Trim();
}
else
{
ediCode = "";
}
}
return ediCode;
}
/// <summary>
/// 获取箱型EDI代码
/// </summary>
/// <param name="Id"></param>
/// <param name="module"></param>
/// <returns></returns>
public string GetCtnEDICode(long Id, string module = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
string ediCode = string.Empty;
var mapEdi = tenantDb.Queryable<MappingCtn>().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<CodeCtn>().First(v => v.Id == Id);
if (entity != null && !string.IsNullOrEmpty(entity.EdiCode))
{
ediCode = entity.EdiCode.Trim();
}
else
{
ediCode = "";
}
}
return ediCode;
}
/// <summary>
///
/// </summary>
/// <param name="code"></param>
/// <param name="module"></param>
/// <returns></returns>
public string GetCtnEDICodeByCode(string code, string module = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
string ediCode = string.Empty;
var mapEdi = tenantDb.Queryable<MappingCtn>().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<CodeCtn>().First(v => v.EdiCode == code);
if (entity != null && !string.IsNullOrEmpty(entity.EdiCode))
{
ediCode = entity.EdiCode.Trim();
}
else
{
ediCode = "";
}
}
return ediCode;
}
/// <summary>
/// 获取箱属船司代码
/// </summary>
/// <param name="carrierId"></param>
/// <param name="module"></param>
/// <returns></returns>
public string GetCtnForCarrier(long carrierId, string module = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
string ediCode = string.Empty;
var codeCarrier = tenantDb.Queryable<InfoClient>().First(v => v.Id == carrierId);
var dictList = db.Queryable<SysDictData>().InnerJoin<SysDictType>((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);
}
}
/// <summary>
/// 根据订舱中的卸货港代码查找映射代码
/// </summary>
/// <param name="Id"></param>
/// <param name="module"></param>
/// <returns></returns>
public string GetDischargePortEDICode(long Id, string module = "")
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
string ediCode = string.Empty;
var mapEdi = tenantDb.Queryable<MappingPort>().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<CodePort>().First(v => v.Id == Id);
if (entity != null && !string.IsNullOrEmpty(entity.EdiCode))
{
ediCode = entity.EdiCode.Trim();
}
else
{
ediCode = "";
}
}
return ediCode;
}
/// <summary>
/// 获取付费方式EDI代码
/// </summary>
/// <param name="frt"></param>
/// <returns></returns>
public string GetFrtEDICode(string frt)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
string ediCode = "P";
var mapEdi = tenantDb.Queryable<MappingFrt>().First(v => v.Code == frt && v.Status == StatusEnum.Enable);
if (mapEdi != null)
{
ediCode = mapEdi.MapCode.Trim();
}
return ediCode;
}
/// <summary>
/// 获取第三方账号- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<CodeThirdParty>> GetAllCodeThirdParty()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<CodeThirdParty>().Where(v => v.Status == StatusEnum.Enable).ToListAsync();
return data;
}
/// <summary>
/// 获取所有箱型- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<CodeCtn>> GetAllCodeCtn()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<CodeCtn>().Where(v => v.Status == StatusEnum.Enable).ToListAsync();
return data;
}
/// <summary>
/// 获取所有船司- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<BusinessEntityDto>> GetAllCodeCarrier()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<InfoClient>().Where(v => v.Status == StatusEnum.Enable.ToEnumInt())
.Select(v => new BusinessEntityDto()
{
EdiCode = v.EDICode,
Name = v.ShortName
}).ToListAsync();
return data;
}
/// <summary>
/// 获取所有箱型映射- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<MappingCtn>> GetAllMappingCtn()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<MappingCtn>().Where(v => v.Status == StatusEnum.Enable).ToListAsync();
return data;
}
/// <summary>
/// 获取所有船司映射- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<MappingCarrier>> GetAllMappingCarrier()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<MappingCarrier>().Where(v => v.Status == StatusEnum.Enable).ToListAsync();
return data;
}
/// <summary>
/// 获取所有付费方式- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<CodeFrt>> GetAllCodeFrt()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<CodeFrt>().Where(v => v.Status == StatusEnum.Enable).ToListAsync();
return data;
}
/// <summary>
/// 获取所有付费方式映射- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<MappingFrt>> GetAllMappingFrt()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<MappingFrt>().Where(v => v.Status == StatusEnum.Enable).ToListAsync();
return data;
}
/// <summary>
/// 获取所有船名映射- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<MappingVessel>> GetAllMappingVessel()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<MappingVessel>().Where(v => v.Status == StatusEnum.Enable).ToListAsync();
return data;
}
/// <summary>
/// 获取所有船名- TODO后期使用缓存
/// </summary>
/// <returns></returns>
public async Task<List<BusinessEntityDto>> GetAllCodeVessel()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<CodeVessel>().Where(v => v.Status == StatusEnum.Enable)
.Select(v => new BusinessEntityDto()
{
EdiCode = v.EdiCode,
Name = v.VesselName
}).ToListAsync();
return data;
}
#endregion
7 months ago
#region 设置货物状态
/// <summary>
/// 设置货物状态完成
/// </summary>
/// <param name="code"></param>
/// <param name="bookingId"></param>
/// <returns></returns>
public async Task SetGoodsStatus(string code, long bookingId)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var CreatedUserId = tenantDb.Queryable<SeaExport>().Filter(null, true).Where(x => x.Id == bookingId).Select(x => x.CreateBy).First();
if (CreatedUserId != null)
{
var gsCfg = tenantDb.Queryable<BookingGoodsStatusConfig>().First(x => x.SystemCode == code && x.CreateBy == (long)CreatedUserId);
if (gsCfg != null)
{
_logger.Info($"检查{code}货物状态:{bookingId}");
var gs = tenantDb.Queryable<BookingGoodsStatus>().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.UserId,
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);
}
}
}
}
/// <summary>
/// 更新主单货物状态
/// </summary>
/// <param name="bookingId"></param>
/// <returns></returns>
public async Task SetBookingOrderGoodsStatus(long bookingId)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var order = tenantDb.Queryable<SeaExport>().Filter(null, true).First(x => x.Id == bookingId);
var createUserid = order.CreateBy;
//获取当前用户已经录入的货物状态
var list = await tenantDb.Queryable<BookingGoodsStatus>().LeftJoin(tenantDb.Queryable<BookingGoodsStatusConfig>(),
(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<SeaExport>();
//newOrder.BSSTATUSNAME = StatusName;
//await SaveLog(newOrder, order, "自动更新货物状态");
}
}
#endregion
#region 更新订舱的状态
/// <summary>
/// 更新订舱的状态
/// </summary>
/// <param name="bookingId">订舱主键</param>
/// <param name="code">状态代码</param>
/// <param name="name">状态名称</param>
/// <returns></returns>
public async Task SaveBookingStatus(long bookingId, string code, string name)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var bookStatus = tenantDb.Queryable<BookingStatus>().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 设定保存订舱的货物状态
///// <summary>
///// 设定保存订舱的货物状态并同步东胜
///// </summary>
///// <param name="bookingId"></param>
///// <param name="isAutoSyncDS">是否默认同步东胜 true-自动同步 false-不自动同步</param>
///// <param name="fromFunc">调用方模块名</param>
///// <returns></returns>
//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<List<ServiceProjectStatusDto>>(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<BookingOrder>();
// 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
/// <summary>
/// 发送XHZ
/// </summary>
/// <param name="bookingId"></param>
/// <param name="filerole"></param>
/// <returns></returns>
public async Task<DataResult> XHZSend(
long bookingId, string filerole)
{
//var repUser = App.GetService<SqlSugarRepository<SysUser>>();
//var repOrder = App.GetService<SqlSugarRepository<BookingOrder>>();
//var repCtn = App.GetService<SqlSugarRepository<BookingCtn>>();
//var repBookingFile = App.GetService<SqlSugarRepository<BookingFile>>();
//var repUserMail = App.GetService<SqlSugarRepository<DjyUserMailAccount>>();
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var order = tenantDb.Queryable<SeaExport>().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<SysTenant>().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<OpCtn>().Where(c => c.BSNO == bookingId.ToString()).ToList();
var yardCodeSetList = db.Queryable<SysDictData>().InnerJoin<SysDictType>((a, b) => a.TypeId == b.Id)
.Where((a, b) => b.Code == "XiaHuoZhiYardCodeSet").OrderBy((a, b) => a.OrderNo)
.Select<SysDictData>().ToList();
//dictData.Where(x => x.TypeCode == "XiaHuoZhiYardCodeSet").ToList(); //所有支持下货纸的场站代码配置 .Select((a, b) => a.Value)
var gljEdiCarrierSetList = db.Queryable<SysDictData>().InnerJoin<SysDictType>((a, b) => a.TypeId == b.Id)
.Where((a, b) => b.Code == "XiaHuoZhiGLJEdiCarrierSet").OrderBy((a, b) => a.OrderNo).Select<SysDictData>().ToList();//港联捷通过EDI发送下货纸船司配置
var gljExcelMailCarrierSetList = db.Queryable<SysDictData>().InnerJoin<SysDictType>((a, b) => a.TypeId == b.Id)
.Where((a, b) => b.Code == "XiaHuoZhiGLJExcelMailCarrierSet").OrderBy((a, b) => a.OrderNo).Select<SysDictData>().ToList();//港联捷通过邮件Excel下货纸船司配置
var mappingCarrierAll = tenantDb.Queryable<MappingCarrier>().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(order.Yard))
{
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;
}
#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(order.Carrier))
{
//租户参数-港联捷下货纸代号
var paraXHZ = db.Queryable<SysConfig>().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($"港联捷场站 下货纸代号未找到或配置有误");
}
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 EDI28 
255
255100
*/
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<SysConfig>().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.YardContactId == 0)
{
return DataResult.Failed("请选择场站关系人");
}
var yardContact = tenantDb.Queryable<CodeOrderContact>().First(x => x.Id == order.YardContactId);
if (yardContact.IsNull())
{
return DataResult.Failed("场站关系人不存在");
}
if (string.IsNullOrEmpty(yardContact.Email))
{
return DataResult.Failed($"场站联系人邮箱未填写");
}
var userMail = tenantDb.Queryable<CodeUserEmail>().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<SysUser>().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<string, byte[]>(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<CodeEdiSet>().First(f => f.EdiTypeCode == "XHZ_GJF");
}
else if (yardCode == yardCodeJieFeng.Value)
{
ftpset = tenantDb.Queryable<CodeEdiSet>().First(f => f.EdiTypeCode == "XHZ_JIEFENG");
}
var yardContact = tenantDb.Queryable<CodeOrderContact>().First(x => x.Id == order.YardContactId);
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<string> listJoinStr = new List<string>();
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<string> 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<SysConfig>().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<SysConfig>().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<CodeEdiSet>().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<SysConfig>().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($"下货纸代号未找到或配置有误");
}
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 ASC0D0A
*/
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<CodeCtn>().Select(x => new { x.EdiCode, x.CtnSize }).ToList();
var ctnEdiList = tenantDb.Queryable<MappingCtn>().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<SysConfig>().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.YardContactId == 0)
{
return DataResult.Failed("请选择场站关系人");
}
var yardContact = tenantDb.Queryable<CodeOrderContact>().First(x => x.Id == order.YardContactId);
if (yardContact.IsNull())
{
return DataResult.Failed("场站关系人不存在");
}
if (string.IsNullOrEmpty(yardContact.Email))
{
return DataResult.Failed($"场站联系人邮箱未填写");
}
var userMail = tenantDb.Queryable<CodeUserEmail>().First(x => x.CreateBy == order.CreateBy);
if (userMail == null
|| string.IsNullOrEmpty(userMail.SmtpServer)
|| userMail.SmtpPort == 0)
{
return DataResult.Failed($"发件邮箱未配置");
}
var usr = db.Queryable<SysUser>().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}<br/>
{order.ReeferQuantity}<br/>
湿{order.Humidity}<br/>";
}
else if (order.CargoId == "D")
{
bodyExt = $@"危险品等级:{order.DangerClass}<br/>
{order.DangerNo}<br/>
{order.LinkMan}<br/>";
}
var body = $@"提单号:{order.MBLNO}<br/>
{order.Vessel}/{order.Voyno}<br/>
{order.LoadPort},{loadPortCode}<br/>
{order.DischargePort},{GetDischargePortEDICode(order.DischargePortId, "XHZ_GLX")}<br/>
{order.Destination},{destinationCode}<br/>
{(order.ETD.HasValue ? order.ETD.Value.ToString("yyyy-MM-dd") : "")}<br/>
{order.CntrTotal}<br/>
{order.PKGS} {order.KindPkgs}/{order.KGS}KGS/{order.CBM}CBM<br/>
{order.Description}<br/>
{bodyExt}
{order.YardRemark}<br/>
<br/>
{tenantName}<br/>
{usr.UserName}<br/>
{usr.Phone} {usr.Phone}<br/>
{usr.Email}<br/>
";
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
7 months ago
}
}