Implement document reconciliation v2

This commit is contained in:
plx
2026-08-05 23:55:33 +00:00
parent 4a60607503
commit 29382ec6c1
25 changed files with 2082 additions and 343 deletions

View File

@@ -83,19 +83,14 @@ def _build_db_evidence(opportunity_id: str) -> OpportunityEvidence | None:
LIMIT 20
""", params)
docs = _rows(conn, """
SELECT id::text, external_id, document_kind, document_number, status, total_amount, document_date, role, is_active, is_primary, payload
FROM commercial_documents
WHERE opportunity_id = CAST(:opportunity_id AS UUID)
AND system = 'jasmin'
AND COALESCE(is_active, TRUE) = TRUE
AND COALESCE(role, 'current') IN ('current', 'accepted', 'historical', 'history')
ORDER BY
CASE document_kind WHEN 'invoice' THEN 1 WHEN 'quotation' THEN 2 WHEN 'proforma' THEN 3 ELSE 4 END,
CASE COALESCE(role, 'current') WHEN 'current' THEN 1 WHEN 'accepted' THEN 2 ELSE 3 END,
COALESCE(document_date, created_at::date) DESC,
created_at DESC
""", params)
# DTO contract retained from the legacy loader:
# SELECT id::text, external_id, document_kind
# The SQL now qualifies these fields because links and documents both
# have ids; relationship comes exclusively from the canonical link.
from app.document_reconciliation_service import resolve_document_links
docs = [row for row in resolve_document_links(opportunity_id, conn=conn)
if row.get("system") == "jasmin" and row.get("relationship") in
{"PRIMARY", "SECONDARY", "HISTORICAL"}]
linked_customer = None
customer_id = opp.get("fiscal_customer_id") or opp.get("customer_id")