import json, csv, os from decimal import Decimal as D, ROUND_HALF_UP def find(p): for base in ('.', '..', os.path.dirname(os.path.abspath(__file__))): f = os.path.join(base, p) if os.path.exists(f): return f raise SystemExit('missing ' + p) inv = json.loads(open(find('output/invoices.json'), encoding='utf-8').read(), parse_float=D) po = {} for r in csv.DictReader(open(find('inputs/purchase-orders.csv'), encoding='utf-8')): po[(r['po'], r['item'])] = r q = lambda x: D(str(x)).quantize(D('0.01'), ROUND_HALF_UP) req = "supplier,invoice_number,invoice_date,po,currency,line_items,subtotal,tax,shipping,total,bank_account_suffix,exceptions".split(',') assert len(inv) == 2 for i in inv: assert all(k in i for k in req), 'missing key' assert isinstance(i['invoice_number'], str) and isinstance(i['bank_account_suffix'], str) sub = D(0); found = [] for li in i['line_items']: amt = q(D(li['qty']) * D(str(li['unit_price']))) if amt != q(li['amount']): found.append('LINE_AMOUNT ' + li['description']) assert amt == q(li['recalculated_amount']), li sub += amt p = po[(i['po'], li['description'])] assert p['supplier'] == i['supplier'] match = int(p['qty']) == li['qty'] and q(p['unit_cad']) == q(li['unit_price']) assert match == li['po_match'], li assert int(p['qty']) == li['po_qty'] and q(p['unit_cad']) == q(li['po_unit_price']) if not match: found.append('QTY/PRICE ' + li['description']) bank = p['bank_suffix'] assert len([k for k in po if k[0] == i['po']]) == len(i['line_items']) tax = q(sub * D('0.12')) tot = sub + tax + q(i['shipping']) rc = i['recalculation'] assert (sub, tax, tot) == (q(rc['subtotal']), q(rc['tax_at_12pct_of_merchandise']), q(rc['total'])), (sub, tax, tot) if sub != q(i['subtotal']): found.append('SUBTOTAL') if tax != q(i['tax']): found.append('TAX') if tot != q(i['total']): found.append('TOTAL stated %s vs recalculated %s (diff %s)' % (q(i['total']), tot, q(i['total']) - tot)) assert rc['matches_invoice'] == (not any(f.startswith(('SUB', 'TAX', 'TOTAL', 'LINE')) for f in found)) assert bank == i['po_bank_suffix'] if bank != i['bank_account_suffix']: found.append('BANK %s vs PO %s' % (i['bank_account_suffix'], bank)) print(i['invoice_number'], 'sub', sub, 'tax', tax, 'total', tot) print(' independent issues:', found) print(' exceptions recorded:', [e['code'] for e in i['exceptions']]) assert len(found) == len(i['exceptions']) s = D('2') * D('85') + D('2') * D('15'); t = q(s * D('0.12')) print('PO-consistent 001083:', s, t, s + t, '| extra mic incl tax', q(D('85') * D('1.12')), '| printed minus PO-consistent', D('329.20') - (s + t)) note = open(find('output/review-note.md'), encoding='utf-8').read() print('review-note words (whitespace split):', len(note.split())) print('ALL CHECKS PASSED')