using Furion;
using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.JsonSerialization;
using ICSharpCode.SharpZipLib.Zip;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Myshipping.Application.ConfigOption;
using Myshipping.Application.Entity;
using Myshipping.Application.Entity.TaskManagePlat;
using Myshipping.Application.Helper;
using Myshipping.Application.Service;
using Myshipping.Core;
using Myshipping.Core.Service;
using NPOI.OpenXmlFormats.Dml.Diagram;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;
namespace Myshipping.Application
{
///
/// 截单回执
///
[ApiDescriptionSettings("Application", Name = "TaskManageSISubmitted", Order = 10)]
public class TaskManageSISubmittedService : ITaskManageSISubmittedService, IDynamicApiController, ITransient
{
private readonly SqlSugarRepository _taskSISubmittedRepository;
private readonly SqlSugarRepository _taskSISubmittedCtnRepository;
private readonly SqlSugarRepository _taskBaseRepository;
private readonly SqlSugarRepository _bookingOrderRepository;
private readonly SqlSugarRepository _bookingCtnRepository;
private readonly SqlSugarRepository _businessCompareDiffRecordRepository;
private readonly SqlSugarRepository _taskFileRepository;
private readonly SqlSugarRepository _bookingFileRepository;
private readonly ILogger _logger;
private readonly IBookingValueAddedService _bookingValueAddedService;
private readonly IDjyTenantParamService _djyTenantParamService;
private readonly IBookingOrderService _bookingOrderService;
//租户SI回执是否自动更新订舱
const string CONST_SI_SUBMITTED_DEFAULT_PARAM = "SI_SUBMITTED_AUTO_UPDATE_ORDER";
public TaskManageSISubmittedService(ILogger logger,
SqlSugarRepository taskSISubmittedRepository,
SqlSugarRepository taskBaseRepository,
SqlSugarRepository bookingOrderRepository,
SqlSugarRepository businessCompareDiffRecordRepository,
SqlSugarRepository bookingCtnRepository,
SqlSugarRepository taskSISubmittedCtnRepository,
SqlSugarRepository taskFileRepository,
SqlSugarRepository bookingFileRepository,
IBookingValueAddedService bookingValueAddedService, IDjyTenantParamService djyTenantParamService,
IBookingOrderService bookingOrderService)
{
_logger = logger;
_taskSISubmittedRepository = taskSISubmittedRepository;
_taskBaseRepository = taskBaseRepository;
_bookingOrderRepository = bookingOrderRepository;
_bookingValueAddedService = bookingValueAddedService;
_djyTenantParamService = djyTenantParamService;
_businessCompareDiffRecordRepository = businessCompareDiffRecordRepository;
_bookingCtnRepository = bookingCtnRepository;
_taskSISubmittedCtnRepository = taskSISubmittedCtnRepository;
_bookingOrderService = bookingOrderService;
_taskFileRepository = taskFileRepository;
_bookingFileRepository = bookingFileRepository;
}
#region 获取截单回执详情
///
/// 获取截单回执详情
///
/// 截单回执主键
/// 返回回执
[HttpGet("/TaskManageSISubmitted/GetInfo")]
public async Task GetInfo(string pkId)
{
TaskSISubmittedShowDto dto = new TaskSISubmittedShowDto();
var siSubmitted = _taskSISubmittedRepository.AsQueryable().First(a => a.PK_ID == pkId);
if (siSubmitted == null)
throw Oops.Oh($"截单回执主键{pkId}无法获取业务信息");
var taskBase = _taskBaseRepository.AsQueryable().First(a => a.PK_ID == siSubmitted.TASK_ID);
if (taskBase == null)
throw Oops.Oh($"任务主键无法获取业务信息");
dto = siSubmitted.Adapt();
if (dto != null)
{
dto.IsComplete = taskBase.IS_COMPLETE == 1 ? true : false;
dto.CompleteTime = taskBase.COMPLETE_DATE;
}
return dto;
}
#endregion
#region 通过任务主键获取截单回执详情
///
/// 通过任务主键获取截单回执详情
///
/// 截单回执任务主键
/// 返回回执
[HttpGet("/TaskManageSISubmitted/GetInfoByTaskId")]
public async Task GetInfoByTaskId(string taskPkId)
{
TaskSISubmittedShowDto dto = new TaskSISubmittedShowDto();
var taskBase = _taskBaseRepository.AsQueryable().First(a => a.PK_ID == taskPkId);
if (taskBase == null)
throw Oops.Oh($"任务主键{taskPkId}无法获取业务信息");
var siSubmitted = _taskSISubmittedRepository.AsQueryable().First(a => a.TASK_ID == taskBase.PK_ID);
if (siSubmitted == null)
throw Oops.Oh($"截单回执主键{taskPkId}无法获取业务信息");
dto = siSubmitted.Adapt();
if (dto != null)
{
dto.IsComplete = taskBase.IS_COMPLETE == 1 ? true : false;
dto.CompleteTime = taskBase.COMPLETE_DATE;
}
return dto;
}
#endregion
#region 同步更新订舱订单的截单状态
///
/// 同步更新订舱订单的截单状态
///
/// 截单回执任务主键
/// 返回回执
[HttpGet("/TaskManageSISubmitted/SyncBookingSIStatus")]
public async Task SyncBookingSIStatus(string taskPkId)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
var taskBase = _taskBaseRepository.AsQueryable().First(a => a.PK_ID == taskPkId);
if (taskBase == null)
throw Oops.Oh($"任务主键{taskPkId}无法获取业务信息");
var siSubmitted = _taskSISubmittedRepository.AsQueryable().First(a => a.TASK_ID == taskBase.PK_ID);
if (siSubmitted == null)
throw Oops.Oh($"截单回执主键{taskPkId}无法获取业务信息");
if(!siSubmitted.BOOKING_ID.HasValue|| siSubmitted.BOOKING_ID.Value < 1)
throw Oops.Oh($"当前截单回执未匹配到对应的订舱订单,请重对应截单");
var bookingOrder = _bookingOrderRepository.AsQueryable()
.FirstAsync(a => a.Id == siSubmitted.BOOKING_ID.Value);
if (bookingOrder == null)
throw Oops.Oh($"订舱订单信息获取失败");
//推送截单货物状态
var pushModel = new ModifyServiceProjectStatusDto
{
BookingId = bookingOrder.Id,
SourceType = TrackingSourceTypeEnum.AUTO,
StatusCodes = new List {
new ModifyServiceProjectStatusDetailDto { StatusCode = "JD" } }
};
if (siSubmitted.NOTICE_DATE.HasValue)
{
pushModel.StatusCodes[0].SetActDate = siSubmitted.NOTICE_DATE.Value;
}
var saveStatusRlt = await _bookingValueAddedService.SaveServiceStatus(pushModel);
_logger.LogInformation("请求JSON={json} 异步推送服务状态[JD 截单]完成,结果={rlt}", JSON.Serialize(pushModel), JSON.Serialize(saveStatusRlt));
result.succ = true;
result.msg = "成功";
return result;
}
#endregion
#region 重新处理截单任务
///
/// 重新处理截单任务
/// 对未匹配订舱订单的任务记录重新对应订舱订单
///
/// 截单回执任务主键
/// 返回回执
[HttpGet("/TaskManageSISubmitted/SearchAndConnectBookingInfo")]
public async Task SearchAndConnectBookingInfo(string taskPkId)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
var taskBase = _taskBaseRepository.AsQueryable().First(a => a.PK_ID == taskPkId);
if (taskBase == null)
throw Oops.Oh($"任务主键{taskPkId}无法获取业务信息");
var siSubmitted = _taskSISubmittedRepository.AsQueryable().First(a => a.TASK_ID == taskBase.PK_ID);
if (siSubmitted == null)
throw Oops.Oh($"截单回执主键{taskPkId}无法获取业务信息");
if (siSubmitted.BOOKING_ID.HasValue)
throw Oops.Oh($"当前截单回执已有匹配的订舱订单");
string mblNo = siSubmitted.MBL_NO.ToUpper().Trim();
var bookingInfo = _bookingOrderRepository.AsQueryable().Filter(null, true)
.FirstAsync(a => a.MBLNO == mblNo && a.IsDeleted == false && (a.ParentId == null || a.ParentId == 0) && a.TenantId == UserManager.TENANT_ID);
if(bookingInfo == null)
throw Oops.Oh($"提单号{mblNo}未提取有效的订舱订单");
siSubmitted.BOOKING_ID = bookingInfo.Id;
siSubmitted.UpdatedUserId = UserManager.UserId;
siSubmitted.UpdatedUserName = UserManager.Name;
//更新任务BC
await _taskSISubmittedRepository.AsUpdateable(siSubmitted).UpdateColumns(it => new
{
it.BOOKING_ID,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
result.succ = true;
result.msg = "成功";
return result;
}
#endregion
#region 处理SI截单回执
///
/// 处理SI截单回执
///
/// 截单回执任务主键
/// 返回回执
public async Task ProcessSISubmitted(string taskPkId)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
TaskSISubmitted siSubmitted = null;
try
{
/*
1、判断当前租户开启了自动更新订舱数据(SI_SUBMITTED_AUTO_UPDATE_ORDER=ENABLE)
2、先与订舱数据进行比对,记录比对结果。
3、更新订舱详情
4、文件挂到订舱的附件上
*/
var taskBase = _taskBaseRepository.AsQueryable().Filter(null,true).First(a => a.PK_ID == taskPkId && a.TenantId == UserManager.TENANT_ID);
if (taskBase == null)
throw Oops.Oh($"任务主键{taskPkId}无法获取业务信息");
siSubmitted = _taskSISubmittedRepository.AsQueryable().Filter(null, true).First(a => a.TASK_ID == taskBase.PK_ID && a.TenantId == UserManager.TENANT_ID);
if (siSubmitted == null)
throw Oops.Oh($"截单回执主键{taskPkId}无法获取业务信息");
if (siSubmitted.BOOKING_ID.HasValue)
throw Oops.Oh($"当前截单回执已有匹配的订舱订单");
DjyTenantParamValueOutput paramConfig = null;
var paramList = _djyTenantParamService.GetParaCodeWithValue(new[] { CONST_SI_SUBMITTED_DEFAULT_PARAM }).GetAwaiter().GetResult();
if (paramList != null && paramList.Count > 0)
{
paramConfig = paramList.FirstOrDefault(a => a.ParaCode.Equals(CONST_SI_SUBMITTED_DEFAULT_PARAM, StringComparison.OrdinalIgnoreCase));
}
var siCtnList = _taskSISubmittedCtnRepository.AsQueryable().Filter(null, true).Where(a => a.P_PKID == siSubmitted.PK_ID && a.TenantId == UserManager.TENANT_ID).ToList();
var orderInfo = _bookingOrderRepository.AsQueryable().Filter(null, true)
.First(a => a.MBLNO == siSubmitted.MBL_NO && a.IsDeleted == false && a.TenantId == UserManager.TENANT_ID && a.ParentId == 0);
if (paramConfig != null && paramConfig.ParaValue.Equals("ENABLE",StringComparison.OrdinalIgnoreCase))
{
siSubmitted.IS_SET_AUTO_UPD_BOOKING = true;
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 配置了自动更新订舱详情");
if(orderInfo != null)
{
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 获取了订舱详情完成 bookingid={orderInfo.Id}");
siSubmitted.BOOKING_ID = orderInfo.Id;
var ctnList = _bookingCtnRepository.AsQueryable().Filter(null, true)
.Where(a => a.BILLID == orderInfo.Id && a.IsDeleted == false && a.TenantId == UserManager.TENANT_ID).ToList();
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 获取订舱集装箱列表完成 ctnnum={ctnList.Count}");
SIFeedBackCompareDto siSrcDto = orderInfo.Adapt();
if (ctnList.Count > 0)
{
siSrcDto.ContaList = ctnList.Select(t => new SIFeedBackCompareContaDto
{
ContaNo = t.CNTRNO,
SealNo = t.SEALNO,
ContaType = t.CTNCODE,
ContaTypeName = t.CTNALL,
PKGS = t.PKGS.HasValue ? t.PKGS.Value : 0,
CBM = t.CBM,
KGS = t.KGS,
WeighType = t.WEIGHTYPE == "累加" ? "ADD" : "ALL",
WeighKGS = t.WEIGHKGS
}).ToList();
}
SIFeedBackCompareDto siTargetDto = siSubmitted.Adapt();
if (siCtnList.Count > 0)
{
siTargetDto.ContaList = siCtnList.Select(t => new SIFeedBackCompareContaDto
{
ContaNo = t.CNTRNO,
SealNo = t.SEALNO,
ContaType = t.CTNCODE,
ContaTypeName = t.CTNALL,
PKGS = t.PKGS.HasValue ? t.PKGS.Value : 0,
CBM = t.CBM,
KGS = t.KGS,
WeighType = t.WEIGHTYPE,
WeighKGS = t.WEIGHKGS
}).ToList();
}
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 开始比对");
//更新前先比对一遍差异
var compareRlt = await PushCompareSIInfo(siSrcDto, siTargetDto, orderInfo.Id, taskPkId);
if (string.IsNullOrWhiteSpace(compareRlt.Item1))
{
siSubmitted.DIFF_NUM = compareRlt.Item2;
}
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 获取比对完成 结果={JSON.Serialize(compareRlt)}");
SaveBookingOrderInput bkModel = null;
if (orderInfo != null)
{
bkModel = new SaveBookingOrderInput
{
Id = orderInfo.Id,
MBLNO = orderInfo.MBLNO,
ctnInputs = new List(),
ChangedFields = new List()
};
if (!string.IsNullOrEmpty(siSubmitted.ISSUETYPE))
{
if (siSubmitted.ISSUETYPE.Equals("seaway", StringComparison.OrdinalIgnoreCase))
{
//bkModel.ISSUETYPE = "seaway";
bkModel.ISSUETYPE = "Seaway Bill";
}
else if (siSubmitted.ISSUETYPE.Equals("telex", StringComparison.OrdinalIgnoreCase))
{
//bkModel.ISSUETYPE = "telex";
bkModel.ISSUETYPE = "Telex";
}
else if (siSubmitted.ISSUETYPE.Equals("original", StringComparison.OrdinalIgnoreCase))
{
//bkModel.ISSUETYPE = "original";
bkModel.ISSUETYPE = "Original";
}
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.ISSUETYPE));
//bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.ISSUETYPE));
}
if (!string.IsNullOrEmpty(siSubmitted.SHIPPER))
{
bkModel.SHIPPER = siSubmitted.SHIPPER;
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.SHIPPER));
}
if (!string.IsNullOrEmpty(siSubmitted.CONSIGNEE))
{
bkModel.CONSIGNEE = siSubmitted.CONSIGNEE;
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.CONSIGNEE));
}
if (!string.IsNullOrEmpty(siSubmitted.NOTIFYPARTY))
{
bkModel.NOTIFYPARTY = siSubmitted.NOTIFYPARTY;
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.NOTIFYPARTY));
}
if (!string.IsNullOrEmpty(siSubmitted.NOTIFYPARTY2))
{
bkModel.NOTIFYPARTY2 = siSubmitted.NOTIFYPARTY2;
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.NOTIFYPARTY2));
}
if (!string.IsNullOrEmpty(siSubmitted.KINDPKGS))
{
bkModel.KINDPKGS = siSubmitted.KINDPKGS;
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.KINDPKGS));
}
if (!string.IsNullOrEmpty(siSubmitted.DESCRIPTION))
{
bkModel.DESCRIPTION = siSubmitted.DESCRIPTION;
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.DESCRIPTION));
}
if (!string.IsNullOrEmpty(siSubmitted.HSCODE))
{
bkModel.HSCODE = siSubmitted.HSCODE;
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.HSCODE));
}
if (!string.IsNullOrEmpty(siSubmitted.MARKS))
{
bkModel.MARKS = siSubmitted.MARKS;
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.MARKS));
}
}
if (ctnList.Count > 0)
{
List oddCtnList = new List();
foreach (var ctn in ctnList)
{
if (!string.IsNullOrWhiteSpace(ctn.CTNCODE) && string.IsNullOrWhiteSpace(ctn.CNTRNO) && ctn.CTNNUM.HasValue && ctn.CTNNUM.Value > 1)
{
for (int i = 0; i < ctn.CTNNUM.Value - 1; i++)
{
oddCtnList.Add(new BookingCtn
{
BILLID = orderInfo.Id,
IsDeleted = false,
CreatedTime = DateTime.Now,
UpdatedTime = DateTime.Now,
CreatedUserId = ctn.CreatedUserId,
CreatedUserName = ctn.CreatedUserName,
CTNCODE = ctn.CTNCODE,
CTNALL = ctn.CTNALL,
});
}
ctn.CTNNUM = 1;
}
}
if (oddCtnList.Count > 0)
{
ctnList.AddRange(oddCtnList);
}
}
if (siCtnList.Count > 0)
{
bkModel.KGS = siCtnList.Sum(x => x.KGS.HasValue ? x.KGS.Value : 0);
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.KGS));
bkModel.PKGS = siCtnList.Sum(x => x.PKGS.HasValue ? x.PKGS.Value : 0);
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.PKGS));
bkModel.CBM = siCtnList.Sum(x => x.CBM.HasValue ? x.CBM.Value : 0);
bkModel.ChangedFields.Add(nameof(SaveBookingOrderInput.CBM));
siCtnList.ForEach(x =>
{
var ctn = ctnList.FirstOrDefault(a => !string.IsNullOrWhiteSpace(x.CNTRNO) && !string.IsNullOrWhiteSpace(a.CNTRNO)
&& a.CNTRNO.Equals(x.CNTRNO, StringComparison.OrdinalIgnoreCase));
if (ctn != null)
{
ctn.CTNCODE = x.CTNCODE;
ctn.CTNALL = x.CTNALL;
ctn.CTNNUM = 1;
ctn.SEALNO = x.SEALNO;
ctn.PKGS = x.PKGS;
ctn.KGS = x.KGS;
ctn.WEIGHTYPE = x.WEIGHTYPE;
ctn.WEIGHKGS = x.WEIGHKGS;
ctn.CBM = x.CBM;
ctn.REMARK += "SI Add";
ctn.TenantId = UserManager.TENANT_ID;
ctn.CreatedTime = DateTime.Now;
ctn.CreatedUserId = UserManager.UserId;
ctn.CreatedUserName = UserManager.Name;
ctn.KINDPKGS = x.KINDPKGS;
if (string.IsNullOrWhiteSpace(x.KINDPKGS) && !string.IsNullOrWhiteSpace(siSubmitted.KINDPKGS))
ctn.KINDPKGS = siSubmitted.KINDPKGS;
if (x.WEIGHKGS.HasValue && x.KGS.HasValue)
ctn.TAREWEIGHT = x.WEIGHKGS.Value - x.KGS.Value;
}
else
{
ctn = ctnList.FirstOrDefault(a => a.CTNCODE == x.CTNCODE && string.IsNullOrWhiteSpace(a.CNTRNO));
if (ctn != null)
{
ctn.CNTRNO = x.CNTRNO;
ctn.CTNCODE = x.CTNCODE;
ctn.CTNALL = x.CTNALL;
ctn.CTNNUM = 1;
ctn.SEALNO = x.SEALNO;
ctn.PKGS = x.PKGS;
ctn.KGS = x.KGS;
ctn.WEIGHTYPE = x.WEIGHTYPE;
ctn.WEIGHKGS = x.WEIGHKGS;
ctn.CBM = x.CBM;
ctn.REMARK += "SI Add";
ctn.TenantId = UserManager.TENANT_ID;
ctn.CreatedTime = DateTime.Now;
ctn.CreatedUserId = UserManager.UserId;
ctn.CreatedUserName = UserManager.Name;
ctn.KINDPKGS = x.KINDPKGS;
if (string.IsNullOrWhiteSpace(x.KINDPKGS) && !string.IsNullOrWhiteSpace(siSubmitted.KINDPKGS))
ctn.KINDPKGS = siSubmitted.KINDPKGS;
if (x.WEIGHKGS.HasValue && x.KGS.HasValue)
ctn.TAREWEIGHT = x.WEIGHKGS.Value - x.KGS.Value;
}
else
{
ctn = ctnList.FirstOrDefault(a => a.CTNALL == x.CTNALL && string.IsNullOrWhiteSpace(a.CNTRNO));
if (ctn != null)
{
ctn.CNTRNO = x.CNTRNO;
ctn.CTNCODE = x.CTNCODE;
ctn.CTNALL = x.CTNALL;
ctn.CTNNUM = 1;
ctn.SEALNO = x.SEALNO;
ctn.PKGS = x.PKGS;
ctn.KGS = x.KGS;
ctn.WEIGHTYPE = x.WEIGHTYPE;
ctn.WEIGHKGS = x.WEIGHKGS;
ctn.CBM = x.CBM;
ctn.REMARK += "SI Add";
ctn.TenantId = UserManager.TENANT_ID;
ctn.CreatedTime = DateTime.Now;
ctn.CreatedUserId = UserManager.UserId;
ctn.CreatedUserName = UserManager.Name;
ctn.KINDPKGS = x.KINDPKGS;
if (string.IsNullOrWhiteSpace(x.KINDPKGS) && !string.IsNullOrWhiteSpace(siSubmitted.KINDPKGS))
ctn.KINDPKGS = siSubmitted.KINDPKGS;
if (x.WEIGHKGS.HasValue && x.KGS.HasValue)
ctn.TAREWEIGHT = x.WEIGHKGS.Value - x.KGS.Value;
}
else
{
ctnList.Add(new BookingCtn
{
BILLID = orderInfo.Id,
IsDeleted = false,
CreatedTime = DateTime.Now,
UpdatedTime = DateTime.Now,
CreatedUserId = UserManager.UserId,
CreatedUserName = UserManager.Name,
TenantId = UserManager.TENANT_ID,
CNTRNO = x.CNTRNO,
CTNCODE = x.CTNCODE,
CTNALL = x.CTNALL,
CTNNUM = 1,
SEALNO = x.SEALNO,
PKGS = x.PKGS,
KGS = x.KGS,
WEIGHTYPE = x.WEIGHTYPE,
WEIGHKGS = x.WEIGHKGS,
CBM = x.CBM,
REMARK = "SI Add",
TAREWEIGHT = x.WEIGHKGS.HasValue && x.KGS.HasValue ? x.WEIGHKGS.Value - x.KGS.Value :0,
KINDPKGS = (string.IsNullOrWhiteSpace(x.KINDPKGS) && !string.IsNullOrWhiteSpace(siSubmitted.KINDPKGS))? siSubmitted.KINDPKGS: x.KINDPKGS,
});
}
}
}
});
if (ctnList.Any(t => string.IsNullOrWhiteSpace(t.REMARK) || t.REMARK.IndexOf("SI Add") < 0))
{
ctnList = ctnList.Where(t => !string.IsNullOrWhiteSpace(t.REMARK) && t.REMARK.IndexOf("SI Add") >= 0).ToList();
}
}
if(ctnList.Count > 0)
{
bkModel.ctnInputs = ctnList.Select(t => new BookingCtnDto
{
BILLID = t.BILLID,
CNTRNO = t.CNTRNO,
CTNALL = t.CTNALL,
CTNCODE = t.CTNCODE,
CTNNUM = t.CTNNUM.HasValue ? t.CTNNUM.Value : 0,
CBM = t.CBM.HasValue ? t.CBM.Value : 0,
KINDPKGS = t.KINDPKGS,
PKGS = t.PKGS.HasValue ? t.PKGS.Value : 0,
SEALNO = t.SEALNO,
KGS = t.KGS.HasValue ? t.KGS.Value : 0,
TAREWEIGHT = t.TAREWEIGHT.HasValue ? t.TAREWEIGHT.Value : 0,
WEIGHKGS = t.WEIGHKGS.HasValue ? t.WEIGHKGS.Value : 0,
WEIGHTYPE = t.WEIGHTYPE,
Id = t.Id,
}).ToList();
}
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 准备更新订舱数据完更");
//更新订舱数据
var bkRlt = await _bookingOrderService.Save(bkModel);
if (bkRlt.Id > 0)
{
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 更新订舱数据成功");
//推送截单货物状态
var pushModel = new ModifyServiceProjectStatusDto
{
BookingId = bkRlt.Id,
SourceType = TrackingSourceTypeEnum.AUTO,
StatusCodes = new List {
new ModifyServiceProjectStatusDetailDto { StatusCode = "JD" } }
};
if (siSubmitted.NOTICE_DATE.HasValue)
{
pushModel.StatusCodes[0].SetActDate = siSubmitted.NOTICE_DATE.Value;
}
var saveStatusRlt = await _bookingValueAddedService.SaveServiceStatus(pushModel);
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 推送截单状态完成 结果={JSON.Serialize(saveStatusRlt)}");
siSubmitted.PROCESS_STATUS = "SUCC";
siSubmitted.PROCESS_DATE = DateTime.Now;
siSubmitted.IS_UPDATE_BOOKING = true;
siSubmitted.UPDATE_BOOKING_DATE = DateTime.Now;
//直接完成SI的回执任务
if (taskBase.IS_PUBLIC == 1)
{
//更新任务的状态
taskBase.IS_PUBLIC = 0;
taskBase.IS_COMPLETE = 1;
taskBase.COMPLETE_DEAL = "AUTO";
taskBase.COMPLETE_DEAL_NAME = "自动";
taskBase.COMPLETE_DATE = DateTime.Now;
if (!string.IsNullOrWhiteSpace(orderInfo.OP))
{
taskBase.RealUserId = long.Parse(orderInfo.OPID);
taskBase.RealUserName = orderInfo.OP;
taskBase.UpdatedTime = DateTime.Now;
taskBase.UpdatedUserId = long.Parse(orderInfo.OPID);
taskBase.UpdatedUserName = orderInfo.OP;
}
else
{
taskBase.RealUserId = orderInfo.CreatedUserId.Value;
taskBase.RealUserName = orderInfo.CreatedUserName;
taskBase.UpdatedTime = DateTime.Now;
taskBase.UpdatedUserId = orderInfo.CreatedUserId.Value;
taskBase.UpdatedUserName = orderInfo.CreatedUserName;
}
//更新任务台,将当前任务变更为个人任务
await _taskBaseRepository.AsUpdateable(taskBase).UpdateColumns(it => new {
it.IS_PUBLIC,
it.RealUserId,
it.RealUserName,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
}
else
{
taskBase.IS_COMPLETE = 1;
taskBase.COMPLETE_DEAL = "AUTO";
taskBase.COMPLETE_DEAL_NAME = "自动";
taskBase.COMPLETE_DATE = DateTime.Now;
if (!string.IsNullOrWhiteSpace(orderInfo.OP))
{
taskBase.RealUserId = long.Parse(orderInfo.OPID);
taskBase.RealUserName = orderInfo.OP;
taskBase.UpdatedTime = DateTime.Now;
taskBase.UpdatedUserId = long.Parse(orderInfo.OPID);
taskBase.UpdatedUserName = orderInfo.OP;
}
else
{
taskBase.RealUserId = orderInfo.CreatedUserId.Value;
taskBase.RealUserName = orderInfo.CreatedUserName;
taskBase.UpdatedTime = DateTime.Now;
taskBase.UpdatedUserId = orderInfo.CreatedUserId.Value;
taskBase.UpdatedUserName = orderInfo.CreatedUserName;
}
//更新任务台,将当前任务变更为个人任务
await _taskBaseRepository.AsUpdateable(taskBase).UpdateColumns(it => new {
it.IS_PUBLIC,
it.RealUserId,
it.RealUserName,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
}
//处理附件
var opt = App.GetOptions();
var dirAbs = opt.basePath;
if (string.IsNullOrEmpty(dirAbs))
{
dirAbs = App.WebHostEnvironment.WebRootPath;
}
string batchNo = IDGen.NextID().ToString();
var fileList = _taskFileRepository.AsQueryable().Filter(null,true).Where(a => a.TASK_PKID == taskPkId && a.TenantId == taskBase.TenantId.Value).ToList();
fileList.ForEach(file =>
{
if (file.FILE_CATEGORY == TaskFileCategoryEnum.SI_SUBMITTED.ToString())
{
var fileFullPath = Path.Combine(dirAbs, file.FILE_PATH);
if (File.Exists(fileFullPath))
{
//如果确认文件读取成功
var bookFilePath = FileAttachHelper.MoveFile(bkRlt.Id.ToString(), fileFullPath, batchNo
, false, null, true).GetAwaiter().GetResult();
//将格式单附件写入订舱的附件
SaveEDIFile(bkRlt.Id, bookFilePath, new System.IO.FileInfo(bookFilePath).Name, taskBase.TenantId.Value).GetAwaiter();
}
}
});
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 上传订舱数据附件完成");
result.succ = true;
result.msg = "处理成功";
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 更新完成");
}
else
{
siSubmitted.PROCESS_STATUS = "FAILURE";
siSubmitted.PROCESS_DATE = DateTime.Now;
siSubmitted.PROCESS_RESULT = "更新订舱信息失败";
siSubmitted.UPDATE_BOOKING_DATE = DateTime.Now;
result.succ = false;
result.msg = "处理失败";
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 处理失败");
}
}
else
{
result.succ = false;
result.msg = $"提单号{siSubmitted.MBL_NO} 检索订舱数据失败";
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 检索订舱数据失败");
}
}
else
{
result.succ = false;
result.msg = "当前租户没开通自动(SI回执是否自动更新订舱)";
siSubmitted.IS_SET_AUTO_UPD_BOOKING = false;
//将文件同步到订舱的附件
if (orderInfo != null)
{
//推送截单货物状态
var pushModel = new ModifyServiceProjectStatusDto
{
BookingId = orderInfo.Id,
SourceType = TrackingSourceTypeEnum.AUTO,
StatusCodes = new List {
new ModifyServiceProjectStatusDetailDto { StatusCode = "JD" } }
};
if (siSubmitted.NOTICE_DATE.HasValue)
{
pushModel.StatusCodes[0].SetActDate = siSubmitted.NOTICE_DATE.Value;
}
var saveStatusRlt = await _bookingValueAddedService.SaveServiceStatus(pushModel);
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 推送截单状态完成 结果={JSON.Serialize(saveStatusRlt)}");
siSubmitted.PROCESS_STATUS = "SUCC";
siSubmitted.PROCESS_DATE = DateTime.Now;
siSubmitted.IS_UPDATE_BOOKING = true;
siSubmitted.UPDATE_BOOKING_DATE = DateTime.Now;
//直接完成SI的回执任务
if (taskBase.IS_PUBLIC == 1)
{
//更新任务的状态
taskBase.IS_PUBLIC = 0;
taskBase.IS_COMPLETE = 1;
taskBase.COMPLETE_DEAL = "AUTO";
taskBase.COMPLETE_DEAL_NAME = "自动";
taskBase.COMPLETE_DATE = DateTime.Now;
if (!string.IsNullOrWhiteSpace(orderInfo.OP))
{
taskBase.RealUserId = long.Parse(orderInfo.OPID);
taskBase.RealUserName = orderInfo.OP;
taskBase.UpdatedTime = DateTime.Now;
taskBase.UpdatedUserId = long.Parse(orderInfo.OPID);
taskBase.UpdatedUserName = orderInfo.OP;
}
else
{
taskBase.RealUserId = orderInfo.CreatedUserId.Value;
taskBase.RealUserName = orderInfo.CreatedUserName;
taskBase.UpdatedTime = DateTime.Now;
taskBase.UpdatedUserId = orderInfo.CreatedUserId.Value;
taskBase.UpdatedUserName = orderInfo.CreatedUserName;
}
//更新任务台,将当前任务变更为个人任务
await _taskBaseRepository.AsUpdateable(taskBase).UpdateColumns(it => new {
it.IS_PUBLIC,
it.RealUserId,
it.RealUserName,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
}
else
{
taskBase.IS_COMPLETE = 1;
taskBase.COMPLETE_DEAL = "AUTO";
taskBase.COMPLETE_DEAL_NAME = "自动";
taskBase.COMPLETE_DATE = DateTime.Now;
if (!string.IsNullOrWhiteSpace(orderInfo.OP))
{
taskBase.RealUserId = long.Parse(orderInfo.OPID);
taskBase.RealUserName = orderInfo.OP;
taskBase.UpdatedTime = DateTime.Now;
taskBase.UpdatedUserId = long.Parse(orderInfo.OPID);
taskBase.UpdatedUserName = orderInfo.OP;
}
else
{
taskBase.RealUserId = orderInfo.CreatedUserId.Value;
taskBase.RealUserName = orderInfo.CreatedUserName;
taskBase.UpdatedTime = DateTime.Now;
taskBase.UpdatedUserId = orderInfo.CreatedUserId.Value;
taskBase.UpdatedUserName = orderInfo.CreatedUserName;
}
//更新任务台,将当前任务变更为个人任务
await _taskBaseRepository.AsUpdateable(taskBase).UpdateColumns(it => new {
it.IS_PUBLIC,
it.RealUserId,
it.RealUserName,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
}
//处理附件
var opt = App.GetOptions();
var dirAbs = opt.basePath;
if (string.IsNullOrEmpty(dirAbs))
{
dirAbs = App.WebHostEnvironment.WebRootPath;
}
string batchNo = IDGen.NextID().ToString();
var fileList = _taskFileRepository.AsQueryable().Filter(null, true).Where(a => a.TASK_PKID == taskPkId && a.TenantId == taskBase.TenantId.Value).ToList();
fileList.ForEach(file =>
{
if (file.FILE_CATEGORY == TaskFileCategoryEnum.SI_SUBMITTED.ToString())
{
var fileFullPath = Path.Combine(dirAbs, file.FILE_PATH);
if (File.Exists(fileFullPath))
{
//如果确认文件读取成功
var bookFilePath = FileAttachHelper.MoveFile(orderInfo.Id.ToString(), fileFullPath, batchNo
, false, null, true).GetAwaiter().GetResult();
//将格式单附件写入订舱的附件
SaveEDIFile(orderInfo.Id, bookFilePath, new System.IO.FileInfo(bookFilePath).Name, taskBase.TenantId.Value).GetAwaiter();
}
}
});
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 上传订舱数据附件完成");
result.succ = true;
result.msg = "处理成功";
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 更新完成");
}
else
{
result.succ = false;
result.msg = $"提单号{siSubmitted.MBL_NO} 检索订舱数据失败";
_logger.LogInformation($"taskPkId={taskPkId} 提单号{siSubmitted.MBL_NO} 检索订舱数据失败");
}
}
}
catch (Exception ex)
{
result.succ= false;
result.msg = ex.Message;
}
if (!result.succ)
{
if (siSubmitted != null)
{
siSubmitted.PROCESS_STATUS = "FAILURE";
siSubmitted.PROCESS_DATE = DateTime.Now;
if (result.msg.Length > 500)
{
siSubmitted.PROCESS_RESULT = result.msg.Substring(0, 500);
}
else
{
siSubmitted.PROCESS_RESULT = result.msg;
}
await _taskSISubmittedRepository.AsUpdateable(siSubmitted).UpdateColumns(x => new
{
x.PROCESS_DATE,
x.PROCESS_STATUS,
x.PROCESS_RESULT,
x.DIFF_NUM,
x.IS_SET_AUTO_UPD_BOOKING,
}).ExecuteCommandAsync();
new EmailNoticeHelper().SendEmailNotice($"MBLNO={siSubmitted.MBL_NO} SI回执回写失败", $"MBLNO={siSubmitted.MBL_NO} SI回执回写失败,原因:{result.msg}", App.Configuration["EmailNoticeDefaultUser"].GetUserEmailList());
}
}
else
{
await _taskSISubmittedRepository.AsUpdateable(siSubmitted).UpdateColumns(x => new
{
x.PROCESS_DATE,
x.PROCESS_STATUS,
x.PROCESS_RESULT,
x.IS_UPDATE_BOOKING,
x.UPDATE_BOOKING_DATE,
x.DIFF_NUM,
x.BOOKING_ID,
x.IS_SET_AUTO_UPD_BOOKING
}).ExecuteCommandAsync();
}
return result;
}
#endregion
#region 异步写入附件表
///
/// 异步写入附件表
///
/// 订舱ID
/// 文件路径
/// 文件名
/// 租户ID
/// 附件类型代码
/// 附件类型名称
/// 附件模块代码
///
[NonAction]
private async Task SaveEDIFile(long boookId, string FilePath, string fileName, long tenantId,
string fileTypeCode = "sifeed", string fileTypeName = "SI submitted", string moudle = "TaskSISubmitted")
{
/*
直接将附件信息写入附件表
*/
//EDI文件
var bookFile = new BookingFile
{
Id = YitIdHelper.NextId(),
FileName = fileName,
FilePath = FilePath,
TypeCode = fileTypeCode,
TypeName = fileTypeName,
BookingId = boookId,
TenantId = tenantId,
Moudle = moudle
};
await _bookingFileRepository.InsertAsync(bookFile);
}
#endregion
///
/// 获取SI反馈信息
///
/// 任务主键
/// 返回结果
[HttpGet("/TaskManageSISubmitted/GetSIFeedBackInfo")]
public async Task GetSIFeedBackInfo(string taskPKId)
{
TaskSISubmittedShowDto dto = new TaskSISubmittedShowDto();
var taskBase = _taskBaseRepository.AsQueryable().First(a => a.PK_ID == taskPKId);
if (taskBase == null)
throw Oops.Oh($"任务主键{taskPKId}无法获取业务信息");
var siSubmitted = _taskSISubmittedRepository.AsQueryable().First(a => a.TASK_ID == taskBase.PK_ID);
if (siSubmitted == null)
throw Oops.Oh($"截单回执主键{taskPKId}无法获取业务信息");
var bookOrderList = _bookingOrderRepository.AsQueryable().Filter(null, true)
.InnerJoin((bk, ctn) => bk.Id == ctn.BILLID)
.Where((bk, ctn) => bk.Id == siSubmitted.BOOKING_ID.Value && bk.TenantId == UserManager.TENANT_ID)
.Select((bk, ctn) => new { bk = bk, ctn = ctn }).ToList();
var orderInfo = bookOrderList.FirstOrDefault().bk;
//var siFeedBackList = _taskSISubmittedRepository.EntityContext.Queryable()
// .InnerJoin((si, ctn) => si.PK_ID == ctn.P_PKID)
// .Where((si, ctn) => si.TASK_PKID == model.TaskId && si.TenantId == UserManager.TENANT_ID)
// .Select((si, ctn) => new { si = si, ctn = ctn }).ToList();
//if (siFeedBackList.Count == 0)
// throw Oops.Oh($"SI反馈信息不存在");
//var siFeedBackInfo = siFeedBackList.FirstOrDefault().si;
//var resultInfo = siFeedBackInfo.Adapt();
//resultInfo.ContaList = siFeedBackList.Select(t => t.ctn.Adapt()).ToList();
//model.BusiInfo = resultInfo;
//if (orderInfo != null)
//{
// //订舱
// model.BookingOrder = orderInfo.Adapt();
//}
////进行数据比对确认差异字段KEY
//var mainDiff = await InnerCompareMainInfoDiff(orderInfo, siFeedBackInfo);
//model.SICompareOrderKeyList = mainDiff;
//var contaDiff = await InnerCompareContaInfoDiff(bookOrderList.Select(t => t.ctn).ToList(),
// siFeedBackList.Select(t => t.ctn).ToList());
//model.SICompareOrderContaKeyList = contaDiff;
return dto;
}
#region 推送BC变更比对
///
/// 推送BC变更比对sysUser
///
/// 订舱详情
/// SI截单详情
/// 订舱主键
/// 任务ID
///
[NonAction]
public async Task> PushCompareSIInfo(SIFeedBackCompareDto siSrcDto, SIFeedBackCompareDto siTargetDto, long bookingId, string taskPKId)
{
string result = string.Empty;
int diffNum = 0;
string batchNo = IDGen.NextID().ToString();
DateTime bDate = DateTime.Now;
var compareResult = await ExcuteCompare(siSrcDto, siTargetDto);
DateTime eDate = DateTime.Now;
TimeSpan ts = eDate.Subtract(bDate);
var timeDiff = ts.TotalMilliseconds;
if (compareResult != null)
{
_logger.LogInformation("批次={no} 请求完成,耗时:{timeDiff}ms. 结果{msg}", batchNo, timeDiff, compareResult.succ ? "成功" : "失败");
if(!compareResult.succ)
{
result = $"比对失败,原因:{compareResult.msg}";
}
}
if (compareResult != null)
{
DateTime nowDate = DateTime.Now;
var hisInfo = _businessCompareDiffRecordRepository.AsQueryable().Filter(null, true).First(a =>
a.BUSI_ID == bookingId.ToString() && a.TASK_ID == taskPKId);
if (hisInfo == null)
{
BusinessCompareDiffRecord entity = new BusinessCompareDiffRecord
{
BUSI_ID = bookingId.ToString(),
TASK_ID = taskPKId,
BUSI_TYPE = "SI_SUBMITTED",
COMPARE_DIFF_NUM = compareResult.extra.IsExistsDiff ? compareResult.extra.ShowDetailList.Count : 0,
CreatedTime = nowDate,
UpdatedTime = nowDate,
CreatedUserId = UserManager.UserId,
CreatedUserName = UserManager.Name,
UpdatedUserId = UserManager.UserId,
UpdatedUserName = UserManager.Name,
COMPARE_TYPE = "SI_MODIFY",
COMPARE_RLT = JSON.Serialize(compareResult.extra.ShowDetailList),
};
await _businessCompareDiffRecordRepository.InsertAsync(entity);
}
else
{
hisInfo.COMPARE_DIFF_NUM = compareResult.extra.IsExistsDiff ? compareResult.extra.ShowDetailList.Count : 0;
hisInfo.UpdatedTime = nowDate;
hisInfo.UpdatedUserId = UserManager.UserId;
hisInfo.UpdatedUserName = UserManager.Name;
hisInfo.COMPARE_RLT = JSON.Serialize(compareResult.extra.ShowDetailList);
await _businessCompareDiffRecordRepository.AsUpdateable(hisInfo).UpdateColumns(it =>
new
{
it.COMPARE_DIFF_NUM,
it.COMPARE_RLT,
it.UpdatedTime,
it.UpdatedUserId,
it.UpdatedUserName
}).ExecuteCommandAsync();
}
if (compareResult.extra.ShowDetailList == null || compareResult.extra.ShowDetailList.Count == 0)
{
result = $"比对失败,没有比对出差异";
new EmailNoticeHelper().SendEmailNotice($"MBLNO={siSrcDto.MblNo} SI 回执比对差异失败,比对结果为0", $"MBLNO={siSrcDto.MblNo} SI 回执比对差异失败,比对结果为0", App.Configuration["EmailNoticeDefaultUser"].GetUserEmailList());
}
else
{
diffNum = compareResult.extra.ShowDetailList.Count;
}
}
else
{
result = $"比对失败,未获取到比对结果";
new EmailNoticeHelper().SendEmailNotice($"MBLNO={siSrcDto.MblNo} SI 回执比对差异失败,未获取到比对结果", $"MBLNO={siSrcDto.MblNo} SI 回执比对差异失败,未获取到比对结果", App.Configuration["EmailNoticeDefaultUser"].GetUserEmailList());
}
return new Tuple(result,diffNum);
}
#endregion
#region 请求BC比对
///
/// 请求SI比对
///
/// 订舱详情
/// SI截单详情
/// 返回回执
[NonAction]
public async Task ExcuteCompare(SIFeedBackCompareDto siSrcDto, SIFeedBackCompareDto siTargetDto)
{
TaskManageExcuteResultDto model = null;
/*
1、读取配置文件中的规则引擎URL
2、填充请求的类,并生成JSON报文
3、POST请求接口,并记录回执。
4、返回信息。
*/
var url = App.Configuration["SICompareUrl"];
using (var httpClient = new HttpClient())
{
try
{
using (var reduceAttach = new MultipartFormDataContent())
{
var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(JSON.Serialize(siSrcDto)));
dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue($"form-data")
{
Name = "srcJson"
};
reduceAttach.Add(dataContent);
var dataContent2 = new ByteArrayContent(Encoding.UTF8.GetBytes(JSON.Serialize(siTargetDto)));
dataContent2.Headers.ContentDisposition = new ContentDispositionHeaderValue($"form-data")
{
Name = "destJson"
};
reduceAttach.Add(dataContent2);
//请求
var response = httpClient.PostAsync(url, reduceAttach).Result;
var result = response.Content.ReadAsStringAsync().Result;
model = JSON.Deserialize(result);
}
}
catch (Exception ex)
{
_logger.LogInformation("推送SI比对异常,原因:{error}", ex.Message);
throw Oops.Oh($"推送SI比对异常,原因:{ex.Message}");
}
}
return model;
}
#endregion
}
}