feat(market-intel): add opportunity alert plan preview
All checks were successful
CD Pipeline / deploy (push) Successful in 1m2s
All checks were successful
CD Pipeline / deploy (push) Successful in 1m2s
This commit is contained in:
@@ -320,7 +320,7 @@ YOUTUBE_API_KEY = os.getenv('YOUTUBE_API_KEY', '')
|
||||
# ==========================================
|
||||
# 系統版本與路徑
|
||||
# ==========================================
|
||||
SYSTEM_VERSION = "V10.196"
|
||||
SYSTEM_VERSION = "V10.197"
|
||||
LOG_FILE_PATH = os.path.join(BASE_DIR, 'logs/system.log')
|
||||
public_url = PUBLIC_URL # 用於模板顯示
|
||||
|
||||
|
||||
@@ -162,6 +162,7 @@ EwoooC 目前已有 MOMO EDM / 節慶活動資料、`promo_products`、PChome
|
||||
- 2026-05-18 追加 opportunity plan preview:`services.market_intel.opportunity_plan` 與 `/api/market_intel/opportunity_plan` 定義競品低價威脅、促銷缺口、深折重疊、活動即將結束四類規則與分級策略。此階段不建立 opportunity queue、不派送 Telegram、不產生 AI 摘要、不寫 DB;高風險項必須先有 confirmed match 與 DB evidence 才能升級。
|
||||
- 2026-05-18 追加 opportunity scoring plan preview:`services.market_intel.opportunity_scoring` 與 `/api/market_intel/opportunity_scoring_plan` 定義價差、折扣深度、比對可信度、活動急迫性與資料新鮮度五個 scoring dimensions、分級門檻、evidence tables 與人工升級順序。此階段不計分、不產生 sample scores、不建立 scoring job、不寫 DB、不派送 Telegram、不產生 AI 摘要。
|
||||
- 2026-05-18 追加 opportunity evidence plan preview:`services.market_intel.opportunity_evidence` 與 `/api/market_intel/opportunity_evidence_plan` 定義 scoring / alert / AI 摘要必須攜帶的 campaign、market product、match review、MOMO reference、scoring trace 五段 evidence bundle contract。此階段不查 DB、不產生 sample evidence、不建立 alert candidate、不派送 Telegram、不產生 AI 摘要。
|
||||
- 2026-05-18 追加 opportunity alert plan preview:`services.market_intel.opportunity_alerts` 與 `/api/market_intel/opportunity_alert_plan` 定義人工審核、每日摘要、Telegram 候選、AI 摘要候選四種 channel 的最低門檻、去重節流、payload contract 與操作順序。此階段不建立 alert queue、不派送 Telegram、不呼叫 LLM、不寫 DB;所有告警必須先有 evidence bundle、dedupe key 與人工批准。
|
||||
|
||||
### Phase 4:Coupang / Shopee Adapter
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
| `edm_routes.py` | EDM 與節慶儀表板 | `/edm`, `/festival` |
|
||||
| `monthly_routes.py` | 月結分析 | `/monthly_summary_analysis`, `/api/monthly_summary_data` |
|
||||
| `daily_sales_routes.py` | 當日業績 | `/daily_sales`, `/daily_sales/export*` |
|
||||
| `market_intel_routes.py` | 市場情報 Phase 37 opportunity evidence plan preview | `/market_intel`, `/market_intel/*`, `/api/market_intel/status`, `/api/market_intel/schema`, `/api/market_intel/schema_smoke`, `/api/market_intel/schema_db_probe`, `/api/market_intel/platform_seed_db_diff`, `/api/market_intel/legacy_source_bridge`, `/api/market_intel/mcp_readiness`, `/api/market_intel/mcp_tool_contract`, `/api/market_intel/mcp_deploy_preflight`, `/api/market_intel/mcp_activation_runbook`, `/api/market_intel/mcp_fetch_gate`, `/api/market_intel/scheduler_plan`, `/api/market_intel/match_review_plan`, `/api/market_intel/opportunity_plan`, `/api/market_intel/opportunity_scoring_plan`, `/api/market_intel/opportunity_evidence_plan`, `/api/market_intel/adapters`, `/api/market_intel/dry_run_plan`, `/api/market_intel/discovery_plan`, `/api/market_intel/manual_discovery`, `/api/market_intel/candidate_preview`, `/api/market_intel/platform_seed_plan`, `/api/market_intel/platform_seed_write_guard`, `/api/market_intel/platform_seed_writer_plan`, `/api/market_intel/migration_blueprint`, `/api/market_intel/seed_writer_cli_status`, `/api/market_intel/write_approval_runbook`, `/api/market_intel/deployment_readiness` |
|
||||
| `market_intel_routes.py` | 市場情報 Phase 38 opportunity alert plan preview | `/market_intel`, `/market_intel/*`, `/api/market_intel/status`, `/api/market_intel/schema`, `/api/market_intel/schema_smoke`, `/api/market_intel/schema_db_probe`, `/api/market_intel/platform_seed_db_diff`, `/api/market_intel/legacy_source_bridge`, `/api/market_intel/mcp_readiness`, `/api/market_intel/mcp_tool_contract`, `/api/market_intel/mcp_deploy_preflight`, `/api/market_intel/mcp_activation_runbook`, `/api/market_intel/mcp_fetch_gate`, `/api/market_intel/scheduler_plan`, `/api/market_intel/match_review_plan`, `/api/market_intel/opportunity_plan`, `/api/market_intel/opportunity_scoring_plan`, `/api/market_intel/opportunity_evidence_plan`, `/api/market_intel/opportunity_alert_plan`, `/api/market_intel/adapters`, `/api/market_intel/dry_run_plan`, `/api/market_intel/discovery_plan`, `/api/market_intel/manual_discovery`, `/api/market_intel/candidate_preview`, `/api/market_intel/platform_seed_plan`, `/api/market_intel/platform_seed_write_guard`, `/api/market_intel/platform_seed_writer_plan`, `/api/market_intel/migration_blueprint`, `/api/market_intel/seed_writer_cli_status`, `/api/market_intel/write_approval_runbook`, `/api/market_intel/deployment_readiness` |
|
||||
| `api_routes.py` | 通用任務與查詢 API | `/api/run_task`, `/api/history/*` |
|
||||
| `export_routes.py` | 匯出功能 | `/api/export/*` |
|
||||
| `import_routes.py` | 匯入功能 | `/api/import_excel`, `/api/import/monthly_summary` |
|
||||
|
||||
@@ -181,6 +181,12 @@ def market_intel_opportunity_evidence_plan():
|
||||
return jsonify(_service().build_opportunity_evidence_plan())
|
||||
|
||||
|
||||
@market_intel_bp.route("/api/market_intel/opportunity_alert_plan")
|
||||
@login_required
|
||||
def market_intel_opportunity_alert_plan():
|
||||
return jsonify(_service().build_opportunity_alert_plan())
|
||||
|
||||
|
||||
@market_intel_bp.route("/api/market_intel/adapters")
|
||||
@login_required
|
||||
def market_intel_adapters():
|
||||
|
||||
183
services/market_intel/opportunity_alerts.py
Normal file
183
services/market_intel/opportunity_alerts.py
Normal file
@@ -0,0 +1,183 @@
|
||||
"""市場情報機會與威脅告警候選 preview。
|
||||
|
||||
只定義未來 alert candidate、Telegram 與 AI 摘要的 gate、去重與節流;
|
||||
不建立 queue、不寫 DB、不派送訊息、不呼叫 LLM。
|
||||
"""
|
||||
|
||||
|
||||
ALERT_CHANNELS = (
|
||||
{
|
||||
"key": "operator_review",
|
||||
"label": "人工審核清單",
|
||||
"minimum_level": "watch",
|
||||
"requires_operator_approval": False,
|
||||
"dispatch_target": "market_intel_review_queue",
|
||||
},
|
||||
{
|
||||
"key": "daily_digest",
|
||||
"label": "每日市場情報摘要",
|
||||
"minimum_level": "medium",
|
||||
"requires_operator_approval": True,
|
||||
"dispatch_target": "openclaw_daily_digest",
|
||||
},
|
||||
{
|
||||
"key": "telegram_candidate",
|
||||
"label": "Telegram 候選告警",
|
||||
"minimum_level": "high",
|
||||
"requires_operator_approval": True,
|
||||
"dispatch_target": "telegram_market_intel_channel",
|
||||
},
|
||||
{
|
||||
"key": "ai_briefing_candidate",
|
||||
"label": "AI 摘要候選",
|
||||
"minimum_level": "medium",
|
||||
"requires_operator_approval": True,
|
||||
"dispatch_target": "hermes_openclaw_briefing",
|
||||
},
|
||||
)
|
||||
|
||||
ALERT_GATES = (
|
||||
{
|
||||
"key": "evidence_bundle_ready",
|
||||
"label": "必須有完整 evidence bundle",
|
||||
"required_for": ["watch", "medium", "high", "critical"],
|
||||
},
|
||||
{
|
||||
"key": "score_threshold_met",
|
||||
"label": "分數需達 channel 最低門檻",
|
||||
"required_for": ["medium", "high", "critical"],
|
||||
},
|
||||
{
|
||||
"key": "dedupe_key_clear",
|
||||
"label": "同日同商品同活動不得重複派送",
|
||||
"required_for": ["medium", "high", "critical"],
|
||||
},
|
||||
{
|
||||
"key": "freshness_window_valid",
|
||||
"label": "價格與活動快照需在 freshness window 內",
|
||||
"required_for": ["medium", "high", "critical"],
|
||||
},
|
||||
{
|
||||
"key": "operator_approval",
|
||||
"label": "人工批准後才可進 Telegram 或 AI 摘要候選",
|
||||
"required_for": ["high", "critical"],
|
||||
},
|
||||
)
|
||||
|
||||
THROTTLE_POLICY = {
|
||||
"dedupe_window_hours": 24,
|
||||
"max_telegram_candidates_per_day": 12,
|
||||
"max_critical_candidates_per_hour": 3,
|
||||
"max_ai_briefing_items_per_digest": 20,
|
||||
}
|
||||
|
||||
|
||||
def build_opportunity_alert_plan_preview(
|
||||
*,
|
||||
runtime_status,
|
||||
opportunity_plan,
|
||||
scoring_plan,
|
||||
evidence_plan,
|
||||
scheduler_plan,
|
||||
):
|
||||
"""建立告警候選與派送 gate 計畫;不建立或派送任何告警。"""
|
||||
opportunity_preview_safe = (
|
||||
opportunity_plan.get("mode") == "opportunity_plan_preview"
|
||||
and not opportunity_plan.get("opportunity_queue_created")
|
||||
and not opportunity_plan.get("threat_alert_dispatched")
|
||||
and not opportunity_plan.get("database_write_executed")
|
||||
)
|
||||
scoring_preview_safe = (
|
||||
scoring_plan.get("mode") == "opportunity_scoring_plan_preview"
|
||||
and not scoring_plan.get("score_calculation_executed")
|
||||
and not scoring_plan.get("scoring_job_created")
|
||||
and not scoring_plan.get("database_write_executed")
|
||||
)
|
||||
evidence_preview_safe = (
|
||||
evidence_plan.get("mode") == "opportunity_evidence_plan_preview"
|
||||
and not evidence_plan.get("evidence_bundle_created")
|
||||
and not evidence_plan.get("evidence_query_executed")
|
||||
and not evidence_plan.get("database_write_executed")
|
||||
)
|
||||
scheduler_preview_safe = (
|
||||
scheduler_plan.get("mode") == "scheduler_attach_plan_preview"
|
||||
and not scheduler_plan.get("scheduler_registration_executed")
|
||||
and not scheduler_plan.get("crawler_job_started")
|
||||
)
|
||||
gate_checks = {
|
||||
"opportunity_plan_preview_safe": opportunity_preview_safe,
|
||||
"scoring_plan_preview_safe": scoring_preview_safe,
|
||||
"evidence_plan_preview_safe": evidence_preview_safe,
|
||||
"scheduler_plan_preview_safe": scheduler_preview_safe,
|
||||
"evidence_bundle_ready": bool(
|
||||
evidence_plan.get("ready_for_evidence_bundle")
|
||||
),
|
||||
"scoring_job_ready": bool(scoring_plan.get("ready_for_scoring_job")),
|
||||
"opportunity_queue_ready": bool(
|
||||
opportunity_plan.get("ready_for_opportunity_queue")
|
||||
),
|
||||
"database_write_still_blocked": not bool(
|
||||
runtime_status.database_write_allowed
|
||||
),
|
||||
"operator_approval": False,
|
||||
}
|
||||
blocked_reasons = [
|
||||
key for key, passed in gate_checks.items()
|
||||
if not passed
|
||||
]
|
||||
|
||||
return {
|
||||
"mode": "opportunity_alert_plan_preview",
|
||||
"ready_for_alert_candidates": False,
|
||||
"alert_candidate_created": False,
|
||||
"alert_queue_created": False,
|
||||
"telegram_dispatched": False,
|
||||
"ai_summary_generated": False,
|
||||
"llm_call_executed": False,
|
||||
"notification_sent": False,
|
||||
"database_session_created": False,
|
||||
"database_write_executed": False,
|
||||
"database_commit_executed": False,
|
||||
"external_network_executed": False,
|
||||
"scheduler_attached": False,
|
||||
"writes_executed": False,
|
||||
"would_write_database": False,
|
||||
"channel_count": len(ALERT_CHANNELS),
|
||||
"channels": list(ALERT_CHANNELS),
|
||||
"alert_gates": list(ALERT_GATES),
|
||||
"throttle_policy": THROTTLE_POLICY,
|
||||
"gate_checks": gate_checks,
|
||||
"blocked_reasons": blocked_reasons,
|
||||
"payload_contract": {
|
||||
"required_fields": [
|
||||
"alert_candidate_id",
|
||||
"rule_key",
|
||||
"threshold_level",
|
||||
"total_score",
|
||||
"bundle_id",
|
||||
"source_batch_id",
|
||||
"dedupe_key",
|
||||
"created_at",
|
||||
],
|
||||
"forbidden_fields": [
|
||||
"customer_personal_data",
|
||||
"login_required_price",
|
||||
"cart_or_order_data",
|
||||
],
|
||||
},
|
||||
"operator_sequence": [
|
||||
"先由 evidence bundle 產生 alert candidate 草案",
|
||||
"依 throttle_policy 去重與節流,不直接推播",
|
||||
"medium 以上進每日摘要候選,high 以上才可進 Telegram 候選",
|
||||
"人工批准後才允許 AI 摘要或 Telegram 候選進入下一階段",
|
||||
"所有派送內容必須附 bundle id、source batch id 與 dedupe key",
|
||||
],
|
||||
"safe_boundaries": [
|
||||
"do_not_create_alert_queue_from_preview",
|
||||
"do_not_dispatch_telegram_from_alert_preview",
|
||||
"do_not_call_llm_from_alert_preview",
|
||||
"do_not_notify_without_evidence_bundle",
|
||||
"do_not_send_duplicate_alerts",
|
||||
"do_not_include_personal_or_login_required_data",
|
||||
],
|
||||
}
|
||||
@@ -27,6 +27,9 @@ from services.market_intel.mcp_deploy_preflight import build_mcp_deploy_prefligh
|
||||
from services.market_intel.mcp_fetch_gate import build_mcp_fetch_gate_preview
|
||||
from services.market_intel.mcp_readiness import build_mcp_readiness_plan
|
||||
from services.market_intel.migration_blueprint import build_migration_blueprint
|
||||
from services.market_intel.opportunity_alerts import (
|
||||
build_opportunity_alert_plan_preview,
|
||||
)
|
||||
from services.market_intel.opportunity_evidence import (
|
||||
build_opportunity_evidence_plan_preview,
|
||||
)
|
||||
@@ -77,7 +80,7 @@ class MarketIntelRuntimeStatus:
|
||||
class MarketIntelService:
|
||||
"""市場情報入口服務,先集中 feature gate 與安全狀態。"""
|
||||
|
||||
phase = "phase_37_opportunity_evidence_plan_preview"
|
||||
phase = "phase_38_opportunity_alert_plan_preview"
|
||||
|
||||
def get_runtime_status(self) -> MarketIntelRuntimeStatus:
|
||||
return MarketIntelRuntimeStatus(
|
||||
@@ -439,6 +442,18 @@ class MarketIntelService:
|
||||
plan["phase"] = self.phase
|
||||
return plan
|
||||
|
||||
def build_opportunity_alert_plan(self):
|
||||
"""回報機會與威脅告警候選計畫;不派送、不呼叫 LLM。"""
|
||||
plan = build_opportunity_alert_plan_preview(
|
||||
runtime_status=self.get_runtime_status(),
|
||||
opportunity_plan=self.build_opportunity_plan(),
|
||||
scoring_plan=self.build_opportunity_scoring_plan(),
|
||||
evidence_plan=self.build_opportunity_evidence_plan(),
|
||||
scheduler_plan=self.build_scheduler_plan(),
|
||||
)
|
||||
plan["phase"] = self.phase
|
||||
return plan
|
||||
|
||||
def build_platform_seed_writer_plan(self, platform_code="all"):
|
||||
"""建立 platform seed writer dry-run plan,不建立 DB session。"""
|
||||
seed_plan = self.build_platform_seed_plan(platform_code=platform_code)
|
||||
@@ -523,6 +538,7 @@ class MarketIntelService:
|
||||
opportunity_plan = self.build_opportunity_plan()
|
||||
opportunity_scoring_plan = self.build_opportunity_scoring_plan()
|
||||
opportunity_evidence_plan = self.build_opportunity_evidence_plan()
|
||||
opportunity_alert_plan = self.build_opportunity_alert_plan()
|
||||
checks = {
|
||||
"schema_smoke_passed": bool(schema_smoke["passed"]),
|
||||
"feature_flags_default_safe": bool(
|
||||
@@ -599,6 +615,13 @@ class MarketIntelService:
|
||||
and not opportunity_evidence_plan["evidence_bundle_created"]
|
||||
and not opportunity_evidence_plan["database_write_executed"]
|
||||
),
|
||||
"opportunity_alert_plan_preview_safe": bool(
|
||||
opportunity_alert_plan["mode"] == "opportunity_alert_plan_preview"
|
||||
and not opportunity_alert_plan["alert_candidate_created"]
|
||||
and not opportunity_alert_plan["telegram_dispatched"]
|
||||
and not opportunity_alert_plan["database_write_executed"]
|
||||
and not opportunity_alert_plan["llm_call_executed"]
|
||||
),
|
||||
}
|
||||
ready_for_production_deploy = all(checks.values())
|
||||
blocked_reasons = [
|
||||
@@ -732,6 +755,7 @@ class MarketIntelService:
|
||||
"/api/market_intel/opportunity_plan",
|
||||
"/api/market_intel/opportunity_scoring_plan",
|
||||
"/api/market_intel/opportunity_evidence_plan",
|
||||
"/api/market_intel/opportunity_alert_plan",
|
||||
],
|
||||
"status": status.to_dict(),
|
||||
"schema_smoke": schema_smoke,
|
||||
@@ -756,4 +780,5 @@ class MarketIntelService:
|
||||
"opportunity_plan": opportunity_plan,
|
||||
"opportunity_scoring_plan": opportunity_scoring_plan,
|
||||
"opportunity_evidence_plan": opportunity_evidence_plan,
|
||||
"opportunity_alert_plan": opportunity_alert_plan,
|
||||
}
|
||||
|
||||
@@ -576,6 +576,24 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="market-intel-panel" data-market-intel-opportunity-alert>
|
||||
<div class="market-intel-preview-head">
|
||||
<div>
|
||||
<p class="market-intel-muted momo-mono mb-1">OPPORTUNITY / ALERT CANDIDATE</p>
|
||||
<h2 class="market-intel-preview-title">機會威脅告警候選</h2>
|
||||
</div>
|
||||
<button class="market-intel-icon-button" type="button" title="重新整理機會威脅告警候選" data-market-intel-opportunity-alert-refresh>
|
||||
<i class="fas fa-rotate-right" aria-hidden="true"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="market-intel-preview-meta" data-market-intel-opportunity-alert-meta>
|
||||
<span class="market-intel-pill">loading</span>
|
||||
</div>
|
||||
<div data-market-intel-opportunity-alert-body>
|
||||
<div class="market-intel-empty">讀取機會威脅告警候選中...</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="market-intel-panel" data-market-intel-migration>
|
||||
<div class="market-intel-preview-head">
|
||||
<div>
|
||||
@@ -650,10 +668,11 @@
|
||||
const opportunityRoot = document.querySelector('[data-market-intel-opportunity]');
|
||||
const opportunityScoringRoot = document.querySelector('[data-market-intel-opportunity-scoring]');
|
||||
const opportunityEvidenceRoot = document.querySelector('[data-market-intel-opportunity-evidence]');
|
||||
const opportunityAlertRoot = document.querySelector('[data-market-intel-opportunity-alert]');
|
||||
const migrationRoot = document.querySelector('[data-market-intel-migration]');
|
||||
const approvalRoot = document.querySelector('[data-market-intel-approval]');
|
||||
const deployRoot = document.querySelector('[data-market-intel-deploy]');
|
||||
if (!root && !writerRoot && !cliRoot && !dbProbeRoot && !seedDiffRoot && !legacyBridgeRoot && !mcpReadinessRoot && !mcpPreflightRoot && !mcpActivationRoot && !mcpFetchGateRoot && !schedulerRoot && !matchReviewRoot && !opportunityRoot && !opportunityScoringRoot && !opportunityEvidenceRoot && !migrationRoot && !approvalRoot && !deployRoot) return;
|
||||
if (!root && !writerRoot && !cliRoot && !dbProbeRoot && !seedDiffRoot && !legacyBridgeRoot && !mcpReadinessRoot && !mcpPreflightRoot && !mcpActivationRoot && !mcpFetchGateRoot && !schedulerRoot && !matchReviewRoot && !opportunityRoot && !opportunityScoringRoot && !opportunityEvidenceRoot && !opportunityAlertRoot && !migrationRoot && !approvalRoot && !deployRoot) return;
|
||||
|
||||
const meta = root ? root.querySelector('[data-market-intel-preview-meta]') : null;
|
||||
const body = root ? root.querySelector('[data-market-intel-preview-body]') : null;
|
||||
@@ -715,6 +734,10 @@
|
||||
const opportunityEvidenceBody = opportunityEvidenceRoot ? opportunityEvidenceRoot.querySelector('[data-market-intel-opportunity-evidence-body]') : null;
|
||||
const opportunityEvidenceRefresh = opportunityEvidenceRoot ? opportunityEvidenceRoot.querySelector('[data-market-intel-opportunity-evidence-refresh]') : null;
|
||||
const opportunityEvidenceEndpoint = "{{ url_for('market_intel.market_intel_opportunity_evidence_plan') }}";
|
||||
const opportunityAlertMeta = opportunityAlertRoot ? opportunityAlertRoot.querySelector('[data-market-intel-opportunity-alert-meta]') : null;
|
||||
const opportunityAlertBody = opportunityAlertRoot ? opportunityAlertRoot.querySelector('[data-market-intel-opportunity-alert-body]') : null;
|
||||
const opportunityAlertRefresh = opportunityAlertRoot ? opportunityAlertRoot.querySelector('[data-market-intel-opportunity-alert-refresh]') : null;
|
||||
const opportunityAlertEndpoint = "{{ url_for('market_intel.market_intel_opportunity_alert_plan') }}";
|
||||
const migrationMeta = migrationRoot ? migrationRoot.querySelector('[data-market-intel-migration-meta]') : null;
|
||||
const migrationBody = migrationRoot ? migrationRoot.querySelector('[data-market-intel-migration-body]') : null;
|
||||
const migrationRefresh = migrationRoot ? migrationRoot.querySelector('[data-market-intel-migration-refresh]') : null;
|
||||
@@ -1958,6 +1981,129 @@
|
||||
}
|
||||
};
|
||||
|
||||
const renderOpportunityAlertMeta = data => {
|
||||
opportunityAlertMeta.innerHTML = [
|
||||
`mode=${data.mode || 'unknown'}`,
|
||||
`ready=${data.ready_for_alert_candidates ? 'yes' : 'no'}`,
|
||||
`channels=${data.channel_count || 0}`,
|
||||
`telegram=${data.telegram_dispatched ? 'sent' : 'blocked'}`,
|
||||
`llm=${data.llm_call_executed ? 'called' : 'blocked'}`
|
||||
].map(item => `<span class="market-intel-pill">${escapeHtml(item)}</span>`).join('');
|
||||
};
|
||||
|
||||
const renderOpportunityAlertBody = data => {
|
||||
const blockers = (data.blocked_reasons || []).join(' / ');
|
||||
const checks = Object.entries(data.gate_checks || {});
|
||||
const channels = data.channels || [];
|
||||
const gates = data.alert_gates || [];
|
||||
const throttle = data.throttle_policy || {};
|
||||
const sequence = data.operator_sequence || [];
|
||||
const payload = data.payload_contract || {};
|
||||
const renderCheck = ([name, passed]) => `
|
||||
<div class="market-intel-check">
|
||||
<div>
|
||||
<strong>${escapeHtml(name)}</strong>
|
||||
</div>
|
||||
<span>${passed ? 'PASS' : 'BLOCK'}</span>
|
||||
</div>
|
||||
`;
|
||||
const renderChannel = item => `
|
||||
<article class="market-intel-operation">
|
||||
<strong>${escapeHtml(item.key)}</strong>
|
||||
<small>${escapeHtml(item.label)} / minimum=${escapeHtml(item.minimum_level)}</small>
|
||||
<small>approval=${item.requires_operator_approval ? 'required' : 'not_required'} / target=${escapeHtml(item.dispatch_target)}</small>
|
||||
</article>
|
||||
`;
|
||||
opportunityAlertBody.innerHTML = `
|
||||
<div class="market-intel-empty mb-3">目前只定義告警候選 gate;不建立 alert queue、不派送 Telegram、不呼叫 LLM、不寫 DB。${blockers ? `阻擋:${escapeHtml(blockers)}` : ''}</div>
|
||||
<div class="market-intel-empty mb-3">dedupe=${escapeHtml(throttle.dedupe_window_hours || 'n/a')}h / telegram_daily=${escapeHtml(throttle.max_telegram_candidates_per_day || 0)} / ai_digest=${escapeHtml(throttle.max_ai_briefing_items_per_digest || 0)}</div>
|
||||
<div class="market-intel-deploy-grid">
|
||||
<div data-market-intel-opportunity-alert-checks>
|
||||
<p class="market-intel-deploy-section-title">ALERT GATES</p>
|
||||
<div class="market-intel-check-list">${
|
||||
checks.length
|
||||
? checks.map(renderCheck).join('')
|
||||
: '<div class="market-intel-empty">尚未提供告警 gate。</div>'
|
||||
}</div>
|
||||
</div>
|
||||
<div data-market-intel-opportunity-alert-channels>
|
||||
<p class="market-intel-deploy-section-title">CHANNELS</p>
|
||||
<div class="market-intel-operation-list">${
|
||||
channels.length
|
||||
? channels.map(renderChannel).join('')
|
||||
: '<div class="market-intel-empty">尚未提供 channel。</div>'
|
||||
}</div>
|
||||
</div>
|
||||
<div data-market-intel-opportunity-alert-escalation>
|
||||
<p class="market-intel-deploy-section-title">ESCALATION</p>
|
||||
<div class="market-intel-check-list">${
|
||||
gates.length
|
||||
? gates.map(item => `
|
||||
<div class="market-intel-check">
|
||||
<div>
|
||||
<strong>${escapeHtml(item.key)}</strong>
|
||||
<small>${escapeHtml(item.label)}</small>
|
||||
</div>
|
||||
<span>${escapeHtml((item.required_for || []).join('/'))}</span>
|
||||
</div>
|
||||
`).join('')
|
||||
: '<div class="market-intel-empty">尚未提供升級 gate。</div>'
|
||||
}</div>
|
||||
</div>
|
||||
<div data-market-intel-opportunity-alert-payload>
|
||||
<p class="market-intel-deploy-section-title">PAYLOAD CONTRACT</p>
|
||||
<div class="market-intel-check-list">
|
||||
<div class="market-intel-check">
|
||||
<div>
|
||||
<strong>required_fields</strong>
|
||||
<small>${escapeHtml((payload.required_fields || []).join(' / '))}</small>
|
||||
</div>
|
||||
<span>REQUIRED</span>
|
||||
</div>
|
||||
<div class="market-intel-check">
|
||||
<div>
|
||||
<strong>forbidden_fields</strong>
|
||||
<small>${escapeHtml((payload.forbidden_fields || []).join(' / '))}</small>
|
||||
</div>
|
||||
<span>BLOCKED</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div data-market-intel-opportunity-alert-sequence>
|
||||
<p class="market-intel-deploy-section-title">OPERATOR SEQUENCE</p>
|
||||
<div class="market-intel-check-list">${
|
||||
sequence.length
|
||||
? sequence.map((item, index) => `
|
||||
<div class="market-intel-check">
|
||||
<div>
|
||||
<strong>${escapeHtml(`step_${index + 1}`)}</strong>
|
||||
<small>${escapeHtml(item)}</small>
|
||||
</div>
|
||||
<span>REQUIRED</span>
|
||||
</div>
|
||||
`).join('')
|
||||
: '<div class="market-intel-empty">尚未提供操作順序。</div>'
|
||||
}</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
};
|
||||
|
||||
const loadOpportunityAlert = async () => {
|
||||
if (!opportunityAlertMeta || !opportunityAlertBody) return;
|
||||
opportunityAlertBody.innerHTML = '<div class="market-intel-empty">讀取機會威脅告警候選中...</div>';
|
||||
try {
|
||||
const response = await fetch(opportunityAlertEndpoint, { credentials: 'same-origin' });
|
||||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||||
const data = await response.json();
|
||||
renderOpportunityAlertMeta(data);
|
||||
renderOpportunityAlertBody(data);
|
||||
} catch (error) {
|
||||
opportunityAlertMeta.innerHTML = '<span class="market-intel-pill">error</span>';
|
||||
opportunityAlertBody.innerHTML = `<div class="market-intel-empty">機會威脅告警候選讀取失敗:${escapeHtml(error.message)}</div>`;
|
||||
}
|
||||
};
|
||||
|
||||
const renderMigrationMeta = data => {
|
||||
const seedWriter = data.command_plan && data.command_plan.seed_writer_command
|
||||
? data.command_plan.seed_writer_command
|
||||
@@ -2237,6 +2383,9 @@
|
||||
if (opportunityEvidenceRefresh) {
|
||||
opportunityEvidenceRefresh.addEventListener('click', loadOpportunityEvidence);
|
||||
}
|
||||
if (opportunityAlertRefresh) {
|
||||
opportunityAlertRefresh.addEventListener('click', loadOpportunityAlert);
|
||||
}
|
||||
if (migrationRefresh) {
|
||||
migrationRefresh.addEventListener('click', loadMigration);
|
||||
}
|
||||
@@ -2261,6 +2410,7 @@
|
||||
loadOpportunity();
|
||||
loadOpportunityScoring();
|
||||
loadOpportunityEvidence();
|
||||
loadOpportunityAlert();
|
||||
loadMigration();
|
||||
loadApproval();
|
||||
loadDeploy();
|
||||
|
||||
@@ -470,6 +470,12 @@ def test_market_intel_preview_template_uses_safe_fetch_false_endpoint():
|
||||
assert "data-market-intel-opportunity-evidence-escalation" in template
|
||||
assert "data-market-intel-opportunity-evidence-tables" in template
|
||||
assert "data-market-intel-opportunity-evidence-sequence" in template
|
||||
assert "data-market-intel-opportunity-alert" in template
|
||||
assert "data-market-intel-opportunity-alert-checks" in template
|
||||
assert "data-market-intel-opportunity-alert-channels" in template
|
||||
assert "data-market-intel-opportunity-alert-escalation" in template
|
||||
assert "data-market-intel-opportunity-alert-payload" in template
|
||||
assert "data-market-intel-opportunity-alert-sequence" in template
|
||||
assert "data-market-intel-migration" in template
|
||||
assert "data-market-intel-migration-tables" in template
|
||||
assert "data-market-intel-approval" in template
|
||||
@@ -492,6 +498,7 @@ def test_market_intel_preview_template_uses_safe_fetch_false_endpoint():
|
||||
assert "market_intel.market_intel_opportunity_plan" in template
|
||||
assert "market_intel.market_intel_opportunity_scoring_plan" in template
|
||||
assert "market_intel.market_intel_opportunity_evidence_plan" in template
|
||||
assert "market_intel.market_intel_opportunity_alert_plan" in template
|
||||
assert "market_intel.market_intel_migration_blueprint" in template
|
||||
assert "market_intel.market_intel_write_approval_runbook" in template
|
||||
assert "market_intel.market_intel_deployment_readiness" in template
|
||||
@@ -517,7 +524,7 @@ def test_legacy_source_bridge_default_is_planned_only():
|
||||
bridge = MarketIntelService().build_legacy_source_bridge()
|
||||
|
||||
assert bridge["mode"] == "legacy_source_bridge_planned"
|
||||
assert bridge["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert bridge["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert bridge["execute_requested"] is False
|
||||
assert bridge["read_only_query_executed"] is False
|
||||
assert bridge["database_connection_opened"] is False
|
||||
@@ -675,7 +682,7 @@ def test_mcp_tool_contract_preview_is_read_only_and_whitelisted():
|
||||
contract = MarketIntelService().build_mcp_tool_contract()
|
||||
|
||||
assert contract["mode"] == "mcp_tool_contract_preview"
|
||||
assert contract["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert contract["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert contract["caller"] == "market_intel"
|
||||
assert contract["contract_ready"] is True
|
||||
assert contract["blocked_reasons"] == []
|
||||
@@ -808,7 +815,7 @@ def test_mcp_activation_runbook_route_is_preview_only():
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "mcp_activation_runbook_preview"
|
||||
assert data["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["deployment_actions_executed"] is False
|
||||
assert data["docker_command_executed"] is False
|
||||
assert data["ssh_command_executed"] is False
|
||||
@@ -821,7 +828,7 @@ def test_mcp_fetch_gate_default_blocks_external_fetch():
|
||||
gate = MarketIntelService().build_mcp_fetch_gate(fetch_requested=True)
|
||||
|
||||
assert gate["mode"] == "mcp_fetch_gate_planned"
|
||||
assert gate["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert gate["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert gate["fetch_requested"] is True
|
||||
assert gate["manual_fetch_gate_open"] is False
|
||||
assert gate["network_request_allowed"] is False
|
||||
@@ -891,7 +898,7 @@ def test_mcp_fetch_gate_route_is_preview_only():
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "mcp_fetch_gate_planned"
|
||||
assert data["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["fetch_requested"] is False
|
||||
assert data["network_request_allowed"] is False
|
||||
assert data["external_network_executed"] is False
|
||||
@@ -903,7 +910,7 @@ def test_scheduler_plan_preview_blocks_job_attachment():
|
||||
plan = MarketIntelService().build_scheduler_plan()
|
||||
|
||||
assert plan["mode"] == "scheduler_attach_plan_preview"
|
||||
assert plan["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert plan["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert plan["ready_to_attach_scheduler"] is False
|
||||
assert plan["scheduler_attached"] is False
|
||||
assert plan["scheduler_registration_executed"] is False
|
||||
@@ -941,7 +948,7 @@ def test_scheduler_plan_route_is_preview_only():
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "scheduler_attach_plan_preview"
|
||||
assert data["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["scheduler_registration_executed"] is False
|
||||
assert data["crawler_job_started"] is False
|
||||
assert data["external_network_executed"] is False
|
||||
@@ -952,7 +959,7 @@ def test_match_review_plan_preview_blocks_auto_confirm():
|
||||
plan = MarketIntelService().build_match_review_plan()
|
||||
|
||||
assert plan["mode"] == "match_review_plan_preview"
|
||||
assert plan["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert plan["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert plan["ready_for_review_queue"] is False
|
||||
assert plan["review_queue_created"] is False
|
||||
assert plan["auto_match_executed"] is False
|
||||
@@ -988,7 +995,7 @@ def test_match_review_plan_route_is_preview_only():
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "match_review_plan_preview"
|
||||
assert data["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["review_queue_created"] is False
|
||||
assert data["auto_confirm_executed"] is False
|
||||
assert data["external_network_executed"] is False
|
||||
@@ -999,7 +1006,7 @@ def test_opportunity_plan_preview_blocks_alerts_and_ai_summary():
|
||||
plan = MarketIntelService().build_opportunity_plan()
|
||||
|
||||
assert plan["mode"] == "opportunity_plan_preview"
|
||||
assert plan["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert plan["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert plan["ready_for_opportunity_queue"] is False
|
||||
assert plan["opportunity_queue_created"] is False
|
||||
assert plan["threat_alert_dispatched"] is False
|
||||
@@ -1040,7 +1047,7 @@ def test_opportunity_plan_route_is_preview_only():
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "opportunity_plan_preview"
|
||||
assert data["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["opportunity_queue_created"] is False
|
||||
assert data["threat_alert_dispatched"] is False
|
||||
assert data["ai_summary_generated"] is False
|
||||
@@ -1051,7 +1058,7 @@ def test_opportunity_scoring_plan_preview_blocks_scoring_and_alerts():
|
||||
plan = MarketIntelService().build_opportunity_scoring_plan()
|
||||
|
||||
assert plan["mode"] == "opportunity_scoring_plan_preview"
|
||||
assert plan["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert plan["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert plan["ready_for_scoring_job"] is False
|
||||
assert plan["scoring_job_created"] is False
|
||||
assert plan["score_calculation_executed"] is False
|
||||
@@ -1099,7 +1106,7 @@ def test_opportunity_scoring_plan_route_is_preview_only():
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "opportunity_scoring_plan_preview"
|
||||
assert data["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["scoring_job_created"] is False
|
||||
assert data["score_calculation_executed"] is False
|
||||
assert data["sample_scores_generated"] is False
|
||||
@@ -1111,7 +1118,7 @@ def test_opportunity_evidence_plan_preview_blocks_queries_and_alerts():
|
||||
plan = MarketIntelService().build_opportunity_evidence_plan()
|
||||
|
||||
assert plan["mode"] == "opportunity_evidence_plan_preview"
|
||||
assert plan["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert plan["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert plan["ready_for_evidence_bundle"] is False
|
||||
assert plan["evidence_bundle_created"] is False
|
||||
assert plan["evidence_query_executed"] is False
|
||||
@@ -1157,7 +1164,7 @@ def test_opportunity_evidence_plan_route_is_preview_only():
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["evidence_bundle_created"] is False
|
||||
assert data["evidence_query_executed"] is False
|
||||
assert data["sample_evidence_generated"] is False
|
||||
@@ -1166,6 +1173,64 @@ def test_opportunity_evidence_plan_route_is_preview_only():
|
||||
assert data["external_network_executed"] is False
|
||||
|
||||
|
||||
def test_opportunity_alert_plan_preview_blocks_dispatch_and_llm_calls():
|
||||
plan = MarketIntelService().build_opportunity_alert_plan()
|
||||
|
||||
assert plan["mode"] == "opportunity_alert_plan_preview"
|
||||
assert plan["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert plan["ready_for_alert_candidates"] is False
|
||||
assert plan["alert_candidate_created"] is False
|
||||
assert plan["alert_queue_created"] is False
|
||||
assert plan["telegram_dispatched"] is False
|
||||
assert plan["ai_summary_generated"] is False
|
||||
assert plan["llm_call_executed"] is False
|
||||
assert plan["notification_sent"] is False
|
||||
assert plan["database_session_created"] is False
|
||||
assert plan["database_write_executed"] is False
|
||||
assert plan["database_commit_executed"] is False
|
||||
assert plan["external_network_executed"] is False
|
||||
assert plan["scheduler_attached"] is False
|
||||
assert plan["writes_executed"] is False
|
||||
assert plan["would_write_database"] is False
|
||||
assert plan["channel_count"] == 4
|
||||
assert {item["key"] for item in plan["channels"]} == {
|
||||
"operator_review",
|
||||
"daily_digest",
|
||||
"telegram_candidate",
|
||||
"ai_briefing_candidate",
|
||||
}
|
||||
assert "evidence_bundle_ready" in plan["blocked_reasons"]
|
||||
assert "scoring_job_ready" in plan["blocked_reasons"]
|
||||
assert "operator_approval" in plan["blocked_reasons"]
|
||||
assert "do_not_dispatch_telegram_from_alert_preview" in plan["safe_boundaries"]
|
||||
assert "do_not_call_llm_from_alert_preview" in plan["safe_boundaries"]
|
||||
assert "customer_personal_data" in plan["payload_contract"]["forbidden_fields"]
|
||||
|
||||
|
||||
def test_opportunity_alert_plan_route_is_preview_only():
|
||||
from routes.market_intel_routes import market_intel_bp
|
||||
|
||||
app = Flask(__name__)
|
||||
app.secret_key = "test-secret"
|
||||
app.register_blueprint(market_intel_bp)
|
||||
client = app.test_client()
|
||||
with client.session_transaction() as session:
|
||||
session["logged_in"] = True
|
||||
|
||||
response = client.get("/api/market_intel/opportunity_alert_plan")
|
||||
data = response.get_json()
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "opportunity_alert_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["alert_candidate_created"] is False
|
||||
assert data["alert_queue_created"] is False
|
||||
assert data["telegram_dispatched"] is False
|
||||
assert data["llm_call_executed"] is False
|
||||
assert data["database_write_executed"] is False
|
||||
assert data["external_network_executed"] is False
|
||||
|
||||
|
||||
def test_mcp_deploy_preflight_blocks_without_required_env():
|
||||
preflight = build_mcp_deploy_preflight_plan(env={})
|
||||
|
||||
@@ -1229,7 +1294,7 @@ def test_mcp_deploy_preflight_route_is_preview_only():
|
||||
|
||||
assert response.status_code == 200
|
||||
assert data["mode"] == "mcp_external_deploy_preflight_preview"
|
||||
assert data["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert data["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert data["deployment_actions_executed"] is False
|
||||
assert data["docker_command_executed"] is False
|
||||
assert data["ssh_command_executed"] is False
|
||||
@@ -1244,7 +1309,7 @@ def test_mcp_readiness_default_is_planned_only(monkeypatch):
|
||||
readiness = MarketIntelService().build_mcp_readiness()
|
||||
|
||||
assert readiness["mode"] == "mcp_readiness_planned"
|
||||
assert readiness["phase"] == "phase_37_opportunity_evidence_plan_preview"
|
||||
assert readiness["phase"] == "phase_38_opportunity_alert_plan_preview"
|
||||
assert readiness["execute_requested"] is False
|
||||
assert readiness["router_enabled"] is False
|
||||
assert readiness["external_mcp_complete"] is False
|
||||
@@ -1636,6 +1701,7 @@ def test_deployment_readiness_reports_app_only_release_gate():
|
||||
assert readiness["checks"]["opportunity_plan_preview_safe"] is True
|
||||
assert readiness["checks"]["opportunity_scoring_plan_preview_safe"] is True
|
||||
assert readiness["checks"]["opportunity_evidence_plan_preview_safe"] is True
|
||||
assert readiness["checks"]["opportunity_alert_plan_preview_safe"] is True
|
||||
assert readiness["checks"]["writer_plan_dry_run_only"] is True
|
||||
assert readiness["writer_plan_summary"]["writes_executed"] is False
|
||||
assert "readiness_checks_not_all_passed" not in readiness["blocked_reasons"]
|
||||
@@ -1661,6 +1727,7 @@ def test_deployment_readiness_reports_app_only_release_gate():
|
||||
assert "/api/market_intel/opportunity_plan" in readiness["production_smoke_targets"]
|
||||
assert "/api/market_intel/opportunity_scoring_plan" in readiness["production_smoke_targets"]
|
||||
assert "/api/market_intel/opportunity_evidence_plan" in readiness["production_smoke_targets"]
|
||||
assert "/api/market_intel/opportunity_alert_plan" in readiness["production_smoke_targets"]
|
||||
assert readiness["write_approval_runbook"]["ready_for_real_write"] is False
|
||||
assert readiness["write_approval_runbook"]["writes_executed"] is False
|
||||
assert readiness["migration_blueprint"]["migration_executed"] is False
|
||||
@@ -1694,6 +1761,10 @@ def test_deployment_readiness_reports_app_only_release_gate():
|
||||
assert readiness["opportunity_evidence_plan"]["evidence_bundle_created"] is False
|
||||
assert readiness["opportunity_evidence_plan"]["evidence_query_executed"] is False
|
||||
assert readiness["opportunity_evidence_plan"]["database_write_executed"] is False
|
||||
assert readiness["opportunity_alert_plan"]["alert_candidate_created"] is False
|
||||
assert readiness["opportunity_alert_plan"]["telegram_dispatched"] is False
|
||||
assert readiness["opportunity_alert_plan"]["llm_call_executed"] is False
|
||||
assert readiness["opportunity_alert_plan"]["database_write_executed"] is False
|
||||
|
||||
|
||||
def test_write_approval_runbook_is_read_only_and_blocks_real_write():
|
||||
|
||||
Reference in New Issue
Block a user