diff --git a/app/billing/backend/supplier_invoices.py b/app/billing/backend/supplier_invoices.py index d595d1d..db96d65 100644 --- a/app/billing/backend/supplier_invoices.py +++ b/app/billing/backend/supplier_invoices.py @@ -900,21 +900,37 @@ async def link_vendor_to_extraction(file_id: int, data: dict): (file_id,)) if not extraction: - raise HTTPException(status_code=404, detail="Ingen extraction fundet for denne fil") - - # Update extraction with vendor match + # Create minimal extraction if none exists + logger.info(f"⚠️ No extraction for file {file_id} — creating minimal extraction for vendor link") + extraction_id = execute_insert( + """INSERT INTO extractions + (file_id, vendor_matched_id, vendor_name, vendor_cvr, + document_id, document_type, document_type_detected, + currency, confidence, status) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + RETURNING extraction_id""", + (file_id, vendor_id, vendor['name'], None, + None, 'invoice', 'invoice', 'DKK', 1.0, 'manual') + ) + else: + extraction_id = extraction['extraction_id'] + execute_update( + "UPDATE extractions SET vendor_matched_id = %s WHERE extraction_id = %s", + (vendor_id, extraction_id) + ) + execute_update( - "UPDATE extractions SET vendor_matched_id = %s WHERE extraction_id = %s", - (vendor_id, extraction['extraction_id']) + "UPDATE incoming_files SET detected_vendor_id = %s, status = 'processed' WHERE file_id = %s", + (vendor_id, file_id) ) - logger.info(f"✅ Linked vendor {vendor['name']} (ID: {vendor_id}) to extraction {extraction['extraction_id']}") + logger.info(f"✅ Linked vendor {vendor['name']} (ID: {vendor_id}) to extraction {extraction_id}") return { "status": "success", "vendor_id": vendor_id, "vendor_name": vendor['name'], - "extraction_id": extraction['extraction_id'] + "extraction_id": extraction_id } except HTTPException: