"""Seed the (disabled) cloud-efficiency IT digest cron. Revision ID: 420 Revises: 419 Create Date: 2026-07-20 Seeds one org-wide scheduled_jobs row for ``cmdb.efficiency_digest`` — a weekly IT-only Feishu digest of the top cloud cost-optimization opportunities. **Seeded DISABLED (`enabled = 0`)**: it pushes to real IT admins, so per the platform red line ("新增通知面一律 IT-only,上线前必须 评估存量触发面") an admin must consciously enable it in ``/admin/scheduled-jobs`` after reviewing the existing notification surface. The handler additionally no-ops on weeks with zero actionable savings, so even once enabled it never sends an empty card. The AI-narrative pass has NO cron of its own — it runs as a best-effort tail of the existing ``cmdb.efficiency_compute`` job. Idempotent: INSERT guarded by NOT EXISTS on handler_key. """ from __future__ import annotations import json import uuid import sqlalchemy as sa from alembic import op revision = "420" down_revision = "419" branch_labels = None depends_on = None _HANDLER = "cmdb.efficiency_digest" def _table_exists(bind, name: str) -> bool: return bind.execute( sa.text( "SELECT 1 FROM information_schema.TABLES " "WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :n" ), {"n": name}, ).scalar() is not None def upgrade() -> None: bind = op.get_bind() if not _table_exists(bind, "scheduled_jobs"): return bind.execute( sa.text( "INSERT INTO scheduled_jobs " "(id, name, display_name, description, handler_key, " " trigger_type, cron_expr, timezone, enabled, config, " " run_count, failure_count, created_at, updated_at) " "SELECT :id, :name, :display, :desc, :handler, 'cron', " ":cron, 'UTC', 0, :config, 0, 0, NOW(), NOW() " "FROM DUAL WHERE NOT EXISTS " "(SELECT 1 FROM scheduled_jobs WHERE handler_key = :handler)" ), { "id": str(uuid.uuid4()), "name": _HANDLER, "display": "云成本优化 · IT 周报摘要", "desc": ( "【IT-only,默认禁用/opt-in】每周把云资源效率洞察的 Top 可省项" "聚合成一条飞书卡片,只发 IT 管理员;当周无可优化项静默不发。" "上线前评估存量触发面后手动启用。" ), "handler": _HANDLER, # Weekly Monday 01:15 UTC. "cron": "15 1 * * 1", "config": json.dumps({"enabled": True}), }, ) def downgrade() -> None: bind = op.get_bind() if _table_exists(bind, "scheduled_jobs"): bind.execute( sa.text("DELETE FROM scheduled_jobs WHERE handler_key = :h"), {"h": _HANDLER}, )