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.

2338 lines
101 KiB
C#

This file contains invisible Unicode characters!

This file contains invisible Unicode characters that may be processed differently from what appears below. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to reveal hidden characters.

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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 Mapster;
using Masuit.Tools;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using NLog;
using NPOI.HSSF.UserModel;
using SqlSugar;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using Logger = NLog.Logger;
using AnyDiff.Extensions;
using static AnyDiff.DifferenceLines;
using Newtonsoft.Json;
using Masuit.Tools.Hardware;
using DS.Module.Core.Data;
using Masuit.Tools.Models;
using System.ComponentModel;
using DS.Module.DjyServiceStatus;
using DS.WMS.Core.Invoice.Dtos;
using NPOI.SS.Formula.Functions;
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;
private readonly IDjyServiceStatusService _djyServiceStatusService;
/// <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>();
_djyServiceStatusService = _serviceProvider.GetRequiredService<IDjyServiceStatusService>();
}
/// <summary>
/// 更新手动更新海运出口派车报关标识
/// </summary>
/// <param name="id"></param>
/// <param name="code"></param>
/// <param name="type">类型 true 勾选保存 false 勾选取消</param>
public async void UpdateSeaExportTag(long id,string code,bool type = true) {
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var order = tenantDb.Queryable<SeaExport>().Filter(null, true).First(x => x.Id == id);
var oldOrder = order.Adapt<SeaExport>();
if (type)
{
if (code == "YPC")
{
order.IsLand = true;
}
if (code == "BG")
{
order.IsCustoms = true;
}
}
else
{
if (code == "YPC")
{
order.IsLand = false;
}
if (code == "BG")
{
order.IsCustoms = false;
}
}
//order.Note = "更新主单货物状态";
await tenantDb.Updateable(order)
.UpdateColumnsIF(code == "YPC", x => new { x.IsLand })
.UpdateColumnsIF(code == "BG", x => new { x.IsCustoms })
.EnableDiffLogEvent().ExecuteCommandAsync();
// 记录日志
await SaveSeaExportLogAsync(new SeaExportSaveLog()
{
OperateType = "Update",
OldOrder = oldOrder,
NewOrder = order,
SourceCode = "UpdateSeaExportTag",
SourceName = "手动更新海运出口标识",
}, tenantDb);
}
#region 海运出口差异日志
/// <summary>
/// 忽略的字段
/// </summary>
private static readonly List<string> IgnoreColumns = new List<string>()
{
"CreateTime",
"CreateUserName",
"CreateBy",
"UpdateTime",
"UpdateUserName",
"UpdateBy",
"DeleteTime",
"DeleteUserName",
"DeleteBy",
"TenantId",
"TenantName",
};
public async Task SaveSeaExportLogAsync(SeaExportSaveLog req, SqlSugarScopeProvider tenantDb)
{
var diff = req.NewOrder.Diff(req.OldOrder);
var log = new OpBusinessLog()
{
BusinessId = req.NewOrder.Id,
OperateType = "Update",
SourceCode = req.SourceCode,
SourceName = req.SourceName,
};
var logId = await tenantDb.Insertable(log).ExecuteReturnEntityAsync();
var detail = new List<OpBusinessLogDetail>();
var list = TypeDescriptor.GetProperties(req.NewOrder);
//foreach (var item in diff)
//{
// Console.WriteLine($"{item.PropertyType} - {item.Property}: {item.LeftValue} => {item.RightValue}");
// if (!item.LeftValue.Equals(item.RightValue))
// {
// if (IgnoreColumns.Contains(item.Property))
// continue;
// var des = string.Empty;
// foreach (PropertyDescriptor descriptor in list)
// {
// string name = descriptor.Name;
// if (!name.Equals(item.Property))
// {
// continue;
// }
// else
// {
// des = string.IsNullOrEmpty(descriptor.Description)? item.Property : descriptor.Description;
// }
// }
// detail.Add(new OpBusinessLogDetail()
// {
// Pid = logId.Id,
// OldValue = item.LeftValue.ToString(),
// NewValue = item.RightValue.ToString(),
// FieldValue = des,
// });
// }
//}
foreach (PropertyDescriptor descriptor in list)
{
string name = descriptor.Name;
if (IgnoreColumns.Contains(name))
{
continue;
}
object value = descriptor.GetValue(req.NewOrder);
var oldvalue = req.OldOrder.GetType().GetProperty(name).GetValue(req.OldOrder, null);
if (name == "KGS" || name == "CBM")
{
if (Convert.ToDecimal(value) == Convert.ToDecimal(oldvalue))
{
continue;
}
}
string _oldvalue = oldvalue != null ? oldvalue.ToString() : "";
string _value = value != null ? value.ToString() : "";
if (_oldvalue != _value && !string.IsNullOrWhiteSpace(descriptor.Description))
{
detail.Add(new OpBusinessLogDetail()
{
Pid = logId.Id,
OldValue = _oldvalue,
NewValue = _value,
FieldValue = descriptor.Description,
});
}
}
if (detail.Count > 0)
{
await tenantDb.Insertable(detail).ExecuteCommandAsync();
}
}
#endregion
#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,
AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
});
}
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,
AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
});
}
else
{
if (accDate.AccountDays == 0)
{
return DataResult<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate,
AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
});
}
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,
AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
});
}
}
}
else if (accDate.AccountType == "约定天数")
{
stlDate = etd.AddDays((int)accDate.AccountDays);
return DataResult<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate,
AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
});
}
else if (accDate.AccountType == "旬结")
{
stlDate = etd.AddDays(10);
return DataResult<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate,
AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
});
}
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,
AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
});
}
else if (accDate.AccountType == "季结")
{
stlDate = etd.AddDays((int)accDate.AccountMonth * 90);
return DataResult<CustomerStlRes>.Success(new CustomerStlRes()
{
StlName = accDate.AccountType,
StlDate = stlDate,
AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
});
}
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="type"></param>
/// <param name="userId"></param>
/// <param name="tenantDb"></param>
/// <param name="customerId"></param>
/// <returns></returns>
public CodeThirdParty GetCodeThirdParty(string type, string userId, SqlSugarScopeProvider tenantDb, long customerId = 0)
{
//var account = new CodeThirdParty();
if (userId.IsNull())
{
return tenantDb.Queryable<CodeThirdParty>().First(x => x.AccountType == type);
}
var uId = long.Parse(userId);
if (customerId == 0)
{
if (tenantDb.Queryable<CodeThirdParty>().Where(x => x.AccountType == type && x.CreateBy == uId).Any())
{
return tenantDb.Queryable<CodeThirdParty>().Where(x => x.AccountType == type && x.CreateBy == uId).First();
}
else
{
return tenantDb.Queryable<CodeThirdParty>().First(x => x.AccountType == type);
}
}
else
{
if (tenantDb.Queryable<CodeThirdParty>().Where(x => x.AccountType == type && x.CreateBy == uId && x.CustomerId == customerId).Any())
{
return tenantDb.Queryable<CodeThirdParty>().Where(x => x.AccountType == type && x.CreateBy == uId && x.CustomerId == customerId).First();
}
else if (tenantDb.Queryable<CodeThirdParty>().Where(x => x.AccountType == type && x.CreateBy == uId).Any())
{
return tenantDb.Queryable<CodeThirdParty>().First(x => x.AccountType == type && x.CreateBy == uId);
}
else
{
return tenantDb.Queryable<CodeThirdParty>().First(x => x.AccountType == type);
}
}
//return account;
}
/// <summary>
/// 获取往来单位代码 有EDICode返 无返回CodeName
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <param name="isEDI"></param>
/// <returns></returns>
public string GetClientCode(long Id, SqlSugarScopeProvider tenantDb, bool isEDI = true)
{
if (Id == 0)
return "";
var client = tenantDb.Queryable<InfoClient>().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;
}
}
/// <summary>
/// 获取场站代码
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public string GetYardCode(long Id, SqlSugarScopeProvider tenantDb)
{
if (Id == 0)
return "";
var yard = tenantDb.Queryable<InfoClient>().First(v => v.Id == Id && v.Status == StatusEnum.Enable.ToEnumInt());
if (yard.IsNull())
{
throw new Exception("请检查场站信息");
}
return yard.EDICode.IsNull() ? yard.CodeName : yard.EDICode;
}
/// <summary>
/// 获取场站映射名称
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public EDIMapperInfo GetYardMapper(long Id, SqlSugarScopeProvider tenantDb)
{
var yard = tenantDb.Queryable<InfoClient>().First(v => v.Id == Id && v.Status == StatusEnum.Enable.ToEnumInt());
if (yard.IsNull())
{
throw new Exception("请检查场站信息");
}
var code = yard.EDICode.IsNull() ? yard.CodeName : yard.EDICode;
var map = tenantDb.Queryable<MappingYard>().Where(v => v.Code == code).Select<EDIMapperInfo>().First();
if (map.IsNull())
{
throw new Exception("请维护场站映射信息");
}
return map;
}
/// <summary>
/// 获取船公司映射名称
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public EDIMapperInfo GetCarrierMapper(long Id, SqlSugarScopeProvider tenantDb)
{
var info = tenantDb.Queryable<CodeCarrier>().First(v => v.Id == Id);
if (info.IsNull())
{
throw new Exception("请检查船公司信息");
}
var code = info.EdiCode.IsNull() ? info.Code : info.EdiCode;
var map = tenantDb.Queryable<MappingCarrier>().Where(v => v.Code == code).Select<EDIMapperInfo>().First();
if (map.IsNull())
{
throw new Exception("请维护船公司映射信息");
}
return map;
}
/// <summary>
/// 获取船公司代码
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public string GetCarrierCode(long Id, SqlSugarScopeProvider tenantDb)
{
if (Id == 0)
return "";
var client = tenantDb.Queryable<CodeCarrier>().First(v => v.Id == Id);
if (client.IsNull())
{
throw new Exception("请检查船公司信息");
}
return client.EdiCode.IsNull() ? client.Code : client.EdiCode;
}
/// <summary>
/// 获取港口代码
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public string GetPortCode(long Id, SqlSugarScopeProvider tenantDb)
{
if (Id == 0)
return "";
var port = tenantDb.Queryable<CodePort>().First(v => v.Id == Id && v.Status == StatusEnum.Enable);
if (port.IsNull())
{
throw new Exception("请检查港口信息");
}
return port.EdiCode.IsNull() ? port.PortName : port.EdiCode;
}
#region 获取港口详情
/// <summary>
/// 获取港口详情
/// </summary>
/// <param name="Id"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public async Task<DataResult<CodePort>> GetPortInfo(long Id, SqlSugarScopeProvider tenantDb)
{
if (Id == 0)
return DataResult<CodePort>.FailedData(null);
var port = await tenantDb.Queryable<CodePort>().FirstAsync(v => v.Id == Id && v.Status == StatusEnum.Enable);
if (port.IsNull())
{
return DataResult<CodePort>.FailedData(port);
}
return DataResult<CodePort>.Success(port);
}
#endregion
/// <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>
/// 获取港口代码
/// </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();
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
#region 设置货物状态
/// <summary>
/// 设置货物状态完成
/// </summary>
/// <param name="code"></param>
/// <param name="bookingId"></param>
/// <returns></returns>
public async Task SetGoodsStatus(string code, long bookingId, SqlSugarScopeProvider tenantDb)
{
var gsCfg = tenantDb.Queryable<BookingGoodsStatusConfig>().First(x => x.SystemCode == code);
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.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, tenantDb);
}
}
}
/// <summary>
/// 更新主单货物状态
/// </summary>
/// <param name="bookingId"></param>
/// <returns></returns>
public async Task SetBookingOrderGoodsStatus(long bookingId, SqlSugarScopeProvider tenantDb)
{
//var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var order = tenantDb.Queryable<SeaExport>().Filter(null, true).First(x => x.Id == bookingId);
//获取当前用户已经录入的货物状态
var list = await tenantDb.Queryable<BookingGoodsStatus>().LeftJoin(tenantDb.Queryable<BookingGoodsStatusConfig>(),
(goods, config) => config.Id == goods.ConfigId).Where((goods, config) => 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 status = list.Where(x => x.FinishTime.HasValue).OrderByDescending(x => x.OrderNo).Select(x => new { x.SystemCode, x.StatusName }).FirstOrDefault();
if (status == null)
{
status = new
{
SystemCode = "",
StatusName = ""
};
}
var oldOrder = order.Adapt<SeaExport>();
order.BusinessStatusName = status.StatusName;
order.BusinessStatus = status.SystemCode;
if (status.SystemCode == "YPC")
order.IsLand = true;
if(status.SystemCode == "BG")
order.IsCustoms = true;
if (status.SystemCode == "YFVGM")
order.IsVGM = true;
if (status.SystemCode == "YFCD")
order.IsBooking = true;
//order.Note = "更新主单货物状态";
await tenantDb.Updateable(order).UpdateColumns(x => new { x.BusinessStatusName, x.BusinessStatus })
.UpdateColumnsIF(status.SystemCode == "YFVGM", x => new { x.IsVGM })
.UpdateColumnsIF(status.SystemCode == "YFCD", x => new { x.IsBooking })
.UpdateColumnsIF(status.SystemCode == "YPC", x => new { x.IsLand })
.UpdateColumnsIF(status.SystemCode == "BG", x => new { x.IsCustoms })
.EnableDiffLogEvent().ExecuteCommandAsync();
// 记录日志
await SaveSeaExportLogAsync(new SeaExportSaveLog()
{
OperateType = "Update",
OldOrder = oldOrder,
NewOrder = order,
SourceCode = "UpdteBusinessStatusName",
SourceName = "自动更新货物状态",
}, tenantDb);
//自动推送货物状态
var pushModel = new EmbedServiceProjectStatusDto
{
businessId = bookingId.ToString(),
SourceType = 1,
StatusCodes = new List<EmbedServiceProjectStatusDetailDto> {
new EmbedServiceProjectStatusDetailDto{
StatusCode = status.SystemCode
}
}
};
var saveStatusRlt = await _djyServiceStatusService.SaveServiceStatus(pushModel);
string batchNo = GuidHelper.GetSnowflakeId();
//写日志
_logger.Log(NLog.LogLevel.Info, "批次={no} id={id} 更新主单货物状态并推送状态 code={code}", batchNo, bookingId, status.SystemCode);
//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 发送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.CarrierId, 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(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<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($"港联捷场站 下货纸代号[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<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.YardId == 0)
{
return DataResult.Failed("请选择场站");
}
var yardContact = tenantDb.Queryable<BusinessOrderContact>().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<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<BusinessOrderContact>().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<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($"下货纸代号[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<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.YardId == 0)
{
return DataResult.Failed("请选择场站");
}
var yardContact = tenantDb.Queryable<BusinessOrderContact>().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<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
/// <summary>
///
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public async Task<DataResult<string>> GetConfigData(string code)
{
var config = await db.Queryable<SysConfig>().Filter(null, true).Where(x => x.Code == code && x.Status == StatusEnum.Enable).FirstAsync();
if (config.IsNull())
{
return await Task.FromResult(DataResult<string>.Failed("OCR接口地址未配置!"));
}
return await Task.FromResult(DataResult<string>.Success(config.Value));
}
#region 海运出口对外开放更新接口
/// <summary>
/// 海运出口对外开放更新接口
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult> SeaExportOpenEdit(SeaExportOpenEditReq req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var order = tenantDb.Queryable<SeaExport>().Where(x => x.Id == req.Id).First();
if (order.IsNull())
{
return await Task.FromResult(DataResult.Failed("海运出口信息不存在!", MultiLanguageConst.SeaExportNotExist));
}
if (tenantDb.Queryable<BusinessFeeStatus>().Where(x => x.BusinessId == req.Id && x.IsBusinessLocking == true).Any())
{
return await Task.FromResult(DataResult.Failed("海运出口信息业务已锁定!", MultiLanguageConst.SeaExportBusinessLock));
}
var oldOrder = order.Adapt<SeaExport>();
var dic = req.GetPropertiesArray();
var info = req.Adapt(order);
info.Note = "对外开放更新接口";
#region 处理箱型箱量
if (req.CtnInfo.IsNotNull() && req.CtnInfo.Count > 0)
{
//处理箱型箱量
info = UpdateSeaExportCtnInfo(info, req.CtnInfo);
var ctnList = await tenantDb.Queryable<OpCtn>().Where(x => x.BSNO == req.Id.ToString()).ToListAsync();
foreach (var item in req.CtnInfo)
{
if (item.Id == 0)
{
var ctn = item.Adapt<OpCtn>();
ctn.BSNO = info.Id.ToString();
await tenantDb.Insertable(ctn).ExecuteCommandAsync();
}
else
{
var ctn = ctnList.First(x => x.Id == item.Id);
ctn = item.Adapt(ctn);
await tenantDb.Updateable(ctn).ExecuteCommandAsync();
}
}
}
#endregion
await tenantDb.Updateable(info).UpdateColumns(dic).EnableDiffLogEvent().ExecuteCommandAsync();
await SaveSeaExportLogAsync(new SeaExportSaveLog()
{
OperateType = "Update",
OldOrder = oldOrder,
NewOrder = info,
SourceCode = "OpenEdit",
SourceName = "开放对接更新",
}, tenantDb);
return await Task.FromResult(DataResult.Successed("更新成功!", MultiLanguageConst.DataUpdateSuccess));
}
#endregion
#region 保存集装箱明细信息需自动更新业务主表 箱量相关字段CNTR1--CNTR10每种箱型的数量列头显示箱型 、TEU合计TEU、CNTRTOTAL集装箱 例如20GP*1 40GP*2
/// <summary>
/// 保存集装箱明细信息需自动更新业务主表
/// </summary>
/// <param name="entity"></param>
/// <param name="ctnList"></param>
/// <returns></returns>
public SeaExport UpdateSeaExportCtnInfo(SeaExport entity, List<OpCtnReq> ctnList)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var dictList = db.Queryable<SysDictData>().InnerJoin<SysDictType>((a, b) => a.TypeId == b.Id)
.Where((a, b) => b.Code == "seaexport_ctn_map").OrderBy((a, b) => a.OrderNo)
.Select((a, b) => a.Value).ToList();
#region 重置相关字段属性
entity.Cntr1 = 0;
entity.Cntr2 = 0;
entity.Cntr3 = 0;
entity.Cntr4 = 0;
entity.Cntr5 = 0;
entity.Cntr6 = 0;
entity.Cntr7 = 0;
entity.Cntr8 = 0;
entity.Cntr9 = 0;
entity.Cntr10 = 0;
entity.OtherCntr = 0;
entity.TEU = 0;
entity.CntrTotal = "";
#endregion
#region CntrTotal
for (int i = 0; i < ctnList.Count; i++)
{
entity.CntrTotal += ctnList[i].Ctn + "*" + ctnList[i].CtnNum + " ";
}
#endregion
#region 处理箱型箱量
for (int i = 0; i < dictList.Count; i++)
{
var ctnCode = dictList[i];
//var ctn = ctnList.Where(x => (x.CtnCode == ctnCode || x.Ctn == ctnCode)).First();
//var ctn = ctnList.Where(x => x.Ctn == ctnCode).First();
if (ctnList.Where(x => x.CtnCode == ctnCode).Any())
{
var ctns = ctnList.Where(x => x.CtnCode == ctnCode).ToList();
foreach (var ctn in ctns)
{
switch (ctnCode.ToUpper())
{
case "40HQ":
entity.Cntr1 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "20GP":
entity.Cntr2 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "40GP":
entity.Cntr3 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "40HC":
entity.Cntr4 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "20OT":
entity.Cntr5 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "40OT":
entity.Cntr6 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "20FR":
entity.Cntr7 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "40FR":
entity.Cntr8 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "20RF":
entity.Cntr9 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
case "40RF":
entity.Cntr10 += ctn.CtnNum;
entity.TEU += ctn.TEU;
//entity.CntrTotal += ctnCode + "*" + ctn.TEU + "";
break;
default:
break;
}
}
}
}
//处理其他箱型
var otherCtns = ctnList.Where(x => !dictList.Contains(x.CtnCode)).ToList();
if (otherCtns.Count > 0)
{
foreach (var item in otherCtns)
{
entity.OtherCntr += item.CtnNum;
entity.TEU += item.TEU;
//entity.CntrTotal += item.CtnCode + "*" + item.TEU + "";
}
}
#endregion
return entity;
}
#endregion
}
}