Browse Source

体检报告短信推送

master
wxd 1 year ago
parent
commit
a2f882d1ed
  1. 93
      src/Shentun.ColumnReferencePlugIns/Sms/CreateSmsTaskDto.cs
  2. 194
      src/Shentun.ColumnReferencePlugIns/Sms/SmsPlugIns.cs
  3. 84
      src/Shentun.Peis.Application/TransToWebPeis/TransToWebPeisAppService.cs
  4. 3
      src/Shentun.Peis.Domain.Shared/Enums/ThirdInterfaceTypeFlag.cs
  5. 2
      src/Shentun.Peis.Domain/Shentun.Peis.Domain.csproj
  6. 5
      src/Shentun.Peis.HttpApi.Host/appsettings.json

93
src/Shentun.ColumnReferencePlugIns/Sms/CreateSmsTaskDto.cs

@ -0,0 +1,93 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shentun.Peis.PlugIns.Sms
{
public class CreateSmsTaskDto
{
/// <summary>
/// 短信类别ID
/// </summary>
public Guid SmsTypeId { get; set; }
/// <summary>
/// 人员ID
/// </summary>
public string PersonId { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string PersonName { get; set; }
/// <summary>
/// 手机号国家代码
/// </summary>
public string CountryCode { get; set; }
/// <summary>
/// 手机号
/// </summary>
public string MobileTelephone { get; set; }
/// <summary>
/// 短信内容
/// </summary>
public string Content { get; set; }
/// <summary>
/// 应用ID
/// </summary>
public Guid SmsAppId { get; set; }
/// <summary>
/// 第三方系统唯一ID
/// </summary>
public string? ThirdId { get; set; }
/// <summary>
/// 任务周期类别
/// </summary>
public char TaskCycleType { get; set; }
/// <summary>
/// 任务表达式
/// </summary>
public string? TaskCorn { get; set; }
/// <summary>
/// 停止执行时间
/// </summary>
public string? StopTime { get; set; }
///// <summary>
///// 是否启用
///// </summary>
//public char IsActive { get; set; } = 'Y';
/// <summary>
/// 发送者用户ID
/// </summary>
public string? SenderId { get; set; }
/// <summary>
/// 发送者用户名
/// </summary>
public string? SenderName { get; set; }
/// <summary>
/// 短信模板ID
/// </summary>
public string TemplateId { get; set; }
}
}

194
src/Shentun.ColumnReferencePlugIns/Sms/SmsPlugIns.cs

@ -0,0 +1,194 @@
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace Shentun.Peis.PlugIns.Sms
{
public class SmsPlugIns : ThirdPlugInsBase
{
private string _smsUser;
private string _smsPassword;
private string _smsBaseAddress;
private static string _smsToken;
public SmsPlugIns(Guid thirdInterfaceId) : base(thirdInterfaceId)
{
var configurationBuilder = new ConfigurationBuilder()
.AddJsonStream(new MemoryStream(Encoding.UTF8.GetBytes(_thirdInterfaceDto.ParmValue)));
InterfaceConfig = configurationBuilder.Build();
_smsUser = InterfaceConfig.GetSection("Interface").GetSection("User").Value;
_smsPassword = InterfaceConfig.GetSection("Interface").GetSection("Password").Value;
_smsBaseAddress = InterfaceConfig.GetSection("Interface").GetSection("BaseAddress").Value;
}
public async Task<TOut> CallSmsAppServiceAsync<TInput, TOut>(string url, TInput data, string method = "post")
{
//if (string.IsNullOrWhiteSpace(_webPeisBaseAddress))
//{
// throw new Exception("_webPeisBaseAddress不能为空");
//}
string baseAddress = _smsBaseAddress;
await CheckSmsLoginAsync();
using (var httpClientHandler = new HttpClientHandler())
{
using (var httpClient = new HttpClient(httpClientHandler))
{
httpClient.BaseAddress = new Uri(baseAddress);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _smsToken);
IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
var sendData = JsonConvert.SerializeObject(data, Formatting.Indented, timeFormat);
using (HttpContent httpContent = new StringContent(sendData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = null;
if (method == "post")
{
response = await httpClient.PostAsync(url, httpContent);
}
else
{
response = await httpClient.GetAsync(url);
}
string result;
if (!response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
}
result = await response.Content.ReadAsStringAsync();
var resultDto = JsonConvert.DeserializeObject<WebApiOutDto<TOut>>(result);
if (resultDto != null)
{
if (resultDto.Code == -1)
{
throw new Exception($"调用WebApi失败,返回-1,消息:" + resultDto.Message);
}
return resultDto.Data;
}
return resultDto.Data;
}
}
}
}
private async Task CheckSmsLoginAsync()
{
if (string.IsNullOrWhiteSpace(_smsToken))
{
await LoginSmsAsync();
}
else
{
var handler = new JwtSecurityTokenHandler();
var payload = handler.ReadJwtToken(_smsToken).Payload;
var claims = payload.Claims;
var exp = claims.First(claim => claim.Type == "exp").Value;
if (exp == null)
{
await LoginSmsAsync();
}
else
{
if (long.TryParse(exp, out var expires))
{
var expireTime = DateTimeOffset.FromUnixTimeSeconds(expires).LocalDateTime;
if (expireTime <= DateTime.Now)
{
await LoginSmsAsync();
}
}
else
{
await LoginSmsAsync();
}
}
}
}
private async Task<WebApiOutDto<LoginOutDataDto>> LoginSmsAsync()
{
if (string.IsNullOrWhiteSpace(_smsUser))
{
throw new Exception("WebPeisUser不能为空");
}
if (string.IsNullOrWhiteSpace(_smsPassword))
{
throw new Exception("WebPeisPassword不能为空");
}
var relult = await LoginSmsAsync(_smsUser, _smsPassword);
return relult;
}
private async Task<WebApiOutDto<LoginOutDataDto>> LoginSmsAsync(string userId, string password)
{
if (string.IsNullOrWhiteSpace(userId))
{
throw new Exception("用户ID不能为空");
}
if (string.IsNullOrWhiteSpace(password))
{
throw new Exception("密码不能为空");
}
using (var httpClientHandler = new HttpClientHandler())
{
using (var httpClient = new HttpClient(httpClientHandler))
{
httpClient.BaseAddress = new Uri(_smsBaseAddress);
httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
var url = "api/app/CustomerUser/UserLogin";
var loginUser = new LoginInputDto()
{
UserName = userId,
Password = password
};
var sendData = JsonConvert.SerializeObject(loginUser);
using (HttpContent httpContent = new StringContent(sendData))
{
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
string result;
if (!response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
}
result = await response.Content.ReadAsStringAsync();
var restultDto = JsonConvert.DeserializeObject<WebApiOutDto<LoginOutDataDto>>(result);
if (restultDto == null)
{
throw new Exception("返回结果是空");
}
if (restultDto.Code != 1)
{
throw new Exception($"登录失败{restultDto.Message}");
}
_smsToken = restultDto.Data.access_token;
return restultDto;
}
}
}
}
}
}

84
src/Shentun.Peis.Application/TransToWebPeis/TransToWebPeisAppService.cs

@ -34,6 +34,8 @@ using Volo.Abp.Uow;
using Shentun.Peis.PrintReports;
using System.Threading;
using NPOI.HSSF.Record.Chart;
using System.IdentityModel.Tokens.Jwt;
using Shentun.Peis.PlugIns.Sms;
namespace Shentun.Peis.TransToWebPeis
{
@ -59,7 +61,8 @@ namespace Shentun.Peis.TransToWebPeis
private readonly IRepository<PatientRegisterExter> _patientRegisterExterRepository;
private readonly UnitOfWorkManager _unitOfWorkManager;
private readonly PrintReportAppService _printReportAppService;
private readonly IConfiguration _configuration;
private readonly IRepository<Patient, Guid> _patientRepository;
private readonly SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
{
@ -93,7 +96,9 @@ namespace Shentun.Peis.TransToWebPeis
IRepository<RegisterCheck, Guid> registerCheckRepository,
IRepository<PatientRegisterExter> patientRegisterExterRepository,
UnitOfWorkManager unitOfWorkManager,
PrintReportAppService printReportAppService)
PrintReportAppService printReportAppService,
IConfiguration configuration,
IRepository<Patient, Guid> patientRepository)
{
_itemTypeRepository = itemTypeRepository;
_logger = logger;
@ -112,6 +117,8 @@ namespace Shentun.Peis.TransToWebPeis
_patientRegisterExterRepository = patientRegisterExterRepository;
_unitOfWorkManager = unitOfWorkManager;
_printReportAppService = printReportAppService;
_configuration = configuration;
_patientRepository = patientRepository;
}
@ -156,7 +163,8 @@ namespace Shentun.Peis.TransToWebPeis
patientRegisterEnt.IsUpload = 'Y';
await _patientRegisterRepository.UpdateAsync(patientRegisterEnt);
//推送短信
await PushSmsAsync(patientRegisterEnt);
}
/// <summary>
@ -1532,5 +1540,75 @@ namespace Shentun.Peis.TransToWebPeis
#endregion
/// <summary>
/// 测试短信
/// </summary>
/// <returns></returns>
[HttpPost("api/app/TransToWebPeis/TestSms")]
public async Task TestSmsAsync(Guid patientRegisterId)
{
//推送短信
var patientRegister = await _patientRegisterRepository.FirstOrDefaultAsync(f => f.Id == patientRegisterId);
await PushSmsAsync(patientRegister);
}
/// <summary>
/// 推送体检报告通知短信
/// </summary>
/// <param name="patientRegister"></param>
/// <returns></returns>
private async Task PushSmsAsync(PatientRegister patientRegister)
{
var smsThirdInterface = await _thirdInterfaceRepository.FirstOrDefaultAsync(o => o.ThirdInterfaceType ==
ThirdInterfaceTypeFlag.SmsPush);
if (smsThirdInterface != null && smsThirdInterface.IsActive == 'Y')
{
var parmValue = smsThirdInterface.ParmValue;
var configurationBuilder = new ConfigurationBuilder()
.AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(parmValue)));
var interfaceConfig = configurationBuilder.Build();
var pushApiAddress = interfaceConfig.GetSection("Interface").GetSection("PushApiAddress").Value;
var isEnableSms = interfaceConfig.GetSection("Interface").GetSection("IsActive").Value;
var noticeTemplateId = interfaceConfig.GetSection("Interface").GetSection("NoticeTemplateId").Value;
if (!string.IsNullOrWhiteSpace(isEnableSms)
&& !string.IsNullOrWhiteSpace(noticeTemplateId)
&& isEnableSms == "Y")
{
SmsPlugIns smsPlugIns = new SmsPlugIns(smsThirdInterface.Id);
var smsAppId = Guid.Parse(interfaceConfig.GetSection("Interface").GetSection("SmsAppId").Value);
var smsTypeId = Guid.Parse(interfaceConfig.GetSection("Interface").GetSection("SmsTypeId").Value);
var patientEnt = await _patientRepository.FirstOrDefaultAsync(f => f.Id == patientRegister.PatientId);
if (patientEnt != null)
{
var inputDto = new CreateSmsTaskDto
{
SmsAppId = smsAppId,
SmsTypeId = smsTypeId,
Content = patientRegister.PatientName,
CountryCode = "86",
MobileTelephone = patientEnt.MobileTelephone,
PersonId = patientRegister.PatientId.ToString(),
PersonName = patientRegister.PatientName,
SenderId = "admin",
SenderName = "体检",
StopTime = "",
TaskCorn = "",
TaskCycleType = '0',
TemplateId = noticeTemplateId,
ThirdId = patientRegister.Id.ToString()
};
await smsPlugIns.CallSmsAppServiceAsync<CreateSmsTaskDto, Task>(pushApiAddress, inputDto);
}
}
}
}
}
}

3
src/Shentun.Peis.Domain.Shared/Enums/ThirdInterfaceTypeFlag.cs

@ -35,5 +35,8 @@ namespace Shentun.Peis.Enums
[Description("同步组合项目价格")]
public const string SyncAsbitemPrice = "09";
[Description("短信推送")]
public const string SmsPush = "10";
}
}

2
src/Shentun.Peis.Domain/Shentun.Peis.Domain.csproj

@ -34,6 +34,8 @@
<ItemGroup>
<Folder Include="SysParmTypes\" />
<Folder Include="DataConfigJson\" />
<Folder Include="CommonTableTypes\" />
<Folder Include="CommonTables\" />
</ItemGroup>
</Project>

5
src/Shentun.Peis.HttpApi.Host/appsettings.json

@ -48,5 +48,10 @@
},
"Hangfire": {
"IsEnabledDashboard": true
},
"Sms": {
"IsEnable": "Y", //
"NoticeTemplateId": "2238651", //ID
"BaseUrl": ""
}
}
Loading…
Cancel
Save