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.

327 lines
14 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 Amazon.Runtime.Internal.Util;
using AngleSharp.Dom;
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.HangfireJob.Dtos;
using DS.WMS.Core.HangfireJob.Interface;
using DS.WMS.Core.Invoice.Dtos;
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 Hangfire;
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;
/// <summary>
///
/// </summary>
/// <param name="serviceProvider"></param>
public OpBusinessYardService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
db = _serviceProvider.GetRequiredService<ISqlSugarClient>();
user = _serviceProvider.GetRequiredService<IUser>();
saasService = _serviceProvider.GetRequiredService<ISaasDbService>();
seaComService = _serviceProvider.GetRequiredService<ISeaExportCommonService>();
_environment = _serviceProvider.GetRequiredService<IWebHostEnvironment>();
}
public DataResult<List<OpBusinessYardRes>> GetListByPage(PageRequest request)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var data = tenantDb.Queryable<BusinessYard>()
.Where(whereList)
.Select<OpBusinessYardRes>().ToQueryPage(request.PageCondition);
return data;
}
public async Task<DataResult<List<OpBusinessYardHistoryRes>>> GetYardHistoryList(PageRequest request)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
//序列化查询条件
var whereList = db.ConfigQuery.Context.Utilities.JsonToConditionalModels(request.QueryCondition);
var data = await tenantDb.Queryable<BusinessYard>()
.LeftJoin<SeaExport>((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<BusinessYard>();
var entity = tenantDb.Insertable(data).ExecuteReturnEntity();
CreateLink(entity.BusinessId,tenantDb);
}
else
{
var info = tenantDb.Queryable<BusinessYard>().Where(x => x.Id == req.Id).First();
info = req.Adapt(info);
tenantDb.Updateable(info).IgnoreColumns(ignoreAllNullColumns: true).IgnoreColumns(it => new
{
it.BusinessId,
}).ExecuteCommand();
CreateLink(info.BusinessId, tenantDb);
}
return DataResult.Successed("保存成功!", MultiLanguageConst.DataUpdateSuccess);
}
private void CreateLink(long id, SqlSugarScopeProvider tenantDb)
{
//生成提箱小票
var allowTxxpCarrier = db.Queryable<SysDictData>()
.InnerJoin<SysDictType>((a, b) => a.TypeId == b.Id).Where((a, b) => b.Code == "txxp_carrier_list").Select((a, b) => a.Value).ToList();
var order = tenantDb.Queryable<SeaExport>().First(x=>x.Id == id);
var jobReq = new BaseJobReq()
{
Id = id,
UserId = long.Parse(user.UserId),
UserName = user.UserName,
TenantId = long.Parse(user.TenantId),
TenantName = user.TenantName,
OrgId = user.OrgId
};
var carrCode = seaComService.GetCarrierCode(order.CarrierId, tenantDb);
if (allowTxxpCarrier.Contains(carrCode))
{
BackgroundJob.Enqueue<IOpJobService>(c => c.TxxpLinkJob(jobReq));
}
//vgm链接
var allowVgmCarrier = db.Queryable<SysDictData>()
.InnerJoin<SysDictType>((a, b) => a.TypeId == b.Id).Where((a, b) => b.Code == "vgm_carrier_list").Select((a, b) => a.Value).ToList();
if (allowVgmCarrier.Contains(carrCode))
{
BackgroundJob.Enqueue<IOpJobService>(c => c.VgmLinkJob(jobReq));
}
}
public DataResult<OpBusinessYardRes> GetOpBusinessYardInfo(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = tenantDb.Queryable<BusinessYard>()
.Where(a => a.Id == long.Parse(id))
.Select<OpBusinessYardRes>()
.Mapper(it =>
it.Urls = tenantDb.Queryable<BookingOrderUrl>().Where(x => x.BusinessId == it.BusinessId).Select<BookingOrderUrlRes>().First()
)
.First();
//data.Urls = tenantDb.Queryable<BookingOrderUrl>().Where(x => x.BusinessId == data.BusinessId).Select<BookingOrderUrlRes>().First();
return DataResult<OpBusinessYardRes>.Success(data, MultiLanguageConst.DataQuerySuccess);
}
public DataResult<OpBusinessYardRes> GetBusinessYardByKeyId(string id)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var data = tenantDb.Queryable<BusinessYard>()
.Where(a => a.BusinessId == long.Parse(id))
.Select<OpBusinessYardRes>()
.Mapper(it =>
{
it.Urls = tenantDb.Queryable<BookingOrderUrl>().Where(x => x.BusinessId == it.BusinessId).Select<BookingOrderUrlRes>().First();
it.Contacts = tenantDb.Queryable<BusinessOrderContact>().Where(x => x.BusinessId == it.BusinessId && x.CustomerType == "controller")
.Select<BusinessOrderContactRes>().ToList();
}
)
.First();
if (data.IsNull())
{
data = new OpBusinessYardRes();
data.Contacts = tenantDb.Queryable<BusinessOrderContact>().Where(x => x.BusinessId == long.Parse(id) && x.CustomerType == "controller")
.Select<BusinessOrderContactRes>().ToList();
}
return DataResult<OpBusinessYardRes>.Success(data, MultiLanguageConst.DataQuerySuccess);
}
public DataResult BatchDelOpBusinessYard(IdModel req)
{
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var list = tenantDb.Queryable<BusinessYard>().Where(x => req.Ids.Contains(x.Id)).ToList();
if (list.Count > 0)
{
tenantDb.Deleteable(list).ExecuteCommand();
}
return DataResult.Successed("删除成功!", MultiLanguageConst.DataDelSuccess);
}
public async Task<DataResult<string>> SendLetterYard(SendShippingOrderReq req)
{
var tenant = db.Queryable<SysTenant>().FirstAsync(t => t.Id == long.Parse(user.TenantId));
var tenantDb = saasService.GetBizDbScopeById(user.TenantId);
var bookingId = req.BookingId;
var letterYard = await tenantDb.Queryable<BusinessYard>().FirstAsync(x => x.BusinessId == bookingId);
if (letterYard.IsNull())
{
return await Task.FromResult(DataResult<string>.Failed("放舱信息未找到,请先保存数据"));
}
if (string.IsNullOrEmpty(letterYard.ToAttnEmail))
{
return await Task.FromResult(DataResult<string>.Failed("ATTN MAIL未正确填写"));
}
if (string.IsNullOrEmpty(letterYard.FromEmail))
{
return await Task.FromResult(DataResult<string>.Failed("FROM MAIL未正确填写"));
}
var order = await tenantDb.Queryable<SeaExport>().FirstAsync(x => x.Id == bookingId);
var userMail = await tenantDb.Queryable<CodeUserEmail>().FirstAsync(x => x.CreateBy == long.Parse(user.UserId));
if (userMail == null)
{
return await Task.FromResult(DataResult<string>.Failed("未配置发件邮箱"));
}
if (string.IsNullOrEmpty(userMail.SmtpServer) || userMail.SmtpPort == 25)
{
return await Task.FromResult(DataResult<string>.Failed("请正确配置发件邮箱且发件不能使用25端口"));
}
var emailUrl = db.Queryable<SysConfig>().Filter(null, true).Where(x => x.Code == "email_api_url" && x.TenantId == 1288018625843826688).First().Value;
if (emailUrl == null)
{
return await Task.FromResult(DataResult<string>.Failed("系统参数未配置email_api_url 请联系管理员"));
}
//处理附件
var attPostArr = new List<dynamic>();
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<string>.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<string>.Failed(jRtn.GetStringValue("Message")));
}
//return await Task.FromResult(DataResult<string>.Success(jRtn.GetStringValue("Message")));
//设置货物状态-放舱
await seaComService.SetGoodsStatus("YFC", bookingId, tenantDb);
return await Task.FromResult(DataResult<string>.Success("发送成功"));
}
}
}