修改MSK API订舱,增加定时订舱

usertest
jianghaiqing 3 months ago
parent db06c45497
commit fc9c99d59c

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DS.WMS.Core.Op.Dtos
{
/// <summary>
/// 定时方案枚举
/// </summary>
public enum MSKAPITimerSchemeTypeEnum
{
/// <summary>
/// 指定具体时间只执行一次
/// </summary>
[Description("从{0}开始,执行一次")]
SpecificTimeDoOnce,
}
}

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DS.WMS.Core.Op.Dtos
{
/// <summary>
/// 定时方案
/// </summary>
public class MSKAPITimerSchemeDto
{
/// <summary>
/// 定时方案代码
/// </summary>
public string code { get; set; }
/// <summary>
/// 定时方案名称
/// </summary>
public string name { get; set; }
}
}

@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DS.WMS.Core.Op.Dtos
{
/// <summary>
/// MSK API 定时订舱请求
/// </summary>
public class MSKAPITimerBookingDto
{
/// <summary>
/// 启动时间yyyy-MM-dd HH:mm
/// </summary>
public string StartTime { get; set; }
/// <summary>
/// 定时方案
/// </summary>
public string TimerSchemeType { get; set; }
/// <summary>
/// 需要设定的预订舱主键组
/// </summary>
public long[] ids { get; set; }
}
}

@ -400,6 +400,11 @@ namespace DS.WMS.Core.Op.Dtos
/// 选择的船期详情 /// 选择的船期详情
/// </summary> /// </summary>
public SearchShipSailingScheduleResultDto selectedShipScheduleShow { get; set; } public SearchShipSailingScheduleResultDto selectedShipScheduleShow { get; set; }
/// <summary>
/// 状态
/// </summary>
public string Status { get; set; }
} }
public class MSKBookingCtnInfo public class MSKBookingCtnInfo

@ -632,5 +632,17 @@ namespace DS.WMS.Core.Op.Entity
/// </summary> /// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "承运人代码", Length = 20, IsNullable = true)] [SqlSugar.SugarColumn(ColumnDescription = "承运人代码", Length = 20, IsNullable = true)]
public string vesselCarrierCode { get; set; } public string vesselCarrierCode { get; set; }
/// <summary>
/// 定时方案ID
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "定时方案ID", Length = 20, IsNullable = true)]
public string TimerPlanId { get; set; }
/// <summary>
/// 定时方案名称
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "定时方案名称", Length = 100, IsNullable = true)]
public string TimerPlanName { get; set; }
} }
} }

@ -0,0 +1,58 @@
using DS.Module.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DS.WMS.Core.Op.Entity
{
/// <summary>
/// 预订舱定时订舱运行表
/// </summary>
[SqlSugar.SugarTable("op_sea_space_booking_order_job_run", "预订舱定时订舱运行表")]
public class SpaceBookingOrderBookingJobRun : BaseModel<long>
{
/// <summary>
/// 主记录ID
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "主记录ID", IsNullable = true)]
public long RecordId { get; set; }
/// <summary>
/// 定时时间
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "定时时间", IsNullable = true)]
public Nullable<DateTime> JobTime { get; set; }
/// <summary>
/// 发送时间
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "发送时间", IsNullable = true)]
public Nullable<DateTime> SendTime { get; set; }
/// <summary>
/// 定时方案ID
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "定时方案ID", Length = 20, IsNullable = true)]
public string TimerPlanId { get; set; }
/// <summary>
/// 定时方案名称
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "定时方案名称", Length = 100, IsNullable = true)]
public string TimerPlanName { get; set; }
/// <summary>
/// 是否已推送报告 1-已推送 0-未推送
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "是否已推送报告 1-已推送 0-未推送", IsNullable = true)]
public bool IsSendReport { get; set; }
/// <summary>
/// 推送报告时间
/// </summary>
[SqlSugar.SugarColumn(ColumnDescription = "推送报告时间", IsNullable = true)]
public Nullable<DateTime> ReportTime { get; set; }
}
}

@ -125,5 +125,31 @@ namespace DS.WMS.Core.Op.Interface
/// </summary> /// </summary>
/// <returns>返回回执</returns> /// <returns>返回回执</returns>
Task<DataResult<List<string>>> GetBookingChannelSelectShow(); Task<DataResult<List<string>>> GetBookingChannelSelectShow();
/// <summary>
/// 批量设定定时订舱时间
/// </summary>
/// <param name="model">请求详情</param>
/// <returns>返回回执</returns>
Task<DataResult<string>> BatchSetupTimerBooking(MSKAPITimerBookingDto model);
/// <summary>
/// 获取定时订舱方案列表
/// </summary>
/// <returns></returns>
Task<DataResult<List<MSKAPITimerSchemeDto>>> GetTimerSchemeList();
/// <summary>
/// 生成订舱订舱报告邮件并自动转发
/// </summary>
/// <returns></returns>
Task<DataResult<string>> GenerateTimerReportEmail();
/// <summary>
/// 批量取消定时订舱时间
/// </summary>
/// <param name="ids">马士基API订舱ID组</param>
/// <returns>返回回执</returns>
Task<DataResult<string>> BatchCancelTimerBooking(long[] ids);
} }
} }

