using Amazon.Runtime.Internal.Util;
using DS.Module.Core;
using DS.Module.Core.Data;
using DS.Module.Core.Extensions;
using DS.Module.Core.Helpers;
using DS.Module.SqlSugar;
using DS.Module.UserModule;
using DS.WMS.Core.Code.Entity;
using DS.WMS.Core.Map.Entity;
using DS.WMS.Core.Op.Dtos;
using DS.WMS.Core.Op.EDI;
using DS.WMS.Core.Op.Entity;
using DS.WMS.Core.Op.Interface;
using DS.WMS.Core.Sys.Entity;
using Mapster;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using NLog;
using Org.BouncyCastle.Ocsp;
using SqlSugar;
using Logger = NLog.Logger;
namespace DS.WMS.Core.Op.Method
{
public class OpBusinessYardService : IOpBusinessYardService
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlSugarClient db;
private readonly IUser user;
private readonly ISaasDbService saasService;
private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
private readonly ISeaExportCommonService seaComService;
private readonly IWebHostEnvironment _environment;
///
///
///
///
public OpBusinessYardService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService();
user = _serviceProvider.GetRequiredService();
saasService = _serviceProvider.GetRequiredService();
seaComService = _serviceProvider.GetRequiredService();
_environment = _serviceProvider.GetRequiredService();
}
public DataResult> GetListByPage(PageRequest request)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var data = tenantDb.Queryable()
.Where(whereList)
.Select().ToQueryPage(request.PageCondition);
return data;
}
public async Task>> GetYardHistoryList(PageRequest request)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var data = await tenantDb.Queryable()
.LeftJoin((a, b) => a.BusinessId == b.Id)
.Select((a, b) => new OpBusinessYardHistoryRes
{
CreateTime = a.CreateTime,
ETD = b.ETD.HasValue ? b.ETD.Value.Date.ToString("yyyy-MM-dd") : "",
MBLNO = b.MBLNO,
HBLNO = b.HBLNO,
CustomerId = b.CustomerId,
CustomerName = b.CustomerName,
CustomerNo = b.CustomerNo,
}, true)
.Where(whereList).ToQueryPageAsync(request.PageCondition);
return data;
}
public DataResult EditOpBusinessYard(OpBusinessYardReq req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
if (req.Id == 0)
{
var data = req.Adapt();
var entity = tenantDb.Insertable(data).ExecuteReturnEntity();
}
else
{
var info = tenantDb.Queryable().Where(x => x.Id == req.Id).First();
info = req.Adapt(info);
tenantDb.Updateable(info).IgnoreColumns(ignoreAllNullColumns: true).IgnoreColumns(it => new
{
it.BusinessId,
}).ExecuteCommand();
}
return DataResult.Successed("保存成功!", MultiLanguageConst.DataUpdateSuccess);
}
//private void CreateLink() {
// //生成提箱小票
// var allowCarrier = _cache.GetAllDictData().Result.Where(x => x.TypeCode == "txxp_carrier_list").Select(x => x.Code).ToList();
// if (allowCarrier.Contains(order.CARRIERID))
// {
// try
// {
// var txxpLink = await TxxpLink(input.BookingId);
// }
// catch { }
// }
// //vgm链接
// allowCarrier = _cache.GetAllDictData().Result.Where(x => x.TypeCode == "vgm_carrier_list").Select(x => x.Code).ToList();
// if (allowCarrier.Contains(order.CARRIERID))
// {
// try
// {
// await VgmLink(input.BookingId);
// }
// catch { }
// }
//}
public DataResult GetOpBusinessYardInfo(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = tenantDb.Queryable()
.Where(a => a.Id == long.Parse(id))
.Select()
.Mapper(it =>
it.Urls = tenantDb.Queryable().Where(x => x.BusinessId == it.BusinessId).Select().First()
)
.First();
//data.Urls = tenantDb.Queryable().Where(x => x.BusinessId == data.BusinessId).Select().First();
return DataResult.Success(data, MultiLanguageConst.DataQuerySuccess);
}
public DataResult GetBusinessYardByKeyId(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = tenantDb.Queryable()
.Where(a => a.BusinessId == long.Parse(id))
.Select()
.Mapper(it =>
it.Urls = tenantDb.Queryable().Where(x => x.BusinessId == it.BusinessId).Select().First()
)
.First();
return DataResult.Success(data, MultiLanguageConst.DataQuerySuccess);
}
public DataResult BatchDelOpBusinessYard(IdModel req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable().Where(x => req.Ids.Contains(x.Id)).ToList();
if (list.Count > 0)
{
tenantDb.Deleteable(list).ExecuteCommand();
}
return DataResult.Successed("删除成功!", MultiLanguageConst.DataDelSuccess);
}
public async Task> SendLetterYard(SendShippingOrderReq req)
{
var tenant = db.Queryable().FirstAsync(t => t.Id == long.Parse(user.TenantId));
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var bookingId = req.BookingId;
var letterYard = await tenantDb.Queryable().FirstAsync(x => x.BusinessId == bookingId);
if (letterYard.IsNull())
{
return await Task.FromResult(DataResult.Failed("放舱信息未找到,请先保存数据"));
}
if (string.IsNullOrEmpty(letterYard.ToAttnEmail))
{
return await Task.FromResult(DataResult.Failed("ATTN MAIL未正确填写"));
}
if (string.IsNullOrEmpty(letterYard.FromEmail))
{
return await Task.FromResult(DataResult.Failed("FROM MAIL未正确填写"));
}
var order = await tenantDb.Queryable().FirstAsync(x => x.Id == bookingId);
var userMail = await tenantDb.Queryable().FirstAsync(x => x.CreateBy == long.Parse(user.UserId));
if (userMail == null)
{
return await Task.FromResult(DataResult.Failed("未配置发件邮箱"));
}
if (string.IsNullOrEmpty(userMail.SmtpServer) || userMail.SmtpPort == 25)
{
return await Task.FromResult(DataResult.Failed("请正确配置发件邮箱,且发件不能使用25端口"));
}
var emailUrl = db.Queryable().Filter(null, true).Where(x => x.Code == "email_api_url" && x.TenantId == 1288018625843826688).First().Value;
if (emailUrl == null)
{
return await Task.FromResult(DataResult.Failed("系统参数未配置email_api_url 请联系管理员"));
}
//处理附件
var attPostArr = new List();
foreach (var file in req.FileList)
{
var basePath = AppSetting.app(new string[] { "FileSettings", "BasePath" });
var relativePath = AppSetting.app(new string[] { "FileSettings", "RelativePath" });
var dirAbs = string.Empty;
var fileRelaPath = string.Empty;
var fileAbsPath = string.Empty;
if (string.IsNullOrEmpty(basePath))
{
dirAbs = Path.Combine(_environment.WebRootPath, relativePath);
}
else
{
dirAbs = Path.Combine(basePath, relativePath);
}
var fileFullName = Path.Combine(dirAbs, file);
//fileFullName = fileFullName.Replace(".OpApi", ".MainApi");
fileFullName = fileFullName.Replace("op-api", "main-api");
var fileSaveName = $"放舱通知_{order.MBLNO}_{DateTime.Now.Ticks}.pdf"; // 文件原始名称
_logger.Info($"发送放舱附件路径:{fileFullName}");
if (!File.Exists(fileFullName))
{
return await Task.FromResult(DataResult.Failed("附件不存在,请检查"));
}
attPostArr.Add(new
{
AttachName = Path.GetFileName(file),
AttachContent = Convert.ToBase64String(File.ReadAllBytes(fileFullName))
});
//挂载附件
var bookFile = new OpFile
{
FileName = fileSaveName,
FilePath = fileRelaPath,
TypeCode = "ruhuotongzhi",
TypeName = ".pdf",
LinkId = order.Id,
};
await tenantDb.Insertable(bookFile).ExecuteCommandAsync();
}
//货运动态
var bookingStatusLog = new BookingStatusLog()
{
BusinessId = bookingId,
Status = $"放舱给客户",
Group = "ship",
OpTime = DateTime.Now,
MBLNO = order.MBLNO
};
await tenantDb.Insertable(bookingStatusLog).ExecuteCommandAsync();
//订舱状态
await seaComService.SaveBookingStatus(bookingId, "sta_letter_yard", "放舱");
var mailJson = new dynamic[]{
new
{
SendTo = req.SendTo,
Title = req.Title,
Body = req.Body,
CCTo= req.CCTo,
SmtpConfig = "",
Account=userMail.MailAccount,
Password=userMail.Password,
Server=userMail.SmtpServer,
Port=userMail.SmtpPort,
UseSSL=userMail.SmtpSSL,
Attaches=attPostArr
}
};
var mailStr = mailJson.ToJsonString();
_logger.Info($"准备发送托书邮件,订舱ID:{req.BookingId},邮箱:{userMail.MailAccount}");
var rtn = RequestHelper.Post(mailStr, emailUrl);
_logger.Info($"发送托书邮件返回:{rtn}。订舱ID:{req.BookingId},邮箱:{userMail.MailAccount}");
var jRtn = JObject.Parse(rtn);
if (!jRtn.GetBooleanValue("Success"))
{
//throw Oops.Bah(jRtn.GetStringValue("Message"));
return await Task.FromResult(DataResult.Failed(jRtn.GetStringValue("Message")));
}
//return await Task.FromResult(DataResult.Success(jRtn.GetStringValue("Message")));
//设置货物状态-放舱
await seaComService.SetGoodsStatus("YFC", bookingId, tenantDb);
return await Task.FromResult(DataResult.Success("发送成功"));
// var bookingId = long.Parse(id);
// var order = await tenantDb.Queryable().FirstAsync(x => x.Id == bookingId);
// var userInfo = await tenantDb.Queryable().FirstAsync(u => u.Id == order.CreateBy);
// var letterYard = await tenantDb.Queryable().FirstAsync(x => x.BusinessId == bookingId);
// if (letterYard.IsNull())
// {
// return await Task.FromResult(DataResult.Failed("放舱信息未找到,请先保存数据"));
// }
// if (string.IsNullOrEmpty(letterYard.ToAttnEmail))
// {
// return await Task.FromResult(DataResult.Failed("ATTN MAIL未正确填写"));
// }
// if (string.IsNullOrEmpty(letterYard.FromEmail))
// {
// return await Task.FromResult(DataResult.Failed("FROM MAIL未正确填写"));
// }
// var mailAcc = await tenantDb.Queryable().FirstAsync(x => x.CreateBy == long.Parse(user.UserId) && x.MailAccount == letterYard.FromEmail && x.SmtpPort > 0 && x.SmtpServer != null && x.SmtpServer != "");
// if (mailAcc == null)
// {
// return await Task.FromResult(DataResult.Failed("用户邮箱未设置或smtp未正确配置"));
// }
// var orderUrl = await tenantDb.Queryable().FirstAsync(u => u.BusinessId == bookingId);
// //if (orderUrl == null)
// //{
// // throw Oops.Bah("未生成链接信息,请重新保存数据");
// //}
// #region 保存放舱文件,并挂载到订舱附件
// var printTemplate = await db.Queryable().FirstAsync(t => t.TemplateCode == "release_the_cabin");
// if (printTemplate.IsNull())
// {
// return await Task.FromResult(DataResult.Failed("打印模板代码[release_the_cabin]未设置"));
// }
// //var bs = await GenPrintFile(bookingId, printTemplate);
// var basePath = AppSetting.app(new string[] { "FileSettings", "BasePath" });
// var relativePath = AppSetting.app(new string[] { "FileSettings", "RelativePath" });
// var dirAbs = string.Empty;
// var fileRelaPath = string.Empty;
// var fileAbsPath = string.Empty;
// var fileSaveName = $"放舱通知_{order.MBLNO}_{DateTime.Now.Ticks}.pdf"; // 文件原始名称
// if (string.IsNullOrEmpty(basePath))
// {
// dirAbs = Path.Combine(_environment.WebRootPath, relativePath);
// }
// else
// {
// dirAbs = Path.Combine(basePath, relativePath);
// }
// if (!Directory.Exists(dirAbs))
// Directory.CreateDirectory(dirAbs);
// fileRelaPath = Path.Combine(relativePath, fileSaveName).ToLower();
// fileAbsPath = Path.Combine(dirAbs, fileSaveName).ToLower();
// File.WriteAllBytes(fileAbsPath, bs);
// //挂载附件
// var bookFile = new OpFile
// {
// FileName = fileSaveName,
// FilePath = fileRelaPath,
// TypeCode = "ruhuotongzhi",
// TypeName = ".pdf",
// LinkId = order.Id,
// };
// await tenantDb.Insertable(bookFile).ExecuteCommandAsync();
// #endregion
// //货运动态
// var bookingStatusLog = new BookingStatusLog()
// {
// BusinessId = bookingId,
// Status = $"放舱给客户",
// Group = "ship",
// OpTime = DateTime.Now,
// MBLNO = order.MBLNO
// };
// await tenantDb.Insertable(bookingStatusLog).ExecuteCommandAsync();
// //订舱状态
// await seaComService.SaveBookingStatus(bookingId, "sta_letter_yard", "放舱");
// #region 发送邮件
// var carrCode = seaComService.GetCarrierCode(order.CarrierId, tenantDb);
// var mailSubject = $"放舱信息:{order.MBLNO}/{carrCode}/{order.Vessel}/{order.Voyno}/PO:{order.CustomerNo}/{userInfo.TenantName}";
// var extContent = string.Empty;
// if (order.CargoId == "R") //冻柜
// {
// extContent = $"温度:{order.TemperatureSet}{order.TemperatureUnit}
通风:{order.ReeferQuantity}
湿度:{order.Humidity}
";
// }
// else if (order.CargoId == "D") //危险品
// {
// extContent = $"危险品等级:{order.DangerClass}
危险品编号:{order.DangerNo}
";
// }
// var linkContent = string.Empty;
// if (orderUrl != null)
// {
// linkContent = $@"提箱小票链接:{orderUrl.UrlTxxp}
//提交VGM链接:{orderUrl.UrlVgm}
";
// }
// var mailContent = $@"TO:{order.CustomerName}贵司委托我司代理订舱出口的货物信息如下,详情请见附件,谢谢!
//提单号:{order.MBLNO}
//船名航次:{order.Vessel}/{order.Voyno}
//目的港:{order.DischargePort}
//预计船期:{(order.ETD.HasValue ? order.ETD.Value.Date.ToString("yyyy-MM-dd") : "")}
//场站:{order.Yard}
//船代:{order.ShipAgency}
//预计截港时间:{order.ClosingDate}
//预计截单时间:{order.CloseDocDate}
//截VGM时间:{order.CloseVgmDate}
//{extContent}
//备注:{order.YardRemark}
//{linkContent}
//
// 温馨提示:
// 如果分票报关,请回箱前通知场站及我司。
// 开船及截港时间以码头具体计划为准。
// 若贵司自输VGM,请不要通过VGM链接提交数据,否则我司收取相关VGM申报费用。
//
// 订舱代理联系人:{user.UserName}
// 电话:{userInfo.Tel} 手机:{userInfo.Phone}
// 邮箱:{userInfo.Email}
//
";
// var sendResult = await MailSendHelper.SendMail(mailAcc, mailSubject, mailContent, letterYard.ToAttnEmail, new KeyValuePair($"放舱通知_{order.MBLNO}.pdf", bs));
// if (!sendResult.Key)
// {
// _logger.Error($"放舱邮件发送失败:从{mailAcc.MailAccount}到{letterYard.ToAttnEmail},主题 {mailSubject}");
// return await Task.FromResult(DataResult.Failed($"邮件发送失败:{sendResult.Value}"));
// }
// #endregion
// //设置货物状态-放舱
// await seaComService.SetGoodsStatus("YFC", bookingId, tenantDb);
// return await Task.FromResult(DataResult.Successed("发送成功"));
}
}
}