This commit is contained in:
@@ -2082,6 +2082,61 @@ def api_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution_p
|
||||
}), 500
|
||||
|
||||
|
||||
@ai_bp.route('/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-resolution-closeout-package')
|
||||
@login_required
|
||||
def api_pchome_growth_direct_mapping_retry_candidate_exception_resolution_closeout_package():
|
||||
"""P2 no-write closeout package for retry candidate exception resolution."""
|
||||
try:
|
||||
from config import DATABASE_PATH
|
||||
from services.pchome_revenue_growth_service import build_pchome_growth_opportunities
|
||||
from services.pchome_mapping_backlog_service import (
|
||||
build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package,
|
||||
)
|
||||
|
||||
force_refresh = str(request.args.get('refresh') or '').strip().lower() in {'1', 'true', 'yes'}
|
||||
execute_search = str(request.args.get('execute_search') or '').strip().lower() in {'1', 'true', 'yes'}
|
||||
execute_retry_search = str(request.args.get('execute_retry_search') or '').strip().lower() in {'1', 'true', 'yes'}
|
||||
limit = request.args.get('limit', 20, type=int)
|
||||
batch_size = request.args.get('batch_size', 5, type=int)
|
||||
limit_per_product = request.args.get('limit_per_product', 8, type=int)
|
||||
max_terms_per_product = request.args.get('max_terms_per_product', 5, type=int)
|
||||
min_score = request.args.get('min_score', 0.45, type=float)
|
||||
limit = max(5, min(limit, 50))
|
||||
|
||||
payload = None
|
||||
if not force_refresh:
|
||||
payload = _get_cached_pchome_growth_payload()
|
||||
|
||||
if payload is None:
|
||||
engine = _create_icaim_dashboard_engine(DATABASE_PATH)
|
||||
try:
|
||||
payload = build_pchome_growth_opportunities(engine, limit=limit)
|
||||
finally:
|
||||
engine.dispose()
|
||||
payload["cache_state"] = "fresh"
|
||||
_set_pchome_growth_cache(payload)
|
||||
|
||||
package = build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package(
|
||||
payload,
|
||||
batch_size=batch_size,
|
||||
execute_search=execute_search,
|
||||
execute_retry_search=execute_retry_search,
|
||||
limit_per_product=limit_per_product,
|
||||
max_terms_per_product=max_terms_per_product,
|
||||
min_score=min_score,
|
||||
)
|
||||
package["source_endpoint"] = (
|
||||
"/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-auto-resolution-package"
|
||||
)
|
||||
return jsonify(package)
|
||||
except Exception as exc:
|
||||
logger.error("[PChomeGrowth] direct mapping retry candidate exception resolution closeout package 讀取失敗: %s", exc, exc_info=True)
|
||||
return jsonify({
|
||||
"success": False,
|
||||
"error": "PChome 商品對應 retry 例外解法收斂包暫時無法讀取,請稍後再試。",
|
||||
}), 500
|
||||
|
||||
|
||||
@ai_bp.route('/api/ai/pchome-growth/ai-automation-readiness')
|
||||
@login_required
|
||||
def api_pchome_growth_ai_automation_readiness():
|
||||
|
||||
@@ -50,6 +50,9 @@ DIRECT_MAPPING_RETRY_CANDIDATE_DECISION_PACKAGE_POLICY = (
|
||||
DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_POLICY = (
|
||||
"read_only_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution"
|
||||
)
|
||||
DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_POLICY = (
|
||||
"read_only_pchome_growth_direct_mapping_retry_candidate_exception_resolution_closeout"
|
||||
)
|
||||
AI_AUTOMATION_READINESS_POLICY = "read_only_pchome_growth_ai_automation_readiness"
|
||||
EVIDENCE_ENRICHMENT_PREVIEW_POLICY = "read_only_pchome_growth_evidence_enrichment_preview"
|
||||
EVIDENCE_SOURCE_PREVIEW_POLICY = "read_only_pchome_growth_evidence_source_preview"
|
||||
@@ -2566,6 +2569,109 @@ def build_pchome_direct_mapping_retry_candidate_exception_auto_resolution_packag
|
||||
}
|
||||
|
||||
|
||||
def build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package(
|
||||
payload: dict[str, Any],
|
||||
batch_size: int = 5,
|
||||
*,
|
||||
execute_search: bool = False,
|
||||
execute_retry_search: bool = False,
|
||||
limit_per_product: int = 8,
|
||||
max_terms_per_product: int = 5,
|
||||
min_score: float = 0.45,
|
||||
search_func: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Close out retry-candidate exception artifacts into machine-verifiable receipts."""
|
||||
auto_resolution = build_pchome_direct_mapping_retry_candidate_exception_auto_resolution_package(
|
||||
payload,
|
||||
batch_size=batch_size,
|
||||
execute_search=execute_search,
|
||||
execute_retry_search=execute_retry_search,
|
||||
limit_per_product=limit_per_product,
|
||||
max_terms_per_product=max_terms_per_product,
|
||||
min_score=min_score,
|
||||
search_func=search_func,
|
||||
)
|
||||
package = auto_resolution.get("retry_exception_auto_resolution_package") or {}
|
||||
artifacts = list(package.get("retry_exception_auto_resolution_artifacts") or [])
|
||||
closeout_receipts = _build_candidate_exception_resolution_closeout_receipts(
|
||||
artifacts,
|
||||
execute_retry_search=execute_retry_search,
|
||||
limit_per_product=limit_per_product,
|
||||
max_terms_per_product=max_terms_per_product,
|
||||
min_score=min_score,
|
||||
search_func=search_func,
|
||||
)
|
||||
closeout_summary = _summarize_exception_resolution_closeout_receipts(closeout_receipts)
|
||||
|
||||
selected_direct_count = int((auto_resolution.get("summary") or {}).get("selected_direct_mapping_count") or 0)
|
||||
artifact_count = int(
|
||||
(auto_resolution.get("summary") or {}).get("retry_exception_auto_resolution_artifact_count") or 0
|
||||
)
|
||||
if not selected_direct_count:
|
||||
result = "NO_DIRECT_MAPPING_TARGETS"
|
||||
elif closeout_receipts:
|
||||
result = "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_READY"
|
||||
elif artifact_count:
|
||||
result = "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
|
||||
else:
|
||||
result = "WAITING_FOR_RETRY_CANDIDATE_EXCEPTIONS"
|
||||
|
||||
return {
|
||||
"policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_POLICY,
|
||||
"result": result,
|
||||
"success": bool(auto_resolution.get("success")),
|
||||
"generated_at": auto_resolution.get("generated_at"),
|
||||
"source_policy": auto_resolution.get("policy"),
|
||||
"stats": auto_resolution.get("stats") or {},
|
||||
"backlog": auto_resolution.get("backlog") or {},
|
||||
"summary": {
|
||||
"direct_mapping_count": int((auto_resolution.get("summary") or {}).get("direct_mapping_count") or 0),
|
||||
"selected_direct_mapping_count": selected_direct_count,
|
||||
"upstream_retry_candidate_count": int(
|
||||
(auto_resolution.get("summary") or {}).get("retry_candidate_count") or 0
|
||||
),
|
||||
"retry_candidate_decision_count": int(
|
||||
(auto_resolution.get("summary") or {}).get("retry_candidate_decision_count") or 0
|
||||
),
|
||||
"retry_machine_review_exception_count": int(
|
||||
(auto_resolution.get("summary") or {}).get("retry_machine_review_exception_count") or 0
|
||||
),
|
||||
"retry_exception_auto_resolution_artifact_count": artifact_count,
|
||||
"retry_exception_resolution_closeout_receipt_count": len(closeout_receipts),
|
||||
**closeout_summary,
|
||||
"retry_exception_closeout_retry_candidate_count": closeout_summary.get("retry_candidate_count", 0),
|
||||
"writes_database_count": 0,
|
||||
"persists_candidate_count": 0,
|
||||
},
|
||||
"retry_exception_resolution_closeout_package": {
|
||||
"stage": "P2_retry_candidate_exception_resolution_closeout",
|
||||
"execute_search": bool(execute_search),
|
||||
"execute_retry_search": bool(execute_retry_search),
|
||||
"closeout_receipts": closeout_receipts,
|
||||
"resolution_mode": "ai_controlled_read_only",
|
||||
"manual_review_mode": "exception_only",
|
||||
},
|
||||
"upstream_retry_exception_auto_resolution_summary": auto_resolution.get("summary") or {},
|
||||
"next_actions": [
|
||||
"Route evidence-delta closeouts into no-write verifier input when identity delta is resolved.",
|
||||
"Feed retry-search candidates back into retry candidate decision package when candidate_count is nonzero.",
|
||||
"Keep database writes behind controlled apply, rollback, verifier, and production readback.",
|
||||
],
|
||||
"safety": {
|
||||
"read_only_preview": True,
|
||||
"executes_search": bool(execute_search),
|
||||
"executes_retry_search": bool(execute_retry_search),
|
||||
"writes_database": False,
|
||||
"persists_candidate": False,
|
||||
"syncs_external_offers": False,
|
||||
"dispatches_telegram": False,
|
||||
"llm_calls_in_preview": False,
|
||||
"gemini_allowed": False,
|
||||
"requires_production_version_truth": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def build_pchome_evidence_enrichment_preview(payload: dict[str, Any], batch_size: int = 5) -> dict[str, Any]:
|
||||
"""Build a read-only evidence enrichment package for mapping targets."""
|
||||
operator_preview = build_pchome_mapping_operator_preview(payload, batch_size=batch_size)
|
||||
|
||||
@@ -76,6 +76,7 @@ from services.pchome_mapping_backlog_service import (
|
||||
build_pchome_direct_mapping_candidate_exception_resolution_closeout_package,
|
||||
build_pchome_direct_mapping_retry_candidate_decision_package,
|
||||
build_pchome_direct_mapping_retry_candidate_exception_auto_resolution_package,
|
||||
build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package,
|
||||
build_pchome_growth_ai_automation_readiness,
|
||||
build_pchome_mapping_operator_preview,
|
||||
parse_pchome_product_page_evidence_html,
|
||||
@@ -663,6 +664,74 @@ def test_direct_mapping_retry_candidate_exception_auto_resolution_package_builds
|
||||
assert call_count["search"] == 2
|
||||
|
||||
|
||||
def test_direct_mapping_retry_candidate_exception_resolution_closeout_package_builds_receipts():
|
||||
call_count = {"search": 0}
|
||||
|
||||
def fake_search(targets, limit_per_product, max_products, max_terms_per_product, min_score):
|
||||
call_count["search"] += 1
|
||||
if targets[0].get("source_artifact_id"):
|
||||
return True, "retry_found", [
|
||||
{
|
||||
"product_id": "MOMO-RETRY-REVIEW",
|
||||
"name": "Direct mapping product 40ml 多款任選",
|
||||
"price": 499,
|
||||
"target_pchome_product_id": "PCH-2",
|
||||
"target_pchome_name": "Direct mapping product 40ml x2",
|
||||
"target_match_score": 0.74,
|
||||
"auto_compare_type": "manual_review",
|
||||
"target_hard_veto": False,
|
||||
},
|
||||
{
|
||||
"product_id": "MOMO-RETRY-VETO",
|
||||
"name": "Direct mapping product 40ml 單入",
|
||||
"price": 520,
|
||||
"target_pchome_product_id": "PCH-2",
|
||||
"target_pchome_name": "Direct mapping product 40ml x2",
|
||||
"target_match_score": 0.91,
|
||||
"auto_compare_type": "unit_price",
|
||||
"target_hard_veto": True,
|
||||
},
|
||||
]
|
||||
return True, "found", [
|
||||
{
|
||||
"product_id": "MOMO-UNIT",
|
||||
"name": "Direct mapping product 40ml",
|
||||
"price": 499,
|
||||
"target_pchome_product_id": "PCH-2",
|
||||
"target_pchome_name": "Direct mapping product 40ml x2",
|
||||
"target_match_score": 0.91,
|
||||
"auto_compare_type": "unit_price",
|
||||
"target_hard_veto": True,
|
||||
}
|
||||
]
|
||||
|
||||
package = build_pchome_direct_mapping_retry_candidate_exception_resolution_closeout_package(
|
||||
_payload(),
|
||||
batch_size=1,
|
||||
execute_search=True,
|
||||
execute_retry_search=True,
|
||||
max_terms_per_product=6,
|
||||
search_func=fake_search,
|
||||
)
|
||||
|
||||
receipts = package["retry_exception_resolution_closeout_package"]["closeout_receipts"]
|
||||
assert package["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_resolution_closeout"
|
||||
assert package["result"] == "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_READY"
|
||||
assert package["summary"]["retry_exception_auto_resolution_artifact_count"] == 2
|
||||
assert package["summary"]["retry_exception_resolution_closeout_receipt_count"] == 2
|
||||
assert package["summary"]["exception_resolution_closeout_receipt_count"] == 2
|
||||
assert package["summary"]["evidence_delta_closeout_count"] == 1
|
||||
assert package["summary"]["retry_search_ready_count"] == 1
|
||||
assert package["summary"]["retry_search_executed_count"] == 1
|
||||
assert package["summary"]["retry_candidate_count"] == 2
|
||||
assert receipts[0]["resolution_status"] == "AUTO_RESOLUTION_CLOSEOUT_READY"
|
||||
assert receipts[0]["guardrails"]["writes_database"] is False
|
||||
assert package["retry_exception_resolution_closeout_package"]["resolution_mode"] == "ai_controlled_read_only"
|
||||
assert package["safety"]["executes_retry_search"] is True
|
||||
assert package["safety"]["writes_database"] is False
|
||||
assert call_count["search"] == 3
|
||||
|
||||
|
||||
def test_ai_automation_readiness_makes_automation_visible_without_manual_primary_flow():
|
||||
readiness = build_pchome_growth_ai_automation_readiness(_payload(), batch_size=1)
|
||||
|
||||
@@ -15023,6 +15092,37 @@ def test_direct_mapping_retry_candidate_exception_auto_resolution_route_uses_cac
|
||||
assert payload["safety"]["writes_database"] is False
|
||||
|
||||
|
||||
def test_direct_mapping_retry_candidate_exception_resolution_closeout_route_uses_cached_payload(monkeypatch):
|
||||
from flask import Flask
|
||||
from routes import ai_routes as routes
|
||||
|
||||
monkeypatch.setattr(routes, "_get_cached_pchome_growth_payload", lambda: _payload())
|
||||
|
||||
def fail_engine(database_path):
|
||||
raise AssertionError("cached retry candidate exception resolution closeout package should not open a DB engine")
|
||||
|
||||
monkeypatch.setattr(routes, "_create_icaim_dashboard_engine", fail_engine)
|
||||
|
||||
app = Flask(__name__)
|
||||
with app.test_request_context(
|
||||
"/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-resolution-closeout-package?batch_size=1"
|
||||
):
|
||||
response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_resolution_closeout_package.__wrapped__()
|
||||
|
||||
payload = response.get_json()
|
||||
assert payload["success"] is True
|
||||
assert payload["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_resolution_closeout"
|
||||
assert payload["source_endpoint"] == (
|
||||
"/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-auto-resolution-package"
|
||||
)
|
||||
assert payload["result"] == "WAITING_FOR_RETRY_CANDIDATE_EXCEPTIONS"
|
||||
assert payload["summary"]["retry_exception_resolution_closeout_receipt_count"] == 0
|
||||
assert payload["retry_exception_resolution_closeout_package"]["resolution_mode"] == "ai_controlled_read_only"
|
||||
assert payload["safety"]["executes_search"] is False
|
||||
assert payload["safety"]["executes_retry_search"] is False
|
||||
assert payload["safety"]["writes_database"] is False
|
||||
|
||||
|
||||
def test_ai_automation_readiness_route_defaults_to_no_search_and_uses_cached_payload(monkeypatch):
|
||||
from flask import Flask
|
||||
from routes import ai_routes as routes
|
||||
|
||||
Reference in New Issue
Block a user