修改邮件账单

dev
jianghaiqing 3 weeks ago
parent b8cede28ce
commit 8ab68fd1ad

@ -0,0 +1,187 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using DS.Module.Core.Helpers;
using DS.WMS.Core.Op.Dtos;
using DS.Module.Core;
namespace DS.WMS.FeeBillRecvService
{
public class EmailNoticeHelper
{
#region 发送邮件(内部方法)
/// <summary>
/// 发送邮件(内部方法)
/// </summary>
/// <param name="emailList">邮件详情列表</param>
/// <returns>返回回执</returns>
public async Task<CommonWebApiResult> InnerSendEmailNotice(List<EmailApiDto> emailList)
{
string emailUrl = string.Empty;
CommonWebApiResult result = new CommonWebApiResult();
//ILogger<RecvFeeBillWorker> logger
//日志
NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
DateTime bDate = DateTime.Now;
try
{
emailUrl = AppSetting.app(new string[] { "FeeSettings", "ExchangeName" });
//var res = await emailUrl.SetBody(emailList, "application/json").PostAsync();
var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(emailList, Formatting.Indented, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
var rlt = RequestHelper.Post(jsonBody, emailUrl);
DateTime eDate = DateTime.Now;
TimeSpan ts = eDate.Subtract(bDate);
var timeDiff = ts.TotalMilliseconds;
_logger.Log(NLog.LogLevel.Info, $"邮件上传完成 用时:{timeDiff}ms.发送邮件返回:{JsonConvert.SerializeObject(rlt)}");
if (!string.IsNullOrWhiteSpace(rlt))
{
var respObj = JsonConvert.DeserializeAnonymousType(rlt, new
{
Success = false,
Message = string.Empty,
Code = -9999,
});
result.succ = respObj.Success;
result.msg = respObj.Message;
}
}
catch (Exception ex)
{
_logger.Log(NLog.LogLevel.Info, $"发送邮件异常:{ex.Message}");
result.succ = false;
result.msg = $"发送邮件异常:{ex.Message}";
}
return result;
}
#endregion
#region 发送邮件
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="title">标题</param>
/// <param name="content">内容</param>
/// <param name="userEmailList">接收人列表</param>
/// <returns></returns>
public async Task<CommonWebApiResult> SendEmailNotice(string title, string content, List<string> userEmailList)
{
List<EmailApiDto> list = new List<EmailApiDto>();
if (userEmailList.Count == 0)
return new CommonWebApiResult { succ = false };
EmailApiDto dto = new EmailApiDto
{
SendTo = string.Join(";", userEmailList.ToArray()),
Title = title,
Body = content,
Attaches = new List<AttachesInfo>(),
};
list.Add(dto);
return await InnerSendEmailNotice(list);
}
#endregion
}
public class EmailApiDto
{
public string SendTo { get; set; }
//public string CCTo { get; set; }
public string Title { get; set; }
public string Body { get; set; }
//public string ShowName { get; set; }
public string SmtpConfig { get; set; } = "NOREPLAY";
//public string Account { get; set; }
//public string Password { get; set; }
//public string Server { get; set; }
//public string Port { get; set; }
//public string UseSSL { get; set; }
public bool isCallback { get; set; } = false;
public List<AttachesInfo> Attaches { get; set; }
}
public class AttachesInfo
{
public string AttachName { get; set; }
public string AttachContent { get; set; }
}
/// <summary>
/// 通用WebApi返回回执
/// </summary>
public class CommonWebApiResult
{
/// <summary>
/// 是否成功 true=成功 false=失败
/// </summary>
public bool succ { get; set; } = false;
/// <summary>
/// 状态 0-成功
/// </summary>
public int status { get; set; } = 0;
/// <summary>
/// 返回消息
/// </summary>
public string msg { get; set; }
/// <summary>
/// 总记录数
/// </summary>
public int total { get; set; }
/// <summary>
/// 当前页列表数据
/// </summary>
public object rows { get; set; }
/// <summary>
/// 合计信息
/// </summary>
public object summary { get; set; }
/// <summary>
/// 扩展信息
/// </summary>
public object extra { get; set; }
/// <summary>
/// 扩展信息2
/// </summary>
public object extra2 { get; set; }
}
}

@ -6,6 +6,7 @@ using System.Threading.Tasks;
using DS.Module.Core; using DS.Module.Core;
using DS.Module.Core.Data; using DS.Module.Core.Data;
using DS.Module.Core.Helpers; using DS.Module.Core.Helpers;
using DS.Module.MQ;
using DS.Module.SqlSugar; using DS.Module.SqlSugar;
using DS.Module.UserModule; using DS.Module.UserModule;
using DS.WMS.Core.Fee.Entity; using DS.WMS.Core.Fee.Entity;
@ -126,6 +127,7 @@ namespace DS.WMS.FeeBillRecvService
string msg = string.Empty; string msg = string.Empty;
string gid = string.Empty;
try try
{ {
var model = GetInfo(json, out msg); var model = GetInfo(json, out msg);
@ -153,19 +155,33 @@ namespace DS.WMS.FeeBillRecvService
string blno = model.BookingBill?.Trim(); string blno = model.BookingBill?.Trim();
gid = model.GID?.Trim();
_logger.LogInformation($"提取订单信息 GID={model.GID} BookingBill={model.BookingBill}"); _logger.LogInformation($"提取订单信息 GID={model.GID} BookingBill={model.BookingBill}");
var booking = tenantDb.Queryable<SeaExport>().ClearFilter(typeof(IOrgId)).First(a => a.MBLNO == blno && a.Deleted == false && (a.IsRefund == null || a.IsRefund.Value == false) var booking = tenantDb.Queryable<SeaExport>().ClearFilter(typeof(IOrgId)).First(a => a.MBLNO == blno && a.Deleted == false && (a.IsRefund == null || a.IsRefund.Value == false)
&& (a.IsChangeETD == null || a.IsChangeETD.Value == false)); && (a.IsChangeETD == null || a.IsChangeETD.Value == false));
var ctnList = tenantDb.Queryable<OpCtn>().ClearFilter(typeof(IOrgId)).Where(a => a.BSNO == booking.Id.ToString() && a.Deleted == false).ToList(); _logger.LogInformation($"提取订单完成 GID={model.GID} BookingBill={model.BookingBill} Order={JsonConvert.SerializeObject(booking)}");
if (booking != null && booking.IsFeeLocking.HasValue && booking.IsFeeLocking.Value)
{
SendCallBack(new SingleBillReceiveResult
{
ReceiveId = model.GID,
Success = false,
Reason = "订单费用已锁定"
});
_logger.LogInformation($"提取订单完成 GID={model.GID} BookingBill={model.BookingBill} Order={JsonConvert.SerializeObject(booking)}"); _logger.LogInformation($"提取订单完成 GID={model.GID} BookingBill={model.BookingBill} id={booking.Id}");
return;
}
if (booking != null) if (booking != null)
{ {
var ctnList = tenantDb.Queryable<OpCtn>().ClearFilter(typeof(IOrgId)).Where(a => a.BSNO == booking.Id.ToString() && a.Deleted == false).ToList();
DateTime etd = DateTime.MinValue; DateTime etd = DateTime.MinValue;
if (booking.ETD.HasValue) if (booking.ETD.HasValue)
@ -187,18 +203,66 @@ namespace DS.WMS.FeeBillRecvService
int start = 1; int start = 1;
//需要先全部费用跟库匹配,存在不匹配的,终止整个入库
Dictionary<string, Tuple<string, bool>> doResultDict = new Dictionary<string, Tuple<string, bool>>();
var checkFeeArg = model.DetailList.Select(f=>f.CustSysName).Distinct().ToList();
string reason = string.Empty;
bool isStop = false;
bool isNoNotice = false;
if (checkFeeArg.Any(x => string.IsNullOrWhiteSpace(x)))
{
isStop = true;
reason = "费用名称不能为空";
//new EmailNoticeHelper().SendEmailNotice("")
isNoNotice = true;
}
var queryFeeList = tenantDb.Queryable<FeeCode>().Where(x => checkFeeArg.Contains(x.Name) && x.IsSea == true).ToList();
if(queryFeeList.Count == 0)
{
isStop = true;
reason = $"费用名称不存在,{(string.Join(",", checkFeeArg))}";
isNoNotice = true;
}
else
{
var checkRlt = checkFeeArg.GroupJoin(queryFeeList, l => l, r => r.Name, (l, r) =>
{
var currFee = r.FirstOrDefault();
if (currFee == null)
return new { Succ = false, Obj = l };
return new { Succ = true, Obj = l };
}).ToList();
if (checkRlt.Any(b => !b.Succ))
{
isStop = true;
reason = "费用名称不存在," + string.Join(",", checkRlt.Where(b => !b.Succ).Select(b => b.Obj).ToArray());
isNoNotice = true;
}
}
if (!isStop)
{
foreach (var fee in model.DetailList) foreach (var fee in model.DetailList)
{ {
string qFee = fee.CustSysName?.Trim(); string qFee = fee.CustSysName?.Trim();
//if(string.IsNullOrWhiteSpace(qFee)) try
//{ {
// errorMsgList.Add("没有费用名称");
// continue;
//}
var feecode = tenantDb.Queryable<FeeCode>().First(x => x.Name == qFee); var feecode = tenantDb.Queryable<FeeCode>().First(x => x.Name == qFee && x.IsSea == true);
if (feecode == null) if (feecode == null)
{ {
@ -318,7 +382,7 @@ namespace DS.WMS.FeeBillRecvService
.First(x => x.CurrencyCode == newfee.Currency && x.OrgId == booking.OrgId .First(x => x.CurrencyCode == newfee.Currency && x.OrgId == booking.OrgId
&& x.StartDate.Value <= etd && x.EndDate.Value >= etd && x.LocalCurrency == "RMB"); && x.StartDate.Value <= etd && x.EndDate.Value >= etd && x.LocalCurrency == "RMB");
if(exchangeInfo == null) if (exchangeInfo == null)
{ {
exchangeInfo = tenantDb.Queryable<FeeCurrencyExchange>().ClearFilter(typeof(IOrgId)) exchangeInfo = tenantDb.Queryable<FeeCurrencyExchange>().ClearFilter(typeof(IOrgId))
.First(x => x.CurrencyCode == newfee.Currency && x.StartDate.Value <= etd && x.EndDate.Value >= etd && x.LocalCurrency == "RMB"); .First(x => x.CurrencyCode == newfee.Currency && x.StartDate.Value <= etd && x.EndDate.Value >= etd && x.LocalCurrency == "RMB");
@ -350,34 +414,167 @@ namespace DS.WMS.FeeBillRecvService
_logger.LogInformation($"写入账单完成 第【{start}】条 GID={model.GID} BookingBill={model.BookingBill} Order={JsonConvert.SerializeObject(newfee)}"); _logger.LogInformation($"写入账单完成 第【{start}】条 GID={model.GID} BookingBill={model.BookingBill} Order={JsonConvert.SerializeObject(newfee)}");
//入库成功
doResultDict.Add(fee.GID, new Tuple<string, bool>(qFee, true));
}
catch (Exception ex)
{
doResultDict.Add(fee.GID, new Tuple<string, bool>(qFee, false));
_logger.LogInformation($"明细写入产生异常qFee={qFee} 原因:{ex.Message}");
}
//callbackList.Add() //callbackList.Add()
start++; start++;
} }
}
List<SingleBillReceiveResult> callbackList = new List<SingleBillReceiveResult>();
//如果存在失败情况,回执失败
if (doResultDict.Count(b => !b.Value.Item2) > 0)
{
reason = "入库失败," + string.Join(",", doResultDict.Where(b => !b.Value.Item2).ToArray());
SendCallBack(new SingleBillReceiveResult
{
ReceiveId = model.GID,
Success = false,
Reason = reason
});
}
else
{
//全部成功,推送成功回执
SendCallBack(new SingleBillReceiveResult
{
ReceiveId = model.GID,
Success = true,
Reason = string.Empty
});
}
}
else
{
if (!isNoNotice)
{
SendCallBack(new SingleBillReceiveResult
{
ReceiveId = model.GID,
Success = false,
Reason = reason
});
}
}
}
else
{
SendCallBack(new SingleBillReceiveResult
{
ReceiveId = model.GID,
Success = false,
Reason = "当前订单不存在"
});
}
}
catch (Exception ex)
{
_logger.LogInformation($"产生异常,原因:{ex.Message}");
//发送回执 if (!string.IsNullOrWhiteSpace(gid))
//var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(queryInfo, Formatting.Indented, new JsonSerializerSettings {
//SendCallBack(new SingleBillReceiveResult
//{ //{
// NullValueHandling = NullValueHandling.Ignore // ReceiveId = gid,
// Success = false,
// Reason = "当前订单不存在"
//}); //});
}
}
}
private void SendCallBack(SingleBillReceiveResult dto)
{
_logger.LogInformation($"开始准备发送回执MQ json={JsonConvert.SerializeObject(dto)}");
var mqRlt = PublishMessage(new MQPublishMessageReqDto
{
BusinessId = dto.ReceiveId,
IsZip = false,
json = JsonConvert.SerializeObject(dto),
mqUri = AppSetting.app(new string[] { "FeeCallBacSettings", "MQUrl" }),
mqExchangeName = AppSetting.app(new string[] { "FeeCallBacSettings", "ExchangeName" }),
mqQueueName = AppSetting.app(new string[] { "FeeCallBacSettings", "QueueName" })
}).GetAwaiter().GetResult();
_logger.LogInformation($"发送回执MQ完成结果 json={JsonConvert.SerializeObject(mqRlt)}");
}
#region 发送MQ报文
/// <summary>
/// 发送MQ报文
/// </summary>
/// <param name="request">请求参数</param>
/// <returns>true-发送成功 false-发送失败</returns>
public async Task<string> PublishMessage(MQPublishMessageReqDto request)
{
bool isException = false;
string msg = string.Empty;
try
{
ConnectionFactory factory = new ConnectionFactory();
factory.Uri = new Uri(request.mqUri);
using (IConnection conn = factory.CreateConnection())
{
try
{
IModel mqModel = conn.CreateModel();
mqModel.ExchangeDeclare(request.mqExchangeName, ExchangeType.Direct);
//var queueName = $"{MqActionQueueName}.{(item.SubTenantId.HasValue && item.SubTenantId > 0 ? item.SubTenantId.Value : item.TenantId)}";
mqModel.QueueDeclare(request.mqQueueName, false, false, false, null);
mqModel.QueueBind(request.mqQueueName, request.mqExchangeName, request.mqQueueName, null);
byte[] messageBodyBytes = Encoding.UTF8.GetBytes(request.json);
//_logger.LogInformation($"请求MSK API查询船期请求{jsonBody}");
//var rlt = RequestHelper.Post(jsonBody, AppSetting.app(new string[] { "FeeSettings", "CallBackUrl" })); IBasicProperties props = mqModel.CreateBasicProperties();
////var rlt = await queryUrl.SetBody(jsonBody).PostAsStringAsync(); props.DeliveryMode = 2;
mqModel.BasicPublish(request.mqExchangeName, request.mqQueueName, props, messageBodyBytes);
//_logger.LogInformation($"请求MSK API查询船期请求{jsonBody}");
_logger.LogInformation($"Id:{request.BusinessId},订舱数据回推,已发送数据到消息队列【{request.mqUri}】,队列名称:【{request.mqQueueName}】");
}
catch (Exception inne)
{
_logger.LogInformation($"Id:{request.BusinessId}推送MQ时发生异常原因:{inne.Message}");
msg = $"Id:{request.BusinessId}推送MQ时发生异常原因:{inne.Message}";
isException = true;
}
finally
{
conn.Close();
}
}
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogInformation($"产生异常,原因:{ex.Message}"); _logger.LogInformation($"Id:{request.BusinessId},启动推送MQ时发生异常原因:{ex.Message}");
msg = $"Id:{request.BusinessId},启动推送MQ时发生异常原因:{ex.Message}";
isException = true;
} }
if (isException)
return msg;
return string.Empty;
} }
#endregion
private FeeBillReadDto GetInfo(string json,out string msg) private FeeBillReadDto GetInfo(string json,out string msg)
{ {

@ -29,5 +29,12 @@
"QueueName": "billcenter.output.ds7new.444c19c1-0bf5-4709-a08b-c9859ca775e6", "QueueName": "billcenter.output.ds7new.444c19c1-0bf5-4709-a08b-c9859ca775e6",
"MQUrl": "amqp://dongsheng8bill:dongsheng8bill@47.104.207.5:12567/billcenter", "MQUrl": "amqp://dongsheng8bill:dongsheng8bill@47.104.207.5:12567/billcenter",
"CallBackUrl": "http://www.myshipping.net:8656/Booking/SingleBillFeedback" "CallBackUrl": "http://www.myshipping.net:8656/Booking/SingleBillFeedback"
},
"FeeCallBacSettings": {
"ExchangeName": "billcenter",
"QueueName": "billcenter.feedback.ds7",
"MQUrl": "amqp://dongsheng8bill:dongsheng8bill@47.104.207.5:12567/billcenter",
"EmailNoticeUrl": "jianghaiqing@myshipping.net;dongyihan@myshipping.net",
"DingDingUrl": "https://oapi.dingtalk.com/robot/send?access_token=3e9d02830e0b35e140a18af1378accc44a17fa345271e8e8d87cb9927b6adb41"
} }
} }

Loading…
Cancel
Save