From 902c0eb301a877e03f38b4f237e2c289ce2aa071 Mon Sep 17 00:00:00 2001 From: zhoukeda <1315948824@qq.com> Date: Thu, 6 Jul 2023 11:18:02 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=E6=8E=A8=E9=80=81=E8=A7=84=E5=88=99,?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E5=81=9C=E6=9C=BA=E6=8E=A8=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Entity/BasPushRuleD.cs | 52 ++++ .../Entity/BasPushRuleH.cs | 72 +++++ .../Entity/BasPushRuleLog.cs | 42 +++ .../IBasPushRuleLogService.cs | 15 + BasicData/Tnb.BasicData/BasMbomService.cs | 2 +- .../Tnb.BasicData/BasPushRuleLogService.cs | 44 +++ .../Entity/EqpEquipment.cs | 5 + .../Entity/EqpRepairApply.cs | 10 + .../PrdCancelCloseDownService.cs | 273 ++++++++++++++---- .../Tnb.ProductionMgr.csproj | 1 + .../Manager/User/UserManager.cs | 4 +- common/Tnb.Common/Enums/RequestType.cs | 5 + message/Tnb.Message/Service/MessageService.cs | 8 +- .../Listener/PushMsgTimeWorker.cs | 233 +++++++++++++++ .../Tnb.TaskScheduler/TimeTaskService.cs | 4 +- .../Tnb.TaskScheduler.csproj | 2 + 16 files changed, 712 insertions(+), 60 deletions(-) create mode 100644 BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleD.cs create mode 100644 BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleH.cs create mode 100644 BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleLog.cs create mode 100644 BasicData/Tnb.BasicData.Interfaces/IBasPushRuleLogService.cs create mode 100644 BasicData/Tnb.BasicData/BasPushRuleLogService.cs create mode 100644 taskschedule/Tnb.TaskScheduler/Listener/PushMsgTimeWorker.cs diff --git a/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleD.cs b/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleD.cs new file mode 100644 index 00000000..c60bd6e1 --- /dev/null +++ b/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleD.cs @@ -0,0 +1,52 @@ +using JNPF.Common.Contracts; +using JNPF.Common.Security; +using SqlSugar; + +namespace Tnb.BasicData.Entities; + +/// +/// 推送规则子表 +/// +[SugarTable("bas_push_rule_d")] +public partial class BasPushRuleD : BaseEntity +{ + public BasPushRuleD() + { + id = SnowflakeIdHelper.NextId(); + } + /// + /// 推送规则主表id + /// + public string push_rule_id { get; set; } = string.Empty; + + /// + /// 推送人id + /// + public string? user_ids { get; set; } + + /// + /// 推送角色id + /// + public string? role_ids { get; set; } + + /// + /// 推送岗位id + /// + public string? position_ids { get; set; } + + /// + /// 间隔(分) + /// + public int interval { get; set; } + + /// + /// 发送配置id + /// + public string? send_config_id { get; set; } + + /// + /// 排序 + /// + public long? ordinal { get; set; } + +} \ No newline at end of file diff --git a/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleH.cs b/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleH.cs new file mode 100644 index 00000000..598ae811 --- /dev/null +++ b/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleH.cs @@ -0,0 +1,72 @@ +using JNPF.Common.Contracts; +using JNPF.Common.Security; +using SqlSugar; + +namespace Tnb.BasicData.Entities; + +/// +/// 推送规则主表 +/// +[SugarTable("bas_push_rule_h")] +public partial class BasPushRuleH : BaseEntity +{ + public BasPushRuleH() + { + id = SnowflakeIdHelper.NextId(); + } + /// + /// 编码 + /// + public string code { get; set; } = string.Empty; + + /// + /// 名称 + /// + public string name { get; set; } = string.Empty; + + /// + /// 是否启用 + /// + public int enabled { get; set; } + + /// + /// 备注 + /// + public string? remark { get; set; } + + /// + /// 创建用户 + /// + public string? create_id { get; set; } + + /// + /// 创建时间 + /// + public DateTime? create_time { get; set; } + + /// + /// 修改用户 + /// + public string? modify_id { get; set; } + + /// + /// 修改时间 + /// + public DateTime? modify_time { get; set; } + + /// + /// 所属组织 + /// + public string? org_id { get; set; } + + /// + /// 流程任务Id + /// + public string? f_flowtaskid { get; set; } + + /// + /// 流程引擎Id + /// + public string? f_flowid { get; set; } + +} \ No newline at end of file diff --git a/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleLog.cs b/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleLog.cs new file mode 100644 index 00000000..01b8de8a --- /dev/null +++ b/BasicData/Tnb.BasicData.Entities/Entity/BasPushRuleLog.cs @@ -0,0 +1,42 @@ +using JNPF.Common.Contracts; +using JNPF.Common.Security; +using SqlSugar; + +namespace Tnb.BasicData.Entities; + +/// +/// 定时消息推送log +/// +[SugarTable("bas_push_rule_log")] +public partial class BasPushRuleLog : BaseEntity +{ + public BasPushRuleLog() + { + id = SnowflakeIdHelper.NextId(); + } + /// + /// 推送规则id + /// + public string push_rule_id { get; set; } = string.Empty; + + /// + /// 定时任务id + /// + public string timetask_id { get; set; } = string.Empty; + + /// + /// 业务主键id + /// + public string biz_id { get; set; } = string.Empty; + + /// + /// 要推送的层级 + /// + public long ordinal { get; set; } + + /// + /// 是否推送 + /// + public int is_push { get; set; } + +} \ No newline at end of file diff --git a/BasicData/Tnb.BasicData.Interfaces/IBasPushRuleLogService.cs b/BasicData/Tnb.BasicData.Interfaces/IBasPushRuleLogService.cs new file mode 100644 index 00000000..e3aa5fa7 --- /dev/null +++ b/BasicData/Tnb.BasicData.Interfaces/IBasPushRuleLogService.cs @@ -0,0 +1,15 @@ +namespace Tnb.BasicData.Interfaces +{ + /// + /// 推送记录服务 + /// + public interface IBasPushRuleLogService + { + /// + /// 停止推送 + /// + /// + /// + public Task Stop(Dictionary dic); + } +} \ No newline at end of file diff --git a/BasicData/Tnb.BasicData/BasMbomService.cs b/BasicData/Tnb.BasicData/BasMbomService.cs index 2ae7b4a9..e4465534 100644 --- a/BasicData/Tnb.BasicData/BasMbomService.cs +++ b/BasicData/Tnb.BasicData/BasMbomService.cs @@ -92,7 +92,7 @@ namespace Tnb.BasicData { var db = _repository.AsSugarClient(); BasMbom mbom = await _repository.GetSingleAsync(x => x.id == id); - List processes = await db.Queryable().Where(x => x.mbom_id == id).ToListAsync(); + List processes = await db.Queryable().Where(x => x.mbom_id == id).OrderBy(x=>x.ordinal).ToListAsync(); List inputs = await db.Queryable().Where(x => x.mbom_id == id).ToListAsync(); List outputs = await db.Queryable().Where(x => x.mbom_id == id).ToListAsync(); MbomDataOutput mbomDataOutput = new MbomDataOutput(); diff --git a/BasicData/Tnb.BasicData/BasPushRuleLogService.cs b/BasicData/Tnb.BasicData/BasPushRuleLogService.cs new file mode 100644 index 00000000..fa07ccda --- /dev/null +++ b/BasicData/Tnb.BasicData/BasPushRuleLogService.cs @@ -0,0 +1,44 @@ +using JNPF.Common.Core.Manager; +using JNPF.DependencyInjection; +using JNPF.DynamicApiController; +using JNPF.VisualDev.Interfaces; +using Microsoft.AspNetCore.Mvc; +using SqlSugar; +using Tnb.BasicData.Entities; +using Tnb.BasicData.Interfaces; + +namespace Tnb.BasicData +{ + /// + /// 推送记录服务 + /// + [ApiDescriptionSettings(Tag = ModuleConst.Tag, Area = ModuleConst.Area, Order = 1102)] + [Route("api/[area]/[controller]/[action]")] + public class BasPushRuleLogService : IBasPushRuleLogService, IDynamicApiController, ITransient + { + private readonly ISqlSugarRepository _repository; + private readonly DataBaseManager _dbManager; + private readonly IUserManager _userManager; + private readonly IRunService _runService; + private readonly IVisualDevService _visualDevService; + + public BasPushRuleLogService( + ISqlSugarRepository repository, + IUserManager userManager) + { + _repository = repository; + _userManager = userManager; + } + + [HttpPost] + public async Task Stop(Dictionary dic) + { + string id = dic["id"]; + await _repository.UpdateAsync(x => new BasPushRuleLog() + { + is_push = 0, + }, x => x.biz_id == id); + return true; + } + } +} \ No newline at end of file diff --git a/EquipMgr/Tnb.EquipMgr.Entities/Entity/EqpEquipment.cs b/EquipMgr/Tnb.EquipMgr.Entities/Entity/EqpEquipment.cs index ff6a8947..fc78a08f 100644 --- a/EquipMgr/Tnb.EquipMgr.Entities/Entity/EqpEquipment.cs +++ b/EquipMgr/Tnb.EquipMgr.Entities/Entity/EqpEquipment.cs @@ -198,4 +198,9 @@ public partial class EqpEquipment : BaseEntity /// public DateTime? warranty_end_time { get; set; } + /// + /// 责任人 + /// + public string? responsibler_id { get; set; } + } diff --git a/EquipMgr/Tnb.EquipMgr.Entities/Entity/EqpRepairApply.cs b/EquipMgr/Tnb.EquipMgr.Entities/Entity/EqpRepairApply.cs index c8a0cd84..a99595b4 100644 --- a/EquipMgr/Tnb.EquipMgr.Entities/Entity/EqpRepairApply.cs +++ b/EquipMgr/Tnb.EquipMgr.Entities/Entity/EqpRepairApply.cs @@ -153,5 +153,15 @@ public partial class EqpRepairApply : BaseEntity /// 维修图片 /// public string? repair_img { get; set; } + + /// + /// 生产任务单id + /// + public string? mo_task_id { get; set; } + + /// + /// 生产任务单号 + /// + public string? mo_task_code { get; set; } } diff --git a/ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs b/ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs index e3f6a029..2e726661 100644 --- a/ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs +++ b/ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs @@ -6,6 +6,7 @@ using System.Text; using System.Threading.Tasks; using Aop.Api.Domain; using JNPF.Common.Core.Manager; +using JNPF.Common.Dtos.Message; using JNPF.Common.Enums; using JNPF.Common.Extension; using JNPF.Common.Security; @@ -13,10 +14,17 @@ using JNPF.DependencyInjection; using JNPF.DynamicApiController; using JNPF.FriendlyException; using JNPF.Logging; +using JNPF.Message.Entitys.Entity; +using JNPF.Message.Service; using JNPF.Systems.Entitys.Permission; +using JNPF.Systems.Entitys.System; using JNPF.Systems.Interfaces.System; +using JNPF.TaskScheduler; +using JNPF.TaskScheduler.Entitys.Dto.TaskScheduler; +using JNPF.TaskScheduler.Entitys.Model; using Mapster; using Microsoft.AspNetCore.Mvc; +using Newtonsoft.Json; using SqlSugar; using Tnb.BasicData; using Tnb.EquipMgr.Entities; @@ -25,6 +33,8 @@ using Tnb.EquipMgr.Interfaces; using Tnb.ProductionMgr.Entities; using Tnb.ProductionMgr.Entities.Dto.PrdManage; using Tnb.ProductionMgr.Interfaces; +using Tnb.BasicData.Entities; +using MessageTemplateEntity = JNPF.Message.Entitys.Entity.MessageTemplateEntity; namespace Tnb.ProductionMgr { @@ -42,9 +52,12 @@ namespace Tnb.ProductionMgr private readonly IPrdMoTaskService _prdMoTaskService; private readonly IUserManager _userManager; private readonly IBillRullService _billRullService; + private readonly TimeTaskService _timeTaskService; + private SendMessageService _sendMessageService; private static Dictionary _dicWorkStationAndShopRelacion = new Dictionary(); private static Dictionary _dicWorkShop = new Dictionary(); + private const string PUSHRULEID = "27121606262805";//异常停机的推送规则id @@ -54,6 +67,8 @@ namespace Tnb.ProductionMgr IToolMoldsService moldsService, IToolMoldMaintainTaskService maintainTaskService, IBillRullService billRullService, + TimeTaskService timeTaskService, + SendMessageService sendMessageService, IUserManager userManager ) { @@ -62,6 +77,8 @@ namespace Tnb.ProductionMgr _moldService = moldsService; _userManager = userManager; _billRullService = billRullService; + _timeTaskService = timeTaskService; + _sendMessageService = sendMessageService; _db = repository.AsSugarClient(); } /// @@ -194,77 +211,175 @@ namespace Tnb.ProductionMgr { if (input == null) throw new ArgumentNullException("input"); if (input.eqp_id.IsNullOrWhiteSpace()) throw new ArgumentException($"parameter {nameof(input.eqp_id)} not be null or empty"); + var eqp = await _db.Queryable().FirstAsync(it => it.id == input.eqp_id); + var cancelCloseDown = input.Adapt(); + EqpRepairApply eqpRepairApply = null; + BasPushRuleD basPushRuleD = await _db.Queryable().FirstAsync(x => x.push_rule_id == PUSHRULEID && x.ordinal == 1); try { - await _db.Ado.BeginTranAsync(); - - var moTaskList = await _prdMoTaskService.GetListByEqpId(input.eqp_id); - if (moTaskList?.Count > 1) throw new AppFriendlyException($"设备{input.eqp_id},目前有两条进行中的生产任务", 500); - if (moTaskList?.Count > 0) + + DbResult result = await _db.Ado.UseTranAsync(async () => { - var cancelCloseDown = input.Adapt(); - cancelCloseDown.id = SnowflakeIdHelper.NextId(); - cancelCloseDown.eqp_id = input.eqp_id; - cancelCloseDown.create_id = _userManager.UserId; - cancelCloseDown.create_time = DateTime.Now; - cancelCloseDown.closedown_start_time = DateTime.Now; - - await _db.Insertable(cancelCloseDown).ExecuteCommandAsync(); - var eqp = await _db.Queryable().FirstAsync(it => it.id == input.eqp_id); - var record = cancelCloseDown.Adapt(); - record.eqp_code = eqp?.code; - record.eqp_name = eqp?.name; - await _db.Insertable(record).ExecuteCommandAsync(); - - var moldId = moTaskList.First().mold_id; - if (!moldId.IsNullOrEmpty()) + var moTaskList = await _prdMoTaskService.GetListByEqpId(input.eqp_id); + if (moTaskList?.Count > 1) throw new AppFriendlyException($"设备{input.eqp_id},目前有两条进行中的生产任务", 500); + if (moTaskList?.Count > 0) { - var mold = await _moldService.GetListById(moldId); - var maintaindTask = new ToolMoldMaintainTask(); - maintaindTask.mold_id = moldId; - maintaindTask.code = mold.mold_code; - maintaindTask.create_id = _userManager.UserId; - maintaindTask.status = DictConst.UnMaintainStatusCode; - maintaindTask.create_time = DateTime.Now; + + cancelCloseDown.id = SnowflakeIdHelper.NextId(); + cancelCloseDown.eqp_id = input.eqp_id; + cancelCloseDown.create_id = _userManager.UserId; + cancelCloseDown.create_time = DateTime.Now; + cancelCloseDown.closedown_start_time = DateTime.Now; - await _maintainTaskService.Create(maintaindTask); - } + await _db.Insertable(cancelCloseDown).ExecuteCommandAsync(); + + var record = cancelCloseDown.Adapt(); + record.eqp_code = eqp?.code; + record.eqp_name = eqp?.name; + await _db.Insertable(record).ExecuteCommandAsync(); - string reason = ""; - if (!string.IsNullOrEmpty(input.reason)) - { - List prdCancelClosedownReasons = await _db.Queryable().ToListAsync(); - string[] reasonArr = input.reason.Split(","); - var reasonList = prdCancelClosedownReasons.Where(x => reasonArr.Contains(x.id)).Select(x => x.reason).ToList(); - reason = string.Join(',', reasonList); + var moldId = moTaskList.First().mold_id; + if (!moldId.IsNullOrEmpty()) + { + var mold = await _moldService.GetListById(moldId); + var maintaindTask = new ToolMoldMaintainTask(); + maintaindTask.mold_id = moldId; + maintaindTask.code = mold?.mold_code ?? ""; + maintaindTask.create_id = _userManager.UserId; + maintaindTask.status = DictConst.UnMaintainStatusCode; + maintaindTask.create_time = DateTime.Now; + + await _maintainTaskService.Create(maintaindTask); + } + + string reason = ""; + if (!string.IsNullOrEmpty(input.reason)) + { + List prdCancelClosedownReasons = await _db.Queryable().ToListAsync(); + string[] reasonArr = input.reason.Split(","); + var reasonList = prdCancelClosedownReasons.Where(x => reasonArr.Contains(x.id)).Select(x => x.reason).ToList(); + reason = string.Join(',', reasonList); + + } + string code = await _billRullService.GetBillNumber("EqpRepair"); + eqpRepairApply = new EqpRepairApply() + { + code = code, + name = eqp.name + "停机", + equip_id = input.eqp_id, + status = Tnb.EquipMgr.RepairApplyStatus.TOBEEXECUTED, + description = reason, + create_id = _userManager.UserId, + create_time = DateTime.Now, + remark = input.remark, + }; + + await _db.Insertable(eqpRepairApply).ExecuteCommandAsync(); + + if (!string.IsNullOrEmpty(eqp.responsibler_id)) + { + List list = await _sendMessageService.SendTest(basPushRuleD.send_config_id); + List toUsers = JsonConvert.DeserializeObject>(eqp.responsibler_id); + + foreach (var item in list) + { + foreach (var param in item.paramJson) + { + if (param.field=="equip_code") + { + param.value = eqp.code; + } + } + item.toUser = toUsers; + } + + foreach (var item in list) + { + await _sendMessageService.SendMessage(item, new Dictionary()); + } + } + } - string code = await _billRullService.GetBillNumber("EqpRepair"); - EqpRepairApply eqpRepairApply = new EqpRepairApply() + else throw Oops.Oh(ErrorCode.COM1001); + }); + if (result.IsSuccess) + { + BasPushRuleH basPushRuleH = await _db.Queryable().SingleAsync(x=>x.id==PUSHRULEID); + if (basPushRuleH?.enabled == 1) { - code = code, - name = eqp.name + "停机", - equip_id = input.eqp_id, - status = Tnb.EquipMgr.RepairApplyStatus.TOBEEXECUTED, - description = reason, - create_id = _userManager.UserId, - create_time = DateTime.Now, - remark = input.remark, - }; + string sendConfigId = basPushRuleD?.send_config_id ?? ""; + List sendModels = await GetSendParamJson(sendConfigId); + + if (sendModels != null && sendModels.Count > 0) + { + DateTime executeTime = DateTime.Now.AddMinutes(2); + // string cron = $"0 {executeTime.Minute} {executeTime.Hour} {executeTime.Day} {executeTime.Month} ? {executeTime.Year}"; + string cron = $"0 {executeTime.Minute} {executeTime.Hour} {executeTime.Day} {executeTime.Month} ?"; + + var comtentModel = new ContentModel(); + // comtentModel.cron = (2 * 60).ToString(); + comtentModel.cron = cron; + comtentModel.interfaceId = ""; + comtentModel.interfaceName = ""; + comtentModel.parameter = new List(); + comtentModel.localHostTaskId = "PushMsgTimeWorker/PushMsg"; + comtentModel.startTime = DateTimeOffset.Now.ToUnixTimeMilliseconds(); + // comtentModel.endTime = DateTimeOffset.Now.AddSeconds(3).ToUnixTimeMilliseconds().ToString(); + comtentModel.TenantId = _userManager?.TenantId; + comtentModel.TenantDbName = _userManager?.TenantDbName; + comtentModel.ConnectionConfig = _userManager?.ConnectionConfig; + comtentModel.Token = _userManager?.ToKen; + + foreach (var item in sendModels) + { + foreach (var param in item.paramJson) + { + if (param.field == "equip_code") + { + param.value = eqp?.code; + } + } + } + + TimeTaskCrInput timeTaskCrInput = new TimeTaskCrInput() + { + enCode = DateTime.Now.ToString("yyyyMMddHHmmss"), + fullName = "临时推送消息" + DateTime.Now.ToString("yyyyMMddHHmmss"), + executeType = "3", + executeContent = comtentModel.ToJsonString(), + description = JsonConvert.SerializeObject(sendModels[0].paramJson), + sortCode = 9999, + enabledMark = 1, + }; - await _db.Insertable(eqpRepairApply).ExecuteCommandAsync(); + await _timeTaskService.Create(timeTaskCrInput,false); + TimeTaskEntity timeTaskEntity = await _db.Queryable().Where(x => x.EnCode == timeTaskCrInput.enCode).FirstAsync(); + + BasPushRuleLog basPushRuleLog = new BasPushRuleLog() + { + push_rule_id = PUSHRULEID, + timetask_id = timeTaskEntity?.Id, + biz_id = eqpRepairApply.id, + ordinal = 1, + is_push = 1, + }; + + await _db.Insertable(basPushRuleLog).ExecuteCommandAsync(); + } + } + } - else throw Oops.Oh(ErrorCode.COM1001); - - await _db.Ado.CommitTranAsync(); + } catch (Exception ex) { Log.Error("停机开始失败", ex); - await _db.Ado.RollbackTranAsync(); + // await _db.Ado.RollbackTranAsync(); throw; } + } /// /// 停机结束 @@ -304,5 +419,57 @@ namespace Tnb.ProductionMgr throw; } } + + private async Task> GetSendParamJson(string id) + { + var list = await _db.Queryable((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().Where(u => u.Type == "1" && u.EnCode == a.MessageType).Select(u => u.FullName), + msgTemplateName = b.FullName, + sendConfigId = a.SendConfigId, + templateId = a.TemplateId, + }).ToListAsync(); + foreach (var item in list) + { + // 是否存在参数. + var flag = await _db.Queryable().AnyAsync(x => x.TemplateId == item.templateId && x.DeleteMark == null); + if (flag) + { + item.paramJson = await _db.Queryable((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 + }).ToListAsync(); + } + else + { + item.paramJson = await _db.Queryable((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 + }).ToListAsync(); + } + } + return list; + } } } diff --git a/ProductionMgr/Tnb.ProductionMgr/Tnb.ProductionMgr.csproj b/ProductionMgr/Tnb.ProductionMgr/Tnb.ProductionMgr.csproj index 0ea7ec46..574ed3cf 100644 --- a/ProductionMgr/Tnb.ProductionMgr/Tnb.ProductionMgr.csproj +++ b/ProductionMgr/Tnb.ProductionMgr/Tnb.ProductionMgr.csproj @@ -11,6 +11,7 @@ + diff --git a/common/Tnb.Common.Core/Manager/User/UserManager.cs b/common/Tnb.Common.Core/Manager/User/UserManager.cs index d9c865ee..d71c492f 100644 --- a/common/Tnb.Common.Core/Manager/User/UserManager.cs +++ b/common/Tnb.Common.Core/Manager/User/UserManager.cs @@ -84,7 +84,7 @@ public class UserManager : IUserManager, IScoped /// public string UserId { - get => _user.FindFirst(ClaimConst.CLAINMUSERID)?.Value; + get => _user?.FindFirst(ClaimConst.CLAINMUSERID)?.Value; } /// @@ -128,7 +128,7 @@ public class UserManager : IUserManager, IScoped /// public ConnectionConfigOptions ConnectionConfig { - get => _user.FindFirst(ClaimConst.CONNECTIONCONFIG)?.Value.ToObject(); + get => _user?.FindFirst(ClaimConst.CONNECTIONCONFIG)?.Value.ToObject(); } /// diff --git a/common/Tnb.Common/Enums/RequestType.cs b/common/Tnb.Common/Enums/RequestType.cs index d93c900d..45154e1c 100644 --- a/common/Tnb.Common/Enums/RequestType.cs +++ b/common/Tnb.Common/Enums/RequestType.cs @@ -22,4 +22,9 @@ public enum RequestType /// POST请求. /// Run = 2, + + /// + /// 本地方法 + /// + Local = 3, } \ No newline at end of file diff --git a/message/Tnb.Message/Service/MessageService.cs b/message/Tnb.Message/Service/MessageService.cs index 3e634ac4..1c72e209 100644 --- a/message/Tnb.Message/Service/MessageService.cs +++ b/message/Tnb.Message/Service/MessageService.cs @@ -410,13 +410,17 @@ public class MessageService : IMessageService, IDynamicApiController, ITransient { try { + //modifyby zhoukeda 20230704 定时任务发起的推送消息没有user + string userManagerUserId = _userManager.UserId ?? ""; + string userManagerTenantId = _userManager.TenantId ?? ""; + MessageEntity entity = new MessageEntity(); entity.Id = SnowflakeIdHelper.NextId(); entity.Title = title; entity.BodyText = bodyText; entity.Type = type; entity.LastModifyTime = DateTime.Now; - entity.LastModifyUserId = _userManager.UserId; + entity.LastModifyUserId = userManagerUserId; entity.FlowType = flowType.ParseToInt(); List receiveEntityList = toUserIds .Select(x => new MessageReceiveEntity() @@ -434,7 +438,7 @@ public class MessageService : IMessageService, IDynamicApiController, ITransient { var userId = item.Replace("-delegate", string.Empty); // 消息推送 - 指定用户 - await _imHandler.SendMessageToUserAsync(string.Format("{0}-{1}", _userManager.TenantId, userId), new { method = "messagePush", messageType = 2, userId = _userManager.UserId, toUserId = toUserIds, title = entity.Title, unreadNoticeCount = 1, id = entity.Id }.ToJsonString()); + await _imHandler.SendMessageToUserAsync(string.Format("{0}-{1}", userManagerTenantId, userId), new { method = "messagePush", messageType = 2, userId = userManagerUserId, toUserId = toUserIds, title = entity.Title, unreadNoticeCount = 1, id = entity.Id }.ToJsonString()); } } } diff --git a/taskschedule/Tnb.TaskScheduler/Listener/PushMsgTimeWorker.cs b/taskschedule/Tnb.TaskScheduler/Listener/PushMsgTimeWorker.cs new file mode 100644 index 00000000..0d9a8089 --- /dev/null +++ b/taskschedule/Tnb.TaskScheduler/Listener/PushMsgTimeWorker.cs @@ -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 +{ + /// + /// 根据推送规则推送消息 + /// + public class PushMsgTimeWorker : ISpareTimeWorker + { + private ISqlSugarRepository _repository => App.GetService>(); + + private TimeTaskService _timeTaskService => App.GetService(); + private SendMessageService _sendMessageService => App.GetService(); + private IUserManager _userManager => App.GetService(); + + + // [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().FirstAsync(x => x.timetask_id == timer.WorkerName); + + + if (basPushRuleLog?.is_push == 1) + { + BasPushRuleH basPushRuleH = await db.Queryable().FirstAsync(x=>x.id==basPushRuleLog.push_rule_id); + BasPushRuleD basPushRuleD = await db.Queryable().FirstAsync(x=>x.push_rule_id==basPushRuleLog.push_rule_id && x.ordinal==basPushRuleLog.ordinal); + BasPushRuleD nextBasPushRuleD = await db.Queryable().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().SingleAsync(x => x.Id == timer.WorkerName); + List list = await _sendMessageService.SendTest(basPushRuleD.send_config_id); + List toUsers = new List(); + + if (!string.IsNullOrEmpty(basPushRuleD.user_ids)) + { + toUsers.AddRange(JsonConvert.DeserializeObject>(basPushRuleD.user_ids)); + } + + if (!string.IsNullOrEmpty(basPushRuleD.position_ids)) + { + + toUsers.AddRange(db.Queryable().Where(x => basPushRuleD.position_ids.Contains(x.Id)).Select(s => s.UserId).ToList()); + } + + if (!string.IsNullOrEmpty(basPushRuleD.role_ids)) + { + + toUsers.AddRange(db.Queryable().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>(timeTaskEntity.Description); + item.toUser = toUsers; + + } + + foreach (var item in list) + { + await _sendMessageService.SendMessage(item, new Dictionary()); + } + + 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(timeTaskEntity.ExecuteContent); + // comtentModel.cron = (nextBasPushRuleD.interval * 60).ToString(); + comtentModel.cron = cron; + comtentModel.interfaceId = ""; + comtentModel.interfaceName = ""; + comtentModel.parameter = new List(); + 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 nextMessageList = await _sendMessageService.SendTest(nextBasPushRuleD.send_config_id); + List messageSendParams = JsonConvert.DeserializeObject>(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().Where(x => x.EnCode == timeTaskCrInput.enCode).FirstAsync(); + string newId = timeTaskEntityNew?.Id ?? ""; + + await db.Updateable() + .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().Where(x => x.Id == timer.WorkerName).ExecuteCommandAsync(); + } + catch (Exception e) + { + Console.WriteLine(e.Message); + Log.Error(e.Message); + } + + + // Log.Information("----------------------结束生成特种设备检验计划----------------------"); + } + + private List SendTest(string id) + { + var db = _repository.AsSugarClient(); + var list = db.Queryable((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().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().Any(x => x.TemplateId == item.templateId && x.DeleteMark == null); + if (flag) + { + item.paramJson = db.Queryable((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((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; + } + } +} \ No newline at end of file diff --git a/taskschedule/Tnb.TaskScheduler/TimeTaskService.cs b/taskschedule/Tnb.TaskScheduler/TimeTaskService.cs index 14d06b18..8e4b6bd2 100644 --- a/taskschedule/Tnb.TaskScheduler/TimeTaskService.cs +++ b/taskschedule/Tnb.TaskScheduler/TimeTaskService.cs @@ -143,7 +143,7 @@ public class TimeTaskService : ITimeTaskService, IDynamicApiController, ITransie /// 实体对象. /// [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); } diff --git a/taskschedule/Tnb.TaskScheduler/Tnb.TaskScheduler.csproj b/taskschedule/Tnb.TaskScheduler/Tnb.TaskScheduler.csproj index 6da949e5..289ac926 100644 --- a/taskschedule/Tnb.TaskScheduler/Tnb.TaskScheduler.csproj +++ b/taskschedule/Tnb.TaskScheduler/Tnb.TaskScheduler.csproj @@ -10,8 +10,10 @@ + + From 0a186ad2a182d3a26d485b588312746054eb2f41 Mon Sep 17 00:00:00 2001 From: zhoukeda <1315948824@qq.com> Date: Thu, 6 Jul 2023 11:32:05 +0800 Subject: [PATCH 2/2] BUG --- ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs b/ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs index 2e726661..541f2ac0 100644 --- a/ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs +++ b/ProductionMgr/Tnb.ProductionMgr/PrdCancelCloseDownService.cs @@ -313,7 +313,7 @@ namespace Tnb.ProductionMgr if (sendModels != null && sendModels.Count > 0) { - DateTime executeTime = DateTime.Now.AddMinutes(2); + DateTime executeTime = DateTime.Now.AddMinutes(basPushRuleD.interval); // string cron = $"0 {executeTime.Minute} {executeTime.Hour} {executeTime.Day} {executeTime.Month} ? {executeTime.Year}"; string cron = $"0 {executeTime.Minute} {executeTime.Hour} {executeTime.Day} {executeTime.Month} ?";