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.

1690 lines
72 KiB
C#

This file contains ambiguous Unicode characters!

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

using AngleSharp.Dom;
using Castle.Core.Resource;
using DS.Module.Core;
using DS.Module.Core.Constants;
using DS.Module.Core.Data;
using DS.Module.Core.Extensions;
using DS.Module.DjyRulesEngine;
using DS.Module.DjyServiceStatus;
using DS.Module.MQ;
using DS.Module.RedisModule;
using DS.Module.SqlSugar;
using DS.Module.UserModule;
using DS.WMS.Core.Code.Entity;
using DS.WMS.Core.Fee.Dtos;
using DS.WMS.Core.Fee.Entity;
using DS.WMS.Core.HangfireJob.Interface;
using DS.WMS.Core.Info.Entity;
using DS.WMS.Core.Op.Dtos;
using DS.WMS.Core.Op.Entity;
using DS.WMS.Core.Op.Interface;
using DS.WMS.Core.Sys.Entity;
using DS.WMS.Core.Sys.Interface;
using DS.WMS.Core.TaskInteraction.Dtos;
using DS.WMS.Core.TaskInteraction.Entity;
using DS.WMS.Core.TaskInteraction.Interface;
using DS.WMS.Core.TaskInteraction.Method;
using DS.WMS.Core.TaskPlat.Entity;
using DS.WMS.Core.TaskPlat.Interface;
using LanguageExt;
using Mapster;
using Masuit.Tools.Systems;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using NLog;
using SqlSugar;
using System.Data;
using Logger = NLog.Logger;
namespace DS.WMS.Core.Op.Method;
public partial class SeaExportService : ISeaExportService
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
private readonly ISaasDbService saasService;
private readonly ICommonService commonService;
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly ISeaExportCommonService seaComService;
private readonly IWebHostEnvironment _environment;
private readonly IDjyServiceStatusService _djyServiceStatusService;
private readonly IRuleEngineService _ruleEngineService;
private readonly IOpJobService opJobService;
private readonly IConfigService _configService;
private readonly ISysCacheService _sysCacheService;
private readonly IRabbitMQService _rabbitMQService;
private readonly IRedisService _redisBaseService;
private readonly IDJYChargeFeeService _dJYChargeFeeService;
private readonly ISeaExportTaskService _seaTaskService;
//private readonly IBookingSlotService _bookingSlotService;
private readonly Lazy<ITaskManageBaseService> _taskManageBaseService;
const string CONST_MAPPING_MODULE = "BOOK_OR_CLOSING";
const string CONST_MAPPING_MODULE_ROUTE = "BOOK_OR_CLOSING_RT";
const string CONST_MAPPING_MODULE_VOLTA = "BOOK_CLOSING_VOLTA";
const string CONST_MAPPING_MODULE_INTTRA = "INTTRA_EDI";
private const string PrintRecentListTypeKey = "booking_print_recent_list";
const string CONST_TSL_EDI_URL = "tsl_edi_declare_url";
const string CONST_TSL_TYPE_CODE = "TslWeb";
const string CONST_ONE_SOFILE_CATE_CODE = "one_so_file_template";
const string PRINT_DATASOURCE_KEY = "booking_order";
/// <summary>
///
/// </summary>
/// <param name="serviceProvider"></param>
public SeaExportService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
saasService = _serviceProvider.GetRequiredService<ISaasDbService>();
commonService = _serviceProvider.GetRequiredService<ICommonService>();
seaComService = _serviceProvider.GetRequiredService<ISeaExportCommonService>();
_environment = _serviceProvider.GetRequiredService<IWebHostEnvironment>();
//_printService = _serviceProvider.GetRequiredService<IPrintService>();
_djyServiceStatusService = _serviceProvider.GetRequiredService<IDjyServiceStatusService>();
_ruleEngineService = _serviceProvider.GetRequiredService<IRuleEngineService>();
opJobService = _serviceProvider.GetRequiredService<IOpJobService>();
_configService = _serviceProvider.GetRequiredService<IConfigService>();
_rabbitMQService = _serviceProvider.GetRequiredService<IRabbitMQService>();
_redisBaseService = _serviceProvider.GetRequiredService<IRedisService>();
_dJYChargeFeeService = _serviceProvider.GetRequiredService<IDJYChargeFeeService>();
//_bookingSlotService = _serviceProvider.GetRequiredService<IBookingSlotService>();
_seaTaskService = _serviceProvider.GetRequiredService<ISeaExportTaskService>();
_taskManageBaseService = _serviceProvider.GetRequiredService<Lazy<ITaskManageBaseService>>();
}
/// <summary>
/// 列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<DataResult<SeaExportListRes>> GetListByPage(PageRequest request)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//启用海运出口列表可视数据权限
(ISugarQueryable<SeaExport> query, _) = await commonService.GetVisibleDataRuleFilter<SeaExport>(tenantDb);
var orgList = db.Queryable<SysOrg>().Where(x => x.Status == StatusEnum.Enable);
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
//var result = tenantDb.Queryable<SeaExport>()
var statusList = tenantDb.Queryable<BookingStatus>().Select<BookingStatusRes>().ToList();
var ctnPrices = tenantDb.Queryable<BusinessCtnPrice>().ToList();
var result = query.Where(a => (a.IsRefund == false && a.IsChangeETD == false))
.InnerJoin<BusinessFeeStatus>((a, b) => a.Id == b.BusinessId)
//.LeftJoin<SysOrg>((a, b, c) => a.SaleOrgId == c.Id, "shippingweb8_dev.sys_org")
//.LeftJoin<SysOrg>((a, b, c) => a.SaleDeptId == c.Id, "shippingweb8_dev.sys_org")
.Select((a, b) => new SeaExportRes()
{
//SaleDeptName = c.OrgName,
QuotePrice = SqlFunc.Subqueryable<BusinessCtnPrice>()
.Where(s => s.BusinessId == a.Id)
.Select(s => s.QuotePrice),
FloorPrice = SqlFunc.Subqueryable<BusinessCtnPrice>()
.Where(s => s.BusinessId == a.Id)
.Select(s => s.FloorPrice)
},
true)//true表示 其余字段自动映射,根据字段名字
//.Select<SeaExportRes>()
.MergeTable()
.Mapper(it =>
{
it.BookingStatus = statusList.Where(x => x.BusinessId == it.Id).ToList();
//var ctnPrice = ctnPrices.First(x => x.BusinessId == it.Id);
//it.QuotePrice = ctnPrice?.QuotePrice;
//it.FloorPrice = ctnPrice?.FloorPrice;
//it.BookingStatus = tenantDb.Queryable<BookingStatus>().Where(x => x.BusinessId == it.Id).Select<BookingStatusRes>().ToList();
//it.StatusLog =
})
.Where(whereList);
//.ToQueryPageAsync(request.PageCondition);
var list = result.ToList();
var data = await result.ToQueryPageAsync(request.PageCondition);
var totalData = new SeaExportDataTotalRes()
{
MainCount = list.Where(x => x.ParentId == 0).Count(),
PartCount = list.Where(x => x.ParentId != 0).Count(),
ReturnCount = 0,
TEU = list.Sum(x => x.TEU),
PKGS = list.Sum(x => x.PKGS),
CBM = list.Sum(x => x.CBM),
KGS = list.Sum(x => x.KGS),
Cntr1 = list.Sum(x => x.Cntr1),
Cntr2 = list.Sum(x => x.Cntr2),
Cntr3 = list.Sum(x => x.Cntr3),
Cntr4 = list.Sum(x => x.Cntr4),
Cntr5 = list.Sum(x => x.Cntr5),
Cntr6 = list.Sum(x => x.Cntr6),
Cntr7 = list.Sum(x => x.Cntr7),
Cntr8 = list.Sum(x => x.Cntr8),
Cntr9 = list.Sum(x => x.Cntr9),
Cntr10 = list.Sum(x => x.Cntr10),
OtherCntr = list.Sum(x => x.OtherCntr),
};
var statusLog = await tenantDb.Queryable<BookingStatusLog>().ToListAsync();
var statusLogDetails = await tenantDb.Queryable<BookingStatusLogDetail>().ToListAsync();
foreach (var item in data.Data)
{
var statusLogIds = statusLog.Where(x => x.BusinessId == item.Id).Select(x => x.Id).ToList();
var dto = statusLogDetails.Where(x => statusLogIds.Contains(x.PId)).ToList();
var ctnLogs = new List<CntrNoRes>();
foreach (var detail in dto)
{
var ctn = ctnLogs.Where(x => x.CNTRNO == detail.CNTRNO).FirstOrDefault();
if (ctn == null)
{
if (detail.Status == "提箱")
{
ctnLogs.Add(new CntrNoRes
{
BookingId = item.Id,
CNTRNO = detail.CNTRNO,
TXOpTime = detail.OpTime,
FCOpTime = null
});
}
if (detail.Status == "返场")
{
ctnLogs.Add(new CntrNoRes
{
BookingId = item.Id,
CNTRNO = detail.CNTRNO,
FCOpTime = detail.OpTime,
TXOpTime = null
});
}
}
else
{
if (detail.Status == "提箱")
{
ctn.TXOpTime = detail.OpTime;
}
if (detail.Status == "返场")
{
ctn.FCOpTime = detail.OpTime;
}
}
}
item.StatusLog = ctnLogs;
}
var res = new SeaExportListRes()
{
List = data.Data,
TotalCount = list.Count(),
DataTotal = totalData
};
return await Task.FromResult(DataResult<SeaExportListRes>.Success(res, MultiLanguageConst.DataQuerySuccess));
}
/// <summary>
/// 海运出口分单列表
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<DataResult<List<SeaExportRes>>> GetSeaExportPartList(PageRequest request)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var result = await tenantDb.Queryable<SeaExport>().Where(a => a.ParentId == 0)
.InnerJoin<BusinessFeeStatus>((a, b) => a.Id == b.BusinessId)
.Select<SeaExportRes>()
.MergeTable()
.Where(whereList).ToQueryPageAsync(request.PageCondition);
return result;
}
/// <summary>
/// 获取海运出口日志
/// </summary>
/// <param name="id">业务Id</param>
/// <returns></returns>
public async Task<DataResult<List<OpBusinessLogRes>>> GetSeaExportLogList(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = await tenantDb.Queryable<OpBusinessLog>()
.Where(a => a.BusinessId == long.Parse(id))
.Select<OpBusinessLogRes>()
.ToListAsync();
return await Task.FromResult(DataResult<List<OpBusinessLogRes>>.Success(data, MultiLanguageConst.DataQuerySuccess));
}
/// <summary>
/// 编辑
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult> EditSeaExport(SeaExportReq req)
{
_logger.Info($"保存订单接收参数 req={JsonConvert.SerializeObject(req)}");
//var dbScope = (SqlSugarScope)db;
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
tenantDb.QueryFilter.Clear<IOrgId>();
if (req.Id == 0)
{
return await CreateSeaExportOrder(req, tenantDb);
}
else
{
if (req.BLType != "拼箱分票" && !string.IsNullOrEmpty(req.MBLNO) && tenantDb.Queryable<SeaExport>().Where(x => x.Id != req.Id && x.MBLNO == req.MBLNO.Trim() && !(x.IsChangeETD == true || x.IsRefund == true)).Any())
{
return await Task.FromResult(DataResult.Failed("海运出口信息主提单号已存在!", MultiLanguageConst.SeaExportMBLNOExist));
}
if (!string.IsNullOrEmpty(req.CustomerNo) && tenantDb.Queryable<SeaExport>().Where(x => x.Id != req.Id && x.CustomerNo == req.CustomerNo.Trim()).Any())
{
return await Task.FromResult(DataResult.Failed("海运出口信息委托编号已存在!", MultiLanguageConst.SeaExportCustomerNoExist));
}
if (!string.IsNullOrEmpty(req.HBLNO) && tenantDb.Queryable<SeaExport>().Where(x => x.Id != req.Id && x.HBLNO == req.HBLNO.Trim()).Any())
{
return await Task.FromResult(DataResult.Failed("海运出口信息分提单号已存在!", MultiLanguageConst.SeaExportHBLNOExist));
}
//添加操作权限
//var operationRule = commonService.GetOperationRuleConditional<SeaExport>();
//var info = await tenantDb.Queryable<SeaExport>().Where(x => x.Id == req.Id).WhereFilterOperationRule(operationRule).FirstAsync();
var info = await tenantDb.Queryable<SeaExport>().Where(x => x.Id == req.Id).FirstAsync();
var oldOrder = info.Adapt<SeaExport>();
var feeStatus = await tenantDb.Queryable<BusinessFeeStatus>().Where(x => x.BusinessId == req.Id).FirstAsync();
if (feeStatus.IsNotNull() && (bool)feeStatus.IsBusinessLocking)
{
return await Task.FromResult(DataResult.Failed("海运出口信息业务已锁定!", MultiLanguageConst.SeaExportBusinessLock));
}
info = req.Adapt(info);
//TODO 会计期间不允许小于已结转期间
if (info.CloseDocDate.IsNotNull() && info.CloseDocDate > info.ETD)
{
return await Task.FromResult(DataResult.Failed("截单日期不允许大于开船日期!", MultiLanguageConst.SeaExportCloseDocDateLimit));
}
if (info.ClosingDate.IsNotNull() && info.ClosingDate > info.ETD)
{
return await Task.FromResult(DataResult.Failed("截港日期不允许大于开船日期!", MultiLanguageConst.SeaExportCloseDateLimit));
}
#region 处理箱型箱量
if (req.CtnInfo.Count > 0)
{
//处理箱型箱量
info = seaComService.UpdateSeaExportCtnInfo(info, req.CtnInfo);
}
#endregion
#region 更新结算方式及结算日期
//更新结算方式及结算日期
var stlInfo = seaComService.GetCustomerStlInfo(new CustomerStlReq() { CustomerId = req.CustomerId, ETD = req.ETD, SaleId = req.SaleId });
if (!stlInfo.Succeeded)
{
return await Task.FromResult(DataResult.Failed(stlInfo.Message));
}
info.StlName = stlInfo.Data.StlName;
info.StlDate = stlInfo.Data.StlDate;
info.AccountDate = stlInfo.Data.AccountDate;
#endregion
#region 复制单据单号重新赋值
if (string.IsNullOrEmpty(info.CustomerNo))
{
var sequence = await commonService.GetSequenceNextAsync<SeaExport>(tenantDb, user, req.SaleId, req.ETD);
if (!sequence.Succeeded)
{
return await Task.FromResult(DataResult.Failed(sequence.Message, MultiLanguageConst.SequenceSetNotExist));
}
info.CustomerNo = sequence.Data;
}
#endregion
#region 回写商品信息
var goodid = WriteBackGoods(info, tenantDb);
info.GoodsId = goodid;
#endregion
//判断是否订阅运踪目的港起运港标识
if (!string.IsNullOrEmpty(info.MBLNO))
{
info.IsBookingYZ = "1";
}
else
{
info.IsBookingYZ = "0";
}
try
{
//开启事务
await tenantDb.Ado.BeginTranAsync();
info.Note = "正常编辑";
await tenantDb.Updateable(info).IgnoreColumns(it => new
{
it.BusinessStatus,
it.BusinessStatusName,
it.IsVGM,it.IsBooking,it.IsLand,it.IsCustoms,
it.IsChangeETD,it.IsRefund
}).EnableDiffLogEvent().ExecuteCommandAsync();//.IgnoreColumns(ignoreAllNullColumns: true)
_logger.Info("执行完订单比对");
await seaComService.SaveSeaExportLogAsync(new SeaExportSaveLog()
{
OperateType = "Update",
OldOrder = oldOrder,
NewOrder = info,
SourceCode = "NormalEdit",
SourceName = "正常编辑",
}, tenantDb);
_logger.Info("执行完保存日志");
//处理订单联系人信息
DealBusinessOrderContact(info, tenantDb);
_logger.Info("执行完订单联系人");
if (req.CtnInfo.IsNotNull() && req.CtnInfo.Count > 0)
{
var ctnList = await tenantDb.Queryable<OpCtn>().Where(x => x.BSNO == req.Id.ToString()).ToListAsync();
foreach (var item in req.CtnInfo)
{
if (item.Id == 0)
{
var ctn = item.Adapt<OpCtn>();
ctn.BSNO = info.Id.ToString();
await tenantDb.Insertable(ctn).ExecuteCommandAsync();
}
else
{
var ctn = ctnList.First(x => x.Id == item.Id);
ctn = item.Adapt(ctn);
await tenantDb.Updateable(ctn).ExecuteCommandAsync();
}
}
}
_logger.Info("执行完集装箱");
if (req.CtnPriceInfo.IsNotNull() && req.CtnPriceInfo.Count > 0)
{
var priceList = await tenantDb.Queryable<BusinessCtnPrice>().Where(x => x.BusinessId == req.Id).ToListAsync();
foreach (var item in req.CtnPriceInfo)
{
if (item.IsNotNull() && item.Id == 0)
{
var price = item.Adapt<BusinessCtnPrice>();
price.BusinessId = info.Id;
await tenantDb.Insertable(price).ExecuteCommandAsync();
}
else
{
var price = priceList.First(x => x.Id == item.Id);
price = item.Adapt(price);
await tenantDb.Updateable(price).ExecuteCommandAsync();
}
}
}
_logger.Info("执行完集装箱单价");
if (req.EdiInfo.IsNotNull())
{
var edi = await tenantDb.Queryable<SeaExportEdi>().Where(x => x.BusinessId == req.Id).FirstAsync();
if (edi.IsNull())
{
var ediInfo = req.EdiInfo.Adapt<SeaExportEdi>();
ediInfo.BusinessId = req.Id;
await tenantDb.Insertable(ediInfo).ExecuteCommandAsync();
}
else
{
var ediInfo = req.EdiInfo.Adapt(edi);
await tenantDb.Updateable(ediInfo).ExecuteCommandAsync();
}
}
_logger.Info("执行完订单EDI附属信息");
if (req.CtnGoodsInfo.IsNotNull() && req.CtnGoodsInfo.Count > 0)
{
var ctnGoods = await tenantDb.Queryable<OpCtnGoods>().Where(x => x.BusinessId == req.Id).ToListAsync();
var existGoods = ctnGoods.Select(x => x.Id);
var reqCtnGoods = req.CtnGoodsInfo.Where(x=>x.Id!=0).Select(x => x.Id);
//删除
IEnumerable<long> delCtnGoods = existGoods.AsQueryable().Except(reqCtnGoods);
if (delCtnGoods.Count() > 0)
{
await tenantDb.Deleteable<OpCtnGoods>()
.Where(it => it.BusinessId == info.Id && delCtnGoods.Contains(it.Id))
.ExecuteCommandAsync();
}
foreach (var item in req.CtnGoodsInfo)
{
if (item.Id == 0)
{
var ctnGood = item.Adapt<OpCtnGoods>();
ctnGood.BusinessId = info.Id;
await tenantDb.Insertable(ctnGood).ExecuteCommandAsync();
}
else
{
var ctnGood = ctnGoods.First(x => x.Id == item.Id);
ctnGood = item.Adapt(ctnGood);
await tenantDb.Updateable(ctnGood).ExecuteCommandAsync();
}
}
}
_logger.Info("执行完订单多品名信息");
#region 241010更新分单 单分单时,后续主单件重尺更新时,分单自动更新,多票分单时不更新;
var partList = await tenantDb.Queryable<SeaExportBillManage>().Where(x => x.BusinessId == req.Id).ToListAsync();
if (partList.IsNotNull() && partList.Count == 1)
{
var part = partList.First();
part.PKGS = info.PKGS;
part.KindPkgs = info.KindPkgs;
part.KindPkgsName = info.KindPkgsName;
part.KGS = info.KGS;
part.CBM = info.CBM;
part.TotalNo = info.TotalNo;
part.CntrNo = info.CntrNo;
part.CntrTotal = info.CntrTotal;
await tenantDb.Updateable(part).ExecuteCommandAsync();
}
#endregion
#region 处理未初始化费用状态表
if (feeStatus.IsNull())
{
feeStatus = BusinessFeeStatus.Init(req.Id);
await tenantDb.Insertable(feeStatus).ExecuteCommandAsync();
}
#endregion
_logger.Info("执行完费用状态");
//return DataResult.Successed("更新成功!", MultiLanguageConst.DataUpdateSuccess);
await tenantDb.Ado.CommitTranAsync();
////保存会同步舱位
//await _bookingSlotService.SyncBookingOrderToSlot(new BookingOrderToSlotDto {
// BookingId = info.Id,
// CustomerId = info.CustomerId,
// CustomerName = info.CustomerName,
// CustomerNo = info.CustomerNo,
// DocId = info.Doc,
// DocName = info.DocName,
// SaleId = info.SaleId,
// SaleName = info.Sale,
// OpId = info.OperatorId,
// OpName = info.OperatorName
//});
return await Task.FromResult(DataResult.Successed("更新成功!", MultiLanguageConst.DataUpdateSuccess));
}
catch (Exception ex)
{
await tenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(db);
return await Task.FromResult(DataResult.Failed("更新失败!" + ex.Message+ ",请联系管理员!"));
}
}
}
/// <summary>
/// 生成海运出口订单
/// </summary>
/// <param name="req"></param>
/// <param name="tenantDb"></param>
/// <returns></returns>
public async Task<DataResult> CreateSeaExportOrder(SeaExportReq req, SqlSugarScopeProvider tenantDb)
{
if (req.BLType != "拼箱分票" && !string.IsNullOrEmpty(req.MBLNO) && tenantDb.Queryable<SeaExport>().Where(x => x.MBLNO == req.MBLNO.Trim()).Any())
{
return await Task.FromResult(DataResult.Failed("海运出口信息主提单号已存在!", MultiLanguageConst.SeaExportMBLNOExist));
}
if (!string.IsNullOrEmpty(req.CustomerNo) && tenantDb.Queryable<SeaExport>().Where(x => x.Id != req.Id && x.CustomerNo == req.CustomerNo.Trim()).Any())
{
return await Task.FromResult(DataResult.Failed("海运出口信息委托编号已存在!", MultiLanguageConst.SeaExportCustomerNoExist));
}
if (!string.IsNullOrEmpty(req.HBLNO) && tenantDb.Queryable<SeaExport>().Where(x => x.HBLNO == req.HBLNO.Trim()).Any())
{
return await Task.FromResult(DataResult.Failed("海运出口信息分提单号已存在!", MultiLanguageConst.SeaExportHBLNOExist));
}
//TODO 会计期间不允许小于已结转期间
if (req.CloseDocDate.IsNotNull() && req.ETD.IsNotNull() && req.CloseDocDate > req.ETD)
{
return await Task.FromResult(DataResult.Failed("截单日期不允许大于开船日期!", MultiLanguageConst.SeaExportCloseDocDateLimit));
}
if (req.ClosingDate.IsNotNull() && req.ETD.IsNotNull() && req.ClosingDate > req.ETD)
{
return await Task.FromResult(DataResult.Failed("截港日期不允许大于开船日期!", MultiLanguageConst.SeaExportCloseDateLimit));
}
//var sequence = commonService.GetSequenceNext<SeaExport>();
//if (!sequence.Succeeded)
//{
// return await Task.FromResult(DataResult.Failed(sequence.Message, MultiLanguageConst.SequenceSetNotExist));
//}
//
var data = req.Adapt<SeaExport>();
if (string.IsNullOrEmpty(req.CustomerNo))
{
var sequence = await commonService.GetSequenceNextAsync<SeaExport>(tenantDb, user, req.SaleId, req.ETD);
if (!sequence.Succeeded)
{
return await Task.FromResult(DataResult.Failed(sequence.Message, MultiLanguageConst.SequenceSetNotExist));
}
data.CustomerNo = sequence.Data;
//新生成委托编号判断是否重复
if (tenantDb.Queryable<SeaExport>().Where(x => x.CustomerNo == sequence.Data).Any())
{
return await Task.FromResult(DataResult.Failed("海运出口信息委托编号已存在!", MultiLanguageConst.SeaExportCustomerNoExist));
}
}
#region 处理箱型箱量
if (req.CtnInfo.Count > 0)
{
//处理箱型箱量
data = seaComService.UpdateSeaExportCtnInfo(data, req.CtnInfo);
}
#endregion
#region 更新结算方式及结算日期
//更新结算方式及结算日期
var stlInfo = seaComService.GetCustomerStlInfo(new CustomerStlReq() { CustomerId = req.CustomerId, ETD = req.ETD, SaleId = req.SaleId });
if (!stlInfo.Succeeded)
{
return await Task.FromResult(DataResult.Failed(stlInfo.Message));
}
data.StlName = stlInfo.Data.StlName;
data.StlDate = stlInfo.Data.StlDate;
data.AccountDate = stlInfo.Data.AccountDate;
#endregion
#region 回写商品信息
var goodid = WriteBackGoods(data, tenantDb);
data.GoodsId = goodid;
#endregion
//判断是否订阅运踪目的港起运港标识
if (!string.IsNullOrEmpty(data.MBLNO))
{
data.IsBookingYZ = "1";
}
else
{
data.IsBookingYZ = "0";
}
data.BusinessStatus = "Uncommitted";
data.BusinessStatusName = "未提交";
try
{
//开启事务
await tenantDb.Ado.BeginTranAsync();
_logger.Info($"执行订单写入 data={JsonConvert.SerializeObject(data)}");
var entity = await tenantDb.Insertable(data).ExecuteReturnEntityAsync();
//处理订单联系人信息
DealBusinessOrderContact(entity, tenantDb);
if (req.CtnInfo.IsNotNull() && req.CtnInfo.Count > 0)
{
foreach (var item in req.CtnInfo)
{
var ctn = item.Adapt<OpCtn>();
ctn.BSNO = entity.Id.ToString();
await tenantDb.Insertable(ctn).ExecuteCommandAsync();
}
}
if (req.CtnPriceInfo.IsNotNull() && req.CtnPriceInfo.Count > 0)
{
foreach (var item in req.CtnPriceInfo)
{
var price = item.Adapt<BusinessCtnPrice>();
price.BusinessId = entity.Id;
await tenantDb.Insertable(price).ExecuteCommandAsync();
}
}
if (req.EdiInfo.IsNotNull())
{
var edi = req.EdiInfo.Adapt<SeaExportEdi>();
edi.BusinessId = entity.Id;
await tenantDb.Insertable(edi).ExecuteCommandAsync();
}
if (req.CtnGoodsInfo.IsNotNull() && req.CtnGoodsInfo.Count > 0)
{
foreach (var item in req.CtnGoodsInfo)
{
var ctnGood = item.Adapt<OpCtnGoods>();
ctnGood.BusinessId = entity.Id;
await tenantDb.Insertable(ctnGood).ExecuteCommandAsync();
}
}
#region 初始化费用状态表
var feeStatus = BusinessFeeStatus.Init(entity.Id);
await tenantDb.Insertable(feeStatus).ExecuteCommandAsync();
#endregion
//return DataResult.Successed("添加成功!", entity.Id, MultiLanguageConst.DataCreateSuccess);
await tenantDb.Ado.CommitTranAsync();
return await Task.FromResult(DataResult.Successed("添加成功!", entity.Id, MultiLanguageConst.DataCreateSuccess));
}
catch (Exception ex)
{
await tenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(db);
return await Task.FromResult(DataResult.Failed("添加失败!" + ex.Message + ",请联系管理员!"));
}
}
/// <summary>
/// 回写商品信息
/// </summary>
/// <param name="seaExport"></param>
/// <param name="sqlSugarScope"></param>
/// <returns></returns>
public long WriteBackGoods(SeaExport seaExport, SqlSugarScopeProvider sqlSugarScope)
{
if (seaExport.GoodsId == 0 && !string.IsNullOrEmpty(seaExport.HSCode) && !string.IsNullOrEmpty(seaExport.GoodsName))
{
var data = new CodeGoods()
{
GoodsCode = seaExport.HSCode,
GoodName = seaExport.GoodsName,
HSCode = seaExport.HSCode
};
var checkInfo = sqlSugarScope.Queryable<CodeGoods>().Where(x => x.HSCode == seaExport.HSCode && x.GoodName == seaExport.GoodsName).First();
if (checkInfo.IsNotNull())
{
return checkInfo.Id;
}
else
{
var entity = sqlSugarScope.Insertable(data).RemoveDataCache($"{SqlSugarCacheConst.Goods}{user.TenantId}").ExecuteReturnEntityAsync();
seaExport.GoodsId = entity.Id;
return entity.Id;
}
}
else if (seaExport.GoodsId.IsNotNull() && !string.IsNullOrEmpty(seaExport.HSCode) && !string.IsNullOrEmpty(seaExport.GoodsName))
{
var info = sqlSugarScope.Queryable<CodeGoods>().Where(x => x.Id == seaExport.GoodsId).First();
if (info.IsNull())
{
throw new Exception("商品信息不存在!");
}
info.GoodName = seaExport.GoodsName;
info.HSCode = seaExport.HSCode;
sqlSugarScope.Updateable(info).RemoveDataCache($"{SqlSugarCacheConst.Goods}{user.TenantId}").IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
return info.Id;
}
else
{
return 0;
}
}
//public async Task<DataResult<CodeGoods>> SaveCheckCodeGood(string goodName,string code)
//{
// DateTime? stlDate;
// DateTime etd;
// var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
// if (goodName.IsNull() || code.IsNull())
// {
// return await Task.FromResult(DataResult<CodeGoods>.Failed("商品名称或HsCode不能为空!"));
// }
// if (tenantDb.Queryable<CodeGoods>().Where(x=>x.HSCode == code).Any)
// {
// }
// var accDate = tenantDb.Queryable<InfoClientAccountDate>().First(x => x.ClientId == req.CustomerId && etd >= x.BeginDate && etd <= x.EndDate);
// if (accDate.IsNull())
// {
// return DataResult<CustomerStlRes>.Success(new CustomerStlRes()
// {
// StlName = "票结",
// StlDate = req.ETD,
// AccountDate = Convert.ToDateTime(req.ETD).ToString("yyyy-MM")
// });
// }
// else
// {
// return DataResult<CustomerStlRes>.Failed("该委托单位未设置账期类型!");
// }
//}
/// <summary>
/// 处理订单联系人信息
/// </summary>
/// <param name="seaExport"></param>
/// <param name="sqlSugarScope"></param>
private void DealBusinessOrderContact(SeaExport seaExport, SqlSugarScopeProvider sqlSugarScope)
{
var contactLists = sqlSugarScope.Queryable<BusinessOrderContact>().Where(x => x.BusinessId == seaExport.Id).ToList();
var addList = new List<BusinessOrderContact>();
var delList = new List<BusinessOrderContact>();
if (seaExport.CustomerId != 0)
{
var delContrllers = contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "controller" && x.CustomerId != seaExport.CustomerId).ToList();
if (delContrllers.Count > 0)
{
delList.AddRange(delContrllers);
}
var defaultContact = sqlSugarScope.Queryable<InfoClientContact>().Where(x => x.ClientId == seaExport.CustomerId && x.IsDefault == true).First();
if (defaultContact.IsNotNull())
{
if (!contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "controller" && x.CustomerId == seaExport.CustomerId).Any())
{
addList.Add(new BusinessOrderContact()
{
BusinessId = seaExport.Id,
CustomerId = seaExport.CustomerId,
CustomerName = seaExport.CustomerName,
CustomerType = "controller",
CustomerTypeName = "委托单位",
Name = defaultContact.Name,
Tel = defaultContact.Tel,
Mobile = defaultContact.Mobile,
Email = defaultContact.Email,
Job = defaultContact.Job,
CustomerContactId = defaultContact.Id
});
}
}
}
if (seaExport.TruckerId != 0)
{
var delTrucks = contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "truck" && x.CustomerId != seaExport.TruckerId).ToList();
if (delTrucks.Count > 0)
{
delList.AddRange(delTrucks);
}
var defaultContact = sqlSugarScope.Queryable<InfoClientContact>().Where(x => x.ClientId == seaExport.TruckerId && x.IsDefault == true).First();
if (defaultContact.IsNotNull())
{
if (!contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "truck" && x.CustomerId == seaExport.TruckerId).Any())
{
addList.Add(new BusinessOrderContact()
{
BusinessId = seaExport.Id,
CustomerId = seaExport.TruckerId,
CustomerName = seaExport.Trucker,
CustomerType = "truck",
CustomerTypeName = "车队",
Name = defaultContact.Name,
Mobile = defaultContact.Mobile,
Tel = defaultContact.Tel,
Email = defaultContact.Email,
Job = defaultContact.Job,
CustomerContactId = defaultContact.Id
});
}
}
}
if (seaExport.YardId != 0)
{
var delYards = contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "yard" && x.CustomerId != seaExport.YardId).ToList();
if (delYards.Count > 0)
{
delList.AddRange(delYards);
}
var defaultContact = sqlSugarScope.Queryable<InfoClientContact>().Where(x => x.ClientId == seaExport.YardId && x.IsDefault == true).First();
if (defaultContact.IsNotNull())
{
if (!contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "yard" && x.CustomerId == seaExport.YardId).Any())
{
addList.Add(new BusinessOrderContact()
{
BusinessId = seaExport.Id,
CustomerId = seaExport.YardId,
CustomerName = seaExport.Yard,
CustomerType = "yard",
CustomerTypeName = "场站",
Name = defaultContact.Name,
Mobile = defaultContact.Mobile,
Tel = defaultContact.Tel,
Email = defaultContact.Email,
Job = defaultContact.Job,
CustomerContactId = defaultContact.Id
});
}
}
}
if (seaExport.ForwarderId != 0)
{
var delForwarders = contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "booking" && x.CustomerId != seaExport.ForwarderId).ToList();
if (delForwarders.Count > 0)
{
delList.AddRange(delForwarders);
}
var defaultContact = sqlSugarScope.Queryable<InfoClientContact>().Where(x => x.ClientId == seaExport.ForwarderId && x.IsDefault == true).First();
if (defaultContact.IsNotNull())
{
//!contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "booking" && x.Name == defaultContact.Name).Any()
if (!contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "booking" && x.CustomerId == seaExport.ForwarderId).Any())
{
addList.Add(new BusinessOrderContact()
{
BusinessId = seaExport.Id,
CustomerId = seaExport.ForwarderId,
CustomerName = seaExport.Forwarder,
CustomerType = "booking",
CustomerTypeName = "订舱口",
Name = defaultContact.Name,
Mobile = defaultContact.Mobile,
Tel = defaultContact.Tel,
Email = defaultContact.Email,
Job = defaultContact.Job,
CustomerContactId = defaultContact.Id
});
}
}
}
if (seaExport.ShipperCnId != 0)
{
var delShipperCns = contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "shippercn" && x.CustomerId != seaExport.ShipperCnId).ToList();
if (delShipperCns.Count > 0)
{
delList.AddRange(delShipperCns);
}
var defaultContact = sqlSugarScope.Queryable<InfoClientContact>().Where(x => x.ClientId == seaExport.ShipperCnId && x.IsDefault == true).First();
if (defaultContact.IsNotNull())
{
if (!contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "shippercn" && x.CustomerId == seaExport.ShipperCnId).Any())
{
addList.Add(new BusinessOrderContact()
{
BusinessId = seaExport.Id,
CustomerId = (long)seaExport.ShipperCnId,
CustomerName = seaExport.ShipperCn,
CustomerType = "shippercn",
CustomerTypeName = "国内发货人",
Name = defaultContact.Name,
Mobile = defaultContact.Mobile,
Tel = defaultContact.Tel,
Email = defaultContact.Email,
Job = defaultContact.Job,
CustomerContactId = defaultContact.Id
});
}
}
}
if (seaExport.CustomserId != 0)
{
var delCustomsers = contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "custom" && x.CustomerId != seaExport.CustomserId).ToList();
if (delCustomsers.Count > 0)
{
delList.AddRange(delCustomsers);
}
var defaultContact = sqlSugarScope.Queryable<InfoClientContact>().Where(x => x.ClientId == seaExport.CustomserId && x.IsDefault == true).First();
if (defaultContact.IsNotNull())
{
if (!contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "custom" && x.CustomerId == seaExport.CustomserId).Any())
{
addList.Add(new BusinessOrderContact()
{
BusinessId = seaExport.Id,
CustomerId = (long)seaExport.CustomserId,
CustomerName = seaExport.CustomerName,
CustomerType = "custom",
CustomerTypeName = "报关行",
Name = defaultContact.Name,
Mobile = defaultContact.Mobile,
Tel = defaultContact.Tel,
Email = defaultContact.Email,
Job = defaultContact.Job,
CustomerContactId = defaultContact.Id
});
}
}
}
if (seaExport.AgentId != 0)
{
var delAgents = contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "agent" && x.CustomerId != seaExport.AgentId).ToList();
if (delAgents.Count > 0)
{
delList.AddRange(delAgents);
}
var defaultContact = sqlSugarScope.Queryable<InfoClientContact>().Where(x => x.ClientId == seaExport.AgentId && x.IsDefault == true).First();
if (defaultContact.IsNotNull())
{
if (!contactLists.Where(x => x.BusinessType == BusinessType.OceanShippingExport && x.CustomerType == "agent" && x.CustomerId == seaExport.AgentId).Any())
{
addList.Add(new BusinessOrderContact()
{
BusinessId = seaExport.Id,
CustomerId = (long)seaExport.AgentId,
CustomerName = seaExport.Agent,
CustomerType = "agent",
CustomerTypeName = "国外代理",
Name = defaultContact.Name,
Mobile = defaultContact.Mobile,
Tel = defaultContact.Tel,
Email = defaultContact.Email,
Job = defaultContact.Job,
CustomerContactId = defaultContact.Id
});
}
}
}
if (addList.Count > 0)
sqlSugarScope.Insertable(addList).ExecuteCommand();
if (delList.Count > 0)
sqlSugarScope.Deleteable(delList).ExecuteCommand();
}
/// <summary>
/// 详情
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<DataResult<SeaExportRes>> GetSeaExportInfo(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
tenantDb.QueryFilter.Clear<IOrgId>();
var data = await tenantDb.Queryable<SeaExport>()
.Where(a => a.Id == long.Parse(id))
.Select<SeaExportRes>()
.Mapper(it =>
{
var edi = tenantDb.Queryable<SeaExportEdi>().First(x => x.BusinessId == it.Id);
if (edi != null)
it.EdiInfo = edi.Adapt<SeaExportEdiRes>();
it.CtnInfo = tenantDb.Queryable<OpCtn>().Where(x => x.BSNO == it.Id.ToString()).Select<OpCtnRes>().ToList();
it.CtnPriceInfo = tenantDb.Queryable<BusinessCtnPrice>().Where(x => x.BusinessId == it.Id).Select<BusinessCtnPriceRes>().ToList();
//it.FormSetList = tenantDb.Queryable<CodeFormSet>().Where(x => x.PermissionName == "海运出口-详情").Select<CodeFormSetRes>().ToList();
it.BusinessLogList = tenantDb.Queryable<OpBusinessLog>().Where(x => x.BusinessId == it.Id)
.Select<OpBusinessLogRes>()
.Mapper(a =>
{
a.Details = tenantDb.Queryable<OpBusinessLogDetail>().Where(x => x.Pid == a.Id).ToList();
})
.ToList();
//多品名信息
it.CtnGoodsInfo = tenantDb.Queryable<OpCtnGoods>().Where(x => x.BusinessId == it.Id).Select<OpCtnGoodsRes>().ToList();
it.OrderContactList = tenantDb.Queryable<BusinessOrderContact>().Where(x => x.BusinessId == it.Id).Select<BusinessOrderContactRes>().ToList();
//var businessTask = tenantDb.Queryable<BusinessTask>().Where(x => x.BusinessId == it.Id && x.TaskType == TaskBaseTypeEnum.WAIT_ORDER_AUDIT).First();
//it.OrderAuditTaskStatus = businessTask.IsNull() ? TaskStatusEnum.Create : businessTask.TaskStatus;
//it.DischargePortCountry = tenantDb.Queryable<CodePort>().Where(x => x.Id == it.DischargePortId).Select(x => x.CountryName).First();
})
.FirstAsync();
if (data != null)
data.AuditStatus = tenantDb.Queryable<BusinessFeeStatus>().Where(x => x.BusinessId == data.Id && x.BusinessType == BusinessType.OceanShippingExport)
.Select(x => x.BillAuditStatus).First();
return await Task.FromResult(DataResult<SeaExportRes>.Success(data, MultiLanguageConst.DataQuerySuccess));
}
/// <summary>
/// 批量更新
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult> SeaExportBatchEdit(SeaExportBatchEditReq req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
if (req.Ids.Count == 0)
{
return DataResult.Failed("海运出口批量编辑未勾选!", MultiLanguageConst.SeaExportBatchEditNoSelect);
}
if (tenantDb.Queryable<SeaExport>().Where(x => !req.Ids.Contains(x.Id)).Any().IsNull())
{
return DataResult.Failed("不存在的海运出口信息!", MultiLanguageConst.SeaExportExist);
}
if (tenantDb.Queryable<BusinessFeeStatus>().Where(x => req.Ids.Contains(x.BusinessId) && x.IsBusinessLocking == true).Any())
{
return DataResult.Failed("海运出口信息业务已锁定!", MultiLanguageConst.SeaExportBusinessLock);
}
if (req.AccountDate.IsNotNull())
{
if (tenantDb.Queryable<BusinessFeeStatus>().Where(x => req.Ids.Contains(x.BusinessId) && x.IsFeeLocking == true).Any())
{
return DataResult.Failed("海运出口信息费用已锁定!", MultiLanguageConst.SeaExportFeeLock);
}
}
var orderList = await tenantDb.Queryable<SeaExport>().Where(x => req.Ids.Contains(x.Id)).ToListAsync();
var dic = req.GetPropertiesArray();
foreach (var item in orderList)
{
var oldOrder = item.Adapt<SeaExport>();
var info = req.Adapt(item);
info.Note = "批量更新";
await tenantDb.Updateable(info).UpdateColumns(dic).EnableDiffLogEvent().ExecuteCommandAsync();
await seaComService.SaveSeaExportLogAsync(new SeaExportSaveLog()
{
OperateType = "Update",
OldOrder = oldOrder,
NewOrder = info,
SourceCode = "BatchEdit",
SourceName = "批量更新",
}, tenantDb);
}
return DataResult.Successed("更新成功!", MultiLanguageConst.DataUpdateSuccess);
}
#region 复制
/// <summary>
/// 业务单据单票复制
/// </summary>
/// <param name="id">业务Id</param>
/// <returns></returns>
public DataResult SeaExportCopy(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var info = tenantDb.Queryable<SeaExport>().Where(x => x.Id == long.Parse(id)).First();
if (info.IsNullOrEmpty())
{
return DataResult.Failed("海运出口信息不存在!", MultiLanguageConst.SeaExportNotExist);
}
//获取表单复制模板
var template = tenantDb.Queryable<CodeFormCopy>().Where(x => x.PermissionId == 1772509201441099776).First();
//var sequence = commonService.GetSequenceNextAsync<SeaExport>(tenantDb, user, info.SaleId).GetAwaiter().GetResult();
//if (!sequence.Succeeded)
//{
// return DataResult.Failed(sequence.Message, MultiLanguageConst.SequenceSetNotExist);
//}
var edi = tenantDb.Queryable<SeaExportEdi>().First(x => x.BusinessId == long.Parse(id));
var data = new SeaExport();
if (template.IsNullOrEmpty())
{
data = info.Adapt(data);
data.Id = 0;
data.ParentId = 0;
//data.IsBusinessLocking = false;
//data.IsFeeLocking = false;
//data.CustomerNo = sequence.Data;
data.BusinessStatus = "Uncommitted";
data.BusinessStatusName = "未提交";
data.CustomerNo = "";
var entity = tenantDb.Insertable(data).ExecuteReturnEntity();
if (edi.IsNotNull())
{
var ediEntity = edi.Adapt<SeaExportEdiRes>();
ediEntity.Id = 0;
ediEntity.BusinessId = entity.Id;
tenantDb.Insertable(ediEntity).ExecuteReturnEntity();
}
#region 初始化费用状态表
var feeStatus = BusinessFeeStatus.Init(entity.Id);
tenantDb.Insertable(feeStatus).ExecuteCommand();
#endregion
return DataResult.Successed("复制成功!", entity.Id, MultiLanguageConst.DataCopySuccess);
}
else
{
data = info.Adapt(data);
data.Id = 0;
data.ParentId = 0;
data.CustomerNo = "";
data.BusinessStatus = "Uncommitted";
data.BusinessStatusName = "未提交";
//data.IsBusinessLocking = false;
//data.IsFeeLocking = false;
//data.CustomerNo = sequence.Data;
var list0 = template.CopyFields.Split(",");
var list1 = new List<string>();
foreach (var item in list0)
{
list1.Add(item.ToUpperCamelCase());
}
list1.Add("IsBusinessLocking");
list1.Add("IsFeeLocking");
//list1.Add("CustomerNo");
var insertColumns = list1.ToArray();
//insertColumns.AddRange(["Id", "ParentId", "IsBusinessLocking", "IsFeeLocking", "CustomerNo"]);
var entity = tenantDb.Insertable(data).InsertColumns(insertColumns).ExecuteReturnEntity();
if (edi.IsNotNull())
{
var ediEntity = edi.Adapt<SeaExportEdiRes>();
ediEntity.Id = 0;
ediEntity.BusinessId = entity.Id;
tenantDb.Insertable(ediEntity).ExecuteReturnEntity();
}
#region 初始化费用状态表
var feeStatus = BusinessFeeStatus.Init(entity.Id);
tenantDb.Insertable(feeStatus).ExecuteCommand();
#endregion
return DataResult.Successed("复制成功!", entity.Id, MultiLanguageConst.DataCopySuccess);
}
}
/// <summary>
/// 业务单据复制-返回前端
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult<SeaExportCopyRes>> GetSeaExportCopyInfo(SeaExportCopyReq req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
tenantDb.QueryFilter.Clear<IOrgId>();
var id = req.Id;
var data = await tenantDb.Queryable<SeaExport>()
.Where(a => a.Id == id)
.Select<SeaExportCopyRes>()
.Mapper(it =>
{
var edi = tenantDb.Queryable<SeaExportEdi>().First(x => x.BusinessId == it.Id);
if (edi != null)
it.EdiInfo = edi.Adapt<SeaExportEdiRes>();
it.CtnInfo = tenantDb.Queryable<OpCtn>().Where(x => x.BSNO == it.Id.ToString()).Select<OpCtnRes>().ToList();
it.CtnPriceInfo = tenantDb.Queryable<BusinessCtnPrice>().Where(x => x.BusinessId == it.Id).Select<BusinessCtnPriceRes>().ToList();
it.OrderContactList = tenantDb.Queryable<BusinessOrderContact>().Where(x => x.BusinessId == it.Id).Select<BusinessOrderContactRes>().ToList();
})
.FirstAsync();
if (data.IsNullOrEmpty())
{
return await Task.FromResult(DataResult<SeaExportCopyRes>.Failed("海运出口信息不存在!", MultiLanguageConst.SeaExportNotExist));
}
//获取表单复制模板
var template = tenantDb.Queryable<CodeFormCopy>().Where(x => x.PermissionId == 1772509201441099776).First();
data.Id = 0;
data.ParentId = 0;
data.BusinessStatus = "Uncommitted";
data.BusinessStatusName = "未提交";
data.CustomerNo = "";
if (data.EdiInfo.IsNotNull())
{
data.EdiInfo.Id = 0;
data.EdiInfo.BusinessId = 0;
}
if (data.CtnInfo.IsNotNull() && data.CtnInfo.Count > 0)
{
foreach (var item in data.CtnInfo)
{
item.Id = 0;
item.BSNO = "";
}
}
if (data.CtnPriceInfo.IsNotNull() && data.CtnPriceInfo.Count > 0)
{
foreach (var item in data.CtnPriceInfo)
{
item.Id = 0;
item.BusinessId = 0;
}
}
if (data.OrderContactList.IsNotNull() && data.OrderContactList.Count > 0)
{
foreach (var item in data.OrderContactList)
{
item.Id = 0;
item.BusinessId = 0;
}
}
if (req.IsCopyFee)
{
var fees = await tenantDb.Queryable<FeeRecord>().Where(x => x.BusinessId == id).ToListAsync();
if (fees.IsNotNull() && fees.Count > 0)
{
foreach (var item in fees)
{
item.Id = 0;
item.BusinessId = 0;
}
data.FeeList = fees.Adapt<List<FeeRecordRes>>();
}
}
//if (template.IsNotNull())
//{
//}
return await Task.FromResult(DataResult<SeaExportCopyRes>.Success("复制成功!", data, MultiLanguageConst.DataCopySuccess));
}
#endregion
#region 删除
/// <summary>
/// 业务单据删除
/// </summary>
/// <param name="id">业务Id</param>
/// <returns></returns>
public async Task<DataResult> SeaExportDel(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var info = tenantDb.Queryable<SeaExport>().Where(x => x.Id == long.Parse(id)).First();
if (info.IsNullOrEmpty())
{
return DataResult.Failed("海运出口信息不存在!", MultiLanguageConst.SeaExportNotExist);
}
if (tenantDb.Queryable<SeaExport>().Where(x => x.ParentId == long.Parse(id)).Any())
{
return DataResult.Failed("海运出口存在分票信息,不能删除!", MultiLanguageConst.SeaExportPartExist);
}
if (tenantDb.Queryable<FeeRecord>().Where(x => x.BusinessId == long.Parse(id)).Any())
{
return DataResult.Failed("海运出口存在费用信息,不能删除!", MultiLanguageConst.SeaExportFeeExist);
}
if (tenantDb.Queryable<BusinessFeeStatus>().Where(x => x.BusinessId == long.Parse(id) && x.IsBusinessLocking == true).Any())
{
return DataResult.Failed("海运出口信息业务已锁定!", MultiLanguageConst.SeaExportBusinessLock);
}
if (tenantDb.Queryable<BusinessFeeStatus>().Where(x => x.BusinessId == long.Parse(id) && x.IsFeeLocking == true).Any())
{
return DataResult.Failed("海运出口信息费用已锁定!", MultiLanguageConst.SeaExportFeeLock);
}
//info.Deleted = true;
//info.DeleteTime = DateTime.Now;
//info.DeleteBy = long.Parse(user.UserId);
//tenantDb.Updateable(info).ExecuteCommand();
//tenantDb.Deleteable(info).IsLogic().ExecuteCommand("Deleted");
try
{
await tenantDb.Ado.BeginTranAsync();
var ctns = await tenantDb.Queryable<OpCtn>().Where(x => x.BSNO == id).ToListAsync();
if (ctns.Count > 0)
await tenantDb.Deleteable(ctns).ExecuteCommandAsync();
var ctnPrices = await tenantDb.Queryable<BusinessCtnPrice>().Where(x => x.BusinessId == long.Parse(id)).ToListAsync();
if (ctnPrices.Count > 0)
await tenantDb.Deleteable(ctnPrices).ExecuteCommandAsync();
var ediInfo = await tenantDb.Queryable<SeaExportEdi>().Where(x => x.BusinessId == long.Parse(id)).FirstAsync();
if (ediInfo.IsNotNull())
await tenantDb.Deleteable(ediInfo).ExecuteCommandAsync();
var contacts = await tenantDb.Queryable<BusinessOrderContact>().Where(x => x.BusinessId == long.Parse(id)).ToListAsync();
if (contacts.Count > 0)
await tenantDb.Deleteable(contacts).ExecuteCommandAsync();
await tenantDb.Deleteable(info).ExecuteCommandAsync();
await tenantDb.Ado.CommitTranAsync();
}
catch (Exception ex)
{
await tenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(db);
return await Task.FromResult(DataResult.Failed("删除失败!" + ",请联系管理员!"));
}
return DataResult.Successed("删除成功!", MultiLanguageConst.DataDelSuccess);
}
/// <summary>
/// 业务单据删除
/// </summary>
/// <param name="req">业务Ids</param>
/// <returns></returns>
public async Task<DataResult> SeaExportBatchDel(IdModel req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
if (req.Ids.Length == 0)
{
return DataResult.Failed("海运出口批量操作未勾选!", MultiLanguageConst.SeaExportBatchOpNoSelect);
}
if (tenantDb.Queryable<SeaExport>().Where(x => req.Ids.Contains(x.Id)).Any().IsNull())
{
return DataResult.Failed("不存在的海运出口信息!", MultiLanguageConst.SeaExportExist);
}
if (tenantDb.Queryable<BusinessFeeStatus>().Where(x => req.Ids.Contains(x.BusinessId) && x.IsBusinessLocking == true).Any())
{
return DataResult.Failed("海运出口信息业务已锁定!", MultiLanguageConst.SeaExportBusinessLock);
}
if (tenantDb.Queryable<BusinessFeeStatus>().Where(x => req.Ids.Contains(x.BusinessId) && x.IsFeeLocking == true).Any())
{
return DataResult.Failed("海运出口信息费用已锁定!", MultiLanguageConst.SeaExportFeeLock);
}
if (tenantDb.Queryable<SeaExport>().Where(x => req.Ids.Contains(x.ParentId)).Any())
{
return DataResult.Failed("海运出口存在分票信息,不能删除!", MultiLanguageConst.SeaExportPartExist);
}
if (tenantDb.Queryable<FeeRecord>().Where(x => req.Ids.Contains(x.BusinessId)).Any())
{
return DataResult.Failed("海运出口存在费用信息,不能删除!", MultiLanguageConst.SeaExportFeeExist);
}
var allotTask = await _taskManageBaseService.Value.GetSeaExportAllotTaskNo(req.Ids.ToList());
if (allotTask.Data?.Count > 0)
{
return DataResult.Failed(string.Format(MultiLanguageConst.GetDescription(MultiLanguageConst.SeaExportTaskExist), string.Join("、", allotTask.Data)));
}
var list = tenantDb.Queryable<SeaExport>().Where(x => req.Ids.Contains(x.Id)).ToList();
//tenantDb.Deleteable(list).IsLogic().ExecuteCommand("Deleted");
//tenantDb.Deleteable<SeaExport>(list).IsLogic().ExecuteCommand("Deleted");
//foreach (var item in list)
//{
// item.Deleted = true;
// item.DeleteTime = DateTime.Now;
// item.DeleteBy = long.Parse(user.UserId);
// tenantDb.Updateable(item).ExecuteCommand();
//}
try
{
await tenantDb.Ado.BeginTranAsync();
foreach (var item in list)
{
var ctns = await tenantDb.Queryable<OpCtn>().Where(x => x.BSNO == item.Id.ToString()).ToListAsync();
if (ctns.Count > 0)
await tenantDb.Deleteable(ctns).ExecuteCommandAsync();
var ctnPrices = await tenantDb.Queryable<BusinessCtnPrice>().Where(x => x.BusinessId == item.Id).ToListAsync();
if (ctnPrices.Count > 0)
await tenantDb.Deleteable(ctnPrices).ExecuteCommandAsync();
var ediInfo = await tenantDb.Queryable<SeaExportEdi>().Where(x => x.BusinessId == item.Id).FirstAsync();
if (ediInfo.IsNotNull())
await tenantDb.Deleteable(ediInfo).ExecuteCommandAsync();
var contacts = await tenantDb.Queryable<BusinessOrderContact>().Where(x => x.BusinessId == item.Id).ToListAsync();
if (contacts.Count > 0)
await tenantDb.Deleteable(contacts).ExecuteCommandAsync();
await tenantDb.Deleteable(item).ExecuteCommandAsync();
}
await tenantDb.Ado.CommitTranAsync();
}
catch (Exception ex)
{
await tenantDb.Ado.RollbackTranAsync();
await ex.LogAsync(db);
return await Task.FromResult(DataResult.Failed("删除失败!" + ",请联系管理员!"));
}
return DataResult.Successed("删除成功!", MultiLanguageConst.DataDelSuccess);
}
#endregion
/// <summary>
/// 订单及货运动态
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public async Task<DataResult<List<BookingStatusLogRes>>> GetBookingStatusLogList(PageRequest request)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var result = await tenantDb.Queryable<BookingStatusLog>()
.Select<BookingStatusLogRes>()
.Mapper(async it =>
{
it.detail = await tenantDb.Queryable<BookingStatusLogDetail>().Where(x => x.PId == it.Id).Select<BookingStatusLogDetailDto>().ToListAsync();
}
).Where(whereList).ToQueryPageAsync(request.PageCondition);
return result;
}
#region 检索订单信息(如果当前为拆、合票,内包含分票信息)
/// <summary>
/// 检索订单信息(如果当前为拆、合票,内包含分票信息)
/// </summary>
/// <param name="mblNo">提单号</param>
/// <returns></returns>
public async Task<DataResult<SeaExportOrderExtension>> SearchOrderInfo(string mblNo)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
SeaExportOrderExtension model = new SeaExportOrderExtension
{
otherOrderList = new List<SeaExportOrderExtensionSubInfo>()
};
/*
1、先用主提单号检索如果没有取到结果再用订舱编号检索。
2、是拆票的找到主票和其他分票并返回当前订单的完整详情。
3、是合票的找到主票和其他分票并返回当前订单的完整详情。
*/
var orderList = await tenantDb.Queryable<SeaExport>()
.Where(a => (a.MBLNO == mblNo || a.OrderNo == mblNo) && a.Deleted == false && (a.ParentId == null || a.ParentId == 0)).ToListAsync();
var currOrder = orderList.FirstOrDefault(a => a.MBLNO == mblNo);
//这里如果是拆票记录,则默认用拆票的第一票作为当前票的对应记录
if (currOrder == null && orderList.Any(b => b.SplitOrMergeFlag == 1))
{
var maxChar = orderList.Select(a =>
{
var startIndx = a.CustomerNo.Length;
return a.MBLNO.Substring(startIndx);
}).Min();
var custNo = orderList.FirstOrDefault().CustomerNo;
currOrder = orderList.FirstOrDefault(a => a.MBLNO == $"{custNo}{maxChar}");
}
if (currOrder != null)
{
model.currOrder = currOrder.Adapt<SeaExportRes>();
model.splitOrMergeFlag = currOrder.SplitOrMergeFlag;
if (currOrder.SplitOrMergeFlag > 0)
{
//拆票
if (currOrder.SplitOrMergeFlag == 1)
{
//如果分单号和订舱编号不一致表示分票已经改成正式的提单号
if (!currOrder.HBLNO.Equals(currOrder.OrderNo))
{
model.finalMBLNo = currOrder.HBLNO;
}
model.orderNo = currOrder.OrderNo;
//找到所有相关的分票
var list = await tenantDb.Queryable<SeaExport>().Filter(null, true)
.Where(a => a.OrderNo == mblNo && a.Deleted == false && a.Id != currOrder.Id && (a.ParentId == null || a.ParentId == 0)).ToListAsync();
model.otherOrderList = list.Select(b => new SeaExportOrderExtensionSubInfo
{
Id = b.Id,
OrderNo = b.OrderNo,
MBLNO = b.MBLNO,
HBLNO = b.HBLNO
}).ToList();
}
else if (currOrder.SplitOrMergeFlag == 2)
{
//合票
if (currOrder.OrderNo.Equals(currOrder.HBLNO))
{
//如果订舱编号和分单号一致,表示当前为主合票信息
model.isMaster = true;
model.masterId = currOrder.Id;
model.orderNo = currOrder.MBLNO;
}
//找到所有相关的分票
var list = await tenantDb.Queryable<SeaExport>().Filter(null, true)
.Where(a => a.HBLNO == currOrder.HBLNO && a.Deleted == false && a.Id != currOrder.Id && (a.ParentId == null || a.ParentId == 0)).ToListAsync();
model.otherOrderList = list.Select(b => new SeaExportOrderExtensionSubInfo
{
Id = b.Id,
OrderNo = b.OrderNo,
MBLNO = b.MBLNO,
HBLNO = b.HBLNO
}).ToList();
var masterOrder = model.otherOrderList.FirstOrDefault(x => x.OrderNo == x.HBLNO);
if (masterOrder != null)
{
model.masterId = masterOrder.Id;
model.orderNo = masterOrder.OrderNo;
}
}
}
}
else
{
return DataResult<SeaExportOrderExtension>.FailedData(model);
}
return DataResult<SeaExportOrderExtension>.Success(model);
}
#endregion
/// <summary>
/// 提交订单
/// </summary>
/// <param name="req"></param>
/// <returns></returns>
public async Task<DataResult> CreateOrderAuditTaskAsync(IdModel req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var id = long.Parse(req.Id);
var info = await tenantDb.Queryable<SeaExport>().Where(x => x.Id == id).FirstAsync();
if (info.IsNull())
return await Task.FromResult(DataResult.Failed("不存在的海运出口信息!", MultiLanguageConst.SeaExportExist));
if (string.IsNullOrEmpty(info.ServiceItem))
return await Task.FromResult(DataResult.Failed("海运出口服务项目不能为空!", MultiLanguageConst.SeaExportServiceItemNotExist));
var items = info.ServiceItem.Split(',');
//订舱 走审单流程
if (items.Contains("dingcang"))
{
var taskReq = new TaskCreationRequest()
{
BusinessId = id,
BusinessType = BusinessType.OceanShippingExport,
TaskTypeName = TaskBaseTypeEnum.WAIT_ORDER_AUDIT.ToString(),
};
var result = await _seaTaskService.CreateTaskAsync(taskReq, false);
if (!result.Succeeded)
return await Task.FromResult(DataResult.Failed(result.Message));
return result;
}
else //没有订舱服务不调用审单流程生成订舱相关任务,直接根据服务项目生成任务。
{
var taskReq = new BusinessTask()
{
BusinessId = id,
BusinessType = BusinessType.OceanShippingExport,
};
await _seaTaskService.CreateSubTaskAsync(taskReq);
return DataResult.Success;
}
}
/// <summary>
/// 更新服务项目
/// </summary>
/// <returns></returns>
public async Task<DataResult> UpdateSeaExportServiceItem()
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = await tenantDb.Queryable<SeaExport>().Where(x => x.ServiceItem == null || x.ServiceItem == "").ToListAsync();//.Where(x => x.IsRefund == false && x.IsChangeETD == false)
foreach (var item in list)
{
var res = await _djyServiceStatusService.GetServiceProjectList(new EmbedQueryServiceProjectWithStatus()
{
BusinessId = item.Id.ToString(),
QueryType = 0,
});
var data = JsonConvert.DeserializeObject<ServiceProjectRoot>(res.data.ToString());
var res1 = data.Ext;
if (res1 != null && res1.Count>0) {
var codes = res1.Where(x=>x.IsYield == true).Select(x=> x.ProjectCode.ToLower()).ToList();
var codeStr = String.Join(",", codes);
item.ServiceItem = codeStr;
await tenantDb.Updateable(item).UpdateColumns(x=>new { x.ServiceItem}).ExecuteCommandAsync();
}
Console.WriteLine(res.data);
}
return DataResult.Success;
}
}