-- =============================================================================
-- S8 订单计划交付超期：近30天灰度草案规则（enabled=0，仅配置留痕，不执行/不建单/不通知）
-- 前提：v_s8_order_delivery_watch 已建（1.0.177.sql）；TIMEOUT evaluator 列名契约已修（9a1d08603）。
-- 安全：enabled=0 被调度三处过滤 + 全局 S8:Scheduler:Enabled 默认 false，绝不执行。
-- 幂等：rule_code 非唯一索引，用 NOT EXISTS 守卫；id 无自增，用派生表 MAX(id)+1。
-- 不启用、不建异常、不发通知；不改其它规则/异常/通知数据。
-- =============================================================================
INSERT INTO ado_s8_watch_rule
  (id, tenant_id, factory_id, rule_code, scene_code, data_source_id, watch_object_type, source_object_type,
   severity, poll_interval_seconds, enabled, rule_type, rule_mechanism, stage_code, order_flow_code,
   trigger_count_required, recover_count_required, consecutive_failure_count, expression, params_json, created_at, updated_at)
SELECT
  m.next_id, 1, 1, 'RULE_S1_ORDER_DELIVERY_DUE_GRAY30_DATE_DELAY', 'S1', 1, 'ORDER', 'ORDER',
  'FOLLOW', 60, 0, 'TIMEOUT', 'DATE', 'S1', NULL,
  1, 1, 0,
  'SELECT order_no AS source_object_id, order_no AS related_object_code, customer_name AS related_object_name, plan_delivery_date AS due_at, delivery_status AS status FROM v_s8_order_delivery_watch WHERE plan_delivery_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND plan_delivery_date < NOW() AND delivery_status NOT IN (''COMPLETED'')',
  '{"dueAtField":"plan_delivery_date","statusField":"delivery_status","completedStates":["COMPLETED"],"graceMinutes":0,"objectIdField":"order_no","objectCodeField":"order_no","objectNameField":"customer_name","exceptionTypeCode":"ORDER_DUE_DATE_DELAY","objectLabel":"订单交付","metricLabel":"计划交付超期","unit":"分钟","thresholdDisplay":"超期即触发"}',
  NOW(), NOW()
FROM (SELECT IFNULL(MAX(id), 0) + 1 AS next_id FROM ado_s8_watch_rule) m
WHERE NOT EXISTS (SELECT 1 FROM ado_s8_watch_rule w WHERE w.rule_code = 'RULE_S1_ORDER_DELIVERY_DUE_GRAY30_DATE_DELAY');
