perf: add opportunity detail read context

This commit is contained in:
plx
2026-08-14 13:24:37 +00:00
parent 07dc9db198
commit 7d138eccdc
13 changed files with 484 additions and 121 deletions

View File

@@ -437,7 +437,11 @@ def _email_domain(email: Any) -> str:
return text_value.rsplit("@", 1)[-1].strip()
def find_jasmin_document_candidates_for_opportunity(opportunity_id: str, *, limit: int = 5) -> List[Dict[str, Any]]:
def find_jasmin_document_candidates_for_opportunity(
opportunity_id: str, *, limit: int = 5,
opportunity: Optional[Dict[str, Any]] = None,
current_documents: Optional[List[Dict[str, Any]]] = None,
) -> List[Dict[str, Any]]:
"""Find Jasmin documents that probably belong to an opportunity but are not imported yet.
This is deliberately conservative and prioritizes fiscal identity (NIF/customer_id)
@@ -446,7 +450,7 @@ def find_jasmin_document_candidates_for_opportunity(opportunity_id: str, *, limi
quotation instead of duplicating it.
"""
with engine.begin() as conn:
opp = conn.execute(text("""
opp = opportunity or conn.execute(text("""
SELECT
o.id::text,
o.customer_name,
@@ -470,7 +474,8 @@ def find_jasmin_document_candidates_for_opportunity(opportunity_id: str, *, limi
raw_domain = _email_domain(fiscal_email)
domain = "" if is_public_email_domain(raw_domain) else raw_domain
current_docs = conn.execute(text("""
if current_documents is None:
current_docs = conn.execute(text("""
SELECT
id::text, document_number, external_id, document_kind, document_date,
total_amount, amount, payload, created_at, updated_at
@@ -479,7 +484,13 @@ def find_jasmin_document_candidates_for_opportunity(opportunity_id: str, *, limi
AND system = 'jasmin'
AND document_kind IN ('quotation', 'proforma')
ORDER BY document_date DESC NULLS LAST, created_at DESC
"""), {"opportunity_id": opportunity_id}).mappings().all()
"""), {"opportunity_id": opportunity_id}).mappings().all()
else:
current_docs = [
row for row in current_documents
if str(row.get("system") or "") == "jasmin"
and str(row.get("document_kind") or "") in {"quotation", "proforma"}
]
candidate_columns = """
ri.id::text,