推送规则,异常停机推送

This commit is contained in:
2023-07-06 11:18:02 +08:00
parent c6e46b4ad9
commit 902c0eb301
16 changed files with 712 additions and 60 deletions

View File

@@ -0,0 +1,233 @@
using JNPF.Common.Core.Manager;
using JNPF.Common.Dtos.Message;
using JNPF.Common.Enums;
using JNPF.Common.Security;
using JNPF.Logging;
using JNPF.Message.Entitys.Entity;
using JNPF.Message.Service;
using JNPF.Systems.Entitys.Permission;
using JNPF.Systems.Entitys.System;
using JNPF.TaskScheduler.Entitys.Dto.TaskScheduler;
using JNPF.TaskScheduler.Entitys.Model;
using JNPF.TaskScheduler.Interfaces.TaskScheduler;
using Newtonsoft.Json;
using SqlSugar;
using Tnb.BasicData.Entities;
using MessageTemplateEntity = JNPF.Systems.Entitys.System.MessageTemplateEntity;
namespace JNPF.TaskScheduler.Listener
{
/// <summary>
/// 根据推送规则推送消息
/// </summary>
public class PushMsgTimeWorker : ISpareTimeWorker
{
private ISqlSugarRepository<BasPushRuleH> _repository => App.GetService<ISqlSugarRepository<BasPushRuleH>>();
private TimeTaskService _timeTaskService => App.GetService<TimeTaskService>();
private SendMessageService _sendMessageService => App.GetService<SendMessageService>();
private IUserManager _userManager => App.GetService<IUserManager>();
// [SpareTime(2*60, "推送消息", ExecuteType = SpareTimeExecuteTypes.Serial,StartNow = false,DoOnce = true)]
[SpareTime("* * * * * ?", "推送消息", ExecuteType = SpareTimeExecuteTypes.Serial,StartNow = false,DoOnce = true)]
public async void PushMsg(SpareTimer timer, long count)
{
// Log.Information("----------------------开始生成特种设备检验计划----------------------");
try
{
var db = _repository.AsSugarClient();
BasPushRuleLog basPushRuleLog = await db.Queryable<BasPushRuleLog>().FirstAsync(x => x.timetask_id == timer.WorkerName);
if (basPushRuleLog?.is_push == 1)
{
BasPushRuleH basPushRuleH = await db.Queryable<BasPushRuleH>().FirstAsync(x=>x.id==basPushRuleLog.push_rule_id);
BasPushRuleD basPushRuleD = await db.Queryable<BasPushRuleD>().FirstAsync(x=>x.push_rule_id==basPushRuleLog.push_rule_id && x.ordinal==basPushRuleLog.ordinal);
BasPushRuleD nextBasPushRuleD = await db.Queryable<BasPushRuleD>().FirstAsync(x=>x.push_rule_id==basPushRuleLog.push_rule_id && x.ordinal==basPushRuleLog.ordinal+1);
if (basPushRuleH?.enabled==1 && basPushRuleD != null)
{
TimeTaskEntity timeTaskEntity = await db.Queryable<TimeTaskEntity>().SingleAsync(x => x.Id == timer.WorkerName);
List<MessageSendModel> list = await _sendMessageService.SendTest(basPushRuleD.send_config_id);
List<string> toUsers = new List<string>();
if (!string.IsNullOrEmpty(basPushRuleD.user_ids))
{
toUsers.AddRange(JsonConvert.DeserializeObject<List<string>>(basPushRuleD.user_ids));
}
if (!string.IsNullOrEmpty(basPushRuleD.position_ids))
{
toUsers.AddRange(db.Queryable<UserRelationEntity>().Where(x => basPushRuleD.position_ids.Contains(x.Id)).Select(s => s.UserId).ToList());
}
if (!string.IsNullOrEmpty(basPushRuleD.role_ids))
{
toUsers.AddRange(db.Queryable<UserRelationEntity>().Where(x => basPushRuleD.role_ids.Contains(x.Id)).Select(s => s.UserId).ToList());
}
if (toUsers.Count > 0)
{
foreach (var item in list)
{
item.paramJson = JsonConvert.DeserializeObject<List<MessageSendParam>>(timeTaskEntity.Description);
item.toUser = toUsers;
}
foreach (var item in list)
{
await _sendMessageService.SendMessage(item, new Dictionary<string, object>());
}
if (nextBasPushRuleD != null)
{
DateTime executeTime = DateTime.Now.AddMinutes(nextBasPushRuleD.interval);
string cron = $"0 {executeTime.Minute} {executeTime.Hour} {executeTime.Day} {executeTime.Month} ?";
var comtentModel = new ContentModel();
var timeTaskComtentModel = JsonConvert.DeserializeObject<ContentModel>(timeTaskEntity.ExecuteContent);
// comtentModel.cron = (nextBasPushRuleD.interval * 60).ToString();
comtentModel.cron = cron;
comtentModel.interfaceId = "";
comtentModel.interfaceName = "";
comtentModel.parameter = new List<InterfaceParameter>();
comtentModel.localHostTaskId = "PushMsgTimeWorker/PushMsg";
comtentModel.startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds();
// comtentModel.endTime = DateTimeOffset.Now.AddSeconds(nextBasPushRuleD.interval+1).ToUnixTimeMilliseconds().ToString();
// comtentModel.TenantId = _userManager?.TenantId;
// comtentModel.TenantDbName = _userManager?.TenantDbName;
// comtentModel.ConnectionConfig = _userManager?.ConnectionConfig;
// comtentModel.Token = _userManager?.ToKen;
comtentModel.TenantId = timeTaskComtentModel?.TenantId;
comtentModel.TenantDbName = timeTaskComtentModel?.TenantDbName;
comtentModel.ConnectionConfig = timeTaskComtentModel?.ConnectionConfig;
comtentModel.Token = timeTaskComtentModel?.Token;
List<MessageSendModel> nextMessageList = await _sendMessageService.SendTest(nextBasPushRuleD.send_config_id);
List<MessageSendParam> messageSendParams = JsonConvert.DeserializeObject<List<MessageSendParam>>(timeTaskEntity.Description);
string paramJson = "";
foreach (var item in nextMessageList)
{
foreach (var param in item.paramJson)
{
var field = messageSendParams.FirstOrDefault(x=>x.fieldName==param.fieldName);
if (field != null)
{
param.value = field.value;
}
}
paramJson = JsonConvert.SerializeObject(item.paramJson);
break;
}
// TimeTaskEntity newTimeTaskEntity = new TimeTaskEntity()
// {
// EnCode = DateTime.Now.ToString("yyyyMMddHHmmss"),
// FullName = "临时推送消息" + DateTime.Now.ToString("yyyyMMddHHmmss"),
// ExecuteType = RequestType.Local,
// ExecuteContent = comtentModel.ToJsonString(),
// ExecuteCycleJson = comtentModel.cron,
// Description = paramJson,
// CreatorTime = DateTime.Now,
// };
TimeTaskCrInput timeTaskCrInput = new TimeTaskCrInput()
{
enCode = DateTime.Now.ToString("yyyyMMddHHmmss"),
fullName = "临时推送消息" + DateTime.Now.ToString("yyyyMMddHHmmss"),
executeType = "3",
executeContent = comtentModel.ToJsonString(),
description = paramJson,
sortCode = 9999,
enabledMark = 1,
};
await _timeTaskService.Create(timeTaskCrInput,false);
TimeTaskEntity timeTaskEntityNew = await db.Queryable<TimeTaskEntity>().Where(x => x.EnCode == timeTaskCrInput.enCode).FirstAsync();
string newId = timeTaskEntityNew?.Id ?? "";
await db.Updateable<BasPushRuleLog>()
.SetColumns(x=>x.timetask_id==newId)
.SetColumns(x => x.ordinal == x.ordinal + 1)
.Where(x=>x.timetask_id==timer.WorkerName).ExecuteCommandAsync();
}
}
}
}
//进入次方法后删除次定时任务
// _timeTaskService.Delete(timer.WorkerName);
SpareTime.Cancel(timer.WorkerName);
await db.Deleteable<TimeTaskEntity>().Where(x => x.Id == timer.WorkerName).ExecuteCommandAsync();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Log.Error(e.Message);
}
// Log.Information("----------------------结束生成特种设备检验计划----------------------");
}
private List<MessageSendModel> SendTest(string id)
{
var db = _repository.AsSugarClient();
var list = db.Queryable<MessageSendTemplateEntity, MessageTemplateEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.TemplateId == b.Id))
.Where((a, b) => a.SendConfigId == id && a.DeleteMark == null && b.DeleteMark == null)
.Select((a, b) => new MessageSendModel
{
accountConfigId = a.AccountConfigId,
id = a.Id,
messageType = SqlFunc.Subqueryable<MessageDataTypeEntity>().Where(u => u.Type == "1" && u.EnCode == a.MessageType).Select(u => u.FullName),
msgTemplateName = b.FullName,
sendConfigId = a.SendConfigId,
templateId = a.TemplateId,
}).ToList();
foreach (var item in list)
{
// 是否存在参数.
var flag = db.Queryable<MessageSmsFieldEntity>().Any(x => x.TemplateId == item.templateId && x.DeleteMark == null);
if (flag)
{
item.paramJson = db.Queryable<MessageTemplateParamEntity, JNPF.Message.Entitys.Entity.MessageTemplateEntity, MessageSmsFieldEntity>((a, b, c) => new JoinQueryInfos(JoinType.Left, a.TemplateId == b.Id, JoinType.Left, a.TemplateId == c.TemplateId))
.Where((a, b, c) => a.TemplateId == item.templateId && a.DeleteMark == null && b.DeleteMark == null && a.Field == c.Field && a.Field != "@flowLink")
.Select((a, b) => new MessageSendParam
{
field = a.Field,
fieldName = a.FieldName,
id = a.Id,
templateCode = b.TemplateCode,
templateId = a.TemplateId,
templateName = b.FullName,
templateType = b.TemplateType
}).ToList();
}
else
{
item.paramJson = db.Queryable<MessageTemplateParamEntity, JNPF.Message.Entitys.Entity.MessageTemplateEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.TemplateId == b.Id))
.Where((a, b) => a.TemplateId == item.templateId && a.DeleteMark == null && b.DeleteMark == null && a.Field != "@flowLink")
.Where((a, b) => b.Title.Contains(a.Field) || b.Content.Contains(a.Field))
.Select((a, b) => new MessageSendParam
{
field = a.Field,
fieldName = a.FieldName,
id = a.Id,
templateCode = b.TemplateCode,
templateId = a.TemplateId,
templateName = b.FullName,
templateType = b.TemplateType
}).ToList();
}
}
return list;
}
}
}

