"""Independent re-check of output/invoices.json. Run from anywhere: python output/validate.py Does NOT trust helper fields in the JSON (po_match, recalculation, etc.): it re-keys the printed invoice values from a second reading of the PNGs, recomputes everything with Decimal, and re-reads the PO CSV.""" import json, csv, os, hashlib, re from decimal import Decimal as D, ROUND_HALF_UP here = os.path.dirname(os.path.abspath(__file__)) root = os.path.dirname(here) P = lambda *a: os.path.join(root, *a) q = lambda x: D(str(x)).quantize(D('0.01'), ROUND_HALF_UP) # Second, separate transcription of what is printed on each image. PRINTED = { 'inputs/invoice-01.png': dict(supplier='Cedar Print', invoice_number='000742', invoice_date='2026-10-18', po='PO-1042', currency='CAD', lines=[('Workshop handbooks', 80, '7.50', '600.00')], subtotal='600.00', tax='72.00', shipping='20.00', total='692.00', bank='0412'), 'inputs/invoice-02.png': dict(supplier='Harbour AV', invoice_number='001083', invoice_date='2026-10-19', po='PO-1043', currency='CAD', lines=[('Microphone rental', 3, '85.00', '255.00'), ('Stand rental', 2, '15.00', '30.00')], subtotal='285.00', tax='34.20', shipping='0.00', total='329.20', bank='8891'), } EXPECTED_CODES = {'000742': set(), '001083': {'BANK_SUFFIX_MISMATCH', 'QTY_EXCEEDS_PO', 'TOTAL_ARITHMETIC_ERROR'}} REQ = "supplier,invoice_number,invoice_date,po,currency,line_items,subtotal,tax,shipping,total,bank_account_suffix,exceptions".split(',') raw = open(P('output', 'invoices.json'), encoding='utf-8').read() inv = json.loads(raw, parse_float=D) po = {} for r in csv.DictReader(open(P('inputs', 'purchase-orders.csv'), encoding='utf-8')): po.setdefault(r['po'], {})[r['item']] = r assert isinstance(inv, list) and len(inv) == len(PRINTED) == 2 # leading zeros survive in the raw file text assert '"invoice_number": "000742"' in raw and '"invoice_number": "001083"' in raw and '"bank_account_suffix": "0412"' in raw for rec in inv: pr = PRINTED[rec['source_file']] assert [k for k in REQ if k not in rec] == [], 'missing required key' # 1. JSON extraction equals the second transcription for k in ('supplier', 'invoice_number', 'invoice_date', 'po', 'currency'): assert rec[k] == pr[k], (k, rec[k], pr[k]) for k in ('subtotal', 'tax', 'shipping', 'total'): assert q(rec[k]) == q(pr[k]), (k, rec[k], pr[k]) assert rec['bank_account_suffix'] == pr['bank'] and isinstance(rec['bank_account_suffix'], str) assert [(l['description'], l['qty'], q(l['unit_price']), q(l['amount'])) for l in rec['line_items']] == \ [(d, n, q(u), q(a)) for d, n, u, a in pr['lines']] # 2. Recalculate from printed lines only issues = set(); sub = D(0) for d, n, u, a in pr['lines']: ext = q(D(n) * D(u)); sub += ext if ext != q(a): issues.add('LINE_AMOUNT_ERROR') tax = q(sub * D('0.12')); tot = sub + tax + q(pr['shipping']) if sub != q(pr['subtotal']): issues.add('SUBTOTAL_ERROR') if tax != q(pr['tax']): issues.add('TAX_ERROR') if tot != q(pr['total']): issues.add('TOTAL_ARITHMETIC_ERROR') # 3. Compare with the PO lines = po[pr['po']] assert set(lines) == {d for d, *_ in pr['lines']}, 'item set differs from PO' for d, n, u, a in pr['lines']: assert lines[d]['supplier'] == pr['supplier'] if n > int(lines[d]['qty']): issues.add('QTY_EXCEEDS_PO') if n < int(lines[d]['qty']): issues.add('QTY_BELOW_PO') if q(u) != q(lines[d]['unit_cad']): issues.add('PRICE_MISMATCH') if {l['bank_suffix'] for l in lines.values()} != {pr['bank']}: issues.add('BANK_SUFFIX_MISMATCH') codes = {e['code'] for e in rec['exceptions']} print(rec['invoice_number'], '| recalculated sub', sub, 'tax', tax, 'total', tot, '| printed total', q(pr['total'])) print(' issues found independently :', sorted(issues)) print(' exception codes in JSON :', sorted(codes)) assert issues == codes == EXPECTED_CODES[rec['invoice_number']] assert q(rec['recalculation']['total']) == tot # figures quoted in the note / JSON detail text s = D(2) * D('85.00') + D(2) * D('15.00'); t = q(s * D('0.12')) assert (s, t, s + t) == (D('200.00'), D('24.00'), D('224.00')) assert q(D('85.00') * D('1.12')) == D('95.20') and D('329.20') - D('224.00') == D('105.20') == D('95.20') + D('10.00') print('quoted figures OK: PO-consistent 200.00 / 24.00 / 224.00; excess 95.20; printed-vs-PO gap 105.20') note = open(P('output', 'review-note.md'), encoding='utf-8').read() ws = len(note.split()); alpha = len(re.findall(r"[A-Za-z0-9][A-Za-z0-9.\-/']*", note)) print('review-note.md words: whitespace-split', ws, '| alphanumeric tokens', alpha) assert ws < 400 and alpha < 400 for n in ('000742', '001083', '8891', '8821', '319.20', '329.20', '95.20', '224.00', '692.00'): assert n in note, n sha = lambda p: hashlib.sha256(open(p, 'rb').read()).hexdigest()[:16] for f in ('invoices.json', 'review-note.md'): o = P('output', 'original-submission', f) print(f, 'current', sha(P('output', f)), '| preserved original', sha(o), '| identical' if sha(o) == sha(P('output', f)) else '| revised') for f in sorted(os.listdir(P('inputs'))): print('input', f, sha(P('inputs', f))) print('ALL CHECKS PASSED')