""" 3-Way Matching Engine with Strict 0% Tolerance for EFINTEL Procurement. Matches Purchase Order vs Goods Receipt vs Electronic Invoice SII (DTE 33). """ from decimal import Decimal from typing import Dict, Any, Optional from datetime import datetime class ThreeWayMatchingEngine: TOLERANCE_CLP = Decimal('0.00') @classmethod def evaluate_match( cls, po, goods_receipt, dte_invoice_net: Decimal, dte_invoice_total: Decimal, dte_invoice_rut: str ) -> Dict[str, Any]: """ Executes strict 3-Way Match validation: 1. Check receipt existence and technical conformity. 2. Check net price difference against PO (0% tolerance). 3. Verify vendor RUT match. """ dte_net = Decimal(str(dte_invoice_net)) dte_total = Decimal(str(dte_invoice_total)) po_net = po.net_amount_clp po_total = po.total_amount_clp # Price Difference price_diff = dte_net - po_net total_diff = dte_total - po_total # Check receipt if not goods_receipt: return { 'status': 'PENDIENTE_RECEPCION', 'is_match': False, 'price_difference': price_diff, 'message': 'No se ha registrado aún la recepción conforme (Guía de Despacho / Acta) para esta OC.' } if not goods_receipt.technical_conformity: return { 'status': 'DISCREPANCIA_CANTIDAD', 'is_match': False, 'price_difference': price_diff, 'message': 'La recepción física fue observada o rechazada técnicamente en terreno.' } # Check Price difference with 0% tolerance if abs(price_diff) > cls.TOLERANCE_CLP: return { 'status': 'DISCREPANCIA_PRECIO', 'is_match': False, 'price_difference': price_diff, 'message': f'Discrepancia en monto neto: OC por ${po_net:,.0f} CLP vs Factura por ${dte_net:,.0f} CLP (Diferencia: ${price_diff:,.0f} CLP). Tolerancia 0% violada.' } return { 'status': 'MATCH_PERFECTO', 'is_match': True, 'price_difference': Decimal('0'), 'message': 'Match 100% perfecto. OC, Recepción Conforme y Factura DTE 33 coinciden al centavo (Tolerancia 0% aprobada).' }