View File

@@ -143,7 +143,7 @@ public class TimeTaskService : ITimeTaskService, IDynamicApiController, ITransie
/// <param name="input">实体对象.</param>
/// <returns></returns>
[HttpPost("")]
public async Task Create([FromBody] TimeTaskCrInput input)
public async Task Create([FromBody] TimeTaskCrInput input,bool startNow = true)
{
if (await _repository.IsAnyAsync(x => (x.EnCode == input.enCode || x.FullName == input.fullName) && x.DeleteMark == null))
throw Oops.Oh(ErrorCode.COM1004);
@@ -162,7 +162,7 @@ public class TimeTaskService : ITimeTaskService, IDynamicApiController, ITransie
_ = result ?? throw Oops.Oh(ErrorCode.COM1000);
// 添加到任务调度里
AddTimerJob(result);
AddTimerJob(result,startNow);
//await AddJob(result);
}

View File

@@ -10,8 +10,10 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\BasicData\Tnb.BasicData.Entities\Tnb.BasicData.Entities.csproj" />
<ProjectReference Include="..\..\common\Tnb.Common.Core\Tnb.Common.Core.csproj" />
<ProjectReference Include="..\..\EquipMgr\Tnb.EquipMgr.Entities\Tnb.EquipMgr.Entities.csproj" />
<ProjectReference Include="..\..\message\Tnb.Message\Tnb.Message.csproj" />
<ProjectReference Include="..\..\system\Tnb.Systems.Interfaces\Tnb.Systems.Interfaces.csproj" />
<ProjectReference Include="..\Tnb.TaskScheduler.Interfaces\Tnb.TaskScheduler.Interfaces.csproj" />
</ItemGroup>