perf: eliminate N+1 in opportunities next actions

This commit is contained in:
plx
2026-08-14 11:56:03 +00:00
parent 5e400cfd38
commit 69116f620c
4 changed files with 331 additions and 14 deletions

View File

@@ -17,7 +17,7 @@ import app.admin_dashboard as legacy
from app.admin_dashboard import * # noqa: F401,F403
from app.admin_ui.labels import primary_action_label
from app.operation_noise import is_noise_operation_item
from app.opportunity_next_action_service import get_opportunity_next_action
from app.opportunity_next_action_service import get_opportunity_next_action, get_opportunity_next_actions
from app.opportunity_action_task_materializer import ensure_pending_task_for_next_action
from app.work_center_action_policy import (
canonical_action_code,
@@ -1451,20 +1451,27 @@ def _attach_central_next_actions(opportunities: list[dict]) -> None:
"Acompanhar produção". Keep this read-only and best-effort: if the
central engine fails for one card, the card falls back to the legacy text.
"""
for opp in opportunities:
if isinstance(opp.get("clientflow_next_action"), dict):
continue
oid = str(opp.get("id") or "").strip()
if not oid:
continue
try:
decision = get_opportunity_next_action(oid)
except Exception as exc:
decision = {
pending = {
str(opp.get("id") or "").strip(): opp
for opp in opportunities
if not isinstance(opp.get("clientflow_next_action"), dict)
and str(opp.get("id") or "").strip()
}
if not pending:
return
try:
decisions = get_opportunity_next_actions(pending)
except Exception as exc:
decisions = {
oid: {
"action_code": "DECISION_ERROR",
"label": opportunity_next_action_text(opp),
"description": f"Falha ao calcular próxima ação central: {exc}",
}
for oid, opp in pending.items()
}
for oid, opp in pending.items():
decision = decisions.get(oid)
if isinstance(decision, dict):
opp["clientflow_next_action"] = decision