"""Recalculate invoices.json against inputs/purchase-orders.csv and assert the recorded results. Note: this checks the JSON transcription, not the PNG images themselves.""" import json, csv from decimal import Decimal as D def d(x): return D(str(x)).quantize(D('0.01')) inv = json.load(open('output/invoices.json')) po = list(csv.DictReader(open('inputs/purchase-orders.csv'))) assert len(inv) == 2, 'expected one record per image' required = ['supplier', 'invoice_number', 'invoice_date', 'po', 'currency', 'line_items', 'subtotal', 'tax', 'shipping', 'total', 'bank_account_suffix', 'exceptions'] for r in inv: missing = [k for k in required if k not in r] assert not missing, (r['invoice_number'], missing) assert isinstance(r['invoice_number'], str) and isinstance(r['bank_account_suffix'], str) sub = sum(D(l['qty']) * d(l['unit_price']) for l in r['line_items']) tax = (sub * D('0.12')).quantize(D('0.01')) tot = sub + tax + d(r['shipping']) rc = r['recalculation'] assert sub == d(r['subtotal']) == d(rc['subtotal']) assert tax == d(r['tax']) assert tot == d(rc['total']) assert (tot == d(r['total'])) == rc['matches_stated'] pos = [p for p in po if p['po'] == r['po']] assert pos and all(p['supplier'] == r['supplier'] for p in pos) po_bank = {p['bank_suffix'] for p in pos} assert (r['bank_account_suffix'] in po_bank) == rc['bank_suffix_match'] for l in r['line_items']: p = [p for p in pos if p['item'] == l['description']][0] assert d(l['qty']) * d(l['unit_price']) == d(l['amount']) == d(l['recalculated_amount']) match = int(p['qty']) == l['qty'] and d(p['unit_cad']) == d(l['unit_price']) assert match == l['po_match'], l posub = sum(D(p['qty']) * d(p['unit_cad']) for p in pos) print(f"{r['invoice_number']}: recalculated {tot} vs stated {d(r['total'])} (diff {d(r['total']) - tot}); " f"PO-basis subtotal {posub}; bank invoice {r['bank_account_suffix']} vs PO {sorted(po_bank)}") print('ALL ASSERTIONS PASSED')