File size: 9,862 Bytes
26b8deb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
"""Deterministic validation logic for DocuParse AI.

This module performs all arithmetic, date, and structural validation.
No LLM calls are made here - all logic is pure Python with Decimal arithmetic.
"""
from __future__ import annotations
from decimal import Decimal
from typing import List, Optional

from .schemas import DocumentExtraction, LineItem, ValidationCheck, ValidationResult
from .normalizer import normalise_date

TOLERANCE = Decimal("0.01")

REQUIRED_FIELDS: dict = {
    "invoice": {
        "errors": ["document_id", "vendor", "document_date", "total"],
        "warnings": ["line_items", "subtotal", "tax"],
    },
    "receipt": {
        "errors": ["vendor", "document_date", "total"],
        "warnings": ["payment_method"],
    },
    "purchase_order": {
        "errors": ["document_id", "vendor", "document_date"],
        "warnings": ["line_items", "total"],
    },
    "unknown": {
        "errors": [],
        "warnings": [],
    },
}


def validate_line_items(line_items: List[LineItem]) -> List[ValidationCheck]:
    """Validate each line item: quantity * unit_price should equal line_total."""
    checks = []
    for i, item in enumerate(line_items):
        label = item.description or f"Item {i + 1}"
        if item.quantity_decimal is None or item.unit_price_decimal is None:
            checks.append(ValidationCheck(
                name=f"line_item_{i + 1}_calculation",
                passed=True,
                severity="INFO",
                message=f"[{label}] Skipped - quantity or unit_price not available.",
            ))
            continue
        expected = item.quantity_decimal * item.unit_price_decimal
        if item.line_total_decimal is None:
            checks.append(ValidationCheck(
                name=f"line_item_{i + 1}_calculation",
                passed=True,
                severity="INFO",
                expected=str(expected),
                actual=None,
                message=f"[{label}] line_total not extracted; expected {expected}.",
            ))
            continue
        diff = abs(expected - item.line_total_decimal)
        passed = diff <= TOLERANCE
        checks.append(ValidationCheck(
            name=f"line_item_{i + 1}_calculation",
            passed=passed,
            severity="ERROR" if not passed else "INFO",
            expected=f"{expected:.2f}",
            actual=f"{item.line_total_decimal:.2f}",
            difference=f"{diff:.2f}",
            message=(
                f"[{label}] {item.quantity_decimal} x {item.unit_price_decimal} = "
                f"{expected:.2f}; extracted line_total = {item.line_total_decimal:.2f}. "
                + ("PASS" if passed else f"MISMATCH - difference {diff:.2f}")
            ),
        ))
    return checks


def validate_subtotal(extraction: DocumentExtraction) -> Optional[ValidationCheck]:
    """Validate sum of line item totals against document subtotal."""
    valid_totals = [
        item.line_total_decimal
        for item in extraction.line_items
        if item.line_total_decimal is not None
    ]
    if not valid_totals:
        return None
    calculated = sum(valid_totals, Decimal("0"))
    if extraction.subtotal_decimal is None:
        return ValidationCheck(
            name="subtotal_reconciliation",
            passed=True,
            severity="INFO",
            expected=f"{calculated:.2f}",
            actual=None,
            message=f"Calculated subtotal from line items: {calculated:.2f}. Document subtotal not extracted.",
        )
    diff = abs(calculated - extraction.subtotal_decimal)
    passed = diff <= TOLERANCE
    return ValidationCheck(
        name="subtotal_reconciliation",
        passed=passed,
        severity="WARNING" if not passed else "INFO",
        expected=f"{calculated:.2f}",
        actual=f"{extraction.subtotal_decimal:.2f}",
        difference=f"{diff:.2f}",
        message=(
            f"Sum of line items: {calculated:.2f}; Document subtotal: {extraction.subtotal_decimal:.2f}. "
            + ("PASS" if passed else f"MISMATCH - difference {diff:.2f}")
        ),
    )


