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.
BookingHeChuan/Myshipping.Application/Service/TaskManagePlat/TaskCautionNoticeService.cs

275 lines
13 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 Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Myshipping.Application.Entity;
using Myshipping.Application.Service.TaskManagePlat.Interface;
using Myshipping.Core.Service;
using Myshipping.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Furion.FriendlyException;
using Myshipping.Core.Entity;
using Furion.JsonSerialization;
using Furion.RemoteRequest.Extensions;
using Newtonsoft.Json;
using System.IO;
using System.Net.Http;
using Myshipping.Core.Helper;
using NPOI.SS.Formula.Functions;
using System.Reflection.Metadata;
using Furion;
using Myshipping.Application.Helper;
namespace Myshipping.Application
{
/// <summary>
/// 重要提醒任务
/// </summary>
[ApiDescriptionSettings("Application", Name = "TaskCautionNotice", Order = 10)]
public class TaskCautionNoticeService : ITaskCautionNoticeService, IDynamicApiController, ITransient
{
private readonly ISysCacheService _cache;
private readonly ILogger<TaskCautionNoticeService> _logger;
private readonly SqlSugarRepository<TaskBaseInfo> _taskBaseRepository;
private readonly SqlSugarRepository<TaskCautionNoticeInfo> _taskCautionNoticeInfoRepository;
private readonly SqlSugarRepository<TaskCautionNoticeDetailInfo> _taskCautionNoticeDetailInfoRepository;
private readonly SqlSugarRepository<DjyUserMailAccount> _djyUserMailAccount;
public TaskCautionNoticeService(ISysCacheService cache, ILogger<TaskCautionNoticeService> logger,
SqlSugarRepository<TaskBaseInfo> taskBaseRepository,
SqlSugarRepository<TaskCautionNoticeInfo> taskCautionNoticeInfoRepository,
SqlSugarRepository<TaskCautionNoticeDetailInfo> taskCautionNoticeDetailInfoRepository,
SqlSugarRepository<DjyUserMailAccount> djyUserMailAccount)
{
_cache = cache;
_logger = logger;
_taskBaseRepository = taskBaseRepository;
_taskCautionNoticeInfoRepository = taskCautionNoticeInfoRepository;
_taskCautionNoticeDetailInfoRepository = taskCautionNoticeDetailInfoRepository;
_djyUserMailAccount = djyUserMailAccount;
}
#region 获取重要提醒任务详情
/// <summary>
/// 获取重要提醒任务详情
/// </summary>
/// <param name="taskPkId">重要提醒任务主键</param>
/// <returns>返回详情</returns>
[HttpGet("/TaskCautionNotice/GetInfoByTaskId")]
public async Task<TaskCautionNoticeShowDto> GetInfoByTaskId(string taskPkId)
{
TaskCautionNoticeShowDto dto = new TaskCautionNoticeShowDto();
var taskBase = _taskBaseRepository.AsQueryable().First(a => a.PK_ID == taskPkId);
if (taskBase == null)
throw Oops.Oh($"任务主键{taskPkId}无法获取业务信息");
var noticeInfo = _taskCautionNoticeInfoRepository.AsQueryable().First(a => a.TASK_ID == taskBase.PK_ID);
if (noticeInfo == null)
throw Oops.Oh($"重要提醒主键{taskPkId}无法获取业务信息");
CautionNoticeTaskEnum cautionNoticeEnum = (CautionNoticeTaskEnum)System.Enum.Parse(typeof(CautionNoticeTaskEnum), noticeInfo.CAUTION_NOTICE_TYPE);
dto = new TaskCautionNoticeShowDto
{
PKId = noticeInfo.PK_ID,
taskPKId = noticeInfo.TASK_ID,
carrier = noticeInfo.CARRIER,
bookingId = noticeInfo.BOOKING_ID,
mblNo = noticeInfo.MBL_NO,
createTime = noticeInfo.CreatedTime,
cautionNoticeType = noticeInfo.CAUTION_NOTICE_TYPE,
cautionNoticeTypeName = cautionNoticeEnum.GetDescription(),
origVal = noticeInfo.OLD_VAL,
newVal = noticeInfo.NEW_VAL
};
return dto;
}
#endregion
#region 触发推送消息
/// <summary>
/// 触发推送消息
/// </summary>
/// <param name="taskPKId">重要提醒任务主键</param>
/// <param name="tenantId">租户ID</param>
/// <returns>返回回执</returns>
[HttpGet("/TaskCautionNotice/TriggerSendNotice")]
public async Task<TaskManageOrderResultDto> TriggerSendNotice(string taskPKId, long tenantId)
{
TaskManageOrderResultDto result = new TaskManageOrderResultDto();
try
{
TaskDraftShowDto dto = new TaskDraftShowDto();
var taskBase = _taskBaseRepository.AsQueryable().Filter(null, true).First(a => a.PK_ID == taskPKId && a.IsDeleted == false && a.TenantId == tenantId);
if (taskBase == null)
throw Oops.Oh($"任务主键{taskPKId}无法获取业务信息");
var noticeInfo = _taskCautionNoticeInfoRepository.AsQueryable().Filter(null, true).First(a => a.TASK_ID == taskBase.PK_ID && a.IsDeleted == false && a.TenantId == tenantId);
var list = _taskCautionNoticeDetailInfoRepository.AsQueryable().Filter(null, true)
.Where(a => a.P_ID == noticeInfo.PK_ID && a.IsDeleted == false && a.TenantId == tenantId).ToList();
TaskBusiTypeEnum currEnum = (TaskBusiTypeEnum)System.Enum.Parse(typeof(TaskBusiTypeEnum), taskBase.TASK_TYPE);
CautionNoticeTaskEnum cautionNoticeEnum = (CautionNoticeTaskEnum)System.Enum.Parse(typeof(CautionNoticeTaskEnum), noticeInfo.CAUTION_NOTICE_TYPE);
if (list.Count > 0)
{
list.ForEach(a => {
if (a.NOTIFY_METHOD == CautionNoticeMethodEnum.Email.ToString())
{
if (!string.IsNullOrWhiteSpace(a.NOTIFY_EMAIL))
{
//提取当前公共邮箱的配置
DjyUserMailAccount publicMailAccount = _djyUserMailAccount.AsQueryable().Filter(null, true).First(x => x.TenantId == tenantId && x.ShowName == "PublicSend"
&& x.SmtpPort > 0 && x.SmtpServer != null && x.SmtpServer != "");
if (publicMailAccount == null)
{
//throw Oops.Oh($"提取公共邮箱配置失败请在用户邮箱账号管理增加配置显示名为PublicSend或者配置个人邮箱");
_logger.LogInformation($"准备邮件通知通知给 uid={a.NOTIFY_USER_NAME} name={a.NOTIFY_USER_NAME},但是没有配置发送邮箱");
new EmailNoticeHelper().SendEmailNotice($"MBLNO={noticeInfo.MBL_NO} {cautionNoticeEnum.GetDescription()} 需要给推送邮件但是没有配公司邮箱", $"MBLNO={noticeInfo.MBL_NO} {cautionNoticeEnum.GetDescription()} 需要给推送邮件但是没有配公司邮箱", App.Configuration["EmailNoticeDefaultUser"].GetUserEmailList());
}
EmailApiUserDefinedDto emailApiUserDefinedDto = new EmailApiUserDefinedDto
{
SendTo = a.NOTIFY_EMAIL,
Title = $"提单号:{noticeInfo.MBL_NO} {cautionNoticeEnum.GetDescription()}",
Body = $"提单号:{noticeInfo.MBL_NO} {cautionNoticeEnum.GetDescription()} {noticeInfo.NOTIFY_CONTENT}",
Account = publicMailAccount.MailAccount?.Trim(),
Password = publicMailAccount.Password?.Trim(),
Server = publicMailAccount.SmtpServer?.Trim(),
Port = publicMailAccount.SmtpPort.HasValue ? publicMailAccount.SmtpPort.Value : 465,
UseSSL = publicMailAccount.SmtpSSL.HasValue ? publicMailAccount.SmtpSSL.Value : true,
Attaches = new List<AttachesInfo>()
};
_logger.LogInformation($"生成请求邮件参数,结果:{JSON.Serialize(emailApiUserDefinedDto)}");
//推送邮件
var emailRlt = PushEmail(emailApiUserDefinedDto).GetAwaiter().GetResult();
_logger.LogInformation($"推送邮件完成,结果:{JSON.Serialize(emailRlt)}");
a.STATUS = emailRlt.succ ? "SUCC" : "FAILURE";
a.STATUS_NAME = emailRlt.succ ? "成功" : "失败";
_taskCautionNoticeDetailInfoRepository.AsUpdateable(a).UpdateColumns(p => new
{
p.STATUS,
p.STATUS_NAME
}).ExecuteCommand();
}
}
else if (a.NOTIFY_METHOD == CautionNoticeMethodEnum.DingDing.ToString())
{
_logger.LogInformation($"准备钉钉通知给 uid={a.NOTIFY_USER_NAME} name={a.NOTIFY_USER_NAME},内容:\r\n{noticeInfo.NOTIFY_CONTENT}");
DingTalkGroupHelper.SendDingTalkGroupMessage($"{taskBase.TenantId}_Notify", cautionNoticeEnum.GetDescription(), $"{noticeInfo.NOTIFY_CONTENT}\r\n{a.NOTIFY_USER_NAME}", false, new string[] { a.NOTIFY_MOBILE }, null);
_logger.LogInformation($"钉钉通知完毕给 uid={a.NOTIFY_USER_NAME} name={a.NOTIFY_USER_NAME},内容:\r\n{noticeInfo.NOTIFY_CONTENT}");
a.STATUS = "SUCC";
a.STATUS_NAME = "成功";
_taskCautionNoticeDetailInfoRepository.AsUpdateable(a).UpdateColumns(p => new
{
p.STATUS,
p.STATUS_NAME
}).ExecuteCommand();
}
});
}
}
catch (Exception ex)
{
new EmailNoticeHelper().SendEmailNotice($"taskPKId={taskPKId} 有重要提醒任务发生异常", $"taskPKId={taskPKId} 有重要提醒任务发生异常 原因:{ex.Message}", App.Configuration["EmailNoticeDefaultUser"].GetUserEmailList());
}
return result;
}
#endregion
#region 推送邮件
/// <summary>
/// 推送邮件
/// </summary>
/// <param name="emailApiUserDefinedDto">自定义邮件详情</param>
/// <param name="filePath">文件路径</param>
/// <returns>返回回执</returns>
private async Task<CommonWebApiResult> PushEmail(EmailApiUserDefinedDto emailApiUserDefinedDto)
{
CommonWebApiResult result = new CommonWebApiResult { succ = true };
List<EmailApiUserDefinedDto> emailList = new List<EmailApiUserDefinedDto>();
var emailUrl = _cache.GetAllDictData().GetAwaiter().GetResult()
.FirstOrDefault(x => x.TypeCode == "url_set" && x.Code == "email_api_url")?.Value;
if (emailUrl == null)
throw Oops.Bah("字典未配置 url_set->email_api_url 请联系管理员");
emailList.Add(emailApiUserDefinedDto);
//string strJoin = System.IO.File.ReadAllText(filePath);
DateTime bDate = DateTime.Now;
HttpResponseMessage res = null;
try
{
res = await emailUrl.SetBody(emailList, "application/json").PostAsync();
}
catch (Exception ex)
{
_logger.LogInformation($"发送邮件异常:{ex.Message}");
}
DateTime eDate = DateTime.Now;
TimeSpan ts = eDate.Subtract(bDate);
var timeDiff = ts.TotalMilliseconds;
_logger.LogInformation($"邮件上传完成 用时:{timeDiff}ms.,");
_logger.LogInformation($"发送邮件返回:{JSON.Serialize(res)}");
if (res != null && res.StatusCode == System.Net.HttpStatusCode.OK)
{
var userResult = await res.Content.ReadAsStringAsync();
var respObj = JsonConvert.DeserializeAnonymousType(userResult, new
{
Success = false,
Message = string.Empty,
Code = -9999,
});
result.succ = respObj.Success;
result.msg = respObj.Message;
}
return result;
}
#endregion
}
}