AdoS8ConfigWatchRulesController.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. using Admin.NET.Plugin.AiDOP.Infrastructure.S8;
  2. using Admin.NET.Plugin.AiDOP.Const.S8;
  3. using System.Security.Claims;
  4. using Admin.NET.Plugin.AiDOP.Entity.S8;
  5. using Admin.NET.Plugin.AiDOP.Infrastructure;
  6. using Admin.NET.Plugin.AiDOP.Service.S8;
  7. using Admin.NET.Plugin.AiDOP.Service.S8.Rules;
  8. using Microsoft.Extensions.Logging;
  9. namespace Admin.NET.Plugin.AiDOP.Controllers.S8;
  10. [ApiController]
  11. [Route("api/aidop/s8/config/watch-rules")]
  12. [NonUnify]
  13. public class AdoS8ConfigWatchRulesController : ControllerBase
  14. {
  15. private const string LegacyHeaderUseInstead = "PUT /api/aidop/s8/config/watch-rules/{id}/params";
  16. private readonly S8WatchRuleService _svc;
  17. private readonly ILogger<AdoS8ConfigWatchRulesController> _logger;
  18. private readonly S8TrustedScopeResolver _scope;
  19. public AdoS8ConfigWatchRulesController(
  20. S8WatchRuleService svc,
  21. ILogger<AdoS8ConfigWatchRulesController> logger,
  22. S8TrustedScopeResolver scope)
  23. {
  24. _svc = svc;
  25. _logger = logger;
  26. _scope = scope;
  27. }
  28. [HttpGet]
  29. [S8Permission(S8PermissionCatalog.ConfigRead)]
  30. public async Task<IActionResult> ListAsync([FromQuery] long tenantId = 1, [FromQuery] long factoryId = 1)
  31. {
  32. // Compatibility-only. Security scope is resolved server-side.
  33. _ = tenantId; _ = factoryId;
  34. var scope = await _scope.ResolveAsync();
  35. return Ok(await _svc.ListAsync(scope.TenantId));
  36. }
  37. // ================================================================================
  38. // S8-RULE-GOVERNANCE-BATCH3:业务侧建规则入口已退役 → 410 Gone。
  39. //
  40. // 选 410 墓碑而非直接删掉 route:直接删会让遗留调用方拿到 405(该路径上还有 GET),
  41. // 而 405 说的是"方法不对",会让人以为换个动词就能建。410 才准确表达
  42. // 「这个能力曾经存在、现已永久退役」,并能把替代路径写进文案。
  43. //
  44. // ⚠️ 不再调用 _scope.ResolveAsync():能力已退役,不该为构造一个用不到的 scope 去读组织库。
  45. // 这保证 DB access = 0,并让工厂组织 0 个/多个的租户也稳定得到 410 而非作用域错误。
  46. // ⚠️ catch 顺序:S8WriteRetiredException 必须排在 S8BizException 之前,否则被基类吞成 400。
  47. // ================================================================================
  48. [Obsolete("Retired. Rules are defined in code (S8RuleCatalog) and provisioned per tenant.")]
  49. [HttpPost]
  50. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  51. public IActionResult CreateAsync([FromBody] AdoS8WatchRule body)
  52. {
  53. MarkLegacyDeprecated("POST /api/aidop/s8/config/watch-rules");
  54. _ = body;
  55. try { _ = _svc.CreateAsync(body, RetiredWriteScope); return Ok(); }
  56. catch (S8WriteRetiredException ex)
  57. {
  58. return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message });
  59. }
  60. }
  61. /// <summary>
  62. /// Legacy endpoint. Rule configuration UI must use PUT /{id}/params.
  63. /// 保留兼容历史脚本/集成调用,但响应 header 与日志会标记为 deprecated。
  64. /// </summary>
  65. // ================================================================================
  66. // S8-STEP6E-CFG-WATCH-FIX-AND-SAFE-CERT-1:本入口已退役 → 410 Gone。
  67. //
  68. // 它是整实体更新,会连带把 13 个 scheduler-owned 运行时列暴露给客户端
  69. //(lock_token / lock_until / paused_until / next_run_at / last_* / consecutive_failure_count),
  70. // 足以窃取租约、制造重复执行、静默停掉监控、伪造调度审计。详见 S8WatchRuleService.UpdateAsync 注释。
  71. //
  72. // 选 410 而非 400/404:语义是「该能力曾经存在、现已永久退役」。
  73. // 400 会暗示「改对入参还能存」,404 会暗示「换个 Id 还能存」,都与事实不符。
  74. //
  75. // ⚠️ 不再调用 _scope.ResolveAsync():写能力已退役,不该为构造一个用不到的 scope 去读组织库;
  76. // 这同时保证 DB access = 0,并让工厂组织 0 个/多个的租户也稳定得到 410 而非作用域错误。
  77. // ⚠️ catch 顺序:S8WriteRetiredException 必须排在 S8NotFoundException / S8BizException 之前。
  78. // GET 与 /params /schedule /run-now /pause /resume 全部不受影响。
  79. // ================================================================================
  80. [Obsolete("Retired full-update endpoint. Use PUT /api/aidop/s8/config/watch-rules/{id}/params or /schedule.")]
  81. [HttpPut("{id:long}")]
  82. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  83. public async Task<IActionResult> UpdateAsync(long id, [FromBody] AdoS8WatchRule body)
  84. {
  85. MarkLegacyDeprecated($"PUT /api/aidop/s8/config/watch-rules/{id}", id);
  86. try { return Ok(await _svc.UpdateAsync(id, body, RetiredWriteScope)); }
  87. catch (S8WriteRetiredException ex)
  88. {
  89. return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message });
  90. }
  91. catch (S8NotFoundException) { return NotFound(); }
  92. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  93. }
  94. /// <summary>
  95. /// 写能力已永久退役:不得为了构造一个不会被使用的 scope 而读取组织库。
  96. /// Service 写方法必须在读取该占位值或访问任何仓储前抛 S8WriteRetiredException。
  97. /// (与 CFG_ALERT 的 RetiredWriteScope 同一模式。)
  98. /// </summary>
  99. private static readonly S8TrustedScope RetiredWriteScope = new(0);
  100. /// <summary>
  101. /// S8-RULE-GOVERNANCE-BATCH3:业务侧删规则入口已退役 → 410 Gone。
  102. /// 规则由系统版本定义;"不想让它跑"的正确表达是 <c>/disable</c>,不是删除。
  103. /// 与 <see cref="UpdateAsync"/> / <see cref="CreateAsync"/> 同一墓碑形态。
  104. /// </summary>
  105. [Obsolete("Retired. Disable the rule instead; rule lifecycle belongs to the code release.")]
  106. [HttpDelete("{id:long}")]
  107. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  108. public IActionResult DeleteAsync(long id)
  109. {
  110. MarkLegacyDeprecated($"DELETE /api/aidop/s8/config/watch-rules/{id}", id);
  111. try { _ = _svc.DeleteAsync(id, RetiredWriteScope); return Ok(); }
  112. catch (S8WriteRetiredException ex)
  113. {
  114. return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status410Gone, new { message = ex.Message });
  115. }
  116. }
  117. // S8-RULE-GOVERNANCE-BATCH3:POST /{id}/test 已物理移除。
  118. // 它做的只是 LoadScoped + 配置字段校验(rule_code/scene 非空、编码唯一、dataset 在目录内、
  119. // 关联场景存在且启用、poll>0),**不取数、不判定**,返回一句"规则基础校验通过"。
  120. // 这些前提现在要么由代码定义保证、要么已不适用(场景行对代码定义的规则是无关约束)。
  121. // 「这条规则启用后会命中什么」由 GET /{id}/preview 真实回答,能力完全覆盖且更强。
  122. // 仓内无任何调用方:前端 s8ConfigApi.watchRules 无 test,通用 CRUD 页的 test 只用于
  123. // 场景/大屏卡片/角色三个 endpoint,不指向 watch-rules。
  124. /// <summary>
  125. /// S8-RULE01-INTEGRATION-PREVIEW-1:只读预演 —— 「这条规则现在启用会命中什么」。
  126. ///
  127. /// 在此之前想回答这个问题只能真把规则 enabled=true 然后等调度器跑,
  128. /// 对 Rule 01 而言那意味着一次性生成 28 条真实异常单,而验证只需要 1 条。
  129. /// 本端点补上这个中间档位:走**与生产完全相同**的 Gateway → Provider → Evaluator 链,
  130. /// 但不写 detection_log / exception / rule_detection_state,不改规则任何列,不发通知。
  131. ///
  132. /// 用 GET 而非 POST 是刻意的:它是一次查询,没有副作用,
  133. /// 用 POST 会让调用方以为「点了就会发生什么」。
  134. ///
  135. /// 权限沿用 ConfigWatchRule(能配规则的人才能预演),作用域由服务端盖章。
  136. /// </summary>
  137. [HttpGet("{id:long}/preview")]
  138. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  139. public async Task<IActionResult> PreviewAsync(long id, [FromServices] S8WatchRulePreviewService preview)
  140. {
  141. try { return Ok(await preview.PreviewAsync(id, await _scope.ResolveAsync())); }
  142. catch (S8NotFoundException) { return NotFound(); }
  143. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  144. catch (S8RuleEvaluatorException ex) { return BadRequest(new { reason = ex.Reason, message = ex.Message }); }
  145. }
  146. /// <summary>
  147. /// S8-RULE-GOVERNANCE-BATCH1:运行参数的**部分更新**。
  148. ///
  149. /// <para>只接受该规则的代码定义所声明的运行参数白名单
  150. /// (轮询间隔 / 抗抖次数 / 宽限分钟 / 严重度 / 部门兜底),未提供的字段保持原值。</para>
  151. ///
  152. /// <para><b>不再接受</b> params_json 原文与任何判定语义字段 —— 那些由代码定义,
  153. /// 出现在载荷里会得到 400 而不是被静默忽略。<b>也不再接受 enabled</b>,
  154. /// 启停请用 <c>/enable</c> 与 <c>/disable</c>。</para>
  155. ///
  156. /// <para>路由暂时保留 <c>/params</c> 以免与前端一次性大改耦合;
  157. /// 前端适配排在 Batch 4。</para>
  158. /// </summary>
  159. [HttpPut("{id:long}/params")]
  160. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  161. public async Task<IActionResult> UpdateParamsAsync(long id, [FromBody] S8RuleParametersPayload body)
  162. {
  163. try { return Ok(await _svc.UpdateParametersAsync(id, body, await _scope.ResolveAsync())); }
  164. catch (S8NotFoundException) { return NotFound(); }
  165. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  166. }
  167. /// <summary>
  168. /// 启用规则。<b>与参数写入完全分离</b>:本端点只写 enabled 与下次执行时间,
  169. /// 不触碰 params_json、不触碰任何参数列、不触碰定义投影列。
  170. ///
  171. /// <para>这条分离是 G1 的结构性修复:此前启停与 params_json 共用一个写入口,
  172. /// 一次「只想关个开关」的调用就会把规则的全部业务配置抹成 NULL。</para>
  173. ///
  174. /// <para>幂等:重复启用不产生写入。</para>
  175. /// </summary>
  176. /// <summary>
  177. /// S8-HANDLER-POOL-1:规则处理账号池。
  178. ///
  179. /// <para>回答「哪些账号负责这条规则」。与「异常操作权限」(哪个角色能做认领这类动作)
  180. /// 正交:最终能否认领 = 动作权限 ∩ 规则责任 ∩ 状态机。</para>
  181. /// </summary>
  182. [HttpGet("{id:long}/handler-pool")]
  183. [S8Permission(S8PermissionCatalog.ConfigRead)]
  184. public async Task<IActionResult> HandlerPoolAsync(long id,
  185. [FromServices] S8RuleHandlerPoolService pool,
  186. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  187. {
  188. try
  189. {
  190. var scope = await _scope.ResolveAsync();
  191. var ruleCode = await ruleRep.AsQueryable().ClearFilter()
  192. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  193. .Select(x => x.RuleCode).FirstAsync()
  194. ?? throw new S8BizException("规则不存在");
  195. return Ok(await pool.GetMembersAsync(scope.TenantId, ruleCode));
  196. }
  197. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  198. }
  199. /// <summary>全量替换规则处理账号池。成员必须是本租户的启用账号。</summary>
  200. [HttpPut("{id:long}/handler-pool")]
  201. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  202. public async Task<IActionResult> SetHandlerPoolAsync(long id,
  203. [FromBody] AdoS8HandlerPoolSetDto? body,
  204. [FromServices] S8RuleHandlerPoolService pool,
  205. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  206. {
  207. try
  208. {
  209. var scope = await _scope.ResolveAsync();
  210. var ruleCode = await ruleRep.AsQueryable().ClearFilter()
  211. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  212. .Select(x => x.RuleCode).FirstAsync()
  213. ?? throw new S8BizException("规则不存在");
  214. await pool.SetMembersAsync(scope, ruleCode, body?.UserIds);
  215. return Ok(new { ruleCode, memberCount = body?.UserIds?.Count ?? 0 });
  216. }
  217. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  218. }
  219. /// <summary>
  220. /// S8-RESPONSIBILITY-POOL-1:读取该规则某一类责任池。
  221. /// <para><c>type</c> ∈ <c>HANDLER</c> / <c>REVIEWER</c> / <c>ESCALATION</c>。
  222. /// 三类共用同一套读写 API —— 存储差异(HANDLER 在存量表)被收敛在服务层,
  223. /// 调用方不需要知道。</para>
  224. /// </summary>
  225. [HttpGet("{id:long}/responsibility/{type}")]
  226. [S8Permission(S8PermissionCatalog.ConfigRead)]
  227. public async Task<IActionResult> ResponsibilityPoolAsync(long id, string type,
  228. [FromServices] S8RuleResponsibilityPoolService pool,
  229. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  230. {
  231. try
  232. {
  233. if (!S8ResponsibilityCatalog.IsKnown(type))
  234. throw new S8BizException($"未知的责任类型:{type}");
  235. var scope = await _scope.ResolveAsync();
  236. var ruleCode = await ruleRep.AsQueryable().ClearFilter()
  237. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  238. .Select(x => x.RuleCode).FirstAsync()
  239. ?? throw new S8BizException("规则不存在");
  240. var members = await pool.GetMembersAsync(scope.TenantId, ruleCode, type);
  241. var def = S8ResponsibilityCatalog.Find(type);
  242. return Ok(new
  243. {
  244. ruleCode,
  245. type,
  246. title = def?.DisplayName,
  247. description = def?.Description,
  248. members,
  249. validCount = members.Count(m => m.Valid),
  250. });
  251. }
  252. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  253. }
  254. /// <summary>全量替换该规则某一类责任池。成员必须是本租户的启用账号。</summary>
  255. [HttpPut("{id:long}/responsibility/{type}")]
  256. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  257. public async Task<IActionResult> SetResponsibilityPoolAsync(long id, string type,
  258. [FromBody] AdoS8HandlerPoolSetDto? body,
  259. [FromServices] S8RuleResponsibilityPoolService pool,
  260. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  261. {
  262. try
  263. {
  264. var scope = await _scope.ResolveAsync();
  265. var ruleCode = await ruleRep.AsQueryable().ClearFilter()
  266. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  267. .Select(x => x.RuleCode).FirstAsync()
  268. ?? throw new S8BizException("规则不存在");
  269. await pool.SetMembersAsync(scope, ruleCode, type, body?.UserIds);
  270. return Ok(new { ruleCode, type, memberCount = body?.UserIds?.Count ?? 0 });
  271. }
  272. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  273. }
  274. /// <summary>
  275. /// S8-RESPONSIBILITY-POOL-1:「通知设置」页的事件开关矩阵。
  276. /// <para>只回答「什么事件需要提醒」;提醒谁由责任关系推导,页面只读展示业务文案。</para>
  277. /// </summary>
  278. [HttpGet("{id:long}/notify-events")]
  279. [S8Permission(S8PermissionCatalog.ConfigRead)]
  280. public async Task<IActionResult> NotifyEventsAsync(long id,
  281. [FromServices] S8NotificationRecipientConfigService svc,
  282. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  283. {
  284. try
  285. {
  286. var scope = await _scope.ResolveAsync();
  287. var ruleCode = await ruleRep.AsQueryable().ClearFilter()
  288. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  289. .Select(x => x.RuleCode).FirstAsync()
  290. ?? throw new S8BizException("规则不存在");
  291. return Ok(new { ruleCode, events = await svc.GetEventSwitchesAsync(scope.TenantId, ruleCode) });
  292. }
  293. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  294. }
  295. /// <summary>按开关启用 / 关闭某事件的通知。收件人类型由目录推导,请求体不传。</summary>
  296. [HttpPut("{id:long}/notify-events/{eventCode}")]
  297. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  298. public async Task<IActionResult> SetNotifyEventAsync(long id, string eventCode,
  299. [FromBody] AdoS8NotifyEventToggleDto? body,
  300. [FromServices] S8NotificationRecipientConfigService svc,
  301. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  302. {
  303. try
  304. {
  305. var scope = await _scope.ResolveAsync();
  306. var ruleCode = await ruleRep.AsQueryable().ClearFilter()
  307. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  308. .Select(x => x.RuleCode).FirstAsync()
  309. ?? throw new S8BizException("规则不存在");
  310. await svc.SetEventEnabledAsync(scope, ruleCode, eventCode, body?.Enabled ?? false);
  311. return Ok(new { ruleCode, eventCode, enabled = body?.Enabled ?? false });
  312. }
  313. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  314. }
  315. /// <summary>
  316. /// S8-RULE-4TAB-1:<b>只读</b>返回「这条规则的异常,审核时到底由谁审」。
  317. ///
  318. /// <para>本批不新建 Rule 级 Reviewer Pool、不改 ApproverType、不动流程节点 ——
  319. /// 只把当前事实如实呈现,包括跨租户引用与"解析为 0 人"这类不好看的事实。
  320. /// 此前页面把审核人显示为「主管」,而系统里根本不存在组织主管关系。</para>
  321. /// </summary>
  322. [HttpGet("{id:long}/review-source")]
  323. [S8Permission(S8PermissionCatalog.ConfigRead)]
  324. public async Task<IActionResult> ReviewSourceAsync(long id,
  325. [FromServices] S8ReviewSourceService reviewSource,
  326. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  327. {
  328. try
  329. {
  330. var scope = await _scope.ResolveAsync();
  331. var row = await ruleRep.AsQueryable().ClearFilter()
  332. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  333. .Select(x => new { x.SceneCode })
  334. .FirstAsync()
  335. ?? throw new S8BizException("规则不存在");
  336. return Ok(new
  337. {
  338. stages = await reviewSource.DescribeAsync(scope.TenantId),
  339. escalateRoles = await reviewSource.DescribeEscalateRolesAsync(scope.TenantId, row.SceneCode),
  340. });
  341. }
  342. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  343. }
  344. /// <summary>S8-NOTIFY-RECIPIENT-1:该规则的事件通知收件人配置。</summary>
  345. [HttpGet("{id:long}/notify-recipients")]
  346. [S8Permission(S8PermissionCatalog.ConfigRead)]
  347. public async Task<IActionResult> NotifyRecipientsAsync(long id,
  348. [FromServices] S8NotificationRecipientConfigService svc,
  349. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  350. {
  351. try
  352. {
  353. var scope = await _scope.ResolveAsync();
  354. var ruleCode = await ruleRep.AsQueryable().ClearFilter()
  355. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  356. .Select(x => x.RuleCode).FirstAsync()
  357. ?? throw new S8BizException("规则不存在");
  358. return Ok(new
  359. {
  360. ruleCode,
  361. recipientTypes = S8NotificationCatalog.RecipientTypes,
  362. events = await svc.GetMatrixAsync(scope.TenantId, ruleCode),
  363. });
  364. }
  365. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  366. }
  367. /// <summary>全量替换某事件的收件人配置。</summary>
  368. /// <remarks>
  369. /// 权限位用 <c>ConfigWatchRule</c> 而不是 <c>ConfigNotification</c>:本端点是<b>规则级</b>配置
  370. /// (路由挂在规则下、作用范围就是这一条规则),一个控制器只用自己那一个 config 能力,
  371. /// 是本仓既有的授权分组约束 —— 混用会让「只有通知权限的人」能从规则控制器写入。
  372. /// 全局的通知分层配置仍由 <c>ConfigNotification</c> 守护,两者互不越界。
  373. /// </remarks>
  374. [HttpPut("{id:long}/notify-recipients/{eventCode}")]
  375. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  376. public async Task<IActionResult> SetNotifyRecipientsAsync(long id, string eventCode,
  377. [FromBody] AdoS8NotifyRecipientSetDto? body,
  378. [FromServices] S8NotificationRecipientConfigService svc,
  379. [FromServices] SqlSugarRepository<Admin.NET.Plugin.AiDOP.Entity.S8.AdoS8WatchRule> ruleRep)
  380. {
  381. try
  382. {
  383. var scope = await _scope.ResolveAsync();
  384. var ruleCode = await ruleRep.AsQueryable().ClearFilter()
  385. .Where(x => x.Id == id && x.TenantId == scope.TenantId)
  386. .Select(x => x.RuleCode).FirstAsync()
  387. ?? throw new S8BizException("规则不存在");
  388. await svc.SetAsync(scope, ruleCode, eventCode, body?.RecipientTypes, body?.SpecificUserIds);
  389. return Ok(new { ruleCode, eventCode, typeCount = body?.RecipientTypes?.Count ?? 0 });
  390. }
  391. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  392. }
  393. [HttpPost("{id:long}/enable")]
  394. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  395. public async Task<IActionResult> EnableAsync(long id)
  396. {
  397. try { return Ok(await _svc.EnableAsync(id, await _scope.ResolveAsync())); }
  398. catch (S8NotFoundException) { return NotFound(); }
  399. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  400. }
  401. /// <summary>
  402. /// S8-RULE-GOVERNANCE-BATCH2:为**当前租户**补齐代码定义规则的运行策略行。
  403. ///
  404. /// <para>用途:研发发布了一条新规则之后,管理员无需重启即可让本租户立刻拿到对应的运行策略
  405. /// (默认停用)。幂等 —— 重复调用不会重复建行。</para>
  406. ///
  407. /// <para><b>只处理调用方自己的租户</b>:全租户对账是启动期的系统级动作。
  408. /// 若在这里放开全量,一个租户管理员就能对全平台其他租户写入运行策略行 ——
  409. /// 那与 S8 其余接口"作用域由服务端从登录身份盖章"的口径直接矛盾。</para>
  410. /// </summary>
  411. [HttpPost("provision")]
  412. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  413. public async Task<IActionResult> ProvisionAsync([FromServices] S8RuleProvisioningService provisioning)
  414. {
  415. try
  416. {
  417. var scope = await _scope.ResolveAsync();
  418. return Ok(await provisioning.SyncTenantAsync(scope.TenantId));
  419. }
  420. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  421. }
  422. /// <summary>
  423. /// 停用规则。只写 enabled;幂等。
  424. /// <b>刻意不过 Enable Gate</b>:数据集出问题之后仍然必须能把规则关掉。
  425. /// </summary>
  426. [HttpPost("{id:long}/disable")]
  427. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  428. public async Task<IActionResult> DisableAsync(long id)
  429. {
  430. try { return Ok(await _svc.DisableAsync(id, await _scope.ResolveAsync())); }
  431. catch (S8NotFoundException) { return NotFound(); }
  432. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  433. }
  434. /// <summary>
  435. /// S8-SCHED-FRONTEND-1:调度参数安全更新(仅 poll_interval_seconds / trigger_count_required / recover_count_required)。
  436. /// S8-RULE-GOVERNANCE-BATCH1:已委托到统一的参数写入路径,语义与 <c>/params</c> 一致。
  437. /// </summary>
  438. [HttpPut("{id:long}/schedule")]
  439. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  440. public async Task<IActionResult> UpdateScheduleAsync(long id, [FromBody] S8WatchRuleSchedulePayload body)
  441. {
  442. try { return Ok(await _svc.UpdateScheduleAsync(id, body, await _scope.ResolveAsync())); }
  443. catch (S8NotFoundException) { return NotFound(); }
  444. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  445. }
  446. /// <summary>S8-SCHED-FRONTEND-1:立即执行一次,next_run_at 置为 NOW,由下一 tick 拾取。</summary>
  447. [HttpPost("{id:long}/run-now")]
  448. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  449. public async Task<IActionResult> RunNowAsync(long id)
  450. {
  451. try { return Ok(await _svc.RunNowAsync(id, await _scope.ResolveAsync())); }
  452. catch (S8NotFoundException) { return NotFound(); }
  453. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  454. }
  455. /// <summary>S8-SCHED-FRONTEND-1:手工暂停,paused_until 置为远未来哨兵 + pause_reason=MANUAL_PAUSED。</summary>
  456. [HttpPost("{id:long}/pause")]
  457. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  458. public async Task<IActionResult> PauseAsync(long id)
  459. {
  460. try { return Ok(await _svc.PauseAsync(id, await _scope.ResolveAsync())); }
  461. catch (S8NotFoundException) { return NotFound(); }
  462. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  463. }
  464. /// <summary>S8-SCHED-FRONTEND-1:恢复,清 paused_until / pause_reason / last_error / consecutive_failure_count,next_run_at = NOW。</summary>
  465. [HttpPost("{id:long}/resume")]
  466. [S8Permission(S8PermissionCatalog.ConfigWatchRule)]
  467. public async Task<IActionResult> ResumeAsync(long id)
  468. {
  469. try { return Ok(await _svc.ResumeAsync(id, await _scope.ResolveAsync())); }
  470. catch (S8NotFoundException) { return NotFound(); }
  471. catch (S8BizException ex) { return BadRequest(new { message = ex.Message }); }
  472. }
  473. /// <summary>
  474. /// 旧端点 deprecated 收口:写入响应 header 标记 + 结构化 warning 日志,便于运行期识别 legacy 调用。
  475. /// 不阻断调用,不改返回结构。
  476. /// </summary>
  477. private void MarkLegacyDeprecated(string endpoint, long? ruleId = null)
  478. {
  479. // 响应 header — Headers 在响应已开始发送后会抛 InvalidOperationException,此处守卫一下避免污染主调用。
  480. var headers = Response.Headers;
  481. if (!headers.ContainsKey("X-AiDOP-Deprecated"))
  482. headers["X-AiDOP-Deprecated"] = "true";
  483. if (!headers.ContainsKey("X-AiDOP-Use-Instead"))
  484. headers["X-AiDOP-Use-Instead"] = LegacyHeaderUseInstead;
  485. var userId = User?.FindFirst("UserId")?.Value
  486. ?? User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
  487. var tenantId = HttpContext?.Request?.Query["tenantId"].ToString();
  488. var factoryId = HttpContext?.Request?.Query["factoryId"].ToString();
  489. _logger.LogWarning(
  490. "legacy_watch_rule_endpoint endpoint={Endpoint} ruleId={RuleId} userId={UserId} tenantId={TenantId} factoryId={FactoryId} useInstead={UseInstead}",
  491. endpoint, ruleId, userId, tenantId, factoryId, LegacyHeaderUseInstead);
  492. }
  493. }
  494. /// <summary>责任池设置载荷(处理 / 复核 / 升级三类共用)。</summary>
  495. public class AdoS8HandlerPoolSetDto
  496. {
  497. /// <summary>完整成员集合(全量替换)。传空数组 = 清空责任池,该规则将无法启用。</summary>
  498. public List<long>? UserIds { get; set; }
  499. }
  500. /// <summary>
  501. /// 事件通知开关载荷。
  502. /// <para><b>刻意只有一个布尔</b>:收件人由责任关系推导,业务用户不选技术类型。</para>
  503. /// </summary>
  504. public class AdoS8NotifyEventToggleDto
  505. {
  506. public bool Enabled { get; set; }
  507. }
  508. /// <summary>事件收件人设置载荷。</summary>
  509. public class AdoS8NotifyRecipientSetDto
  510. {
  511. /// <summary>收件人类型集合(全量替换)。传空 = 该事件不发通知(会回落 LEGACY 分层)。</summary>
  512. public List<string>? RecipientTypes { get; set; }
  513. /// <summary>仅当包含 SPECIFIC_USER 时有效。</summary>
  514. public List<long>? SpecificUserIds { get; set; }
  515. }