using System.Text.Json; using Admin.NET.Plugin.AiDOP.Entity.S8; using Admin.NET.Plugin.AiDOP.Infrastructure; using Admin.NET.Plugin.AiDOP.Service.S8.Rules; namespace Admin.NET.Plugin.AiDOP.Service.S8; public class S8WatchRuleService : ITransient { private readonly SqlSugarRepository _rep; private readonly SqlSugarRepository _dataSourceRep; private readonly SqlSugarRepository _sceneRep; public S8WatchRuleService( SqlSugarRepository rep, SqlSugarRepository dataSourceRep, SqlSugarRepository sceneRep) { _rep = rep; _dataSourceRep = dataSourceRep; _sceneRep = sceneRep; } public async Task> ListAsync(long tenantId, long factoryId) => await _rep.AsQueryable() .Where(x => x.TenantId == tenantId && x.FactoryId == factoryId) .ToListAsync(); // S8-TENANT-FACTORY-P0-CLOSURE-1:归属一律由服务端可信作用域盖章,忽略 body.TenantId / body.FactoryId。 public async Task CreateAsync(AdoS8WatchRule body, S8TrustedScope scope) { body.TenantId = scope.TenantId; body.FactoryId = scope.FactoryId; await ValidateAsync(body, scope); body.Id = 0; body.CreatedAt = DateTime.Now; await _rep.InsertAsync(body); return body; } // S8-TENANT-FACTORY-P0-CLOSURE-1:按 Id + 可信作用域绑行;越权 Id 视为不存在,归属不可被 body 改写。 public async Task UpdateAsync(long id, AdoS8WatchRule body, S8TrustedScope scope) { var e = await LoadScopedAsync(id, scope); body.TenantId = e.TenantId; body.FactoryId = e.FactoryId; await ValidateAsync(body, scope, id); body.Id = id; body.CreatedAt = e.CreatedAt; body.UpdatedAt = DateTime.Now; await _rep.UpdateAsync(body); return body; } // S8-TENANT-FACTORY-P0-CLOSURE-1:删除必须先按可信作用域绑行,禁止裸 DeleteByIdAsync(id)。 public async Task DeleteAsync(long id, S8TrustedScope scope) { var e = await LoadScopedAsync(id, scope); await _rep.DeleteByIdAsync(e.Id); } /// 按 Id + 可信作用域取行;不在作用域内一律按「不存在」处理,不泄露他租户资源是否存在。 private async Task LoadScopedAsync(long id, S8TrustedScope scope) => await _rep.AsQueryable() .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId) .FirstAsync() ?? throw new S8NotFoundException(); /// /// R4 安全更新:只更新 params_json 与 enabled。expression / rule_code / data_source_id / /// scene_code / watch_object_type / rule_type / source_object_type 一律不通过此路径修改。 /// 当 RuleType 非空时,按对应 evaluator 的 Params.Parse 进行 schema 校验,解析失败抛 S8BizException。 /// public async Task UpdateParamsAsync(long id, S8WatchRuleParamsPayload payload, S8TrustedScope scope) { var entity = await LoadScopedAsync(id, scope); var paramsJson = payload.ParamsJson?.Trim(); if (!string.IsNullOrEmpty(paramsJson)) { ValidateParamsJsonByRuleType(entity.RuleType, paramsJson); } entity.ParamsJson = string.IsNullOrEmpty(paramsJson) ? null : paramsJson; entity.Enabled = payload.Enabled; // TASK-002-RESET-DIMENSION-MODEL-DEV-2B:维度归属 + 报警机制按 payload 原样落库(含 null 清空)。 entity.StageCode = NormalizeOrNull(payload.StageCode); entity.OrderFlowCode = NormalizeOrNull(payload.OrderFlowCode); entity.RuleMechanism = NormalizeOrNull(payload.RuleMechanism); entity.UpdatedAt = DateTime.Now; await _rep.UpdateAsync(entity); return entity; } private static string? NormalizeOrNull(string? value) { if (string.IsNullOrWhiteSpace(value)) return null; var trimmed = value.Trim(); return trimmed.Length == 0 ? null : trimmed; } private static void ValidateParamsJsonByRuleType(string? ruleType, string paramsJson) { try { switch (ruleType) { case S8TimeoutRuleEvaluator.RuleTypeCode: { var p = S8TimeoutParams.Parse(paramsJson); if (string.IsNullOrWhiteSpace(p.DueAtField) || string.IsNullOrWhiteSpace(p.StatusField) || string.IsNullOrWhiteSpace(p.ExceptionTypeCode)) throw new S8BizException("TIMEOUT params 缺少必填字段:dueAtField / statusField / exceptionTypeCode"); break; } case S8ShortageRuleEvaluator.RuleTypeCode: { var p = S8ShortageParams.Parse(paramsJson); if (string.IsNullOrWhiteSpace(p.TargetQtyField) || string.IsNullOrWhiteSpace(p.ActualQtyField) || string.IsNullOrWhiteSpace(p.ExceptionTypeCode)) throw new S8BizException("SHORTAGE params 缺少必填字段:targetQtyField / actualQtyField / exceptionTypeCode"); break; } case S8OutOfRangeRuleEvaluator.RuleTypeCode: { var p = S8OutOfRangeParams.Parse(paramsJson); if (string.IsNullOrWhiteSpace(p.MeasuredValueField)) throw new S8BizException("OUT_OF_RANGE params 缺少必填字段:measuredValueField"); if (p.LowerBound == null && p.UpperBound == null && string.IsNullOrWhiteSpace(p.LowerBoundField) && string.IsNullOrWhiteSpace(p.UpperBoundField)) throw new S8BizException("OUT_OF_RANGE params 必须提供 upperBound / lowerBound 或对应行内字段之一"); break; } default: // RuleType 为空或非三类已知值:仅做 JSON 合法性校验,避免阻塞历史数据。 using (JsonDocument.Parse(paramsJson)) { } break; } } catch (JsonException ex) { throw new S8BizException($"params_json 不是合法 JSON:{ex.Message}"); } } public async Task TestAsync(long id, S8TrustedScope scope) { var entity = await LoadScopedAsync(id, scope); await ValidateAsync(entity, scope, id); return new { id, success = true, message = "规则基础校验通过", pollIntervalSeconds = entity.PollIntervalSeconds }; } // S8-SCHED-FRONTEND-1:远未来手工暂停哨兵值(与 SqlSugar DateTime 兼容;前端按 paused_until > now 判定)。 private static readonly DateTime ManualPausedSentinel = new(9999, 12, 31, 23, 59, 59); /// /// S8-SCHED-FRONTEND-1:调度参数安全更新。仅修改 poll_interval_seconds / trigger_count_required / /// recover_count_required;不动 params_json / expression / rule_type / scene_code / data_source_id。 /// public async Task UpdateScheduleAsync(long id, S8WatchRuleSchedulePayload payload, S8TrustedScope scope) { var entity = await LoadScopedAsync(id, scope); if (payload.PollIntervalSeconds < 60 || payload.PollIntervalSeconds > 86400) throw new S8BizException("poll_interval_seconds 必须在 60–86400 之间"); if (payload.TriggerCountRequired < 1 || payload.TriggerCountRequired > 10) throw new S8BizException("trigger_count_required 必须在 1–10 之间"); if (payload.RecoverCountRequired < 1 || payload.RecoverCountRequired > 10) throw new S8BizException("recover_count_required 必须在 1–10 之间"); await _rep.Context.Updateable() .SetColumns(x => new AdoS8WatchRule { PollIntervalSeconds = payload.PollIntervalSeconds, TriggerCountRequired = payload.TriggerCountRequired, RecoverCountRequired = payload.RecoverCountRequired, UpdatedAt = DateTime.Now }) .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId) .ExecuteCommandAsync(); return await LoadScopedAsync(id, scope); } /// /// S8-SCHED-FRONTEND-1:立即执行一次。把 next_run_at 置为 NOW,让下个 tick 拾取。 /// 不直接同步执行 evaluator;不阻塞请求;返回 200 + 提示。 /// public async Task RunNowAsync(long id, S8TrustedScope scope) { var entity = await LoadScopedAsync(id, scope); if (!entity.Enabled) throw new S8BizException("规则未启用,不能立即执行"); var now = DateTime.Now; if (entity.PausedUntil.HasValue && entity.PausedUntil.Value > now) throw new S8BizException("规则已暂停,请先恢复"); if (entity.LockUntil.HasValue && entity.LockUntil.Value > now) throw new S8BizException("规则正在执行中,请稍后再试"); await _rep.Context.Updateable() .SetColumns(x => new AdoS8WatchRule { NextRunAt = now, UpdatedAt = now }) .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId) .ExecuteCommandAsync(); return new { id, queued = true, message = "已排队,最长 1 分钟内执行" }; } /// /// S8-SCHED-FRONTEND-1:手工暂停。paused_until = 9999-12-31 哨兵 + pause_reason=MANUAL_PAUSED。 /// 不强杀正在执行的 lease;当前运行完成后下一轮自然不被拾取。 /// 不清 last_status / last_error。 /// public async Task PauseAsync(long id, S8TrustedScope scope) { var entity = await LoadScopedAsync(id, scope); await _rep.Context.Updateable() .SetColumns(x => new AdoS8WatchRule { PausedUntil = ManualPausedSentinel, PauseReason = "MANUAL_PAUSED", UpdatedAt = DateTime.Now }) .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId) .ExecuteCommandAsync(); return new { id, paused = true, message = "已暂停" }; } /// /// S8-SCHED-FRONTEND-1:恢复。清 paused_until / pause_reason / last_error;归零 consecutive_failure_count; /// next_run_at = NOW 让下个 tick 立即拾取。不改 enabled / params_json / rule_type。 /// public async Task ResumeAsync(long id, S8TrustedScope scope) { var entity = await LoadScopedAsync(id, scope); var now = DateTime.Now; await _rep.Context.Updateable() .SetColumns(x => new AdoS8WatchRule { PausedUntil = null, PauseReason = null, ConsecutiveFailureCount = 0, LastError = null, NextRunAt = now, UpdatedAt = now }) .Where(x => x.Id == id && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId) .ExecuteCommandAsync(); return new { id, resumed = true, message = "已恢复,并将在下一轮调度中执行" }; } private async Task ValidateAsync(AdoS8WatchRule body, S8TrustedScope scope, long? id = null) { if (string.IsNullOrWhiteSpace(body.RuleCode) || string.IsNullOrWhiteSpace(body.SceneCode)) throw new S8BizException("规则编码和场景编码必填"); var exists = await _rep.AsQueryable() .AnyAsync(x => x.Id != (id ?? 0) && x.TenantId == body.TenantId && x.FactoryId == body.FactoryId && x.RuleCode == body.RuleCode); if (exists) throw new S8BizException("监视规则编码已存在"); // S8-TENANT-FACTORY-P0-CLOSURE-1:关联数据源必须同属可信作用域,禁止引用他租户数据源。 var dataSource = await _dataSourceRep.GetFirstAsync( x => x.Id == body.DataSourceId && x.TenantId == scope.TenantId && x.FactoryId == scope.FactoryId) ?? throw new S8BizException("关联数据源不存在"); if (!dataSource.Enabled) throw new S8BizException("关联数据源未启用"); var scene = await _sceneRep.GetFirstAsync(x => x.TenantId == body.TenantId && x.FactoryId == body.FactoryId && x.SceneCode == body.SceneCode) ?? throw new S8BizException("关联场景不存在"); if (!scene.Enabled) throw new S8BizException("关联场景未启用"); if (body.PollIntervalSeconds <= 0) throw new S8BizException("轮询间隔必须大于 0"); } }