This commit is contained in:
@@ -2027,6 +2027,61 @@ def api_pchome_growth_direct_mapping_retry_candidate_decision_package():
|
||||
}), 500
|
||||
|
||||
|
||||
@ai_bp.route('/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-exception-auto-resolution-package')
|
||||
@login_required
|
||||
def api_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution_package():
|
||||
"""P2 no-write auto-resolution package for retry candidate exceptions."""
|
||||
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_auto_resolution_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_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,
|
||||
)
|
||||
package["source_endpoint"] = (
|
||||
"/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-decision-package"
|
||||
)
|
||||
return jsonify(package)
|
||||
except Exception as exc:
|
||||
logger.error("[PChomeGrowth] direct mapping retry candidate exception auto-resolution 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():
|
||||
|
||||
@@ -47,6 +47,9 @@ DIRECT_MAPPING_CANDIDATE_EXCEPTION_RESOLUTION_CLOSEOUT_POLICY = (
|
||||
DIRECT_MAPPING_RETRY_CANDIDATE_DECISION_PACKAGE_POLICY = (
|
||||
"read_only_pchome_growth_direct_mapping_retry_candidate_decision_package"
|
||||
)
|
||||
DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_POLICY = (
|
||||
"read_only_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution"
|
||||
)
|
||||
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"
|
||||
@@ -2470,6 +2473,99 @@ def build_pchome_direct_mapping_retry_candidate_decision_package(
|
||||
}
|
||||
|
||||
|
||||
def build_pchome_direct_mapping_retry_candidate_exception_auto_resolution_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]:
|
||||
"""Build retry-exception auto-resolution artifacts without routing to human review."""
|
||||
retry_package = build_pchome_direct_mapping_retry_candidate_decision_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 = retry_package.get("retry_candidate_decision_package") or {}
|
||||
retry_exception_receipts = list(package.get("machine_review_exception_receipts") or [])
|
||||
artifacts = _build_candidate_exception_auto_resolution_artifacts(retry_exception_receipts)
|
||||
artifact_summary = _summarize_exception_auto_resolution_artifacts(artifacts)
|
||||
|
||||
selected_direct_count = int((retry_package.get("summary") or {}).get("selected_direct_mapping_count") or 0)
|
||||
retry_decision_count = int((retry_package.get("summary") or {}).get("retry_candidate_decision_count") or 0)
|
||||
if not selected_direct_count:
|
||||
result = "NO_DIRECT_MAPPING_TARGETS"
|
||||
elif artifacts:
|
||||
result = "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
|
||||
elif retry_decision_count:
|
||||
result = "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTIONS_CLEAR"
|
||||
else:
|
||||
result = "WAITING_FOR_RETRY_CANDIDATE_DECISIONS"
|
||||
|
||||
return {
|
||||
"policy": DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_POLICY,
|
||||
"result": result,
|
||||
"success": bool(retry_package.get("success")),
|
||||
"generated_at": retry_package.get("generated_at"),
|
||||
"source_policy": retry_package.get("policy"),
|
||||
"stats": retry_package.get("stats") or {},
|
||||
"backlog": retry_package.get("backlog") or {},
|
||||
"summary": {
|
||||
"direct_mapping_count": int((retry_package.get("summary") or {}).get("direct_mapping_count") or 0),
|
||||
"selected_direct_mapping_count": selected_direct_count,
|
||||
"retry_candidate_count": int((retry_package.get("summary") or {}).get("retry_candidate_count") or 0),
|
||||
"retry_candidate_decision_count": retry_decision_count,
|
||||
"retry_no_write_verifier_input_count": int(
|
||||
(retry_package.get("summary") or {}).get("retry_no_write_verifier_input_count") or 0
|
||||
),
|
||||
"retry_machine_review_exception_count": len(retry_exception_receipts),
|
||||
"retry_exception_auto_resolution_artifact_count": len(artifacts),
|
||||
"ready_for_no_write_verifier_count": int(
|
||||
(retry_package.get("summary") or {}).get("ready_for_no_write_verifier_count") or 0
|
||||
),
|
||||
**artifact_summary,
|
||||
"writes_database_count": 0,
|
||||
"persists_candidate_count": 0,
|
||||
},
|
||||
"retry_exception_auto_resolution_package": {
|
||||
"stage": "P2_retry_candidate_exception_auto_resolution",
|
||||
"execute_search": bool(execute_search),
|
||||
"execute_retry_search": bool(execute_retry_search),
|
||||
"retry_machine_review_exception_receipts": retry_exception_receipts,
|
||||
"retry_exception_auto_resolution_artifacts": artifacts,
|
||||
"resolution_mode": "ai_controlled_read_only",
|
||||
"manual_review_mode": "exception_only",
|
||||
},
|
||||
"upstream_retry_decision_summary": retry_package.get("summary") or {},
|
||||
"next_actions": [
|
||||
"Feed retry exception artifacts into a retry exception closeout package before another search cycle.",
|
||||
"Send ready no-write verifier receipts into verifier artifact preview before any persistence.",
|
||||
"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)
|
||||
|
||||
@@ -75,6 +75,7 @@ from services.pchome_mapping_backlog_service import (
|
||||
build_pchome_direct_mapping_candidate_exception_auto_resolution_package,
|
||||
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_growth_ai_automation_readiness,
|
||||
build_pchome_mapping_operator_preview,
|
||||
parse_pchome_product_page_evidence_html,
|
||||
@@ -593,6 +594,75 @@ def test_direct_mapping_retry_candidate_decision_package_routes_retry_candidates
|
||||
assert call_count["search"] == 2
|
||||
|
||||
|
||||
def test_direct_mapping_retry_candidate_exception_auto_resolution_package_builds_artifacts():
|
||||
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_auto_resolution_package(
|
||||
_payload(),
|
||||
batch_size=1,
|
||||
execute_search=True,
|
||||
execute_retry_search=True,
|
||||
max_terms_per_product=6,
|
||||
search_func=fake_search,
|
||||
)
|
||||
|
||||
artifacts = package["retry_exception_auto_resolution_package"]["retry_exception_auto_resolution_artifacts"]
|
||||
assert package["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution"
|
||||
assert package["result"] == "DIRECT_MAPPING_RETRY_CANDIDATE_EXCEPTION_AUTO_RESOLUTION_READY"
|
||||
assert package["summary"]["retry_candidate_count"] == 2
|
||||
assert package["summary"]["retry_candidate_decision_count"] == 2
|
||||
assert package["summary"]["retry_machine_review_exception_count"] == 2
|
||||
assert package["summary"]["retry_exception_auto_resolution_artifact_count"] == 2
|
||||
assert package["summary"]["variant_bundle_discriminator_count"] == 1
|
||||
assert package["summary"]["named_candidate_evidence_delta_count"] == 1
|
||||
assert package["summary"]["unit_basis_search_expansion_count"] == 1
|
||||
assert package["summary"]["writes_database_count"] == 0
|
||||
assert artifacts[0]["resolution_status"] == "AUTO_RESOLUTION_ARTIFACT_READY"
|
||||
assert artifacts[0]["guardrails"]["writes_database"] is False
|
||||
assert package["retry_exception_auto_resolution_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"] == 2
|
||||
|
||||
|
||||
def test_ai_automation_readiness_makes_automation_visible_without_manual_primary_flow():
|
||||
readiness = build_pchome_growth_ai_automation_readiness(_payload(), batch_size=1)
|
||||
|
||||
@@ -14922,6 +14992,37 @@ def test_direct_mapping_retry_candidate_decision_route_uses_cached_payload(monke
|
||||
assert payload["safety"]["writes_database"] is False
|
||||
|
||||
|
||||
def test_direct_mapping_retry_candidate_exception_auto_resolution_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 auto-resolution 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-auto-resolution-package?batch_size=1"
|
||||
):
|
||||
response = routes.api_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution_package.__wrapped__()
|
||||
|
||||
payload = response.get_json()
|
||||
assert payload["success"] is True
|
||||
assert payload["policy"] == "read_only_pchome_growth_direct_mapping_retry_candidate_exception_auto_resolution"
|
||||
assert payload["source_endpoint"] == (
|
||||
"/api/ai/pchome-growth/mapping-backlog/direct-mapping-retry-candidate-decision-package"
|
||||
)
|
||||
assert payload["result"] == "WAITING_FOR_RETRY_CANDIDATE_DECISIONS"
|
||||
assert payload["summary"]["retry_exception_auto_resolution_artifact_count"] == 0
|
||||
assert payload["retry_exception_auto_resolution_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