短信服务

This commit is contained in:
tongfei
2024-03-29 15:15:43 +08:00
parent 2f224fcaf3
commit 806af3bb70
24 changed files with 829 additions and 93 deletions

View File

@@ -1,56 +0,0 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using WMS.Web.Domain.IService;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Aliyun.Acs.Core.Exceptions;
namespace WMS.Web.Domain.Services
{
/// <summary>
/// 阿里云短息服务
/// </summary>
public class AliyunSmsService: IAliyunSmsService
{
private readonly ILogger<AliyunSmsService> _logger;
private readonly IAcsClient profile;
public AliyunSmsService(ILogger<AliyunSmsService> logger, string accessKeyId, string accessKeySecret)
{
_logger = logger;
profile = new DefaultAcsClient(DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret));
}
public bool SendSms(string phoneNumbers, string templateCode, string signName, string templateParam = null)
{
SendSmsRequest request = new SendSmsRequest
{
PhoneNumbers = phoneNumbers,
SignName = signName,
TemplateCode = templateCode,
TemplateParam = templateParam
};
try
{
SendSmsResponse response = profile.GetAcsResponse(request);
return response.Code == "OK";
}
catch (ServerException ex)
{
// 处理服务端异常
Console.WriteLine(ex.Message);
}
catch (ClientException ex)
{
// 处理客户端异常
Console.WriteLine(ex.Message);
}
return false;
}
}
}

View File

@@ -183,7 +183,7 @@ namespace WMS.Web.Domain.Services.Public
//3.获取金蝶采购订单:拼接参数和条件
var query = new ErpBillQueryDto(token_result.Data);
var param = new ErpBillQueryParamDto(FormIdParam.PUR_PurchaseOrder.ToString());
param.FieldKeys = "FBillNo,FSupplierId,FPurchaseOrgId,FMaterialId.FNumber,FSOSTOCKID,FQty,FEntryNote,FCreateDate,FCHUCHANGPRICE,FSOSTOCKID.FNumber,FStockInQty,FPurchaseOrgId.FNumber,FPOOrderEntry_FEntryID,FDEMANDBILLNO";
param.FieldKeys = "FBillNo,FSupplierId,FPurchaseOrgId,FMaterialId.FNumber,FSOSTOCKID,FQty,FEntryNote,FCreateDate,FCHUCHANGPRICE,FSOSTOCKID.FNumber,FStockInQty,FPurchaseOrgId.FNumber,FPOOrderEntry_FEntryID,FDEMANDBILLNO,F_client.FNumber";
param.Limit = 10000;
//查询条件:备注其中的条件值以金蝶的值为准!!!
//1.创建时间在两天前和当天时间之间
@@ -263,6 +263,7 @@ namespace WMS.Web.Domain.Services.Public
lis.OrgCode = item[11];
lis.ErpDetailId = Convert.ToInt32(item[12]);
lis.SaleBillNo = item[13];
lis.CustomerCode = item[14];
lis.Type = (int)InstockType.Purchase;
erp_list.Add(lis);
}

View File