@ -34,10 +34,16 @@ using Microsoft.Owin.Security.Provider;
using LanguageExt; using LanguageExt;
using DS.Module.Core.Data; using DS.Module.Core.Data;
using DS.WMS.Core.TaskPlat.Dtos; using DS.WMS.Core.TaskPlat.Dtos;
using NLog.Fluent;
using Fasterflect; using Fasterflect;
using AutoMapper; using AutoMapper;
using System.Reflection; using System.Reflection;
using DS.WMS.Core.Code.Method;
using Microsoft.AspNetCore.Identity;
using Masuit.Tools.Systems;
using Amazon.Runtime.Internal.Util;
using DS.WMS.Core.Op.EDI;
using HtmlAgilityPack;
using MySqlConnector.Logging;
namespace DS.WMS.Core.Op.Method namespace DS.WMS.Core.Op.Method
{ {
@ -51,10 +57,11 @@ namespace DS.WMS.Core.Op.Method
private readonly string mskAPIUserKey; private readonly string mskAPIUserKey;
private readonly string mskAPIUserSecret; private readonly string mskAPIUserSecret;
private readonly string mskAPIEnvironment; private readonly string mskAPIEnvironment;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly NLog.Logger Logger = LogManager.GetCurrentClassLogger();
private readonly IMappingCtnService mappingCtnService; private readonly IMappingCtnService mappingCtnService;
private readonly IRedisService redisService; private readonly IRedisService redisService;
private readonly IConfigService configService; private readonly IConfigService configService;
private readonly IUserEmailService _userEmailService;
const string CONST_MSK_API_Poing2P_SECD_URL = "MSKApiSailingSchedulePoint2Point"; const string CONST_MSK_API_Poing2P_SECD_URL = "MSKApiSailingSchedulePoint2Point";
@ -77,6 +84,7 @@ namespace DS.WMS.Core.Op.Method
mappingCtnService = _serviceProvider.GetRequiredService<IMappingCtnService>(); mappingCtnService = _serviceProvider.GetRequiredService<IMappingCtnService>();
redisService = _serviceProvider.GetRequiredService<IRedisService>(); redisService = _serviceProvider.GetRequiredService<IRedisService>();
configService = _serviceProvider.GetRequiredService<IConfigService>(); configService = _serviceProvider.GetRequiredService<IConfigService>();
_userEmailService = _serviceProvider.GetRequiredService<IUserEmailService>();
mskAPIUserKey = AppSetting.app(new string[] { "MSKAPIService", "UserKey" }); mskAPIUserKey = AppSetting.app(new string[] { "MSKAPIService", "UserKey" });
mskAPIUserSecret = AppSetting.app(new string[] { "MSKAPIService", "UserSecret" }); mskAPIUserSecret = AppSetting.app(new string[] { "MSKAPIService", "UserSecret" });
@ -544,8 +552,8 @@ namespace DS.WMS.Core.Op.Method
throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICarrierCodeNull))); throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPICarrierCodeNull)));
//船公司代码不能为空 //船公司代码不能为空
//if (string.IsNullOrWhiteSpace(model.carrierId)) if (string.IsNullOrWhiteSpace(model.vesselCarrierCode))
//throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIVesselCarrierCodeNull))); throw new Exception(MultiLanguageConst.GetDescription(nameof(MultiLanguageConst.SpaceBookingAPIVesselCarrierCodeNull)));
string sendUrl = string.Empty; string sendUrl = string.Empty;
@ -609,11 +617,6 @@ namespace DS.WMS.Core.Op.Method
var recordInfo = model.Adapt<SpaceBookingOrder>(); var recordInfo = model.Adapt<SpaceBookingOrder>();
var recordCtnList = model.ctns.Adapt<List<SpaceBookingOrderCtn>>(); var recordCtnList = model.ctns.Adapt<List<SpaceBookingOrderCtn>>();
//var ctnCodeMappingList = _cache.GetAllMappingCtn().GetAwaiter().GetResult().ToList();
//if (ctnCodeMappingList.Count > 0)
//ctnCodeMappingList = ctnCodeMappingList.Where(x => x.CarrierCode == "MSK" && x.Module == "BOOK_MSK_API").ToList();
MSKAPIBookingDto bookingDto = new MSKAPIBookingDto MSKAPIBookingDto bookingDto = new MSKAPIBookingDto
{ {
userKey = mskAPIUserKey, userKey = mskAPIUserKey,
@ -682,7 +685,7 @@ namespace DS.WMS.Core.Op.Method
} }
else else
{ {
//throw Oops.Bah($"查询船期错误pid={model.PId} 预计离港日期departureDate 格式解析错误"); throw new Exception($"查询船期错误pid={model.PId} 预计离港日期departureDate 格式解析错误");
} }
for (int i = 0; i < selectedShipSchedule.transportLegs.Count; i++) for (int i = 0; i < selectedShipSchedule.transportLegs.Count; i++)
@ -698,7 +701,7 @@ namespace DS.WMS.Core.Op.Method
} }
else else
{ {
//throw Oops.Bah($"查询船期错误pid={model.PId} 预计离港日期departureDate 格式解析错误"); throw new Exception($"查询船期错误pid={model.PId} 预计离港日期departureDate 格式解析错误");
} }
//ETA //ETA
@ -708,7 +711,7 @@ namespace DS.WMS.Core.Op.Method
} }
else else
{ {
//throw Oops.Bah($"查询船期错误pid={model.PId} 预计到港日期arrivalDateTime 格式解析错误"); throw new Exception($"查询船期错误pid={model.PId} 预计到港日期arrivalDateTime 格式解析错误");
} }
if (detail.transport.vessel != null) if (detail.transport.vessel != null)
@ -834,8 +837,8 @@ namespace DS.WMS.Core.Op.Method
var ctnMapping = mappingCtnService.QueryMappingCtn(model.carrierId.Value, CONST_MSK_API_MAPPING_MODULE, ctn.ctnCode).GetAwaiter().GetResult()?.Data; var ctnMapping = mappingCtnService.QueryMappingCtn(model.carrierId.Value, CONST_MSK_API_MAPPING_MODULE, ctn.ctnCode).GetAwaiter().GetResult()?.Data;
//var ctnMapping = ctnCodeMappingList.FirstOrDefault(t => t.Code.Equals(ctn.ctnCode)); //var ctnMapping = ctnCodeMappingList.FirstOrDefault(t => t.Code.Equals(ctn.ctnCode));
//if (ctnMapping == null) if (ctnMapping == null)
//throw Oops.Oh($"未配置相应的箱型对应{ctn.ctnName},请联系管理员"); throw new Exception($"未配置相应的箱型对应{ctn.ctnName},请联系管理员");
MSKAPIBookingEquipmentAndHaulage haulage = new MSKAPIBookingEquipmentAndHaulage MSKAPIBookingEquipmentAndHaulage haulage = new MSKAPIBookingEquipmentAndHaulage
{ {
@ -879,13 +882,13 @@ namespace DS.WMS.Core.Op.Method
var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(bookingDto); var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(bookingDto);
//_logger.LogInformation($"开始请求MSK API订舱JSON={jsonBody}"); Logger.Log(NLog.LogLevel.Info, $"开始请求MSK API订舱JSON={jsonBody}");
//var rlt = await sendUrl.SetBody(jsonBody).PostAsStringAsync(); //var rlt = await sendUrl.SetBody(jsonBody).PostAsStringAsync();
var rlt = RequestHelper.Post(jsonBody, sendUrl); var rlt = RequestHelper.Post(jsonBody, sendUrl);
//_logger.LogInformation($"开始请求MSK API订舱返回结果 JSON={JSON.Serialize(rlt)}"); Logger.Log(NLog.LogLevel.Info, $"开始请求MSK API订舱返回结果 JSON={rlt}");
if (!string.IsNullOrWhiteSpace(rlt)) if (!string.IsNullOrWhiteSpace(rlt))
{ {
@ -895,9 +898,9 @@ namespace DS.WMS.Core.Op.Method
} }
catch (Exception ex) catch (Exception ex)
{ {
//_logger.LogInformation($"请求MSK API订舱异常原因{ex.Message}"); Logger.Log(NLog.LogLevel.Info, $"请求MSK API订舱异常原因{ex.Message}");
//throw Oops.Bah($"请求MSK API订舱异常原因{ex.Message}"); throw new Exception($"请求MSK API订舱异常原因{ex.Message}");
} }
} }
@ -940,14 +943,14 @@ namespace DS.WMS.Core.Op.Method
}).ExecuteCommandAsync(); }).ExecuteCommandAsync();
//throw Oops.Bah(resultInfo.msg); throw new Exception(resultInfo.msg);
} }
result.succ = true; result.succ = true;
} }
catch (Exception ex) catch (Exception ex)
{ {
//_logger.LogError($"MSK API订舱异常req={JSON.Serialize(model)} 原因:{ex.Message}"); Logger.Log(NLog.LogLevel.Error, $"MSK API订舱异常req={JsonConvert.SerializeObject(model)} 原因:{ex.Message}");
//throw Oops.Bah($"MSK API订舱失败{ex.Message}"); //throw Oops.Bah($"MSK API订舱失败{ex.Message}");
@ -1138,13 +1141,13 @@ namespace DS.WMS.Core.Op.Method
//当前订舱合同号是非订舱方合约持约方不能和订舱方ID信息一样请根据实际情况填写 //当前订舱合同号是非订舱方合约持约方不能和订舱方ID信息一样请根据实际情况填写
if (model.bookedByMaerskPartyCode.Equals(model.priceOwnerMaerskPartyCode)) if (model.bookedByMaerskPartyCode.Equals(model.priceOwnerMaerskPartyCode))
{ {
//throw Oops.Bah($"当前订舱合同号是非订舱方合约持约方不能和订舱方ID信息一样请根据实际情况填写"); throw new Exception($"当前订舱合同号是非订舱方合约持约方不能和订舱方ID信息一样请根据实际情况填写");
} }
//当前订舱合同号是非订舱方合约,持约方公司名称不能和订舱方公司名称信息一样,请根据实际情况填写 //当前订舱合同号是非订舱方合约,持约方公司名称不能和订舱方公司名称信息一样,请根据实际情况填写
if (model.bookedByCompanyName.Equals(model.priceOwnerCompanyName)) if (model.bookedByCompanyName.Equals(model.priceOwnerCompanyName))
{ {
//throw Oops.Bah($"当前订舱合同号是非订舱方合约,持约方公司名称不能和订舱方公司名称信息一样,请根据实际情况填写"); throw new Exception($"当前订舱合同号是非订舱方合约,持约方公司名称不能和订舱方公司名称信息一样,请根据实际情况填写");
} }
} }
else else
@ -1152,13 +1155,13 @@ namespace DS.WMS.Core.Op.Method
//当前订舱合同号是订舱方合约持约方ID必需和订舱方ID信息一致请根据实际情况填写 //当前订舱合同号是订舱方合约持约方ID必需和订舱方ID信息一致请根据实际情况填写
if (!model.bookedByMaerskPartyCode.Equals(model.priceOwnerMaerskPartyCode)) if (!model.bookedByMaerskPartyCode.Equals(model.priceOwnerMaerskPartyCode))
{ {
//throw Oops.Bah($"当前订舱合同号是订舱方合约持约方ID必需和订舱方ID信息一致请根据实际情况填写"); throw new Exception($"当前订舱合同号是订舱方合约持约方ID必需和订舱方ID信息一致请根据实际情况填写");
} }
//当前订舱合同号是订舱方合约,持约方名称必需和订舱方名称信息一致,请根据实际情况填写 //当前订舱合同号是订舱方合约,持约方名称必需和订舱方名称信息一致,请根据实际情况填写
if (!model.bookedByCompanyName.Equals(model.priceOwnerCompanyName)) if (!model.bookedByCompanyName.Equals(model.priceOwnerCompanyName))
{ {
//throw Oops.Bah($"当前订舱合同号是订舱方合约,持约方名称必需和订舱方名称信息一致,请根据实际情况填写"); throw new Exception($"当前订舱合同号是订舱方合约,持约方名称必需和订舱方名称信息一致,请根据实际情况填写");
} }
} }
} }
@ -1438,6 +1441,7 @@ namespace DS.WMS.Core.Op.Method
bookingChannelType = entity.BookingChannelTypeName, bookingChannelType = entity.BookingChannelTypeName,
carrierCollectionOriginGeoID = entity.PlaceReceiptGeoId, carrierCollectionOriginGeoID = entity.PlaceReceiptGeoId,
carrierDeliveryDestinationGeoID = entity.PlaceDeliveryGeoId, carrierDeliveryDestinationGeoID = entity.PlaceDeliveryGeoId,
Status = entity.Status,
}; };
var ctnList = tenantDb.Queryable<SpaceBookingOrderCtn>().Where(a => a.RecordId == id && a.Deleted == false).ToList(); var ctnList = tenantDb.Queryable<SpaceBookingOrderCtn>().Where(a => a.RecordId == id && a.Deleted == false).ToList();
@ -1534,9 +1538,9 @@ namespace DS.WMS.Core.Op.Method
} }
if (selectedShipSchedule == null) if (selectedShipSchedule == null)
//throw Oops.Oh("船期数据校验失败,请重新查询船期信息"); throw new Exception("船期数据校验失败,请重新查询船期信息");
model.placeOfReceiptCountryName = selectedShipSchedule.originCountryName; model.placeOfReceiptCountryName = selectedShipSchedule.originCountryName;
model.placeOfReceiptRegionName = selectedShipSchedule.originRegionName; model.placeOfReceiptRegionName = selectedShipSchedule.originRegionName;
model.carrierCollectionOriginGeoID = selectedShipSchedule.originGeoId; model.carrierCollectionOriginGeoID = selectedShipSchedule.originGeoId;
@ -1976,8 +1980,8 @@ namespace DS.WMS.Core.Op.Method
var list = await tenantDb.Queryable<SpaceBookingOrder>() var list = await tenantDb.Queryable<SpaceBookingOrder>()
.Where(a => ids.Contains(a.Id)).ToListAsync(); .Where(a => ids.Contains(a.Id)).ToListAsync();
//if (list.Count != ids.Length) if (list.Count != ids.Length)
//throw Oops.Oh("订舱数据获取失败,请确认选中的记录是否存在"); throw new Exception("订舱数据获取失败,请确认选中的记录是否存在");
List<string> msgList = new List<string>(); List<string> msgList = new List<string>();
int totalNum = list.Count; int totalNum = list.Count;
@ -2062,6 +2066,10 @@ namespace DS.WMS.Core.Op.Method
var ctnList = tenantDb.Queryable<SpaceBookingOrderCtn>() var ctnList = tenantDb.Queryable<SpaceBookingOrderCtn>()
.Where(a => a.RecordId == model.originalId && a.Deleted == false).ToList(); .Where(a => a.RecordId == model.originalId && a.Deleted == false).ToList();
var shipScheduleRecord = await tenantDb.Queryable<SpaceBookingOrderShipSchedule>()
.FirstAsync(a => a.RecordId == model.originalId && a.ShipRatePid != null &&
a.ShipRatePid.Value == entity.ShipRatePId && a.Deleted == false);
var numArg = "".PadLeft(model.copyNum, '0').Select((a, idx) => idx + 1).ToList(); var numArg = "".PadLeft(model.copyNum, '0').Select((a, idx) => idx + 1).ToList();
DateTime nowDate = DateTime.Now; DateTime nowDate = DateTime.Now;
@ -2155,6 +2163,20 @@ namespace DS.WMS.Core.Op.Method
await tenantDb.Insertable<SpaceBookingOrderCtn>(ctnEntity).ExecuteReturnEntityAsync(); await tenantDb.Insertable<SpaceBookingOrderCtn>(ctnEntity).ExecuteReturnEntityAsync();
}); });
} }
if (shipScheduleRecord != null)
{
var currShipScheduleRecord = shipScheduleRecord.Adapt<SpaceBookingOrderShipSchedule>();
currShipScheduleRecord.Id = 0;
currShipScheduleRecord.RecordId = copyEntity.Id;
currShipScheduleRecord.CreateTime = nowDate;
currShipScheduleRecord.UpdateTime = nowDate;
currShipScheduleRecord.CreateBy = long.Parse(user.UserId);
currShipScheduleRecord.CreateUserName = user.UserName;
await tenantDb.Insertable<SpaceBookingOrderShipSchedule>(currShipScheduleRecord).ExecuteCommandAsync();
}
} }
return DataResult<string>.Success(JsonConvert.SerializeObject(new { Total = totalNum })); return DataResult<string>.Success(JsonConvert.SerializeObject(new { Total = totalNum }));
@ -2192,7 +2214,7 @@ namespace DS.WMS.Core.Op.Method
model.LstRecvBCDate = nowDate; model.LstRecvBCDate = nowDate;
model.UpdateTime = nowDate; model.UpdateTime = nowDate;
model.UpdateBy = long.Parse(user.UserId); model.UpdateBy = long.Parse(user.UserId);
//model.UpdatedUserName = UserManager.Name; model.UpdateUserName = user.UserName;
await tenantDb.Updateable<SpaceBookingOrder>(model).UpdateColumns(x => new await tenantDb.Updateable<SpaceBookingOrder>(model).UpdateColumns(x => new
{ {
@ -2200,7 +2222,7 @@ namespace DS.WMS.Core.Op.Method
x.LstRecvBCDate, x.LstRecvBCDate,
x.UpdateTime, x.UpdateTime,
x.UpdateBy, x.UpdateBy,
//x.UpdatedUserName x.UpdateUserName
}).ExecuteCommandAsync(); }).ExecuteCommandAsync();
} }
else if (opTypeName == "Cancellation") else if (opTypeName == "Cancellation")
@ -2209,7 +2231,7 @@ namespace DS.WMS.Core.Op.Method
model.LstRecvBKCancelDate = nowDate; model.LstRecvBKCancelDate = nowDate;
model.UpdateTime = nowDate; model.UpdateTime = nowDate;
model.UpdateBy = long.Parse(user.UserId); model.UpdateBy = long.Parse(user.UserId);
//model.UpdatedUserName = UserManager.Name; model.UpdateUserName = user.UserName;
await tenantDb.Updateable<SpaceBookingOrder>(model).UpdateColumns(x => new await tenantDb.Updateable<SpaceBookingOrder>(model).UpdateColumns(x => new
{ {
@ -2217,7 +2239,7 @@ namespace DS.WMS.Core.Op.Method
x.LstRecvBKCancelDate, x.LstRecvBKCancelDate,
x.UpdateTime, x.UpdateTime,
x.UpdateBy, x.UpdateBy,
//x.UpdatedUserName x.UpdateUserName
}).ExecuteCommandAsync(); }).ExecuteCommandAsync();
} }
@ -2449,5 +2471,397 @@ namespace DS.WMS.Core.Op.Method
return DataResult<List<string>>.FailedData(new List<string>()); return DataResult<List<string>>.FailedData(new List<string>());
} }
#endregion #endregion
#region 批量设定定时订舱时间
/// <summary>
/// 批量设定定时订舱时间
/// </summary>
/// <param name="model">请求详情</param>
/// <returns>返回回执</returns>
public async Task<DataResult<string>> BatchSetupTimerBooking(MSKAPITimerBookingDto model)
{
/*
1
2
3
4
*/
string result = string.Empty;
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = await tenantDb.Queryable<SpaceBookingOrder>()
.Where(a => model.ids.Contains(a.Id)).ToListAsync();
if (list.Count != model.ids.Length)
throw new Exception("订舱数据获取失败,请确认选中的记录是否存在");
StringBuilder msgBuilder = new StringBuilder();
foreach (var item in list)
{
var bookingOrder = GetInfo(item.Id).GetAwaiter().GetResult().Data;
try
{
if (item.Status == "SUCC")
{
throw new Exception($"当前状态是已发送成功,不能重复发送");
}
ValidateMSKAPIData(bookingOrder);
var runInfo = tenantDb.Queryable<SpaceBookingOrderBookingJobRun>().Filter(null, true)
.First(a => a.RecordId == item.Id && a.Deleted == false);
if (runInfo != null)
{
throw new Exception($"当前记录已开始定时发送不能修改");
}
item.IsJob = true;
DateTime jobTime = DateTime.MinValue;
if (DateTime.TryParse(model.StartTime, out jobTime))
{
item.JobTime = jobTime;
}
item.TimerPlanId = model.TimerSchemeType;
item.TimerPlanName = string.Format(((MSKAPITimerSchemeTypeEnum)System.Enum.Parse(typeof(MSKAPITimerSchemeTypeEnum), model.TimerSchemeType)).GetDescription(), model.StartTime);
item.UpdateTime = DateTime.Now;
item.UpdateBy = long.Parse(user.UserId);
item.UpdateUserName = user.UserName;
tenantDb.Updateable<SpaceBookingOrder>(item).UpdateColumns(x => new
{
x.IsJob,
x.JobTime,
x.TimerPlanId,
x.TimerPlanName,
x.UpdateTime,
x.UpdateBy,
x.UpdateUserName
}).ExecuteCommand();
}
catch (Exception ex)
{
msgBuilder.Append(ex.Message);
}
}
var msg = msgBuilder.ToString();
if (!string.IsNullOrWhiteSpace(msg))
throw new Exception(msg);
return DataResult<string>.Success(msg);
}
#endregion
#region 获取定时订舱方案列表
/// <summary>
/// 获取定时订舱方案列表
/// </summary>
/// <returns></returns>
public async Task<DataResult<List<MSKAPITimerSchemeDto>>> GetTimerSchemeList()
{
List<MSKAPITimerSchemeDto> list = new List<MSKAPITimerSchemeDto>();
list.Add(new MSKAPITimerSchemeDto
{
code = MSKAPITimerSchemeTypeEnum.SpecificTimeDoOnce.ToString(),
name = MSKAPITimerSchemeTypeEnum.SpecificTimeDoOnce.GetDescription()
});
return DataResult<List<MSKAPITimerSchemeDto>>.Success(list);
}
#endregion
#region 生成订舱订舱报告邮件并自动转发
/// <summary>
/// 生成订舱订舱报告邮件并自动转发
/// </summary>
/// <returns></returns>
public async Task<DataResult<string>> GenerateTimerReportEmail()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
DateTime nowDate = DateTime.Now;
DateTime startDate = new DateTime(nowDate.Year, nowDate.Month, nowDate.Day);
var runList = tenantDb.Queryable<SpaceBookingOrderBookingJobRun>().Filter(null, true)
.Where(a => a.SendTime >= startDate && a.Deleted == false && a.IsSendReport == false).ToList();
if (runList.Count > 0)
{
var idList = runList.Select(a => a.RecordId).ToList();
var orderList = tenantDb.Queryable<SpaceBookingOrder>().Filter(null, true)
.Where(a => a.Deleted == false && idList.Contains(a.Id)).ToList();
Logger.Log(NLog.LogLevel.Info, $"获取相关预订舱记录,{string.Join(",", idList.ToArray())}");
orderList.GroupBy(a => a.CreateBy).ToList().ForEach(b =>
{
var nextJobTime = DateTime.MinValue;
var waitList = tenantDb.Queryable<SpaceBookingOrder>().Filter(null, true)
.Where(a => a.Deleted == false && a.JobTime != null && a.JobTime.Value >= nowDate && a.CreateBy == b.Key && a.Status == "TEMP").OrderBy(a => a.JobTime.Value).ToList();
if (waitList.Count > 0)
nextJobTime = waitList.FirstOrDefault().JobTime.Value;
Logger.Log(NLog.LogLevel.Info, $"获取完待订舱的记录");
var opUser = tenantDb.Queryable<SysUser>().Filter(null, true).First(a => a.Id == b.Key);
//提取当前公共邮箱的配置
CodeUserEmailRes publicMailAccount = _userEmailService.GetEmailSettings("PublicSend").GetAwaiter().GetResult().Data;
if (publicMailAccount == null)
{
Logger.Log(NLog.LogLevel.Info, $"提取公共邮箱配置失败请在用户邮箱账号管理增加配置显示名为PublicSend或者配置个人邮箱");
}
Logger.Log(NLog.LogLevel.Info, $"取完邮箱配置");
string emailHtml = string.Empty;
var currList = b.OrderBy(t => t.SendTime.Value).ToList();
//string templatePath = App.Configuration["EmailTemplateFilePath"];
//var opt = App.GetOptions<BookingAttachOptions>();
//var dirAbs = opt.basePath;
//if (string.IsNullOrEmpty(dirAbs))
//{
// dirAbs = App.WebHostEnvironment.WebRootPath;
//}
string dirAbs = string.Empty;
//string templatePath = string.Empty;
string templatePath = $"{dirAbs}\\MSKAPITimerReportTemplate.html";
Logger.Log(NLog.LogLevel.Info, $"取完模板");
string baseHtml = File.ReadAllText(templatePath);
baseHtml = baseHtml.Replace("#ReportTime#", nowDate.ToString("yyyy-MM-dd HH:mm:ss"));
baseHtml = baseHtml.Replace("#total#", currList.Count.ToString());
baseHtml = baseHtml.Replace("#succ#", currList.Count(x => x.Status == "SUCC").ToString());
baseHtml = baseHtml.Replace("#failure#", currList.Count(x => x.Status == "FAILURE").ToString());
if (waitList.Count > 0)
{
baseHtml = baseHtml.Replace("#wait#", currList.Count().ToString());
}
else
{
baseHtml = baseHtml.Replace("#wait#", "0");
}
if (nextJobTime != DateTime.MinValue)
{
baseHtml = baseHtml.Replace("#NextTime#", nextJobTime.ToString("yyyy-MM-dd HH:mm"));
}
else
{
baseHtml = baseHtml.Replace("#NextTime#", "");
}
HtmlDocument html = new HtmlDocument();
html.LoadHtml(baseHtml);
var tableNode = html.DocumentNode.SelectSingleNode(".//table[@id='show-table']");
if (tableNode != null)
{
for (int i = 0; i < currList.Count; i++)
{
StringBuilder tableBuilder = new StringBuilder();
tableBuilder.Append($"<tr><td>{i + 1}</td><td>{(currList[i].SendTime.HasValue ? currList[i].SendTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "")}</td>");
tableBuilder.Append($"<td>{currList[i].StatusName}</td><td>{currList[i].BookingReference}</td><td>{currList[i].PlaceReceiptCity}</td><td>{currList[i].PlaceDeliveryCity}</td>");
tableBuilder.Append($"<td>{currList[i].CtnStat}</td><td>{(currList[i].ETD.HasValue ? currList[i].ETD.Value.ToString("yyyy-MM-dd HH:mm") : "")}</td>");
tableBuilder.Append($"<td>{(currList[i].TotalCargoWeight.HasValue ? currList[i].TotalCargoWeight.Value.ToString() : "")}</td><td>{currList[i].PriceReference}</td>");
tableBuilder.Append($"<td>{(currList[i].IsRecvBC ? "1" : "")}</td><td>{(currList[i].IsRecvBKCancel ? "1" : "")}</td><td>{(currList[i].JobTime.HasValue ? currList[i].JobTime.Value.ToString("yyyy-MM-dd HH:mm") : "")}</td></tr>");
tableNode.ChildNodes.Add(HtmlNode.CreateNode(tableBuilder.ToString()));
}
}
emailHtml = html.DocumentNode.OuterHtml;
Logger.Log(NLog.LogLevel.Info, $"填充完邮件正文");
EmailApiUserDefinedDto emailApiUserDefinedDto = new EmailApiUserDefinedDto
{
SendTo = opUser.Email,
CCTo = "",
Title = $"马士基API定时订舱统计报告 {nowDate.ToString("yyyy-MM-dd HH:mm:ss")}",
Body = emailHtml,
Account = publicMailAccount.MailAccount?.Trim(),
Password = publicMailAccount.Password?.Trim(),
Server = publicMailAccount.SmtpServer?.Trim(),
Port = publicMailAccount.SmtpPort.HasValue ? publicMailAccount.SmtpPort.Value : 465,
UseSSL = publicMailAccount.SmtpSSL.HasValue ? publicMailAccount.SmtpSSL.Value : true,
Attaches = new List<AttachesInfo>()
};
List<EmailApiUserDefinedDto> emailList = new List<EmailApiUserDefinedDto>();
var emailUrl = db.Queryable<SysConfig>().Filter(null, true).Where(x => x.Code == "email_api_url" && x.TenantId == 1288018625843826688).First().Value;
Logger.Log(NLog.LogLevel.Info, $"获取完邮件API地址");
if (emailUrl == null)
Logger.Log(NLog.LogLevel.Info, "字典未配置 url_set->email_api_url 请联系管理员");
emailList.Add(emailApiUserDefinedDto);
//string strJoin = System.IO.File.ReadAllText(filePath);
DateTime bDate = DateTime.Now;
string res = string.Empty;
try
{
var jsonBody = JsonConvert.SerializeObject(emailList);
res = RequestHelper.Post(jsonBody, emailUrl);
}
catch (Exception ex)
{
Logger.Log(NLog.LogLevel.Info, $"发送邮件异常:{ex.Message}");
}
DateTime eDate = DateTime.Now;
TimeSpan ts = eDate.Subtract(bDate);
var timeDiff = ts.TotalMilliseconds;
Logger.Log(NLog.LogLevel.Info, $"发送邮件返回:{JsonConvert.SerializeObject(res)}");
if (!string.IsNullOrWhiteSpace(res))
{
var respObj = JsonConvert.DeserializeAnonymousType(res, new
{
Success = false,
Message = string.Empty,
Code = -9999,
});
if (respObj.Success)
{
var updateList = currList.Join(runList, l => l.Id, r => r.RecordId, (l, r) =>
{
return r;
}).ToList();
foreach (var update in updateList)
{
update.IsSendReport = true;
update.ReportTime = DateTime.Now;
tenantDb.Updateable<SpaceBookingOrderBookingJobRun>(update).UpdateColumns(x => new
{
x.IsSendReport,
x.ReportTime
}).ExecuteCommand();
};
}
}
});
}
else
{
Logger.Log(NLog.LogLevel.Info, $"自动订舱报告失败,没有可执行的记录");
}
return DataResult<string>.SuccessMsg("");
}
#endregion
#region 批量取消定时订舱时间
/// <summary>
/// 批量取消定时订舱时间
/// </summary>
/// <param name="ids">马士基API订舱ID组</param>
/// <returns>返回回执</returns>
public async Task<DataResult<string>> BatchCancelTimerBooking(long[] ids)
{
string result = string.Empty;
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = await tenantDb.Queryable<SpaceBookingOrder>()
.Where(a => ids.Contains(a.Id)).ToListAsync();
if (list.Count != ids.Length)
throw new Exception("订舱数据获取失败,请确认选中的记录是否存在");
StringBuilder msgBuilder = new StringBuilder();
foreach (var item in list)
{
var bookingOrder = GetInfo(item.Id).GetAwaiter().GetResult();
try
{
if (item.Status == "SUCC")
{
throw new Exception($"当前状态是已发送成功,不能取消");
}
var runInfo = tenantDb.Queryable<SpaceBookingOrderBookingJobRun>().Filter(null, true)
.First(a => a.RecordId == item.Id && a.Deleted == false);
if (runInfo != null)
{
throw new Exception($"当前记录已开始定时发送不能修改");
}
item.IsJob = false;
item.JobTime = null;
item.TimerPlanId = null;
item.TimerPlanName = null;
item.UpdateTime = DateTime.Now;
item.UpdateBy = long.Parse(user.UserId);
item.UpdateUserName = user.UserName;
tenantDb.Updateable<SpaceBookingOrder>(item).UpdateColumns(x => new
{
x.IsJob,
x.JobTime,
x.TimerPlanId,
x.TimerPlanName,
x.UpdateTime,
x.UpdateBy,
x.UpdateUserName
}).ExecuteCommand();
}
catch (Exception ex)
{
msgBuilder.Append(ex.Message);
}
}
var msg = msgBuilder.ToString();
if (!string.IsNullOrWhiteSpace(msg))
throw new Exception(msg);
return DataResult<string>.Success(msg);
}
#endregion
} }
} }

Loading…
Cancel
Save