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.

2148 lines
97 KiB
C#

5 months ago
using DS.Module.Core;
using DS.Module.SqlSugar;
using DS.Module.UserModule;
using DS.WMS.Core.Code.Dtos;
using DS.WMS.Core.Code.Entity;
using DS.WMS.Core.Op.Dtos;
using DS.WMS.Core.Sys.Entity;
using Microsoft.Extensions.DependencyInjection;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DS.WMS.Core.Code.Interface;
using Newtonsoft.Json;
using DS.Module.Core.Helpers;
using NLog;
5 months ago
using DS.WMS.Core.Map.Interface;
using DS.Module.Core.Extensions;
using DS.WMS.Core.Sys.Dtos;
using DS.Module.RedisModule;
using System.Text.RegularExpressions;
using DS.WMS.Core.Sys.Interface;
using DS.WMS.Core.Sys.Method;
using DS.WMS.Core.Op.Entity;
using Mapster;
using System.Text.Json.Nodes;
using LanguageExt.Pipes;
using DS.WMS.Core.Op.Interface;
using DS.WMS.Core.Map.Method;
5 months ago
namespace DS.WMS.Core.Op.Method
{
5 months ago
public class SpaceBookingMSKAPIService: ISpaceBookingMSKAPIService
5 months ago
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
private readonly ISaasDbService saasService;
private readonly ICodeThirdPartyService codeThirdPartyService;
private readonly string mskAPIUserKey;
private readonly string mskAPIUserSecret;
private readonly string mskAPIEnvironment;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
5 months ago
private readonly IMappingCtnService mappingCtnService;
private readonly IRedisService redisService;
private readonly IConfigService configService;
5 months ago
const string CONST_MSK_API_Poing2P_SECD_URL = "MSKApiSailingSchedulePoint2Point";
5 months ago
const string CONST_MSK_API_BOOKING_URL = "MSKApiBooking";
const string CONST_MSK_API_LOCATION_URL = "MSKApilocation";
const string CONST_MSK_API_COMMODITY_URL = "MSKApiCommodity";
const string CONST_MSK_API_MAPPING_MODULE = "BOOK_MSK_API";
5 months ago
const long CONST_ADMIN_TENANTID = 1288018625843826688;
public SpaceBookingMSKAPIService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
saasService = _serviceProvider.GetRequiredService<ISaasDbService>();
codeThirdPartyService = _serviceProvider.GetRequiredService<ICodeThirdPartyService>();
5 months ago
mappingCtnService = _serviceProvider.GetRequiredService<IMappingCtnService>();
redisService = _serviceProvider.GetRequiredService<IRedisService>();
configService = _serviceProvider.GetRequiredService<IConfigService>();
5 months ago
mskAPIUserKey = AppSetting.app(new string[] { "MSKAPIService", "SaveServiceProjectUrl" });
mskAPIUserSecret = AppSetting.app(new string[] { "MSKAPIService", "CancelServiceProjectUrl" });
mskAPIEnvironment = AppSetting.app(new string[] { "MSKAPIService", "GetServiceProjectListUrl" });
}
#region 检索海运船期详情
/// <summary>
/// 检索海运船期详情
/// </summary>
/// <param name="model">请求船期详情</param>
/// <returns>返回船期结果</returns>
public async Task<DataResult<List<SearchShipSailingScheduleResultDto>>> SearchShipSailingSchedule(QueryShipSailingScheduleDto model)
{
List<SearchShipSailingScheduleResultDto> list = new List<SearchShipSailingScheduleResultDto>();
/*
MSKApiSailingSchedulePoint2Point
*/
try
{
5 months ago
//始发地不能为空
5 months ago
if (string.IsNullOrWhiteSpace(model.collectionOriginCityName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIOriginCityNameNull)));
5 months ago
5 months ago
//目的地不能为空
5 months ago
if (string.IsNullOrWhiteSpace(model.deliveryDestinationCityName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIDestCityNameNull)));
5 months ago
5 months ago
//服务船公司不能为空
5 months ago
if (string.IsNullOrWhiteSpace(model.vesselOperatorCarrierCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIVesselCarrierCodeNull)));
5 months ago
5 months ago
//船公司代码不能为空
if (string.IsNullOrWhiteSpace(model.carrierCode))
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICarrierIdNull)));
5 months ago
5 months ago
//预计离港日期不能为空
5 months ago
if (string.IsNullOrWhiteSpace(model.startDate))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIETDNull)));
5 months ago
DateTime etd = DateTime.MinValue;
5 months ago
//预计离港日期格式错误
5 months ago
if (!DateTime.TryParse(model.startDate, out etd))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIETDFormatError)));
5 months ago
string queryUrl = string.Empty;
5 months ago
if (model.carrierCode.Equals("MSK", StringComparison.OrdinalIgnoreCase))
5 months ago
{
5 months ago
queryUrl = configService.GetConfig(CONST_MSK_API_Poing2P_SECD_URL).GetAwaiter().GetResult()?.Data?.Value;
5 months ago
}
else
{
5 months ago
throw new Exception(string.Format(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPISearchShipNoSupport)), model.carrierCode));
5 months ago
}
5 months ago
//未配置查询船期请求接口地址,请联系管理员
5 months ago
if (string.IsNullOrWhiteSpace(queryUrl))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPISearchShipNoConfig)));
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var webAccountConfig = codeThirdPartyService.GetCodeThirdPartyInfoWithCompany("MSKApi").GetAwaiter().GetResult()?.Data;
5 months ago
//未配置第三方账户个人账户MSKApi
5 months ago
if (webAccountConfig == null)
return DataResult<List<SearchShipSailingScheduleResultDto>>.Failed("未配置第三方账户个人账户MSKApi", MultiLanguageConst.SpaceBookingAPIThirdPartyNull);
MSKAPISearchPoint2PointScheduleDto queryInfo = new MSKAPISearchPoint2PointScheduleDto
{
userKey = mskAPIUserKey,
userSecret = mskAPIUserSecret,
operatingEnvironment = mskAPIEnvironment,
mskAppKey = webAccountConfig.AppKey,
cargoType = model.cargoType,
exportServiceMode = model.exportServiceMode,
importServiceMode = model.importServiceMode,
vesselOperatorCarrierCode = model.vesselOperatorCarrierCode,
startDate = etd.ToString("yyyy-MM-dd"),
startDateType = "D",
};
if (!string.IsNullOrWhiteSpace(model.carrierCollectionOriginGeoID) && !string.IsNullOrWhiteSpace(model.carrierDeliveryDestinationGeoID))
{
queryInfo.carrierCollectionOriginGeoID = model.carrierCollectionOriginGeoID;
queryInfo.carrierDeliveryDestinationGeoID = model.carrierDeliveryDestinationGeoID;
}
else
{
queryInfo.collectionOriginCityName = model.collectionOriginCityName;
queryInfo.collectionOriginCountryCode = model.collectionOriginCountryCode;
queryInfo.deliveryDestinationCityName = model.deliveryDestinationCityName;
queryInfo.deliveryDestinationCountryCode = model.deliveryDestinationCountryCode;
}
//有时候船期需要带上箱型检索
if (!string.IsNullOrWhiteSpace(model.ISOEquipmentCode))
{
//这里需要翻译一下箱型
5 months ago
//var ctnCodeMappingList = _cache.GetAllMappingCtn().GetAwaiter().GetResult().ToList();
5 months ago
5 months ago
//if (ctnCodeMappingList.Count > 0)
//ctnCodeMappingList = ctnCodeMappingList.Where(x => x.CarrierCode == "MSK" && x.Module == "BOOK_MSK_API").ToList();
5 months ago
5 months ago
//var ctnMapping = ctnCodeMappingList.FirstOrDefault(t => t.Code.Equals(model.ISOEquipmentCode));
var ctnMapping = mappingCtnService.QueryMappingCtn(model.carrierId, "BOOK_MSK_API", model.ISOEquipmentCode).GetAwaiter().GetResult().Data;
5 months ago
if (ctnMapping == null)
{
queryInfo.ISOEquipmentCode = model.ISOEquipmentCode;
}
else
{
queryInfo.ISOEquipmentCode = ctnMapping.MapCode;
}
}
if (!string.IsNullOrWhiteSpace(model.stuffingWeight))
{
queryInfo.stuffingWeight = model.stuffingWeight;
}
if (model.stuffingVolume > 0)
{
queryInfo.stuffingVolume = model.stuffingVolume;
}
MSKAPISearchPoint2PointScheduleResultDto resultInfo = null;
var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(queryInfo, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
var rlt = RequestHelper.Post(jsonBody, queryUrl);
//var rlt = await queryUrl.SetBody(jsonBody).PostAsStringAsync();
Logger.Log(NLog.LogLevel.Info, $"请求MSK API查询船期请求{jsonBody}");
if (!string.IsNullOrWhiteSpace(rlt))
{
try
{
Logger.Log(NLog.LogLevel.Info, $"请求MSK API查询船期结果{rlt}");
resultInfo = JsonConvert.DeserializeObject<MSKAPISearchPoint2PointScheduleResultDto>(rlt);
}
catch (Exception ex)
{
//_logger.LogInformation($"请求MSK API查询船期异常原因{ex.Message}");
return DataResult<List<SearchShipSailingScheduleResultDto>>.Failed("请求MSK API查询船期异常原因", MultiLanguageConst.SpaceBookingAPISearchShipException);
}
}
if (resultInfo != null && resultInfo.code == 200
&& resultInfo.data != null && resultInfo.data.Count > 0)
{
resultInfo.data.ForEach(t =>
{
t.transportSchedules.ForEach(a =>
{
a.originGeoId = model.carrierCollectionOriginGeoID;
a.originUnLocCode = model.collectionOriginUNLocationCode;
a.originRegionName = model.collectionOriginUNRegionName;
a.originCityName = model.collectionOriginCityName;
a.originCountryName = model.collectionOriginCountryName;
a.destinationGeoId = model.carrierDeliveryDestinationGeoID;
a.destinationUnLocCode = model.deliveryDestinationUNLocationCode;
a.destinationRegionName = model.deliveryDestinationUNRegionName;
a.destinationCityName = model.deliveryDestinationCityName;
a.destinationCountryName = model.deliveryDestinationCountryName;
CacheShipSailingSchedule(a).GetAwaiter().GetResult();
});
var currList = t.transportSchedules.Select(a =>
{
return GetShipScheduleShow(a);
}).ToList();
if (currList.Count > 0)
list.AddRange(currList);
});
}
}
catch (Exception ex)
{
//_logger.LogError($"检索海运船期详情异常req={JsonConvert.SerializeObject(model)} 原因:{ex.Message}");
//throw Oops.Bah($"检索海运船期详情失败,{ex.Message}");
return DataResult<List<SearchShipSailingScheduleResultDto>>.Failed("请求MSK API查询船期异常原因", MultiLanguageConst.SpaceBookingAPISearchShipException);
}
return DataResult<List<SearchShipSailingScheduleResultDto>>.Success(list);
}
#endregion
#region 组织返回船期数据
/// <summary>
/// 组织返回船期数据
/// </summary>
/// <param name="model">查询的船期详情</param>
/// <returns>返回显示的船期数据</returns>
private SearchShipSailingScheduleResultDto GetShipScheduleShow(MSKAPISearchTransportSchedules model)
{
SearchShipSailingScheduleResultDto showDto = new SearchShipSailingScheduleResultDto
{
PId = model.PId,
MD5 = model.MD5,
orignCarrierCityGeoID = model.originGeoId,
orignUNLocationCode = model.originUnLocCode,
orignCityName = model.originCityName,
originRegionName = model.originRegionName,
originCountryName = model.originCountryName,
deliveryCarrierCityGeoID = model.destinationGeoId,
deliveryUNLocationCode = model.destinationUnLocCode,
deliveryCityName = model.destinationCityName,
deliveryRegionName = model.destinationRegionName,
deliveryCountryName = model.destinationCountryName,
vesselName = model.firstDepartureVessel.vesselName,
carrierDepartureVoyageNumber = model.transportLegs.FirstOrDefault().transport.carrierDepartureVoyageNumber,
Legs = new List<MSKAPISPOTScheduleRateResultShowLegsDto>()
};
//ETD
if (model.departureDateTime.HasValue)
{
showDto.ETD = model.departureDateTime.Value;
}
else
{
5 months ago
//查询船期错误,预计离港日期查询为空
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPISearchShipETDNull)));
5 months ago
}
//ETA
if (model.arrivalDateTime.HasValue)
{
showDto.ETA = model.arrivalDateTime.Value;
}
else
{
5 months ago
//查询船期错误,预计到港日期查询为空
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPISearchShipETANull)));
5 months ago
}
//计算预计天数
if (showDto.ETD.HasValue && showDto.ETD.HasValue)
{
TimeSpan ts = showDto.ETA.Value.Subtract(showDto.ETD.Value);
var timeDiff = ts.TotalHours;
showDto.days = (int)Math.Ceiling(timeDiff / 24.0);
}
if (model.transportLegs.Count > 1)
showDto.isTransfer = true;
//Legs
if (model.facilities != null)
{
showDto.orignCountryCode = model.facilities.collectionOrigin.countryCode;
showDto.deliveryCountryCode = model.facilities.deliveryDestination.countryCode;
var legs = new List<MSKAPISPOTScheduleRateResultShowLegsDto>();
for (int i = 0; i < model.transportLegs.Count; i++)
{
var b = model.transportLegs[i];
MSKAPISPOTScheduleRateResultShowLegsDto leg = new MSKAPISPOTScheduleRateResultShowLegsDto
{
vesselName = b.transport.vessel.vesselName,
VoyageNo = b.transport.carrierDepartureVoyageNumber,
From = new MSKAPISPOTScheduleRateResultShowLegsLocationDto
{
CityName = b.facilities.startLocation.cityName,
CountryCode = b.facilities.startLocation.countryCode,
SiteGeoId = b.facilities.startLocation.carrierSiteGeoID,
LocationType = "From",
},
To = new MSKAPISPOTScheduleRateResultShowLegsLocationDto
{
CityName = b.facilities.endLocation.cityName,
CountryCode = b.facilities.endLocation.countryCode,
SiteGeoId = b.facilities.endLocation.carrierSiteGeoID,
LocationType = "To",
}
};
//ETD
if (b.departureDateTime.HasValue)
{
leg.ETD = b.departureDateTime.Value;
}
else
{
5 months ago
//查询船期错误,预计离港日期查询为空
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPISearchShipETDNull)));
5 months ago
}
//ETA
if (b.arrivalDateTime.HasValue)
{
leg.ETA = b.arrivalDateTime.Value;
}
else
{
5 months ago
//查询船期错误,预计到港日期查询为空
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPISearchShipETANull)));
5 months ago
}
leg.SortNo = i + 1;
leg.From.SiteGeoId = b.facilities.startLocation.carrierSiteGeoID;
leg.From.CityName = b.facilities.startLocation.cityName;
leg.From.CountryCode = b.facilities.startLocation.countryCode;
leg.From.UnLocCode = b.facilities.startLocation.UNLocationCode;
leg.To.SiteGeoId = b.facilities.endLocation.carrierSiteGeoID;
leg.To.CityName = b.facilities.endLocation.cityName;
leg.To.CountryCode = b.facilities.endLocation.countryCode;
leg.To.UnLocCode = b.facilities.endLocation.UNLocationCode;
if (i == 0 && i == model.transportLegs.Count - 1)
{
leg.From.CityGeoId = model.originGeoId;
leg.From.CountryName = model.originCountryName;
leg.From.RegionName = model.originRegionName;
leg.To.CityGeoId = model.destinationGeoId;
leg.To.CountryName = model.destinationCountryName;
leg.To.RegionName = model.destinationRegionName;
}
else
{
if (i == 0)
{
leg.From.CityGeoId = model.originGeoId;
leg.From.CountryName = model.originCountryName;
leg.From.RegionName = model.originRegionName;
leg.From.UnLocCode = model.originUnLocCode;
}
else if (i == model.transportLegs.Count - 1)
{
leg.To.CityGeoId = model.destinationGeoId;
leg.To.CountryName = model.destinationCountryName;
leg.To.RegionName = model.destinationRegionName;
leg.To.UnLocCode = model.destinationUnLocCode;
}
}
legs.Add(leg);
}
showDto.Legs = legs.OrderBy(t => t.ETD).Select((t, idx) => {
t.SortNo = idx + 1;
return t;
}).ToList();
}
return showDto;
}
#endregion
#region 缓存船期数据
/// <summary>
/// 缓存船期数据
/// </summary>
/// <param name="model">船期查询结果明细</param>
/// <param name="busiType">船期类型 MSKSPOT-马士基即期</param>
/// <returns>返回主键ID</returns>
private async Task CacheShipSailingSchedule(MSKAPISearchTransportSchedules model, string busiType = "MSKCON")
{
/*
1IDKEY
2JSONMD5
3ID
*/
5 months ago
var newModel = model.MapTo<MSKAPISearchTransportSchedules, MSKAPISearchTransportSchedules>();
5 months ago
//newModel.priceID = null;
var json = Newtonsoft.Json.JsonConvert.SerializeObject(newModel);
5 months ago
model.PId = SnowFlakeSingle.Instance.NextId();
5 months ago
5 months ago
//string md5 = json.ToMd5();
5 months ago
5 months ago
//model.MD5 = md5;
5 months ago
var shareKey = model.PId.ToString();
DateTime nowDate = DateTime.Now;
DateTime expireDateTime = DateTime.Now.AddHours(4);
var expireTimeSpan = expireDateTime.Subtract(nowDate).Duration();
5 months ago
if (!redisService.Exists($"{shareKey}_{busiType}"))
5 months ago
{
5 months ago
redisService.SetValue($"{shareKey}_{busiType}", Newtonsoft.Json.JsonConvert.SerializeObject(model), 4 * 3600);
5 months ago
}
}
#endregion
5 months ago
#region 获取缓存的船期数据
/// <summary>
/// 获取缓存的船期数据
/// </summary>
/// <param name="pid">船期Pid</param>
/// <param name="busiType">类型 MSKCON-合约船期</param>
/// <returns>返回船期详情</returns>
5 months ago
private MSKAPISearchTransportSchedules GetCacheShipSailingSchedule(long pid, string busiType = "MSKCON")
{
5 months ago
if (redisService.Exists($"{pid}_{busiType}"))
5 months ago
{
5 months ago
return redisService.GetEntity<MSKAPISearchTransportSchedules>($"{pid}_{busiType}");
5 months ago
}
return null;
}
5 months ago
#endregion
5 months ago
#region 发送马士基订舱请求
/// <summary>
/// 发送马士基订舱请求
/// </summary>
/// <param name="model">请求订舱详情</param>
/// <returns></returns>
5 months ago
public async Task<DataResult<MSKBookingResultDto>> SendMSKBooking(MSKBookingDto model)
5 months ago
{
5 months ago
return await InnerSendMSKBooking(model, 0);
5 months ago
}
#endregion
#region 发送马士基订舱请求(内部方法)
/// <summary>
/// 发送马士基订舱请求(内部方法)
/// </summary>
/// <param name="model">请求订舱详情</param>
/// <param name="currId">当前马士基订舱主键</param>
/// <param name="isDefaultSave">是否默认保存</param>
/// <returns></returns>
5 months ago
private async Task<DataResult<MSKBookingResultDto>> InnerSendMSKBooking(MSKBookingDto model, long currId, bool isDefaultSave = true)
5 months ago
{
MSKBookingResultDto result = new MSKBookingResultDto();
/*
MSKApiBooking
*/
try
{
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//服务船公司不能为空
5 months ago
if (string.IsNullOrWhiteSpace(model.carrierCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICarrierCodeNull)));
5 months ago
5 months ago
//船公司代码不能为空
//if (string.IsNullOrWhiteSpace(model.carrierId))
//throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIVesselCarrierCodeNull)));
5 months ago
string sendUrl = string.Empty;
5 months ago
if (model.carrierCode.Equals("MSK", StringComparison.OrdinalIgnoreCase))
5 months ago
{
5 months ago
sendUrl = configService.GetConfig(CONST_MSK_API_BOOKING_URL).GetAwaiter().GetResult()?.Data?.Value;
5 months ago
}
else
{
5 months ago
//当前船公司 {model.carrierId} 未配置相应的请求接口
throw new Exception(string.Format(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIBookingNotSupport)), model.carrierId));
5 months ago
}
5 months ago
//未配置发送订舱请求接口地址,请联系管理员
5 months ago
if (string.IsNullOrWhiteSpace(sendUrl))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIBookingUrlNull)));
5 months ago
5 months ago
var webAccountConfig = codeThirdPartyService.GetCodeThirdPartyInfoWithCompany("MSKApi").GetAwaiter().GetResult()?.Data;
5 months ago
5 months ago
//未配置个人账户,请先配置个人账户 类型-MSKApi
5 months ago
if (webAccountConfig == null)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIThirdPartyNull)));
5 months ago
//这里是校验必填项
ValidateMSKAPIData(model);
5 months ago
SpaceBookingOrderShipSchedule spaceBookingOrderShipSchedule = null;
5 months ago
MSKAPISearchTransportSchedules selectedShipSchedule = null;
5 months ago
//船期信息不能为空,请重新检索船期
5 months ago
if (model.PId == 0)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIShipScheduleNotNull)));
5 months ago
if (model.PId > 0)
{
if (model.id.HasValue && model.id.Value > 0)
{
var recordId = model.id.Value;
5 months ago
spaceBookingOrderShipSchedule = tenantDb.Queryable<SpaceBookingOrderShipSchedule>().First(a => a.RecordId == recordId && a.ShipRatePid != null &&
a.ShipRatePid.Value == model.PId && a.Deleted == false);
5 months ago
}
5 months ago
if (spaceBookingOrderShipSchedule == null)
5 months ago
{
selectedShipSchedule = GetCacheShipSailingSchedule(model.PId);
}
else
{
5 months ago
selectedShipSchedule = JsonConvert.DeserializeObject<MSKAPISearchTransportSchedules>(spaceBookingOrderShipSchedule.ShipJson);
5 months ago
}
5 months ago
//船期数据校验失败,请重新查询船期信息
5 months ago
if (selectedShipSchedule == null)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIShipScheduleCheckFailNotNull)));
5 months ago
}
DateTime nowDate = DateTime.Now;
5 months ago
var recordInfo = model.Adapt<SpaceBookingOrder>();
var recordCtnList = model.ctns.Adapt<List<SpaceBookingOrderCtn>>();
5 months ago
5 months ago
//var ctnCodeMappingList = _cache.GetAllMappingCtn().GetAwaiter().GetResult().ToList();
5 months ago
5 months ago
//if (ctnCodeMappingList.Count > 0)
//ctnCodeMappingList = ctnCodeMappingList.Where(x => x.CarrierCode == "MSK" && x.Module == "BOOK_MSK_API").ToList();
5 months ago
MSKAPIBookingDto bookingDto = new MSKAPIBookingDto
{
5 months ago
userKey = mskAPIUserKey,
userSecret = mskAPIUserSecret,
operatingEnvironment = mskAPIEnvironment,
mskAppKey = webAccountConfig.AppKey,
mskAppSecret = webAccountConfig.AppSecret,
5 months ago
bookingBody = new MSKAPIBookingBodyDto()
};
bookingDto.bookingBody.references = new MSKAPIBookingReferenceDto
{
priceReference = model.priceReference,
productCode = model.productCode,
sender = model.sender,
bookingOfficeUNLocationCode = "CNTAO"
};
bookingDto.bookingBody.mandatoryParties = new MSKAPIBookingMandatoryParties
{
bookedByCompanyName = model.bookedByCompanyName,
bookedByMaerskPartyCode = model.bookedByMaerskPartyCode,
bookedByPartyContact = new MSKAPIBookingMandatoryPartyContact
{
name = model.bookedByCompanyContactName,
email = model.bookedByCompanyContactEmail
},
priceOwnerCompanyName = model.priceOwnerCompanyName,
priceOwnerMaerskPartyCode = model.priceOwnerMaerskPartyCode,
priceOwnerPartyContact = new MSKAPIBookingMandatoryPartyContact
{
name = model.priceOwnerContactName,
email = model.priceOwnerContactEmail
},
};
bookingDto.bookingBody.transport = new MSKAPIBookingTransport
{
carrierCode = model.carrierCode,
earliestDepartureDate = model.earliestDepartureDate.Value.ToString("yyyy-MM-ddTHH:mm:ss"),
exportServiceMode = model.exportServiceMode,
importServiceMode = model.importServiceMode,
routeDetails = new MSKAPIBookingRouteDetails
{
placeOfReceipt = new MSKAPIBookingRouteDetailsBase
{
UNLocationCode = model.userPlaceOfReceiptUnLocCode,
maerskCityGeoId = selectedShipSchedule.originGeoId,
},
placeOfDelivery = new MSKAPIBookingRouteDetailsBase
{
UNLocationCode = model.userPlaceOfDeliveryUnLocCode,
maerskCityGeoId = selectedShipSchedule.destinationGeoId,
},
selectedRoute = new MSKAPIBookingRoute
{
bookingSchedules = new List<MSKAPIBookingSchedules>(),
},
}
};
//ETD
if (selectedShipSchedule.departureDateTime.HasValue)
{
bookingDto.bookingBody.transport.earliestDepartureDate = selectedShipSchedule.departureDateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss");
}
else
{
5 months ago
//throw Oops.Bah($"查询船期错误pid={model.PId} 预计离港日期departureDate 格式解析错误");
5 months ago
}
for (int i = 0; i < selectedShipSchedule.transportLegs.Count; i++)
{
var detail = selectedShipSchedule.transportLegs[i];
var currDto = new MSKAPIBookingSchedules();
//ETD
if (detail.departureDateTime.HasValue)
{
currDto.originDepartureDateTimeLocal = detail.departureDateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss");
}
else
{
5 months ago
//throw Oops.Bah($"查询船期错误pid={model.PId} 预计离港日期departureDate 格式解析错误");
5 months ago
}
//ETA
if (detail.arrivalDateTime.HasValue)
{
currDto.destinationArrivalDateTimeLocal = detail.arrivalDateTime.Value.ToString("yyyy-MM-ddTHH:mm:ss");
}
else
{
5 months ago
//throw Oops.Bah($"查询船期错误pid={model.PId} 预计到港日期arrivalDateTime 格式解析错误");
5 months ago
}
currDto.transportMode = new MSKAPIBookingTransportMode
{
vessel = new MSKAPIBookingTransportModeVessel
{
name = detail.transport.vessel.vesselName,
maerskVesselCode = detail.transport.vessel.carrierVesselCode,
vesselIMONumber = detail.transport.vessel.vesselIMONumber
},
exportVoyageNumber = detail.transport.carrierDepartureVoyageNumber,
};
currDto.serviceCode = detail.transport.carrierServiceCode;
currDto.transportModeCode = detail.transport.transportMode;
//首个
if (i == 0)
{
currDto.startLocation = new MSKAPIBookingRouteDetailsBase
{
cityName = detail.facilities.startLocation.cityName,
ISOcountryCode = detail.facilities.startLocation.countryCode,
UNLocationCode = detail.facilities.startLocation.UNLocationCode,
maerskCityGeoId = selectedShipSchedule.originGeoId,
};
if (i == selectedShipSchedule.transportLegs.Count - 1)
{
currDto.endLocation = new MSKAPIBookingRouteDetailsBase
{
cityName = detail.facilities.endLocation.cityName,
ISOcountryCode = detail.facilities.endLocation.countryCode,
UNLocationCode = detail.facilities.endLocation.UNLocationCode,
maerskCityGeoId = selectedShipSchedule.destinationGeoId,
};
}
else
{
currDto.endLocation = new MSKAPIBookingRouteDetailsBase
{
cityName = detail.facilities.endLocation.cityName,
ISOcountryCode = detail.facilities.endLocation.countryCode,
UNLocationCode = detail.facilities.endLocation.UNLocationCode,
maerskSiteGeoId = detail.facilities.endLocation.carrierSiteGeoID,
};
}
}
else if (i == selectedShipSchedule.transportLegs.Count - 1)
{
currDto.startLocation = new MSKAPIBookingRouteDetailsBase
{
cityName = detail.facilities.startLocation.cityName,
ISOcountryCode = detail.facilities.startLocation.countryCode,
UNLocationCode = detail.facilities.startLocation.UNLocationCode,
maerskSiteGeoId = detail.facilities.startLocation.carrierSiteGeoID,
};
currDto.endLocation = new MSKAPIBookingRouteDetailsBase
{
cityName = detail.facilities.endLocation.cityName,
ISOcountryCode = detail.facilities.endLocation.countryCode,
UNLocationCode = detail.facilities.endLocation.UNLocationCode,
maerskCityGeoId = selectedShipSchedule.destinationGeoId,
};
}
else
{
currDto.startLocation = new MSKAPIBookingRouteDetailsBase
{
cityName = detail.facilities.startLocation.cityName,
ISOcountryCode = detail.facilities.startLocation.countryCode,
UNLocationCode = detail.facilities.startLocation.UNLocationCode,
maerskSiteGeoId = detail.facilities.startLocation.carrierSiteGeoID,
};
currDto.endLocation = new MSKAPIBookingRouteDetailsBase
{
cityName = detail.facilities.endLocation.cityName,
ISOcountryCode = detail.facilities.endLocation.countryCode,
UNLocationCode = detail.facilities.endLocation.UNLocationCode,
maerskSiteGeoId = detail.facilities.endLocation.carrierSiteGeoID,
};
}
bookingDto.bookingBody.transport.routeDetails.selectedRoute.bookingSchedules.Add(currDto);
}
bookingDto.bookingBody.cargo = new MSKAPIBookingCargo
{
commodityCode = model.commodityCode,
commodityCodeType = "MaerskCode",
cargoType = model.cargoType,
totalCargoWeight = model.totalCargoWeight
};
//是否冷冻处理
if (model.isReefer)
{
bookingDto.bookingBody.cargo.reeferSettings = new MSKAPIBookingCargoReeferSettings();
bookingDto.bookingBody.cargo.reeferSettings.temperatureDetails = model.temperature;
bookingDto.bookingBody.cargo.reeferSettings.temperatureMeasureUnit = "C";
bookingDto.bookingBody.cargo.reeferSettings.noOfProbes = model.noOfProbes;
//每小时需要的通风量,单位为立方米(0-285)
bookingDto.bookingBody.cargo.reeferSettings.ventilation = model.ventilation;
bookingDto.bookingBody.cargo.reeferSettings.humidity = model.humidity;
}
bookingDto.bookingBody.equipmentAndHaulage = new List<MSKAPIBookingEquipmentAndHaulage>();
if (model.ctns != null && model.ctns.Count > 0)
{
5 months ago
model.ctns.ForEach(async ctn =>
5 months ago
{
5 months ago
var ctnMapping = mappingCtnService.QueryMappingCtn(model.carrierId, CONST_MSK_API_MAPPING_MODULE, ctn.ctnCode).GetAwaiter().GetResult()?.Data;
//var ctnMapping = ctnCodeMappingList.FirstOrDefault(t => t.Code.Equals(ctn.ctnCode));
5 months ago
5 months ago
//if (ctnMapping == null)
//throw Oops.Oh($"未配置相应的箱型对应{ctn.ctnName},请联系管理员");
5 months ago
MSKAPIBookingEquipmentAndHaulage haulage = new MSKAPIBookingEquipmentAndHaulage
{
equipmentDetails = new MSKAPIBookingEquipmentAndHaulageItem(),
stuffingDetails = new List<MSKAPIBookingStuffingdetails>()
};
if (model.isShipperOwned)
haulage.equipmentDetails.isShipperOwned = model.isShipperOwned;
if (model.isImportReturned)
haulage.equipmentDetails.isImportReturned = model.isImportReturned;
haulage.equipmentDetails.ISOEquipmentCode = ctnMapping.MapCode;
haulage.equipmentDetails.equipmentQuantity = ctn.ctnNum;
haulage.stuffingDetails.Add(new MSKAPIBookingStuffingdetails
{
stuffingValue = (int)ctn.ctnSufferWeight.Value,
stuffingMeasurementType = "WEIGHT",
stuffingMeasurementUnit = "KGS"
});
bookingDto.bookingBody.equipmentAndHaulage.Add(haulage);
});
}
long id = 0;
if (isDefaultSave)
{
5 months ago
id = InnerSave(model, isSendApi: true).GetAwaiter().GetResult().Data;
5 months ago
}
else
{
id = currId;
}
result.id = id;
MSKAPIBookingResultDto resultInfo = null;
var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(bookingDto);
5 months ago
//_logger.LogInformation($"开始请求MSK API订舱JSON={jsonBody}");
5 months ago
5 months ago
//var rlt = await sendUrl.SetBody(jsonBody).PostAsStringAsync();
5 months ago
5 months ago
var rlt = RequestHelper.Post(jsonBody, sendUrl);
//_logger.LogInformation($"开始请求MSK API订舱返回结果 JSON={JSON.Serialize(rlt)}");
5 months ago
if (!string.IsNullOrWhiteSpace(rlt))
{
try
{
5 months ago
resultInfo = JsonConvert.DeserializeObject<MSKAPIBookingResultDto>(rlt);
5 months ago
}
catch (Exception ex)
{
5 months ago
//_logger.LogInformation($"请求MSK API订舱异常原因{ex.Message}");
5 months ago
5 months ago
//throw Oops.Bah($"请求MSK API订舱异常原因{ex.Message}");
5 months ago
}
}
MSKAPIBookingResultDataDto resultData = null;
if (resultInfo.code == 200)
{
5 months ago
resultData = JsonConvert.DeserializeObject<MSKAPIBookingResultDataDto>(JsonConvert.SerializeObject(resultInfo.data));
5 months ago
}
5 months ago
var entity = tenantDb.Queryable<SpaceBookingOrder>().First(a => a.Id == id);
5 months ago
if (resultInfo != null && resultInfo.code == 200
&& resultData != null)
{
5 months ago
entity.RequestAcknowledgementId = resultData.requestAcknowledgementId;
entity.BookingReference = resultData.bookingReference;
entity.Status = "SUCC";
entity.StatusName = "发送成功";
5 months ago
5 months ago
await tenantDb.Updateable(entity).UpdateColumns(x => new
5 months ago
{
5 months ago
x.RequestAcknowledgementId,
x.BookingReference,
x.Status,
x.StatusName
5 months ago
}).ExecuteCommandAsync();
}
else
{
5 months ago
entity.Status = "FAILURE";
entity.StatusName = "发送失败";
entity.Notes = resultInfo.msg.Length > 500 ? resultInfo.msg.Substring(0, 500) : resultInfo.msg;
5 months ago
5 months ago
await tenantDb.Updateable(entity).UpdateColumns(x => new
5 months ago
{
5 months ago
x.Status,
x.StatusName,
x.Notes
5 months ago
}).ExecuteCommandAsync();
5 months ago
//throw Oops.Bah(resultInfo.msg);
5 months ago
}
result.succ = true;
}
catch (Exception ex)
{
5 months ago
//_logger.LogError($"MSK API订舱异常req={JSON.Serialize(model)} 原因:{ex.Message}");
5 months ago
//throw Oops.Bah($"MSK API订舱失败{ex.Message}");
result.succ = false;
result.msg = $"MSK API订舱失败{ex.Message}";
5 months ago
//throw Oops.Bah($"MSK API订舱失败{ex.Message}");
5 months ago
}
5 months ago
return DataResult<MSKBookingResultDto>.Success(result);
5 months ago
}
#endregion
#region 校验马士基API订舱必填项
/// <summary>
/// 校验马士基API订舱必填项
/// </summary>
/// <param name="model"></param>
private void ValidateMSKAPIData(MSKBookingDto model)
{
/*
API
1
2
3
4
5
6UNLOC
7UNLOC
8ETDETA
9
10
11
12
13
14=*
15
*/
5 months ago
//订舱合同惟一ID必填
5 months ago
if (string.IsNullOrWhiteSpace(model.priceReference))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIPriceReferNull)));
5 months ago
5 months ago
//订舱合同惟一ID格式错误 [a-zA-Z0-9_/,-]{1,50}
5 months ago
if (!Regex.IsMatch(model.priceReference, "[a-zA-Z0-9_/,-]{1,50}"))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIPriceReferFormatError)));
5 months ago
5 months ago
//请求类别必填
5 months ago
if (string.IsNullOrWhiteSpace(model.sender))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPISenderNull)));
5 months ago
5 months ago
//服务船公司代码必填
5 months ago
if (string.IsNullOrWhiteSpace(model.carrierCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICarrierCodeNull)));
5 months ago
5 months ago
//订舱公司名称必填
5 months ago
if (string.IsNullOrWhiteSpace(model.bookedByCompanyName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIBookCompanyNameNull)));
5 months ago
5 months ago
//订舱方ID必填
5 months ago
if (string.IsNullOrWhiteSpace(model.bookedByMaerskPartyCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIBookCompanyCodeNull)));
5 months ago
5 months ago
//订舱方公司联系人必填
5 months ago
if (string.IsNullOrWhiteSpace(model.bookedByCompanyContactName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIBookCompanyContactNull)));
5 months ago
5 months ago
//订舱方公司邮箱必填
5 months ago
if (string.IsNullOrWhiteSpace(model.bookedByCompanyContactEmail))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIBookCompanyContactEmailNull)));
5 months ago
5 months ago
//持约方公司名称必填
if (string.IsNullOrWhiteSpace(model.priceOwnerCompanyName))
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIPriceOwnerCompanyNameNull)));
5 months ago
5 months ago
//持约方ID必填
5 months ago
if (string.IsNullOrWhiteSpace(model.priceOwnerMaerskPartyCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIPriceOwnerCompanyCodeNull)));
5 months ago
5 months ago
//持约方公司联系人必填
5 months ago
if (string.IsNullOrWhiteSpace(model.priceOwnerContactName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIPriceOwnerCompanyContactNull)));
5 months ago
5 months ago
//持约方公司邮箱必填
5 months ago
if (string.IsNullOrWhiteSpace(model.priceOwnerContactEmail))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIPriceOwnerCompanyContactEmailNull)));
5 months ago
5 months ago
//始发地城市名称必填
5 months ago
if (string.IsNullOrWhiteSpace(model.placeOfReceiptCityName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIOriginCityNameNull)));
5 months ago
5 months ago
//始发地UN CODE必填
5 months ago
if (string.IsNullOrWhiteSpace(model.placeOfReceiptUnLocCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIOriginUnCodeNull)));
5 months ago
5 months ago
//始发地国家代码必填
5 months ago
if (string.IsNullOrWhiteSpace(model.placeOfReceiptCountryCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIOriginCountryCodeNull)));
5 months ago
5 months ago
//始发地服务模式必填
5 months ago
if (string.IsNullOrWhiteSpace(model.exportServiceMode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIOriginServiceModeNull)));
5 months ago
5 months ago
//目的地城市名称必填
5 months ago
if (string.IsNullOrWhiteSpace(model.placeOfDeliveryCityName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIDestCityNameNull)));
5 months ago
5 months ago
//目的地UN CODE必填
5 months ago
if (string.IsNullOrWhiteSpace(model.placeOfDeliveryUnLocCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIDestUnCodeNull)));
5 months ago
5 months ago
//目的地国家代码必填
5 months ago
if (string.IsNullOrWhiteSpace(model.placeOfDeliveryCountryCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIDestCountryCodeNull)));
5 months ago
5 months ago
//目的地服务模式必填
5 months ago
if (string.IsNullOrWhiteSpace(model.importServiceMode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIDestServiceModeNull)));
5 months ago
5 months ago
//船名必填,请确认正确选择了船期
5 months ago
if (string.IsNullOrWhiteSpace(model.vesselName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIVesselNameNull)));
5 months ago
5 months ago
//航次号必填,请确认正确选择了船期
5 months ago
if (string.IsNullOrWhiteSpace(model.exportVoyageNumber))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIVoynoNull)));
5 months ago
5 months ago
//ETD必填请确认正确选择了船期
5 months ago
if (!model.originDepartureDateTimeLocal.HasValue)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIOriginDepartureDateNull)));
5 months ago
5 months ago
//ETA必填请确认正确选择了船期
5 months ago
if (!model.destinationArrivalDateTimeLocal.HasValue)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIDestArrivalDateNull)));
5 months ago
5 months ago
//商品代码必填,请确认正确选择了商品
5 months ago
if (string.IsNullOrWhiteSpace(model.commodityCode))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICommodityNull)));
5 months ago
5 months ago
//商品名称必填,请确认正确选择了商品
5 months ago
if (string.IsNullOrWhiteSpace(model.commodityName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICommodityNameNull)));
5 months ago
5 months ago
//总重必填
5 months ago
if (!model.totalCargoWeight.HasValue || model.totalCargoWeight.Value < 1)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPITotalCargoWTNull)));
5 months ago
5 months ago
//货物标志必填
5 months ago
if (string.IsNullOrWhiteSpace(model.cargoType))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICargoTypeNull)));
5 months ago
5 months ago
//预计离港日期必填
5 months ago
if (!model.earliestDepartureDate.HasValue)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIEarliestDepartDateNull)));
5 months ago
if (model.isReefer)
{
5 months ago
//选择了冷冻处理,温度必填
5 months ago
if (!model.temperature.HasValue)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIIsReeferTempNull)));
5 months ago
}
5 months ago
//箱型箱量信息必填
5 months ago
if (model.ctns.Count == 0)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICtnAndNumNull)));
5 months ago
5 months ago
//箱型不能为空
5 months ago
if (model.ctns.Any(a => string.IsNullOrWhiteSpace(a.ctnCode)))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICtnCodeNull)));
5 months ago
5 months ago
//箱量不能为空并且不能小于1
5 months ago
if (model.ctns.Any(a => !a.ctnNum.HasValue || a.ctnNum.Value < 1))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICtnNumLower)));
5 months ago
5 months ago
//箱内重量不能为空并且不能小于1
5 months ago
if (model.ctns.Any(a => !a.ctnSufferWeight.HasValue || a.ctnSufferWeight.Value < 1))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICtnSufferWeightLower)));
5 months ago
5 months ago
//箱内重量合计不等于总重,请修改
5 months ago
if (model.totalCargoWeight.Value != model.ctns.Sum(b => b.ctnNum.Value * b.ctnSufferWeight.Value))
{
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICtnWeightUnequalTotal)));
5 months ago
}
5 months ago
//当前订舱合同号是非订舱方合约持约方不能和订舱方ID信息一样请根据实际情况填写
5 months ago
if (!model.isBookingPartOwnPrice)
{
5 months ago
//当前订舱合同号是非订舱方合约持约方不能和订舱方ID信息一样请根据实际情况填写
5 months ago
if (model.bookedByMaerskPartyCode.Equals(model.priceOwnerMaerskPartyCode))
{
5 months ago
//throw Oops.Bah($"当前订舱合同号是非订舱方合约持约方不能和订舱方ID信息一样请根据实际情况填写");
5 months ago
}
5 months ago
//当前订舱合同号是非订舱方合约,持约方公司名称不能和订舱方公司名称信息一样,请根据实际情况填写
5 months ago
if (model.bookedByCompanyName.Equals(model.priceOwnerCompanyName))
{
5 months ago
//throw Oops.Bah($"当前订舱合同号是非订舱方合约,持约方公司名称不能和订舱方公司名称信息一样,请根据实际情况填写");
5 months ago
}
}
else
{
5 months ago
//当前订舱合同号是订舱方合约持约方ID必需和订舱方ID信息一致请根据实际情况填写
5 months ago
if (!model.bookedByMaerskPartyCode.Equals(model.priceOwnerMaerskPartyCode))
{
5 months ago
//throw Oops.Bah($"当前订舱合同号是订舱方合约持约方ID必需和订舱方ID信息一致请根据实际情况填写");
5 months ago
}
5 months ago
//当前订舱合同号是订舱方合约,持约方名称必需和订舱方名称信息一致,请根据实际情况填写
5 months ago
if (!model.bookedByCompanyName.Equals(model.priceOwnerCompanyName))
{
5 months ago
//throw Oops.Bah($"当前订舱合同号是订舱方合约,持约方名称必需和订舱方名称信息一致,请根据实际情况填写");
5 months ago
}
}
}
#endregion
#region 检索商品名称
/// <summary>
/// 检索商品名称
/// </summary>
/// <param name="model">请求详情</param>
/// <returns>返回检索结果</returns>
5 months ago
public async Task<DataResult<List<SearchCommodityResultDto>>> SearchCommodities(QueryCommoditiesDto model)
5 months ago
{
List<SearchCommodityResultDto> list = new List<SearchCommodityResultDto>();
/*
MSKApiCommodity
*/
try
{
5 months ago
//商品名称不能为空
5 months ago
if (string.IsNullOrWhiteSpace(model.commodityName))
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICommodityNameQueryNull)));
5 months ago
5 months ago
//船公司代码不能为空
//if (string.IsNullOrWhiteSpace(model.carrierCode))
//throw Oops.Oh("");
//throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICommodityNameQueryNull)));
5 months ago
5 months ago
//商品名称至少输入3个以上字符
// if (model.commodityName.Length < 3)
//throw Oops.Oh("");
//throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICommodityNameQueryNull)));
5 months ago
string queryUrl = string.Empty;
if (model.carrierId.Equals("MSK", StringComparison.OrdinalIgnoreCase))
{
5 months ago
queryUrl = configService.GetConfig(CONST_MSK_API_COMMODITY_URL).GetAwaiter().GetResult()?.Data?.Value;
5 months ago
}
else
{
5 months ago
//throw Oops.Oh($"当前船公司 {model.carrierId} 未配置相应的请求接口");
5 months ago
}
5 months ago
//if (string.IsNullOrWhiteSpace(queryUrl))
//throw Oops.Oh("未配置商品请求接口地址,请联系管理员");
5 months ago
5 months ago
var webAccountConfig = codeThirdPartyService.GetCodeThirdPartyInfoWithCompany("MSKApi").GetAwaiter().GetResult()?.Data;
5 months ago
5 months ago
//if (webAccountConfig == null)
//throw Oops.Oh("未配置个人账户,请先配置个人账户 类型-MSKApi");
5 months ago
MSKAPISearchCommodityDto queryInfo = new MSKAPISearchCommodityDto
{
5 months ago
userKey = mskAPIUserKey,
userSecret = mskAPIUserSecret,
operatingEnvironment = mskAPIEnvironment,
5 months ago
commodityName = model.commodityName,
5 months ago
mskAppKey = webAccountConfig.AppKey
5 months ago
};
MSKAPISearchCommodityResultDto resultInfo = null;
5 months ago
//var rlt = await queryUrl.SetBody(queryInfo).PostAsStringAsync();
var rlt = RequestHelper.Post(JsonConvert.SerializeObject(queryInfo), queryUrl);
5 months ago
if (!string.IsNullOrWhiteSpace(rlt))
{
try
{
5 months ago
resultInfo = JsonConvert.DeserializeObject<MSKAPISearchCommodityResultDto>(rlt);
5 months ago
}
catch (Exception ex)
{
5 months ago
//_logger.LogInformation($"请求MSK API检索商品异常原因{ex.Message}");
5 months ago
5 months ago
//throw Oops.Bah($"请求MSK API检索商品异常原因{ex.Message}");
5 months ago
}
}
if (resultInfo != null && resultInfo.code == 200
&& resultInfo.data != null && resultInfo.data.Count > 0)
{
list = resultInfo.data.Adapt<List<SearchCommodityResultDto>>();
}
}
catch (Exception ex)
{
5 months ago
//_logger.LogError($"检索商品名称异常req={JSON.Serialize(model)} 原因:{ex.Message}");
5 months ago
5 months ago
//throw Oops.Bah($"检索商品名称失败,{ex.Message}");
5 months ago
}
5 months ago
return DataResult<List<SearchCommodityResultDto>>.Success(list);
5 months ago
}
#endregion
#region 检索始发地、目的港口信息
/// <summary>
/// 检索始发地、目的港口信息
/// </summary>
/// <param name="model">请求详情</param>
/// <returns>返回检索结果</returns>
5 months ago
public async Task<DataResult<List<QueryLocationsResultDto>>> SearchLocations(QueryLocationsDto model)
5 months ago
{
List<QueryLocationsResultDto> list = new List<QueryLocationsResultDto>();
/*
MSKApiCommodity
*/
try
{
5 months ago
//if (string.IsNullOrWhiteSpace(model.cityName))
// throw Oops.Oh("港口或城市名称不能为空");
5 months ago
5 months ago
//if (string.IsNullOrWhiteSpace(model.carrierCode))
// throw Oops.Oh("服务船公司不能为空");
5 months ago
5 months ago
//if (string.IsNullOrWhiteSpace(model.carrierId))
// throw Oops.Oh("船公司代码不能为空");
5 months ago
5 months ago
//if (model.cityName.Length < 3)
// throw Oops.Oh("港口或城市名称至少输入3个以上字符");
5 months ago
string queryUrl = string.Empty;
if (model.carrierId.Equals("MSK", StringComparison.OrdinalIgnoreCase))
{
5 months ago
queryUrl = configService.GetConfig(CONST_MSK_API_LOCATION_URL).GetAwaiter().GetResult()?.Data?.Value;
5 months ago
}
else
{
5 months ago
//throw Oops.Oh($"当前船公司 {model.carrierId} 未配置相应的请求接口");
5 months ago
}
5 months ago
//if (string.IsNullOrWhiteSpace(queryUrl))
//throw Oops.Oh("未配置商品请求接口地址,请联系管理员");
var webAccountConfig = codeThirdPartyService.GetCodeThirdPartyInfoWithCompany("MSKApi").GetAwaiter().GetResult()?.Data;
5 months ago
5 months ago
//if (webAccountConfig == null)
//throw Oops.Oh("未配检索始发地、目的港口,请先配置个人账户 类型-MSKApi");
5 months ago
MSKAPISearchLocationDto queryInfo = new MSKAPISearchLocationDto
{
5 months ago
userKey = mskAPIUserKey,
userSecret = mskAPIUserSecret,
operatingEnvironment = mskAPIEnvironment,
5 months ago
name = model.cityName,
5 months ago
mskAppKey = webAccountConfig.AppKey,
5 months ago
carrierCode = model.carrierCode
};
MSKAPISearchLocationResultDto resultInfo = null;
5 months ago
//var rlt = await queryUrl.SetBody(queryInfo).PostAsStringAsync();
var rlt = RequestHelper.Post(JsonConvert.SerializeObject(queryInfo), queryUrl);
5 months ago
if (!string.IsNullOrWhiteSpace(rlt))
{
try
{
5 months ago
resultInfo = JsonConvert.DeserializeObject<MSKAPISearchLocationResultDto>(rlt);
5 months ago
}
catch (Exception ex)
{
5 months ago
//_logger.LogInformation($"请求MSK API检索始发地、目的港口异常原因{ex.Message}");
5 months ago
5 months ago
//throw Oops.Bah($"请求MSK API检索始发地、目的港口异常原因{ex.Message}");
5 months ago
}
}
if (resultInfo != null && resultInfo.code == 200
&& resultInfo.data != null && resultInfo.data.Count > 0)
{
list = resultInfo.data.Adapt<List<QueryLocationsResultDto>>();
}
}
catch (Exception ex)
{
5 months ago
//_logger.LogError($"检索始发地、目的港口异常req={JSON.Serialize(model)} 原因:{ex.Message}");
5 months ago
5 months ago
//throw Oops.Bah($"检索始发地、目的港口失败,{ex.Message}");
5 months ago
}
5 months ago
return DataResult<List<QueryLocationsResultDto>>.Success(list);
5 months ago
}
#endregion
#region 获取马士基API订舱详情
/// <summary>
/// 获取马士基API订舱详情
/// </summary>
/// <param name="id">马士基API订舱ID</param>
/// <returns>返回详情</returns>
5 months ago
public async Task<DataResult<MSKBookingDto>> GetInfo(long id)
5 months ago
{
MSKBookingDto model = null;
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var entity = await tenantDb.Queryable<SpaceBookingOrder>().FirstAsync(a => a.Id == id);
5 months ago
5 months ago
//if (entity == null)
//throw Oops.Oh($"获取马士基API订舱详情失败不存在或已作废");
5 months ago
model = entity.Adapt<MSKBookingDto>();
5 months ago
var ctnList = tenantDb.Queryable<SpaceBookingOrderCtn>().Where(a => a.RecordId == id && a.Deleted == false).ToList();
5 months ago
if (ctnList.Count > 0)
{
model.ctns = ctnList.Select(a => new MSKBookingCtnInfo
{
id = a.Id,
5 months ago
ctnCode = a.CtnCode,
carrierCtnCode = a.CarrierCtnCode,
ctnNum = a.CtnNum,
ctnName = a.CtnName,
ctnSufferWeight = a.CtnSufferWeight,
stuffingMeasurementType = a.StuffingMeasurementType,
stuffingMeasurementUnit = a.StuffingMeasurementUnit
5 months ago
}).ToList();
}
MSKAPISearchTransportSchedules selectedShipSchedule = null;
if (model.PId > 0)
{
5 months ago
var shipScheduleRecord = await tenantDb.Queryable<SpaceBookingOrderShipSchedule>()
.FirstAsync(a => a.ShipRatePid != null && a.ShipRatePid.Value == model.PId);
5 months ago
if (shipScheduleRecord != null)
{
5 months ago
selectedShipSchedule = JsonConvert.DeserializeObject<MSKAPISearchTransportSchedules>(shipScheduleRecord.ShipJson);
5 months ago
if (selectedShipSchedule != null)
{
model.selectedShipScheduleShow = GetShipScheduleShow(selectedShipSchedule);
}
}
}
5 months ago
return DataResult<MSKBookingDto>.Success(model);
5 months ago
}
#endregion
#region 保存
/// <summary>
/// 保存
/// </summary>
/// <param name="model">请求订舱详情</param>
/// <returns>返回ID</returns>
5 months ago
public async Task<DataResult<long>> Save(MSKBookingDto model)
5 months ago
{
return await InnerSave(model);
}
#endregion
#region 保存内部方法
/// <summary>
/// 保存内部方法
/// </summary>
/// <param name="model">API订舱详情</param>
/// <param name="isSendApi">是否发送APItrue-发送需要校验状态false-不校验状态</param>
/// <returns></returns>
5 months ago
private async Task<DataResult<long>> InnerSave(MSKBookingDto model, bool isSendApi = false)
5 months ago
{
DateTime nowDate = DateTime.Now;
string ctnStat = string.Empty;
5 months ago
//_logger.LogInformation($"获取请求马士基API订舱报文JSON={JSON.Serialize(model)}");
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
5 months ago
5 months ago
SpaceBookingOrderShipSchedule shipScheduleRecord = null;
5 months ago
MSKAPISearchTransportSchedules selectedShipSchedule = null;
if (model.PId > 0)
{
if (model.id.HasValue && model.id.Value > 0)
{
var recordId = model.id.Value;
5 months ago
shipScheduleRecord = await tenantDb.Queryable<SpaceBookingOrderShipSchedule>()
.FirstAsync(a => a.RecordId == recordId && a.ShipRatePid != null &&
a.ShipRatePid.Value == model.PId && a.Deleted == false);
5 months ago
}
if (shipScheduleRecord == null)
{
selectedShipSchedule = GetCacheShipSailingSchedule(model.PId);
}
else
{
5 months ago
selectedShipSchedule = JsonConvert.DeserializeObject<MSKAPISearchTransportSchedules>(shipScheduleRecord.ShipJson);
5 months ago
}
5 months ago
//if (selectedShipSchedule == null)
//throw Oops.Oh("船期数据校验失败,请重新查询船期信息");
5 months ago
model.placeOfReceiptCountryName = selectedShipSchedule.originCountryName;
model.placeOfReceiptRegionName = selectedShipSchedule.originRegionName;
model.carrierCollectionOriginGeoID = selectedShipSchedule.originGeoId;
model.placeOfDeliveryCountryName = selectedShipSchedule.destinationCountryName;
model.placeOfDeliveryRegionName = selectedShipSchedule.destinationRegionName;
model.carrierDeliveryDestinationGeoID = selectedShipSchedule.destinationGeoId;
}
if (model.ctns != null && model.ctns.Count > 0)
{
ctnStat = string.Join(",", model.ctns.GroupBy(a => a.ctnName)
.Select(a => $"{a.Key}*{a.ToList().Sum(b => b.ctnNum.HasValue ? b.ctnNum.Value : 0)}").ToArray());
}
if (model.id.HasValue && model.id.Value > 0)
{
5 months ago
var oldInfo = tenantDb.Queryable<SpaceBookingOrder>()
5 months ago
.First(a => a.Id == model.id);
5 months ago
//if (oldInfo == null)
//throw Oops.Oh("订舱数据不存在或已作废");
5 months ago
5 months ago
if (oldInfo.Status == "SUCC")
5 months ago
{
5 months ago
//if (isSendApi)
//throw Oops.Oh("订舱数据已发送成功,不能重复发送");
5 months ago
5 months ago
//throw Oops.Oh("订舱数据已发送成功,不能修改");
5 months ago
}
5 months ago
SpaceBookingOrder entity = model.Adapt<SpaceBookingOrder>();
5 months ago
entity.Id = model.id.Value;
5 months ago
entity.UpdateTime = nowDate;
entity.UpdateBy = long.Parse(user.UserId);
//entity.UpdatedUserName = UserManager.Name;
entity.CtnStat = ctnStat;
entity.BookingChannelType = "CON_API";
entity.BookingChannelTypeName = "合约订舱";
await tenantDb.Updateable<SpaceBookingOrder>(entity).IgnoreColumns(x => new
{
x.CreateTime,
x.CreateBy,
//x.CreatedUserName,
x.BookingReference,
5 months ago
x.BookingId,
5 months ago
x.RequestAcknowledgementId,
x.Status,
//x.TenantId,
x.IsRecvBC,
x.LstRecvBCDate,
x.IsRecvBKCancel,
x.LstRecvBKCancelDate
5 months ago
}).ExecuteCommandAsync();
if (model.ctns != null && model.ctns.Count > 0)
{
5 months ago
var ctnEntityList = tenantDb.Queryable<SpaceBookingOrderCtn>()
.Where(a => a.RecordId == entity.Id && a.Deleted == false).ToList();
5 months ago
model.ctns.ForEach(ctn =>
{
if (ctn.id.HasValue && ctn.id.Value > 0)
{
if (ctnEntityList.Any(x => x.Id == ctn.id.Value))
{
ctnEntityList.Remove(ctnEntityList.FirstOrDefault(x => x.Id == ctn.id.Value));
}
//更新
5 months ago
var ctnEntity = ctn.Adapt<SpaceBookingOrderCtn>();
5 months ago
ctnEntity.Id = ctn.id.Value;
5 months ago
ctnEntity.RecordId = entity.Id;
ctnEntity.UpdateTime = nowDate;
ctnEntity.UpdateBy = long.Parse(user.UserId);
//ctnEntity.UpdatedUserName = UserManager.Name;
tenantDb.Updateable<SpaceBookingOrderCtn>(ctnEntity).IgnoreColumns(x => new {
x.CreateBy,
//x.CreatedUserName,
x.CreateTime,
//x.TenantId,
x.StuffingMeasurementType,
x.StuffingMeasurementUnit,
x.CtnSufferWeight
5 months ago
}).ExecuteCommand();
}
else
{
5 months ago
var ctnEntity = new SpaceBookingOrderCtn
5 months ago
{
5 months ago
CtnCode = ctn.ctnCode,
CtnName = ctn.ctnName,
CtnNum = ctn.ctnNum.Value,
CtnSufferWeight = (int)ctn.ctnSufferWeight.Value,
5 months ago
};
5 months ago
ctnEntity.RecordId = entity.Id;
ctnEntity.CreateTime = nowDate;
ctnEntity.UpdateTime = nowDate;
ctnEntity.CreateBy = long.Parse(user.UserId);
//ctnEntity.CreatedUserName = UserManager.Name;
ctnEntity.StuffingMeasurementType = "WEIGHT";
ctnEntity.StuffingMeasurementUnit = "KGS";
5 months ago
5 months ago
tenantDb.Insertable<SpaceBookingOrderCtn>(ctnEntity).ExecuteCommand();
5 months ago
}
});
if (ctnEntityList.Count > 0)
{
ctnEntityList.ForEach(async ctn => {
5 months ago
ctn.Deleted = true;
ctn.DeleteTime = nowDate;
ctn.DeleteBy = long.Parse(user.UserId);
//ctn.UpdatedUserName = UserManager.Name;
await tenantDb.Updateable<SpaceBookingOrderCtn>(ctn).UpdateColumns(x => new {
x.Deleted,
x.DeleteTime,
x.DeleteBy,
//x.UpdatedUserName
5 months ago
}).ExecuteCommandAsync();
});
}
}
if (shipScheduleRecord == null)
{
if (model.PId > 0 && selectedShipSchedule != null)
{
5 months ago
shipScheduleRecord = new SpaceBookingOrderShipSchedule
5 months ago
{
5 months ago
Id = SnowFlakeSingle.Instance.NextId(),
RecordId = model.id.Value,
ShipRatePid = selectedShipSchedule.PId,
ShipRateMD5 = selectedShipSchedule.MD5,
ShipJson = Newtonsoft.Json.JsonConvert.SerializeObject(selectedShipSchedule),
CreateTime = nowDate,
UpdateTime = nowDate,
CreateBy = long.Parse(user.UserId),
//CreatedUserName = UserManager.Name
5 months ago
};
5 months ago
await tenantDb.Insertable<SpaceBookingOrderShipSchedule>(shipScheduleRecord).ExecuteCommandAsync();
5 months ago
}
}
5 months ago
return DataResult<long>.Success(model.id.Value);
5 months ago
}
else
{
5 months ago
SpaceBookingOrder entity = model.Adapt<SpaceBookingOrder>();
5 months ago
5 months ago
entity.CreateTime = nowDate;
entity.UpdateTime = nowDate;
entity.CreateBy = long.Parse(user.UserId);
//entity.CreatedUserName = UserManager.Name;
entity.Status = "TEMP";
entity.StatusName = "暂存";
entity.CtnStat = ctnStat;
entity.BookingChannelType = "CON_API";
entity.BookingChannelTypeName = "合约订舱";
5 months ago
5 months ago
await tenantDb.Insertable<SpaceBookingOrder>(entity).ExecuteReturnEntityAsync();
5 months ago
if (model.ctns != null && model.ctns.Count > 0)
{
model.ctns.ForEach(ctn =>
{
5 months ago
var ctnEntity = new SpaceBookingOrderCtn
5 months ago
{
5 months ago
CtnCode = ctn.ctnCode,
CtnName = ctn.ctnName,
CtnNum = ctn.ctnNum.Value,
CtnSufferWeight = (int)ctn.ctnSufferWeight.Value,
5 months ago
};
5 months ago
ctnEntity.RecordId = entity.Id;
ctnEntity.CreateTime = nowDate;
ctnEntity.UpdateTime = nowDate;
ctnEntity.CreateBy = long.Parse(user.UserId);
//ctnEntity.CreatedUserName = UserManager.Name;
ctnEntity.StuffingMeasurementType = "WEIGHT";
ctnEntity.StuffingMeasurementUnit = "KGS";
5 months ago
5 months ago
tenantDb.Insertable<SpaceBookingOrderCtn>(ctnEntity).ExecuteCommand();
5 months ago
});
}
if (shipScheduleRecord == null)
{
if (model.PId > 0 && selectedShipSchedule != null)
{
5 months ago
shipScheduleRecord = new SpaceBookingOrderShipSchedule
5 months ago
{
5 months ago
Id = SnowFlakeSingle.Instance.NextId(),
RecordId = entity.Id,
ShipRatePid = selectedShipSchedule.PId,
ShipRateMD5 = selectedShipSchedule.MD5,
ShipJson = Newtonsoft.Json.JsonConvert.SerializeObject(selectedShipSchedule),
CreateTime = nowDate,
UpdateTime = nowDate,
CreateBy = long.Parse(user.UserId),
//CreatedUserName = UserManager.Name
5 months ago
};
5 months ago
await tenantDb.Insertable<SpaceBookingOrderShipSchedule>(shipScheduleRecord).ExecuteCommandAsync();
5 months ago
}
}
else
{
//只有船期发生变化时才重新写入新的船期记录
5 months ago
if (model.PId != shipScheduleRecord.ShipRatePid.Value)
5 months ago
{
5 months ago
//_logger.LogInformation($"MSK CON id={model.id} 换了船期 原记录:{selectedShipSchedule.PId} 新记录:{model.PId} 作废原船期,插入新船期");
shipScheduleRecord.Deleted = true;
shipScheduleRecord.DeleteTime = nowDate;
shipScheduleRecord.DeleteBy = long.Parse(user.UserId);
//shipScheduleRecord.UpdatedUserName = UserManager.Name;
await tenantDb.Updateable<SpaceBookingOrderShipSchedule>(shipScheduleRecord).UpdateColumns(x => new {
x.Deleted,
x.DeleteTime,
x.DeleteBy,
//x.UpdatedTime
5 months ago
}).ExecuteCommandAsync();
5 months ago
shipScheduleRecord = new SpaceBookingOrderShipSchedule
5 months ago
{
5 months ago
Id = SnowFlakeSingle.Instance.NextId(),
RecordId = model.id.Value,
ShipRatePid = selectedShipSchedule.PId,
ShipRateMD5 = selectedShipSchedule.MD5,
ShipJson = Newtonsoft.Json.JsonConvert.SerializeObject(selectedShipSchedule),
CreateTime = nowDate,
UpdateTime = nowDate,
CreateBy = long.Parse(user.UserId),
//CreatedUserName = UserManager.Name
5 months ago
};
5 months ago
await tenantDb.Insertable<SpaceBookingOrderShipSchedule>(shipScheduleRecord).ExecuteCommandAsync();
5 months ago
}
else
{
5 months ago
//_logger.LogInformation($"MSK CON id={model.id} 船期没变化 model.PId={model.PId} shipScheduleRecord.SHIP_RATE_PID={shipScheduleRecord.SHIP_RATE_PID.Value}");
5 months ago
}
}
5 months ago
return DataResult<long>.Success(entity.Id);
5 months ago
}
}
#endregion
#region 删除
/// <summary>
/// 删除
/// </summary>
/// <param name="id">请求订舱ID</param>
/// <returns></returns>
5 months ago
public async Task<DataResult<string>> Delete(long id)
5 months ago
{
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var info = tenantDb.Queryable<SpaceBookingOrder>().First(a => a.Id == id);
5 months ago
5 months ago
//删除失败,业务信息不存在或已作废
5 months ago
if (info == null)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIDeleteFailNoExists)));
info.Deleted = true;
info.DeleteTime = DateTime.Now;
info.DeleteBy = long.Parse(user.UserId);
//info.UpdatedUserName = UserManager.Name;
await tenantDb.Updateable<SpaceBookingOrder>(info).UpdateColumns(x => new {
x.Deleted,
x.DeleteTime,
x.DeleteBy
5 months ago
}).ExecuteCommandAsync();
5 months ago
return DataResult<string>.Success("成功");
5 months ago
}
#endregion
#region 批量发送
/// <summary>
/// 批量发送
/// </summary>
/// <param name="ids">马士基API订舱ID组</param>
/// <returns>返回执行结果消息</returns>
5 months ago
public async Task<DataResult<string>> BatchSend(long[] ids)
5 months ago
{
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = await tenantDb.Queryable<SpaceBookingOrder>()
5 months ago
.Where(a => ids.Contains(a.Id)).ToListAsync();
5 months ago
//if (list.Count != ids.Length)
//throw Oops.Oh("订舱数据获取失败,请确认选中的记录是否存在");
5 months ago
List<string> msgList = new List<string>();
int totalNum = list.Count;
int succNum = 0;
int failNum = 0;
if (list.Count > 1)
{
list.ForEach(entity =>
{
MSKBookingResultDto result = null;
try
{
5 months ago
var model = GetInfo(entity.Id).GetAwaiter().GetResult().Data;
result = InnerSendMSKBooking(model, entity.Id, false).GetAwaiter().GetResult()?.Data;
5 months ago
succNum++;
}
catch (Exception ex)
{
msgList.Add(ex.Message);
failNum++;
}
Thread.Sleep(1000);
});
msgList.Add($"共计{totalNum} 条 成功{succNum}条 失败:{failNum}");
}
else
{
MSKBookingResultDto result = null;
try
{
var entity = list.FirstOrDefault();
5 months ago
var model = GetInfo(entity.Id).GetAwaiter().GetResult()?.Data;
result = InnerSendMSKBooking(model, entity.Id, false).GetAwaiter().GetResult()?.Data;
5 months ago
if (result.succ)
5 months ago
return DataResult<string>.Success("成功");
5 months ago
}
catch (Exception ex)
{
msgList.Add(ex.Message);
}
}
5 months ago
return DataResult<string>.Success(string.Join("#", msgList.ToArray()));
5 months ago
}
#endregion
#region 批量复制
/// <summary>
/// 批量复制
/// </summary>
/// <param name="model">马士基API批量复制指定数据</param>
/// <returns>返回执行结果消息</returns>
5 months ago
public async Task<DataResult<string>> BatchCopy(MSKAPIBookingCopyDto model)
5 months ago
{
5 months ago
//if (model.copyNum < 1)
// throw Oops.Oh($"复制数量不能小于1");
5 months ago
5 months ago
//if (model.copyNum > 1000)
// throw Oops.Oh($"复制数量不能大于1000");
5 months ago
5 months ago
//if (string.IsNullOrWhiteSpace(model.opType))
// throw Oops.Oh($"请求的操作类型不能为空");
5 months ago
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var entity = await tenantDb.Queryable<SpaceBookingOrder>().FirstAsync(a => a.Id == model.originalId);
5 months ago
5 months ago
//if (entity == null)
// throw Oops.Oh($"获取马士基API订舱详情失败不存在或已作废");
5 months ago
5 months ago
var ctnList = tenantDb.Queryable<SpaceBookingOrderCtn>()
.Where(a => a.RecordId == model.originalId && a.Deleted == false).ToList();
5 months ago
var numArg = "".PadLeft(model.copyNum, '0').Select((a, idx) => idx + 1).ToList();
DateTime nowDate = DateTime.Now;
5 months ago
//_logger.LogInformation("获取到批量复制功能");
5 months ago
//如果是指定的编辑信息需要先把编辑数据同步到实体类,再进行复制
if (model.opType == "copy_edit")
{
string ctnStat = string.Empty;
if (model.bookingDto.ctns != null && model.bookingDto.ctns.Count > 0)
{
ctnStat = string.Join(",", model.bookingDto.ctns.GroupBy(a => a.ctnName)
.Select(a => $"{a.Key}*{a.ToList().Sum(b => b.ctnNum.HasValue ? b.ctnNum.Value : 0)}").ToArray());
5 months ago
ctnList = new List<SpaceBookingOrderCtn>();
5 months ago
model.bookingDto.ctns.ForEach(ctn =>
{
5 months ago
var ctnEntity = new SpaceBookingOrderCtn
5 months ago
{
5 months ago
CtnCode = ctn.ctnCode,
CtnName = ctn.ctnName,
CtnNum = ctn.ctnNum.Value,
CtnSufferWeight = (int)ctn.ctnSufferWeight.Value,
5 months ago
};
5 months ago
ctnEntity.CreateTime = nowDate;
ctnEntity.UpdateTime = nowDate;
ctnEntity.CreateBy = long.Parse(user.UserId);
//ctnEntity.CreatedUserName = UserManager.Name;
ctnEntity.StuffingMeasurementType = "WEIGHT";
ctnEntity.StuffingMeasurementUnit = "KGS";
5 months ago
ctnList.Add(ctnEntity);
});
}
5 months ago
entity = model.bookingDto.Adapt<SpaceBookingOrder>();
entity.CreateTime = nowDate;
entity.UpdateTime = nowDate;
entity.CreateBy = long.Parse(user.UserId);
//entity.CreatedUserName = UserManager.Name;
entity.Status = "TEMP";
entity.StatusName = "暂存";
entity.CtnStat = ctnStat;
entity.BookingChannelType = "CON_API";
entity.BookingChannelTypeName = "合约订舱";
5 months ago
}
int totalNum = 0;
foreach (var a in numArg)
{
5 months ago
var copyEntity = entity.Adapt<SpaceBookingOrder>();
5 months ago
copyEntity.Id = 0;
5 months ago
copyEntity.CreateTime = nowDate;
copyEntity.CreateBy = long.Parse(user.UserId);
//copyEntity.CreatedUserName = UserManager.Name;
copyEntity.UpdateTime = nowDate;
copyEntity.Status = "TEMP";
copyEntity.StatusName = "暂存";
copyEntity.IsRecvBC = false;
copyEntity.LstRecvBCDate = null;
copyEntity.IsRecvBKCancel = false;
copyEntity.LstRecvBKCancelDate = null;
copyEntity.RequestAcknowledgementId = null;
copyEntity.BookingReference = null;
copyEntity.Notes = $"COPY NO.{a} BY={model.originalId}";
await tenantDb.Insertable<SpaceBookingOrder>(copyEntity).ExecuteReturnEntityAsync();
5 months ago
totalNum++;
if (ctnList.Count > 0)
{
ctnList.ForEach(async ctn =>
{
5 months ago
var ctnEntity = ctn.Adapt<SpaceBookingOrderCtn>();
5 months ago
ctnEntity.Id = 0;
5 months ago
ctnEntity.RecordId = copyEntity.Id;
ctnEntity.CreateTime = nowDate;
ctnEntity.UpdateTime = nowDate;
ctnEntity.CreateBy = long.Parse(user.UserId);
//ctnEntity.CreatedUserName = UserManager.Name;
5 months ago
5 months ago
await tenantDb.Insertable<SpaceBookingOrderCtn>(ctnEntity).ExecuteReturnEntityAsync();
5 months ago
});
}
}
5 months ago
return DataResult<string>.Success(JsonConvert.SerializeObject(new { Total = totalNum }));
5 months ago
}
#endregion
#region 同步BC状态BC,Cancellation
/// <summary>
/// 同步BC状态BC,Cancellation
/// </summary>
/// <param name="mblno">提单号</param>
/// <param name="tenantId">租户ID</param>
/// <param name="opTypeName">操作类型 BC-同步BC状态 Cancellation-同步取消状态</param>
/// <returns>返回回执</returns>
5 months ago
public async Task<DataResult<MSKBookingResultDto>> SyncBCInfo(string mblno, long tenantId, string opTypeName = "BookingConfirmation")
5 months ago
{
MSKBookingResultDto result = new MSKBookingResultDto();
try
{
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var model = await tenantDb.Queryable<SpaceBookingOrder>()
.FirstAsync(a => a.BookingReference == mblno && a.Deleted == false);
5 months ago
5 months ago
//预订舱数据不存在或已作废
5 months ago
if (model == null)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIOrderDeletedOrNoExists)));
5 months ago
if (opTypeName == "BookingConfirmation")
{
5 months ago
model.IsRecvBC = true;
model.LstRecvBCDate = DateTime.Now;
model.UpdateTime = model.LstRecvBCDate;
model.UpdateBy = long.Parse(user.UserId);
//model.UpdatedUserName = UserManager.Name;
await tenantDb.Updateable<SpaceBookingOrder>(model).UpdateColumns(x => new {
x.IsRecvBC,
x.LstRecvBCDate,
x.UpdateTime,
x.UpdateBy,
//x.UpdatedUserName
5 months ago
}).ExecuteCommandAsync();
}
else if (opTypeName == "Cancellation")
{
5 months ago
model.IsRecvBKCancel = true;
model.LstRecvBKCancelDate = DateTime.Now;
model.UpdateTime = model.LstRecvBKCancelDate;
model.UpdateBy = long.Parse(user.UserId);
//model.UpdatedUserName = UserManager.Name;
await tenantDb.Updateable<SpaceBookingOrder>(model).UpdateColumns(x => new {
x.IsRecvBKCancel,
x.LstRecvBKCancelDate,
x.UpdateTime,
x.UpdateBy,
//x.UpdatedUserName
5 months ago
}).ExecuteCommandAsync();
}
result.succ = true;
}
catch (Exception ex)
{
result.succ = false;
result.msg = $"同步BC状态异常原因{ex.Message}";
}
5 months ago
return DataResult<MSKBookingResultDto>.Success(result);
5 months ago
}
#endregion
#region 批量复制前调取校验预警
/// <summary>
/// 批量复制前调取校验预警
/// </summary>
/// <param name="model">马士基API批量复制指定数据</param>
/// <returns>返回提示信息</returns>
5 months ago
public async Task<DataResult<string>> CheckWarningBatchCopy(MSKAPIBookingCopyDto model)
5 months ago
{
/*
1退
2opType=copy_edit-使
3
*/
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var entity = await tenantDb.Queryable<SpaceBookingOrder>().FirstAsync(a => a.Id == model.originalId);
5 months ago
if (entity != null)
{
List<string> msgList = new List<string>();
5 months ago
if (entity.IsShipperOwner || (model.bookingDto != null && model.bookingDto.isShipperOwned))
5 months ago
{
5 months ago
//含有指定托运人自己的集装箱
msgList.Add(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIIncludeShipperOwner)));
5 months ago
}
5 months ago
if (entity.IsImportReturned || (model.bookingDto != null && model.bookingDto.isImportReturned))
5 months ago
{
5 months ago
//含有指定进口退货集装箱或者其他三角集运
msgList.Add(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIIncludeImportReturned)));
5 months ago
}
5 months ago
if (entity.IsReefer || (model.bookingDto != null && model.bookingDto.isReefer))
5 months ago
{
5 months ago
//含有是冷冻处理
msgList.Add(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIIncludeReefer)));
5 months ago
}
5 months ago
if (model.bookingDto != null && model.bookingDto.cargoType != entity.CargoType)
5 months ago
{
5 months ago
//货物标志与被复制货物标志不一致
msgList.Add(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICargoTypeWithCopyDiff)));
5 months ago
}
if (msgList.Count > 0)
5 months ago
throw new Exception(string.Join(",", msgList.ToArray()));
5 months ago
}
else
{
5 months ago
return DataResult<string>.Success(string.Empty);
5 months ago
}
5 months ago
return DataResult<string>.Success("校验成功");
5 months ago
}
#endregion
#region 批量发送API前调取校验预警
/// <summary>
/// 批量发送API前调取校验预警
/// </summary>
/// <param name="ids">马士基API订舱ID组</param>
/// <returns>返回提示信息</returns>
5 months ago
public async Task<DataResult<string>> CheckWarningBatchSend(long[] ids)
5 months ago
{
5 months ago
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = await tenantDb.Queryable<SpaceBookingOrder>().Where(a => ids.Contains(a.Id)).ToListAsync();
5 months ago
if (list.Count > 0)
{
List<string> msgList = new List<string>();
5 months ago
if (list.Any(a => a.IsShipperOwner))
5 months ago
{
5 months ago
//含有指定托运人自己的集装箱
msgList.Add(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIIncludeShipperOwner)));
5 months ago
}
5 months ago
if (list.Any(a => a.IsImportReturned))
5 months ago
{
5 months ago
//含有指定进口退货集装箱或者其他三角集运
msgList.Add(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIIncludeImportReturned)));
5 months ago
}
5 months ago
if (list.Any(a => a.IsReefer))
5 months ago
{
5 months ago
//含有是冷冻处理
msgList.Add(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIIncludeReefer)));
5 months ago
}
if (msgList.Count > 0)
5 months ago
throw new Exception(string.Join(",", msgList.ToArray()));
5 months ago
}
5 months ago
return DataResult<string>.Success("校验成功");
5 months ago
}
#endregion
#region 获取初始化页面默认值
/// <summary>
/// 获取初始化页面默认值
/// </summary>
/// <returns>返回详情</returns>
5 months ago
public async Task<DataResult<MSKSPOTBookingInitDto>> GetInitInfo()
5 months ago
{
MSKSPOTBookingInitDto dto = null;
5 months ago
var webAccountConfig = codeThirdPartyService.GetCodeThirdPartyInfoWithCompany("MSKApi").GetAwaiter().GetResult()?.Data;
5 months ago
5 months ago
//未配置公司或个人的第三方账户维护-MSK API合约请联系管理员
5 months ago
if (webAccountConfig == null)
5 months ago
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIMSKConThirdPartySettingNull)));
5 months ago
if (string.IsNullOrWhiteSpace(webAccountConfig.RegistPartyCode)
|| string.IsNullOrWhiteSpace(webAccountConfig.RegistPartyName) || string.IsNullOrWhiteSpace(webAccountConfig.RegistContractName)
|| string.IsNullOrWhiteSpace(webAccountConfig.RegistContractEmail))
{
5 months ago
//第三方账户MSK API合约维护配置缺少备案代码、备案全称、联系人、邮箱必填请联系管理员
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIMSKConThirdPartySettingShortage)));
5 months ago
}
dto = new MSKSPOTBookingInitDto
{
bookedByMaerskPartyCode = webAccountConfig.RegistPartyCode,
bookedByCompanyName = webAccountConfig.RegistPartyName,
priceOwnerMaerskPartyCode = webAccountConfig.RegistPartyCode,
priceOwnerCompanyName = webAccountConfig.RegistPartyName,
bookedByCompanyContactName = webAccountConfig.RegistContractName,
bookedByCompanyContactEmail = webAccountConfig.RegistContractEmail,
priceOwnerContactName = webAccountConfig.RegistContractName,
priceOwnerContactEmail = webAccountConfig.RegistContractEmail,
};
5 months ago
return DataResult<MSKSPOTBookingInitDto>.Success(dto);
5 months ago
}
#endregion
}
}