@@ -0,0 +1,249 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using WMS.Web.Domain.IService;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using Aliyun.Acs.Core.Exceptions;
using WMS.Web.Core.Internal.Results;
using System.Threading.Tasks;
using WMS.Web.Domain.Options;
using Microsoft.Extensions.Options;
using MimeKit;
using MailKit.Net.Smtp;
using MailKit.Security;
using Newtonsoft.Json;
using WMS.Web.Domain.Infrastructure;
using WMS.Web.Core.Dto;
using System.Linq;
using WMS.Web.Domain.IService.Public;
using WMS.Web.Core.Dto.Erp;
namespace WMS.Web.Domain.Services
{
/// <summary>
/// 阿里云短息服务
/// </summary>
public class SendMessageService: ISendMessageService
{
private readonly ILogger<SendMessageService> _logger;
private readonly IClientProfile profile;
private readonly DefaultAcsClient client;
private readonly EmailOptions _emailOptions;
private readonly SmsOptions _smsOptions;
private readonly IInStockRepositories _inStockRepositories;
private readonly IInStockTaskRepositories _inStockTaskRepositories;
private readonly IErpBasicDataExtendService _erpBasicDataExtendService;
private readonly ISubscribeNotificationRepositories _subscribeNotificationRepositories;
private readonly IErpService _erpService;
public SendMessageService(ILogger<SendMessageService> logger,
IOptions<EmailOptions> emailOptions,
IOptions<SmsOptions> smsOptions,
IInStockRepositories inStockRepositories,
IErpService erpService,
IErpBasicDataExtendService erpBasicDataExtendService,
IInStockTaskRepositories inStockTaskRepositories,
ISubscribeNotificationRepositories subscribeNotificationRepositories)
{
_logger = logger;
_erpService = erpService;
_inStockRepositories = inStockRepositories;
_erpBasicDataExtendService = erpBasicDataExtendService;
_inStockTaskRepositories = inStockTaskRepositories;
_subscribeNotificationRepositories = subscribeNotificationRepositories;
_emailOptions = emailOptions?.Value;
_smsOptions = smsOptions?.Value;
profile = DefaultProfile.GetProfile("cn-hangzhou", _smsOptions.AccessKeyId, _smsOptions.AccessKeySecret);
client = new DefaultAcsClient(profile);
}
/// <summary>
/// 短信发送
/// </summary>
/// <param name="phoneNumbers"></param>
/// <param name="content"></param>
/// <returns></returns>
public bool SendSms(string phoneNumbers, string content)
{
// 构造短信请求
SendSmsRequest request = new SendSmsRequest();
request.PhoneNumbers = phoneNumbers; // 目标手机号
request.SignName = _smsOptions.SignName; // 短信签名
request.TemplateCode = _smsOptions.TemplateCode; // 短信模板编号
request.TemplateParam = "{\"material\":\"" + content+"\"}"; // 模板参数,根据实际情况填写
try
{
// 发送短信
SendSmsResponse response = client.GetAcsResponse(request);
_logger.LogInformation("短信发送消息:成功->手机号码:" + phoneNumbers + " 内容:" + content);
return true;
}
catch (ServerException e)
{
_logger.LogInformation($"短信发送消息Server失败:{e.ErrorMessage}->手机号码:" + phoneNumbers + " 内容:" + content);
return false;
}
catch (ClientException e)
{
_logger.LogInformation($"短信发送消息Client失败:{e.ErrorMessage}->手机号码:" + phoneNumbers + " 内容:" + content);
return false;
}
}
/// <summary>
/// 邮箱发送消息
/// </summary>
/// <param name="toMailList"></param>
/// <param name="textBody"></param>
/// <returns></returns>
public async Task<Result> SendEmail(List<MailboxAddress> toMailList,string textBody)
{
// 创建 MimeMessage 实例
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress(_emailOptions.SenderName, _emailOptions.SenderEmail)); // 设置发件人姓名和邮箱地址
//message.To.Add(new MailboxAddress("Recipient Name", "244188119@qq.com")); // 设置收件人姓名和邮箱地址
message.To.AddRange(toMailList);
message.Subject = _emailOptions.SendTitle+$"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}"; // 设置邮件主题
// 创建邮件正文
BodyBuilder bodyBuilder = new BodyBuilder();
bodyBuilder.TextBody = textBody; // 设置纯文本内容
//bodyBuilder.HtmlBody = "<p>This is a <b>test</b> email sent from <i>.NETCore.MailKit</i>.lst</p>"; // 设置 HTML 内容
message.Body = bodyBuilder.ToMessageBody();
try
{
// 连接 SMTP 服务器并发送邮件
using (SmtpClient client = new SmtpClient())
{
await client.ConnectAsync(_emailOptions.SmtpServer, _emailOptions.SmtpPort, SecureSocketOptions.StartTls); // 连接 SMTP 服务器
await client.AuthenticateAsync(_emailOptions.SenderEmail, _emailOptions.SenderEmailPwd); // 进行身份验证
await client.SendAsync(message); // 发送邮件
await client.DisconnectAsync(true); // 断开连接
}
_logger.LogInformation("邮箱发送消息:成功->收件方:"+JsonConvert.SerializeObject(toMailList)+" 内容:"+textBody);
return Result.ReSuccess();
}
catch (Exception ex)
{
_logger.LogInformation("邮箱发送消息:失败->收件方:" + JsonConvert.SerializeObject(toMailList) + " 内容:" + textBody);
return Result.ReFailure("邮箱发送失败:"+ex.Message,50006);
}
}
/// <summary>
/// 获取数据
/// </summary>
/// <returns></returns>
public async Task<Result<List<SendDataDto>>> GetSendContent()
{
//1.获取物料集合和组织集合和供应商的集合
var materials = new List<ErpMaterialDto>();
var materials_result = await _erpService.BillQueryForMaterial();
if (materials_result.IsSuccess)
materials = materials_result.Data.ToList();
//客户
var customerList= await _subscribeNotificationRepositories.GetList();
//要处理发送的明细
var notSendDetails=await _inStockTaskRepositories.GetNotSendErpDetails();
var sendDataList = new List<SendDataDto>();
if (customerList != null && customerList.Count != 0)
{
if (notSendDetails != null && notSendDetails.Count != 0)
{
var taskIds= notSendDetails.GroupBy(x => x.Fid).Select(x => x.Key).ToList();
var instockTotalDetails= await _inStockRepositories.GetInStockTotalDetails(taskIds);
foreach (var item in customerList)
{
var current_notSendDetails= notSendDetails.Where(x => x.CustomerCode == item.CustomerNumber).ToList();
if (current_notSendDetails != null && current_notSendDetails.Count != 0)
{
var data = new SendDataDto();
data.CustomerCode = item.CustomerNumber;
data.CustomerName = item.CustomerName;
data.PhoneNumbers = string.Join(",", item.Telephones);
data.Emails= string.Join(",", item.Emails);
foreach (var ema in item.Emails)
{
data.EmailList.Add(new MailboxAddress("Recipient Name", ema));
}
foreach (var current_det in current_notSendDetails)
{
var det = new SendDataDetailsDto();
det.MaterialName = _erpBasicDataExtendService.GetMaterialName(materials, current_det.MaterialNumber);
det.Specifications = _erpBasicDataExtendService.GetMaterialSpecifications(materials, current_det.MaterialNumber);
det.MaterialNumber = current_det.MaterialNumber;
det.Qty=instockTotalDetails.Where(x => x.TaskId == current_det.Fid && x.MaterialNumber == current_det.MaterialNumber).Sum(x => x.Qty);
if (det.Qty > 0)
data.Details.Add(det);
}
if (data.Details.Count != 0)
sendDataList.Add(data);
}
}
}
}
return Result<List<SendDataDto>>.ReSuccess(sendDataList);
}
/// <summary>
/// 执行
/// </summary>
/// <returns></returns>
public async Task<Result> Execute()
{
try
{
var sendContentList_result = await this.GetSendContent();
if (sendContentList_result.IsSuccess)
{
var sendContentList = sendContentList_result.Data;
if (sendContentList != null && sendContentList.Count != 0)
{
foreach (var item in sendContentList)
{
var content = "";
int i = 1;
foreach (var det in item.Details)
{
if (i == item.Details.Count)
content = det.Specifications + " X 数量" + det.Qty;
else
content = det.Specifications + " X 数量" + det.Qty + "";
i = i + 1;
}
//邮箱
await this.SendEmail(item.EmailList, content);
//短信
this.SendSms(item.PhoneNumbers, content);
}
}
}
return Result.ReSuccess();
}
catch (Exception ex)
{
return Result.ReFailure("发送失败:"+ex.Message,50006);
}
}
}
}