fix(validator): make pdf_abgleich compare XML values with the PDF text
The check only recognized the English patterns "Invoice" and "Total:", so it compared nothing on German invoices and always passed. It now reports every key XML value (invoice number, net, VAT and gross total) that does not appear in the PDF text, tolerant of number notation and of columns running together in extracted text. Mismatches stay warnings. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
+81
-16
@@ -2,6 +2,7 @@
|
||||
|
||||
import re
|
||||
import time
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Any
|
||||
|
||||
from pydantic import ValidationError
|
||||
@@ -312,6 +313,84 @@ def validate_pdf_abgleich(xml_data: XmlData, pdf_values: dict) -> list[ErrorDeta
|
||||
return errors
|
||||
|
||||
|
||||
def _amount_notations(amount: float) -> set[str]:
|
||||
"""Build the common written forms of a monetary amount.
|
||||
|
||||
Args:
|
||||
amount: Monetary amount; the sign is ignored
|
||||
|
||||
Returns:
|
||||
Notations with two decimals, e.g. for 1234.5: '1234.50', '1234,50',
|
||||
'1.234,50', '1,234.50', '1 234,50', "1'234.50"
|
||||
"""
|
||||
quantized = Decimal(str(abs(amount))).quantize(
|
||||
Decimal("0.01"), rounding=ROUND_HALF_UP
|
||||
)
|
||||
integer_part, decimals = f"{quantized:.2f}".split(".")
|
||||
grouped = f"{int(integer_part):,}"
|
||||
|
||||
return {
|
||||
f"{integer_part}.{decimals}",
|
||||
f"{integer_part},{decimals}",
|
||||
f"{grouped}.{decimals}",
|
||||
f"{grouped.replace(',', '.')},{decimals}",
|
||||
f"{grouped.replace(',', ' ')},{decimals}",
|
||||
f"{grouped.replace(',', chr(39))}.{decimals}",
|
||||
}
|
||||
|
||||
|
||||
def find_pdf_text_mismatches(xml_data: XmlData, pdf_text: str) -> list[ErrorDetail]:
|
||||
"""Check that the key XML values appear in the visible PDF text.
|
||||
|
||||
A hybrid invoice must show the same data in the PDF as in the XML. PDF
|
||||
text extraction loses layout (columns run together, labels vary by
|
||||
issuer), so this does not locate labelled fields. It searches the text
|
||||
for the invoice number and for net, VAT and gross total in the usual
|
||||
number notations and reports every value that occurs nowhere.
|
||||
|
||||
Args:
|
||||
xml_data: Parsed invoice data
|
||||
pdf_text: Text extracted from the PDF
|
||||
|
||||
Returns:
|
||||
Warnings for XML values that are missing in the PDF text
|
||||
"""
|
||||
errors = []
|
||||
|
||||
def add_missing(field: str, xml_value: Any) -> None:
|
||||
errors.append(
|
||||
ErrorDetail(
|
||||
check="pdf_abgleich",
|
||||
field=field,
|
||||
error_code="pdf_mismatch",
|
||||
message=(
|
||||
f"PDF mismatch for '{field}': XML has {xml_value}, "
|
||||
"which does not appear in the PDF text"
|
||||
),
|
||||
severity="warning",
|
||||
)
|
||||
)
|
||||
|
||||
# Non-breaking and narrow spaces are used as thousands separators
|
||||
text = re.sub(r"[\u00a0\u202f\u2009]", " ", pdf_text).replace("\u2019", "'")
|
||||
compact_text = re.sub(r"\s+", "", text).lower()
|
||||
|
||||
invoice_number = re.sub(r"\s+", "", xml_data.invoice_number).lower()
|
||||
if invoice_number and invoice_number not in compact_text:
|
||||
add_missing("invoice_number", xml_data.invoice_number)
|
||||
|
||||
amounts = {
|
||||
"totals.net": xml_data.totals.net,
|
||||
"totals.vat_total": xml_data.totals.vat_total,
|
||||
"totals.gross": xml_data.totals.gross,
|
||||
}
|
||||
for field, amount in amounts.items():
|
||||
if not any(notation in text for notation in _amount_notations(amount)):
|
||||
add_missing(field, amount)
|
||||
|
||||
return errors
|
||||
|
||||
|
||||
def validate_invoice(request: ValidateRequest) -> ValidationResult:
|
||||
"""Run selected validation checks."""
|
||||
start_time = time.time()
|
||||
@@ -390,22 +469,8 @@ def validate_invoice(request: ValidateRequest) -> ValidationResult:
|
||||
check_errors.append(error)
|
||||
checks_run += 1
|
||||
elif check_name == "pdf_abgleich":
|
||||
if request.pdf_text:
|
||||
# For simplicity, try to extract values from PDF text
|
||||
pdf_values = {}
|
||||
try:
|
||||
if "Invoice" in request.pdf_text:
|
||||
parts = request.pdf_text.split()
|
||||
if len(parts) > 1:
|
||||
pdf_values["invoice_number"] = parts[1]
|
||||
if "Total:" in request.pdf_text:
|
||||
parts = request.pdf_text.split("Total:")
|
||||
if len(parts) > 1:
|
||||
total_str = parts[1].strip().split()[0]
|
||||
pdf_values["totals.gross"] = total_str
|
||||
except Exception:
|
||||
pass
|
||||
check_errors = validate_pdf_abgleich(xml_data, pdf_values)
|
||||
if request.pdf_text and request.pdf_text.strip():
|
||||
check_errors = find_pdf_text_mismatches(xml_data, request.pdf_text)
|
||||
checks_run += 1
|
||||
|
||||
# Separate errors and warnings
|
||||
|
||||
Reference in New Issue
Block a user