def validate_total(extraction: DocumentExtraction) -> Optional[ValidationCheck]:
    """Validate: subtotal + tax + shipping - discount = total."""
    if extraction.subtotal_decimal is None or extraction.total_decimal is None:
        return ValidationCheck(
            name="total_reconciliation",
            passed=True,
            severity="INFO",
            message="Total reconciliation skipped - subtotal or total not available.",
        )
    tax = extraction.tax_decimal or Decimal("0")
    shipping = extraction.shipping_decimal or Decimal("0")
    discount = extraction.discount_decimal or Decimal("0")
    expected = extraction.subtotal_decimal + tax + shipping - discount
    diff = abs(expected - extraction.total_decimal)
    passed = diff <= TOLERANCE
    return ValidationCheck(
        name="total_reconciliation",
        passed=passed,
        severity="ERROR" if not passed else "INFO",
        expected=f"{expected:.2f}",
        actual=f"{extraction.total_decimal:.2f}",
        difference=f"{diff:.2f}",
        message=(
            f"Calculated total ({extraction.subtotal_decimal:.2f} + {tax:.2f} tax "
            f"+ {shipping:.2f} shipping - {discount:.2f} discount = {expected:.2f}); "
            f"Document total: {extraction.total_decimal:.2f}. "
            + ("PASS" if passed else f"MISMATCH - difference {diff:.2f}")
        ),
    )


def validate_dates(extraction: DocumentExtraction) -> List[ValidationCheck]:
    """Validate document_date and due_date."""
    checks = []
    if extraction.document_date is None:
        checks.append(ValidationCheck(
            name="date_validation",
            passed=True,
            severity="INFO",
            message="document_date not extracted.",
        ))
    else:
        normalised = normalise_date(extraction.document_date)
        if normalised is None:
            checks.append(ValidationCheck(
                name="date_validation",
                passed=False,
                severity="WARNING",
                actual=extraction.document_date,
                message=f"document_date '{extraction.document_date}' could not be parsed to a valid calendar date.",
            ))
        else:
            checks.append(ValidationCheck(
                name="date_validation",
                passed=True,
                severity="INFO",
                actual=normalised,
                message=f"document_date is valid: {normalised}.",
            ))

    if extraction.due_date is not None and extraction.document_date is not None:
        norm_due = normalise_date(extraction.due_date)
        norm_doc = normalise_date(extraction.document_date)
        if norm_due and norm_doc:
            if norm_due < norm_doc:
                checks.append(ValidationCheck(
                    name="due_date_validation",
                    passed=False,
                    severity="WARNING",
                    expected=f">= {norm_doc}",
                    actual=norm_due,
                    message=f"due_date ({norm_due}) is earlier than document_date ({norm_doc}).",
                ))
            else:
                checks.append(ValidationCheck(
                    name="due_date_validation",
                    passed=True,
                    severity="INFO",
                    message=f"due_date ({norm_due}) is on or after document_date ({norm_doc}). PASS",
                ))
    return checks


def validate_required_fields(extraction: DocumentExtraction) -> List[ValidationCheck]:
    """Validate required fields for the document type."""
    checks = []
    doc_type = extraction.document_type
    required = REQUIRED_FIELDS.get(doc_type, REQUIRED_FIELDS["unknown"])

    def check_field(field_name: str, severity: str) -> ValidationCheck:
        value = getattr(extraction, field_name, None)
        if field_name == "line_items":
            present = isinstance(value, list) and len(value) > 0
        else:
            present = value is not None and str(value).strip() != ""
        return ValidationCheck(
            name=f"required_field_{field_name}",
            passed=present,
            severity=severity if not present else "INFO",
            actual=str(value) if present else None,
            message=(
                f"Field '{field_name}' is present." if present
                else f"Required field '{field_name}' is missing for document type '{doc_type}'."
            ),
        )

    for field in required.get("errors", []):
        checks.append(check_field(field, "ERROR"))
    for field in required.get("warnings", []):
        checks.append(check_field(field, "WARNING"))
    return checks


def run_all_validations(extraction: DocumentExtraction) -> ValidationResult:
    """Run all deterministic validations and return aggregated result."""
    all_checks = []

    all_checks.extend(validate_line_items(extraction.line_items))

    sub_check = validate_subtotal(extraction)
    if sub_check:
        all_checks.append(sub_check)

    total_check = validate_total(extraction)
    if total_check:
        all_checks.append(total_check)

    all_checks.extend(validate_dates(extraction))
    all_checks.extend(validate_required_fields(extraction))

    errors = [c.message for c in all_checks if not c.passed and c.severity == "ERROR"]
    warnings = [c.message for c in all_checks if not c.passed and c.severity == "WARNING"]

    if errors:
        status = "INVALID"
        is_valid = False
    elif warnings:
        status = "WARNING"
        is_valid = True
    else:
        status = "VALID"
        is_valid = True

    return ValidationResult(
        is_valid=is_valid,
        overall_status=status,
        checks=all_checks,
        warnings=warnings,
        errors=errors,
    )