diff --git a/config.py b/config.py
index 330ef92..25d6b38 100644
--- a/config.py
+++ b/config.py
@@ -320,7 +320,7 @@ YOUTUBE_API_KEY = os.getenv('YOUTUBE_API_KEY', '')
# ==========================================
# 系統版本與路徑
# ==========================================
-SYSTEM_VERSION = "V10.192"
+SYSTEM_VERSION = "V10.193"
LOG_FILE_PATH = os.path.join(BASE_DIR, 'logs/system.log')
public_url = PUBLIC_URL # 用於模板顯示
diff --git a/docs/adr/ADR-035-cross-platform-market-campaign-intelligence.md b/docs/adr/ADR-035-cross-platform-market-campaign-intelligence.md
index 5845e05..70be3ae 100644
--- a/docs/adr/ADR-035-cross-platform-market-campaign-intelligence.md
+++ b/docs/adr/ADR-035-cross-platform-market-campaign-intelligence.md
@@ -159,6 +159,7 @@ EwoooC 目前已有 MOMO EDM / 節慶活動資料、`promo_products`、PChome
- 2026-05-18 追加 MCP fetch gate preview:`services.market_intel.mcp_fetch_gate` 與 `/api/market_intel/mcp_fetch_gate` 將人工 discovery fetch 改成必須先通過市場情報 feature flags、MCP readiness、router、外部 MCP health 與 tool contract gate;`run_manual_discovery(fetch=true)` 即使 flags 開啟也會先被此 gate 阻擋,直到 MCP 條件全過。此 gate 不抓電商頁、不寫 DB、不掛 scheduler、不執行 deployment,UI 預設只呼叫 `fetch=false&execute=false`。
- 2026-05-18 追加 scheduler attach plan preview:`services.market_intel.scheduler_plan` 與 `/api/market_intel/scheduler_plan` 描述未來 `campaign_discovery_daily`、`campaign_product_probe`、`product_match_review_seed` 三個 job 的 cadence、gate、fallback 與安全邊界。此階段不註冊 scheduler job、不啟動 crawler、不連外、不寫 DB;排程掛載必須等 migration、seed、MCP fetch gate、manual sample 與人工批准全過。
- 2026-05-18 追加 match review plan preview:`services.market_intel.match_review_plan` 與 `/api/market_intel/match_review_plan` 定義商品比對訊號、分數門檻、`needs_review → confirmed/rejected` HITL 流程與安全邊界。此階段不建立 review queue、不自動 confirmed、不寫 `market_product_matches`、不呼叫 MCP;價格只能作為輔助訊號,不能單獨決定同品比對。
+- 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 才能升級。
### Phase 4:Coupang / Shopee Adapter
diff --git a/routes/README.md b/routes/README.md
index 8ebb902..4ac87be 100644
--- a/routes/README.md
+++ b/routes/README.md
@@ -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 34 match review 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/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 35 opportunity 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/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` |
diff --git a/routes/market_intel_routes.py b/routes/market_intel_routes.py
index ccd5f18..a01e0cd 100644
--- a/routes/market_intel_routes.py
+++ b/routes/market_intel_routes.py
@@ -163,6 +163,12 @@ def market_intel_match_review_plan():
return jsonify(_service().build_match_review_plan())
+@market_intel_bp.route("/api/market_intel/opportunity_plan")
+@login_required
+def market_intel_opportunity_plan():
+ return jsonify(_service().build_opportunity_plan())
+
+
@market_intel_bp.route("/api/market_intel/adapters")
@login_required
def market_intel_adapters():
diff --git a/services/market_intel/opportunity_plan.py b/services/market_intel/opportunity_plan.py
new file mode 100644
index 0000000..13c38f9
--- /dev/null
+++ b/services/market_intel/opportunity_plan.py
@@ -0,0 +1,142 @@
+"""市場情報機會與威脅判讀 preview。
+
+只定義未來 opportunity / threat scoring 規則;不建立 queue、不寫 DB、
+不派送 Telegram、不產生 AI 報告。
+"""
+
+
+OPPORTUNITY_RULES = (
+ {
+ "key": "competitor_price_threat",
+ "label": "競品活動價低於 MOMO 參考價",
+ "severity": "high",
+ "requires_confirmed_match": True,
+ "minimum_evidence": [
+ "confirmed_or_reviewed_match",
+ "current_market_price",
+ "momo_reference_price",
+ ],
+ "action_hint": "進入價格威脅審核,不自動調價。",
+ },
+ {
+ "key": "promotion_gap",
+ "label": "競品有強促銷但我方未跟活動",
+ "severity": "medium",
+ "requires_confirmed_match": True,
+ "minimum_evidence": [
+ "active_competitor_campaign",
+ "confirmed_match",
+ "momo_campaign_absent_or_weaker",
+ ],
+ "action_hint": "標記為活動缺口,交由人工決策是否跟進。",
+ },
+ {
+ "key": "deep_discount_overlap",
+ "label": "同品或近似品出現深折重疊",
+ "severity": "medium",
+ "requires_confirmed_match": False,
+ "minimum_evidence": [
+ "needs_review_match_score_above_threshold",
+ "discount_rate_over_threshold",
+ "campaign_context",
+ ],
+ "action_hint": "送入商品比對審核,不直接派送威脅告警。",
+ },
+ {
+ "key": "campaign_ending_watch",
+ "label": "高折扣活動即將結束",
+ "severity": "low",
+ "requires_confirmed_match": False,
+ "minimum_evidence": [
+ "campaign_end_at",
+ "recent_price_snapshot",
+ "discount_or_coupon_signal",
+ ],
+ "action_hint": "排入觀察清單,避免過期活動持續推播。",
+ },
+)
+
+
+def build_opportunity_plan_preview(
+ *,
+ runtime_status,
+ match_review_plan,
+ scheduler_plan,
+ legacy_source_bridge,
+):
+ """建立市場機會與威脅判讀計畫;不執行任何推播或寫入。"""
+ legacy_bridge_safe = (
+ legacy_source_bridge.get("mode") == "legacy_source_bridge_planned"
+ and not legacy_source_bridge.get("read_only_query_executed")
+ and not legacy_source_bridge.get("database_write_executed")
+ )
+ scheduler_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")
+ )
+ match_review_safe = (
+ match_review_plan.get("mode") == "match_review_plan_preview"
+ and not match_review_plan.get("auto_confirm_executed")
+ and not match_review_plan.get("database_write_executed")
+ )
+ gate_checks = {
+ "match_review_plan_present": match_review_plan.get("mode")
+ == "match_review_plan_preview",
+ "match_review_candidates_available": bool(
+ match_review_plan.get("ready_for_review_queue")
+ ),
+ "auto_confirm_disabled": not bool(
+ (match_review_plan.get("thresholds") or {}).get("auto_confirm_enabled")
+ ),
+ "scheduler_plan_preview_safe": scheduler_safe,
+ "legacy_bridge_planned_safe": legacy_bridge_safe,
+ "database_write_still_blocked": not bool(
+ runtime_status.database_write_allowed
+ ),
+ "match_review_preview_safe": match_review_safe,
+ "manual_operator_approval": False,
+ }
+ blocked_reasons = [
+ key for key, passed in gate_checks.items()
+ if not passed
+ ]
+
+ return {
+ "mode": "opportunity_plan_preview",
+ "ready_for_opportunity_queue": False,
+ "opportunity_queue_created": False,
+ "threat_alert_dispatched": False,
+ "telegram_dispatched": False,
+ "ai_summary_generated": 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,
+ "rule_count": len(OPPORTUNITY_RULES),
+ "rules": list(OPPORTUNITY_RULES),
+ "gate_checks": gate_checks,
+ "blocked_reasons": blocked_reasons,
+ "severity_policy": {
+ "high": "只建立人工審核項,不自動調價、不直接派送高頻告警。",
+ "medium": "進入日報摘要或審核清單,需 confirmed match 才能升級。",
+ "low": "只做觀察,不觸發即時通知。",
+ },
+ "operator_sequence": [
+ "先完成商品比對審核,至少取得 confirmed 或 needs_review 高信心候選",
+ "用 campaign / price history 計算威脅與機會分數",
+ "高風險項先進人工審核清單,不直接派送 Telegram",
+ "人工確認後才允許進入 OpenClaw / Hermes 摘要",
+ "所有 AI 摘要必須附上 DB evidence id 與規則 key",
+ ],
+ "safe_boundaries": [
+ "do_not_dispatch_alerts_from_preview",
+ "do_not_generate_ai_summary_from_preview",
+ "do_not_auto_adjust_price",
+ "do_not_escalate_without_confirmed_match",
+ "do_not_write_opportunity_queue_from_preview",
+ ],
+ }
diff --git a/services/market_intel/service.py b/services/market_intel/service.py
index ea6d42c..ffeab8b 100644
--- a/services/market_intel/service.py
+++ b/services/market_intel/service.py
@@ -27,6 +27,7 @@ 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_plan import build_opportunity_plan_preview
from services.market_intel.platform_seed import build_platform_seed_rows
from services.market_intel.platform_seed_db_diff import build_platform_seed_db_diff_plan
from services.market_intel.scheduler_plan import build_scheduler_attach_plan
@@ -70,7 +71,7 @@ class MarketIntelRuntimeStatus:
class MarketIntelService:
"""市場情報入口服務,先集中 feature gate 與安全狀態。"""
- phase = "phase_34_match_review_plan_preview"
+ phase = "phase_35_opportunity_plan_preview"
def get_runtime_status(self) -> MarketIntelRuntimeStatus:
return MarketIntelRuntimeStatus(
@@ -393,6 +394,17 @@ class MarketIntelService:
plan["phase"] = self.phase
return plan
+ def build_opportunity_plan(self):
+ """回報市場機會與威脅判讀計畫;不派送、不產生 AI 報告。"""
+ plan = build_opportunity_plan_preview(
+ runtime_status=self.get_runtime_status(),
+ match_review_plan=self.build_match_review_plan(),
+ scheduler_plan=self.build_scheduler_plan(),
+ legacy_source_bridge=self.build_legacy_source_bridge(),
+ )
+ 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)
@@ -474,6 +486,7 @@ class MarketIntelService:
mcp_fetch_gate = self.build_mcp_fetch_gate()
scheduler_plan = self.build_scheduler_plan()
match_review_plan = self.build_match_review_plan()
+ opportunity_plan = self.build_opportunity_plan()
checks = {
"schema_smoke_passed": bool(schema_smoke["passed"]),
"feature_flags_default_safe": bool(
@@ -530,6 +543,12 @@ class MarketIntelService:
and not match_review_plan["auto_confirm_executed"]
and not match_review_plan["database_write_executed"]
),
+ "opportunity_plan_preview_safe": bool(
+ opportunity_plan["mode"] == "opportunity_plan_preview"
+ and not opportunity_plan["opportunity_queue_created"]
+ and not opportunity_plan["threat_alert_dispatched"]
+ and not opportunity_plan["database_write_executed"]
+ ),
}
ready_for_production_deploy = all(checks.values())
blocked_reasons = [
@@ -660,6 +679,7 @@ class MarketIntelService:
"/api/market_intel/mcp_fetch_gate",
"/api/market_intel/scheduler_plan",
"/api/market_intel/match_review_plan",
+ "/api/market_intel/opportunity_plan",
],
"status": status.to_dict(),
"schema_smoke": schema_smoke,
@@ -681,4 +701,5 @@ class MarketIntelService:
"mcp_fetch_gate": mcp_fetch_gate,
"scheduler_plan": scheduler_plan,
"match_review_plan": match_review_plan,
+ "opportunity_plan": opportunity_plan,
}
diff --git a/templates/market_intel/disabled.html b/templates/market_intel/disabled.html
index 8ce8101..ec23034 100644
--- a/templates/market_intel/disabled.html
+++ b/templates/market_intel/disabled.html
@@ -522,6 +522,24 @@
+
+
+
+
OPPORTUNITY / THREAT PLAN
+
市場機會與威脅計畫
+
+
+
+
+ loading
+
+
+
+
@@ -593,10 +611,11 @@
const mcpFetchGateRoot = document.querySelector('[data-market-intel-mcp-fetch-gate]');
const schedulerRoot = document.querySelector('[data-market-intel-scheduler]');
const matchReviewRoot = document.querySelector('[data-market-intel-match-review]');
+ const opportunityRoot = document.querySelector('[data-market-intel-opportunity]');
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 && !migrationRoot && !approvalRoot && !deployRoot) return;
+ if (!root && !writerRoot && !cliRoot && !dbProbeRoot && !seedDiffRoot && !legacyBridgeRoot && !mcpReadinessRoot && !mcpPreflightRoot && !mcpActivationRoot && !mcpFetchGateRoot && !schedulerRoot && !matchReviewRoot && !opportunityRoot && !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;
@@ -646,6 +665,10 @@
const matchReviewBody = matchReviewRoot ? matchReviewRoot.querySelector('[data-market-intel-match-review-body]') : null;
const matchReviewRefresh = matchReviewRoot ? matchReviewRoot.querySelector('[data-market-intel-match-review-refresh]') : null;
const matchReviewEndpoint = "{{ url_for('market_intel.market_intel_match_review_plan') }}";
+ const opportunityMeta = opportunityRoot ? opportunityRoot.querySelector('[data-market-intel-opportunity-meta]') : null;
+ const opportunityBody = opportunityRoot ? opportunityRoot.querySelector('[data-market-intel-opportunity-body]') : null;
+ const opportunityRefresh = opportunityRoot ? opportunityRoot.querySelector('[data-market-intel-opportunity-refresh]') : null;
+ const opportunityEndpoint = "{{ url_for('market_intel.market_intel_opportunity_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;
@@ -1549,6 +1572,108 @@
}
};
+ const renderOpportunityMeta = data => {
+ opportunityMeta.innerHTML = [
+ `mode=${data.mode || 'unknown'}`,
+ `ready=${data.ready_for_opportunity_queue ? 'yes' : 'no'}`,
+ `rules=${data.rule_count || 0}`,
+ `alerts=${data.threat_alert_dispatched ? 'sent' : 'blocked'}`,
+ `ai=${data.ai_summary_generated ? 'generated' : 'blocked'}`
+ ].map(item => `
${escapeHtml(item)}`).join('');
+ };
+
+ const renderOpportunityBody = data => {
+ const blockers = (data.blocked_reasons || []).join(' / ');
+ const checks = Object.entries(data.gate_checks || {});
+ const rules = data.rules || [];
+ const sequence = data.operator_sequence || [];
+ const severity = Object.entries(data.severity_policy || {});
+ const renderCheck = ([name, passed]) => `
+
+
+ ${escapeHtml(name)}
+
+
${passed ? 'PASS' : 'BLOCK'}
+
+ `;
+ const renderRule = item => `
+
+ ${escapeHtml(item.key)}
+ ${escapeHtml(item.label)} / severity=${escapeHtml(item.severity)}
+ ${escapeHtml((item.minimum_evidence || []).join(' + '))}
+ ${escapeHtml(item.action_hint)}
+
+ `;
+ opportunityBody.innerHTML = `
+
目前只建立機會與威脅判讀規則;不建立 queue、不派送 Telegram、不產生 AI 摘要、不寫 DB。${blockers ? `阻擋:${escapeHtml(blockers)}` : ''}
+
+
+
OPPORTUNITY GATES
+
${
+ checks.length
+ ? checks.map(renderCheck).join('')
+ : '
尚未提供機會判讀 gate。
'
+ }
+
+
+
RULES
+
${
+ rules.length
+ ? rules.map(renderRule).join('')
+ : '
尚未提供規則。
'
+ }
+
+
+
SEVERITY POLICY
+
${
+ severity.length
+ ? severity.map(([key, label]) => `
+
+
+ ${escapeHtml(key)}
+ ${escapeHtml(label)}
+
+
POLICY
+
+ `).join('')
+ : '
尚未提供分級策略。
'
+ }
+
+
+
OPERATOR SEQUENCE
+
${
+ sequence.length
+ ? sequence.map((item, index) => `
+
+
+ ${escapeHtml(`step_${index + 1}`)}
+ ${escapeHtml(item)}
+
+
REQUIRED
+
+ `).join('')
+ : '
尚未提供操作順序。
'
+ }
+
+
+ `;
+ };
+
+ const loadOpportunity = async () => {
+ if (!opportunityMeta || !opportunityBody) return;
+ opportunityBody.innerHTML = '
讀取市場機會與威脅計畫中...
';
+ try {
+ const response = await fetch(opportunityEndpoint, { credentials: 'same-origin' });
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
+ const data = await response.json();
+ renderOpportunityMeta(data);
+ renderOpportunityBody(data);
+ } catch (error) {
+ opportunityMeta.innerHTML = '
error';
+ opportunityBody.innerHTML = `
市場機會與威脅計畫讀取失敗:${escapeHtml(error.message)}
`;
+ }
+ };
+
const renderMigrationMeta = data => {
const seedWriter = data.command_plan && data.command_plan.seed_writer_command
? data.command_plan.seed_writer_command
@@ -1819,6 +1944,9 @@
if (matchReviewRefresh) {
matchReviewRefresh.addEventListener('click', loadMatchReview);
}
+ if (opportunityRefresh) {
+ opportunityRefresh.addEventListener('click', loadOpportunity);
+ }
if (migrationRefresh) {
migrationRefresh.addEventListener('click', loadMigration);
}
@@ -1840,6 +1968,7 @@
loadMcpFetchGate();
loadScheduler();
loadMatchReview();
+ loadOpportunity();
loadMigration();
loadApproval();
loadDeploy();
diff --git a/tests/test_market_intel_skeleton.py b/tests/test_market_intel_skeleton.py
index 99c4aa2..5c26ba5 100644
--- a/tests/test_market_intel_skeleton.py
+++ b/tests/test_market_intel_skeleton.py
@@ -453,6 +453,11 @@ def test_market_intel_preview_template_uses_safe_fetch_false_endpoint():
assert "data-market-intel-match-review-signals" in template
assert "data-market-intel-match-review-actions" in template
assert "data-market-intel-match-review-sequence" in template
+ assert "data-market-intel-opportunity" in template
+ assert "data-market-intel-opportunity-checks" in template
+ assert "data-market-intel-opportunity-rules" in template
+ assert "data-market-intel-opportunity-severity" in template
+ assert "data-market-intel-opportunity-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
@@ -472,6 +477,7 @@ def test_market_intel_preview_template_uses_safe_fetch_false_endpoint():
assert "market_intel.market_intel_mcp_fetch_gate" in template
assert "market_intel.market_intel_scheduler_plan" in template
assert "market_intel.market_intel_match_review_plan" in template
+ assert "market_intel.market_intel_opportunity_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
@@ -497,7 +503,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_34_match_review_plan_preview"
+ assert bridge["phase"] == "phase_35_opportunity_plan_preview"
assert bridge["execute_requested"] is False
assert bridge["read_only_query_executed"] is False
assert bridge["database_connection_opened"] is False
@@ -655,7 +661,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_34_match_review_plan_preview"
+ assert contract["phase"] == "phase_35_opportunity_plan_preview"
assert contract["caller"] == "market_intel"
assert contract["contract_ready"] is True
assert contract["blocked_reasons"] == []
@@ -788,7 +794,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_34_match_review_plan_preview"
+ assert data["phase"] == "phase_35_opportunity_plan_preview"
assert data["deployment_actions_executed"] is False
assert data["docker_command_executed"] is False
assert data["ssh_command_executed"] is False
@@ -801,7 +807,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_34_match_review_plan_preview"
+ assert gate["phase"] == "phase_35_opportunity_plan_preview"
assert gate["fetch_requested"] is True
assert gate["manual_fetch_gate_open"] is False
assert gate["network_request_allowed"] is False
@@ -871,7 +877,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_34_match_review_plan_preview"
+ assert data["phase"] == "phase_35_opportunity_plan_preview"
assert data["fetch_requested"] is False
assert data["network_request_allowed"] is False
assert data["external_network_executed"] is False
@@ -883,7 +889,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_34_match_review_plan_preview"
+ assert plan["phase"] == "phase_35_opportunity_plan_preview"
assert plan["ready_to_attach_scheduler"] is False
assert plan["scheduler_attached"] is False
assert plan["scheduler_registration_executed"] is False
@@ -921,7 +927,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_34_match_review_plan_preview"
+ assert data["phase"] == "phase_35_opportunity_plan_preview"
assert data["scheduler_registration_executed"] is False
assert data["crawler_job_started"] is False
assert data["external_network_executed"] is False
@@ -932,7 +938,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_34_match_review_plan_preview"
+ assert plan["phase"] == "phase_35_opportunity_plan_preview"
assert plan["ready_for_review_queue"] is False
assert plan["review_queue_created"] is False
assert plan["auto_match_executed"] is False
@@ -968,13 +974,65 @@ 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_34_match_review_plan_preview"
+ assert data["phase"] == "phase_35_opportunity_plan_preview"
assert data["review_queue_created"] is False
assert data["auto_confirm_executed"] is False
assert data["external_network_executed"] is False
assert data["database_write_executed"] is False
+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_35_opportunity_plan_preview"
+ assert plan["ready_for_opportunity_queue"] is False
+ assert plan["opportunity_queue_created"] is False
+ assert plan["threat_alert_dispatched"] is False
+ assert plan["telegram_dispatched"] is False
+ assert plan["ai_summary_generated"] 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["rule_count"] == 4
+ assert {item["key"] for item in plan["rules"]} == {
+ "competitor_price_threat",
+ "promotion_gap",
+ "deep_discount_overlap",
+ "campaign_ending_watch",
+ }
+ assert "match_review_candidates_available" in plan["blocked_reasons"]
+ assert "manual_operator_approval" in plan["blocked_reasons"]
+ assert "do_not_dispatch_alerts_from_preview" in plan["safe_boundaries"]
+ assert "do_not_auto_adjust_price" in plan["safe_boundaries"]
+
+
+def test_opportunity_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_plan")
+ data = response.get_json()
+
+ assert response.status_code == 200
+ assert data["mode"] == "opportunity_plan_preview"
+ assert data["phase"] == "phase_35_opportunity_plan_preview"
+ assert data["opportunity_queue_created"] is False
+ assert data["threat_alert_dispatched"] is False
+ assert data["ai_summary_generated"] is False
+ assert data["database_write_executed"] is False
+
+
def test_mcp_deploy_preflight_blocks_without_required_env():
preflight = build_mcp_deploy_preflight_plan(env={})
@@ -1038,7 +1096,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_34_match_review_plan_preview"
+ assert data["phase"] == "phase_35_opportunity_plan_preview"
assert data["deployment_actions_executed"] is False
assert data["docker_command_executed"] is False
assert data["ssh_command_executed"] is False
@@ -1053,7 +1111,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_34_match_review_plan_preview"
+ assert readiness["phase"] == "phase_35_opportunity_plan_preview"
assert readiness["execute_requested"] is False
assert readiness["router_enabled"] is False
assert readiness["external_mcp_complete"] is False
@@ -1442,6 +1500,7 @@ def test_deployment_readiness_reports_app_only_release_gate():
assert readiness["checks"]["mcp_fetch_gate_preview_safe"] is True
assert readiness["checks"]["scheduler_plan_preview_safe"] is True
assert readiness["checks"]["match_review_plan_preview_safe"] is True
+ assert readiness["checks"]["opportunity_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"]
@@ -1464,6 +1523,7 @@ def test_deployment_readiness_reports_app_only_release_gate():
assert "/api/market_intel/mcp_fetch_gate" in readiness["production_smoke_targets"]
assert "/api/market_intel/scheduler_plan" in readiness["production_smoke_targets"]
assert "/api/market_intel/match_review_plan" in readiness["production_smoke_targets"]
+ assert "/api/market_intel/opportunity_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
@@ -1488,6 +1548,9 @@ def test_deployment_readiness_reports_app_only_release_gate():
assert readiness["match_review_plan"]["review_queue_created"] is False
assert readiness["match_review_plan"]["auto_confirm_executed"] is False
assert readiness["match_review_plan"]["database_write_executed"] is False
+ assert readiness["opportunity_plan"]["opportunity_queue_created"] is False
+ assert readiness["opportunity_plan"]["threat_alert_dispatched"] is False
+ assert readiness["opportunity_plan"]["database_write_executed"] is False
def test_write_approval_runbook_is_read_only_and_blocks_real_write():