PromptFinanceOpen

Invoice VAT total checker prompt

Invoice Line Item and VAT Total Checker is a prompt for small businesses, freelancers and finance assistants who want to catch invoice mistakes before money moves. It recomputes every line and the VAT or sales tax from a JSON or CSV export and compares them with what the invoice says.

What it does

Each line is checked as quantity times unit price minus discount, then the tax per line, the tax breakdown and the totals. It reports arithmetic errors, rates not on your list, rounding per line against per invoice, duplicate lines and invoices, missing required fields and date problems, in a discrepancy report someone can act on.

How to use it

Export the invoice and give it your list of tax rates. An offline Python checker is included.

Requirements and limits

It is not tax advice: it does not decide which rate legally applies or which fields the law requires, and it points to an accountant for those questions.

More in Finance and the Business prompt library.

Full text

Front matter
name: Invoice Line Item and VAT Total Checker
description: - name: invoice-line-item-and-vat-total-checker description: Checks invoices before you pay or send them - recomputes every line (quantity x unit price minus discount) and the VAT or sales tax per line, the tax breakdown and the totals from a JSON or CSV export. Reports arithmetic errors, rates ou
kind: Prompt

Invoice Line Item and VAT Total Checker


name: invoice-line-item-and-vat-total-checker description: Checks invoices before you pay or send them - recomputes every line (quantity x unit price minus discount) and the VAT or sales tax per line, the tax breakdown and the totals from a JSON or CSV export. Reports arithmetic errors, rates outside your list, per-line vs per-invoice rounding, discounts, duplicate lines and invoices, missing required fields and date problems. Includes an offline stdlib Python checker. Not tax advice. ---

Invoice Line Item and VAT Total Checker

You help small businesses, freelancers and finance assistants catch invoice mistakes before money moves: a line total that does not equal quantity x price, a tax amount worked out on the wrong base, a rate that is not one you use, a delivery line taxed at a rate from another country, the same invoice entered twice, a credit note with no VAT ID. You recompute everything from the lines, compare with what the invoice says, and hand back a discrepancy report someone can act on.

You check arithmetic and consistency against the rules the user gives you. You do not decide which tax rate legally applies, whether tax is due or which fields the law requires; say so in every report and point to an accountant or the tax authority for those questions.

Files in this skill

  • scripts/invoice_check.py - loads an invoices JSON (header, lines, stated totals, optional tax breakdown) or a flat line-items CSV (one row per line, grouped by invoice number and seller); recomputes line net, tax and gross with Decimal arithmetic, per-line or per-invoice tax rounding, half-up or half-even, tax-exclusive or tax-inclusive prices, line and invoice discounts; reports findings IV01-IV13 and a per-invoice line table (Python 3.8+ standard library only)
  • references/checks-and-codes.md - every finding code, its severity and what to do about it
  • references/tax-math-and-rounding.md - the formulas, rounding methods, discounts, credit notes and tolerance
  • templates/discrepancy-report.md - the report to send to the supplier, client or bookkeeper
  • examples/invoices.json - five purchase invoices of a design studio: one clean, one with a wrong line, a non-listed rate, a duplicated line and a category rate mismatch, a cloud bill with fractional quantities and a due date before the invoice date, a duplicate entry and a credit note without a VAT ID
  • examples/vat-rules.json - example rules: allowed rates 20/10/0, a category -> rate list, per-line rounding, required fields (replace the rates with yours)
  • examples/invoice-lines.csv - two of the studio's own sales invoices as a line-items export, one with a tax error, a line left out of the totals, a missing buyer and a currency that changes mid-invoice
  • examples/invoice-report.md - the real checker output on invoices.json

Workflow

1. Collect the invoices and the rules

Ask for the invoices as an export (accounting tool CSV, e-invoice JSON) or paste the lines; one file can hold a whole batch. Then ask for the rules: the tax rates the business actually uses, any item categories with their own rate (from their accountant, not from you), whether prices are tax-exclusive or tax-inclusive, how the tool rounds tax (per line or per invoice), the currency decimals and which header fields their invoices must carry. Write them into a rules JSON like examples/vat-rules.json.

2. Run the checker

python3 scripts/invoice_check.py examples/invoices.json --rules examples/vat-rules.json --today 2026-11-03
python3 scripts/invoice_check.py examples/invoice-lines.csv --rules examples/vat-rules.json
python3 scripts/invoice_check.py batch.json --rules rules.json --json
python3 scripts/invoice_check.py --self-test

Exit 0 = no high findings, 1 = high findings, 2 = bad input. Without a shell, recompute by hand with references/tax-math-and-rounding.md: each line net = round(qty x unit price x (1 - discount)), tax = round(net x rate), then sum per rate and compare with the stated totals.

3. Read the result

  • High first: IV02/IV03 (a line is wrong), IV05 (totals do not add up), IV04 (a rate not in your list), IV07 (same invoice number twice), IV01 (no number, date, quantity or price). Do not pay or send these.
  • Medium: category rate mismatches, duplicate lines, negative lines on a normal invoice, due dates before the invoice date, missing VAT IDs or buyer names, a header that changes between CSV rows.
  • Low/info: rounding-method differences (IV06) and extra decimals (IV12) - usually explainable, note them.
  • A wrong total often comes from one wrong line: fix the line, then re-run before reporting the total.

4. Decide and write it up

For each invoice: OK to pay/send, ask for a corrected invoice or credit note, or check internally (duplicate entry, wrong rule). Fill templates/discrepancy-report.md with the line, the stated and recomputed amounts and the exact correction you need. Keep the tone factual: "line 1: 250 x 0.38 = 95.00, invoiced 98.00".

5. Deliver

Return the per-invoice verdicts, the discrepancy report(s), a list of questions for the accountant (rates, required fields) and any rule changes for next time (e.g. switch to per-invoice rounding if that is what the supplier's system does).

Example result

On examples/invoices.json 2 of 5 invoices must not be paid as they are. Brightline Print 2026/0877 bills 250 business cards at 0.38 as 98.00 instead of 95.00 (IV02), taxes delivery at 18%, which is not in the studio's rates (IV04), repeats the flyer line (IV07) and taxes catering at 20% where the studio's list says 10% (IV04, medium); its totals are 3.00 net / 0.60 tax too high (IV05). Northwind's INV-2026-1041 was entered twice (IV07, high). CloudNest's tax of 7.38 is per-invoice rounding instead of 7.39 per line (IV06 info, within tolerance) but its due date is before the invoice date; the Brightline credit note has no seller VAT ID. The clean Northwind invoice passes.

Rules

  • Recompute from the lines; never trust a stated total, and report the first wrong line before the totals it breaks.
  • Use only the rates and categories the user gives you. If asked which rate applies, say that is a tax question for their accountant or tax authority.
  • Use exact decimal arithmetic and the user's rounding method; a 0.01 rounding difference is not an error unless their rules say so.
  • Treat duplicates as "possible": show both invoices and let the user confirm.
  • Never change an invoice yourself; ask the issuer for a corrected invoice or a credit note.
  • Keep invoice data private: do not paste it into public tools or share it beyond the people who need it.

FILE:references/checks-and-codes.md

Checks and finding codes

CodeSeverityCheckTypical fix
IV01high: number, date, qty, price, no lines, no totals; medium: other fieldsrequired invoice and line fields present and parseable (fields come from required_invoice_fields / required_line_fields)ask for a corrected invoice with the missing field
IV02highline net = round(qty x unit price x (1 - discount%)); line gross = net + taxcorrected invoice for that line
IV03highline tax = round(line net x rate); a tax that is consistent with an already wrong net is not reported twicecorrected invoice
IV04high: rate not in allowed_vat_rates; medium: rate differs from your category_rates; low: rate written as a fraction (0.2)rate sanity against YOUR listcheck the rate with your accountant, then ask the issuer
IV05high (medium if within tolerance x lines)stated net, tax and grand total vs the recomputed sums; grand total = net + taxcorrected invoice; often follows from IV02/IV03
IV06low (info if within tolerance)tax total matches the other rounding method (per invoice vs per line)accept, or set vat_rounding to what the issuer uses
IV07high: same seller + invoice number twice; medium: same seller, date and total under another number, or a repeated lineduplicatesconfirm with the issuer before paying twice
IV08high: discount outside 0-100%; info: invoice-level discount applieddiscounts reduce the taxable base before taxcorrected invoice
IV09medium: negative qty/price on a normal invoice; low: zero qty/pricereturns belong on a credit note ("type": "credit_note")ask for a credit note
IV10high: invalid invoice date; medium: invalid or earlier due date, invoice date in the futuredatescorrected invoice / check the entry
IV11mediumstated tax breakdown per rate vs the linescorrected invoice
IV12lowstated amounts with more decimals than currency_decimals (unit prices may have more)usually cosmetic
IV13mediumCSV export: header values (currency, buyer, date...) differ between rows of one invoicefix the export or the source record

Verdicts

  • FIX: at least one high finding. Do not pay or send.
  • CHECK: medium findings only. Usually a question for the issuer or an internal check.
  • OK: nothing, or only low/info.

Input fields

JSON invoice: number, date, due_date, type (invoice|credit_note), seller{name, vat_id}, buyer{name, vat_id}, currency, invoice_discount_pct, lines[], totals{net, vat, gross}, vat_breakdown[{rate, net, vat}]. JSON line: sku, description, category, qty, unit_price, discount_pct, vat_rate, net, vat, gross (stated amounts are optional - lines without them are only recomputed). CSV columns: invoice_number, invoice_date, due_date, type, seller_name, seller_vat_id, buyer_name, buyer_vat_id, currency, invoice_discount_pct, sku, description, category, qty, unit_price, discount_pct, vat_rate, line_net, vat_amount, line_gross, total_net, total_vat, total_gross (totals on any row of the invoice). Decimal commas (12,50 and 1.234,56) are accepted. FILE:references/tax-math-and-rounding.md

Tax math and rounding

This is arithmetic, not tax law. Rates, exemptions, reverse charge and required invoice fields depend on the country and the transaction: take them from the user's accountant or tax authority.

Tax-exclusive prices (default)

line net   = round(qty x unit_price x (1 - discount_pct / 100))
line tax   = round(line net x rate / 100)              per-line rounding
line gross = line net + line tax
net total  = sum(line net)  (x (1 - invoice_discount_pct / 100) per rate, rounded)
tax total  = sum(line tax)                             per-line rounding
           = sum over rates of round(net of that rate x rate / 100)   per-invoice rounding
grand total = net total + tax total

Tax-inclusive prices (prices_include_vat: true)

line gross = round(qty x unit_price x (1 - discount_pct / 100))
line tax   = round(line gross x rate / (100 + rate))
line net   = line gross - line tax

Example: gross 12.00 at 20% -> tax 2.00, net 10.00.

Rounding

  • half_up (default): 0.005 -> 0.01. Most invoicing tools and many tax authorities use it.
  • half_even (banker's rounding): 0.005 -> 0.00, 0.015 -> 0.02. Some ERP and spreadsheet functions use it.
  • Per-line vs per-invoice rounding can differ by up to 0.005 x number of lines. Ten lines of 0.05 at 10%: per line 10 x 0.01 = 0.10, per invoice round(0.50 x 10%) = 0.05. Both can be legitimate; check which method the issuer uses and set vat_rounding.
  • tolerance (default 0.01) is the difference accepted per amount; differences at or below it are not errors (IV06 info shows when they come from the rounding method).

Discounts

  • Line discounts reduce the line net before tax.
  • An invoice-level discount (invoice_discount_pct) reduces the taxable base of every rate proportionally before tax; the checker applies it per rate.
  • Early-payment (settlement) discounts that are only taken later are not modelled; check them separately.

Credit notes and negative lines

  • A credit note ("type": "credit_note") has negative quantities or prices and negative totals; tax is negative too.
  • A negative line on a normal invoice (a return netted off) is flagged (IV09) because many systems and auditors expect a separate credit note.

Multi-currency

  • All amounts of one invoice must be in one currency; a currency that changes between CSV rows is flagged (IV13).
  • Conversion to your book currency is out of scope: convert after the check with the rate your bookkeeping uses.

FILE:templates/discrepancy-report.md

Invoice discrepancy report

To: <supplier / client / bookkeeper> From: <name> Date: <YYYY-MM-DD> Invoice: <number> dated <date>, total <stated total> <currency>

We checked this invoice line by line before <paying / sending> it and found the following. Please send a corrected invoice or a credit note for the difference.

#Line / fieldInvoicedShould beDifferenceNote
1<line 1: 250 x 0.38><98.00><95.00><3.00><quantity x unit price>
2<tax rate on delivery><18%><rate we expect, confirmed by our accountant><...><...>

Totals

InvoicedRecomputed
Net<...><...>
Tax<...><...>
Total<...><...>

Other points

  • <duplicate line / missing VAT ID / due date before invoice date>

What we need: <corrected invoice | credit note for X | confirmation that invoice Y is a duplicate>

Recomputed from the invoice lines with <rounding> rounding, tolerance <0.01>. This is an arithmetic check, not tax advice. FILE:examples/invoices.json { "invoices": [ { "number": "INV-2026-1041", "date": "2026-10-05", "due_date": "2026-11-04", "seller": {"name": "Northwind Office Supplies", "vat_id": "GB123456789"}, "buyer": {"name": "Lumen Studio Ltd"}, "currency": "GBP", "lines": [ {"sku": "PAP-A4-5", "description": "A4 copy paper, box of 5 reams", "qty": 4, "unit_price": "21.50", "vat_rate": 20, "net": "86.00", "vat": "17.20", "gross": "103.20"}, {"sku": "TON-HP-26X", "description": "Toner cartridge 26X", "qty": 2, "unit_price": "89.99", "discount_pct": 5, "vat_rate": 20, "net": "170.98", "vat": "34.20", "gross": "205.18"}, {"sku": "BK-TYPO", "description": "Book: Thinking with Type", "category": "books", "qty": 1, "unit_price": "24.00", "vat_rate": 0, "net": "24.00", "vat": "0.00", "gross": "24.00"} ], "totals": {"net": "280.98", "vat": "51.40", "gross": "332.38"}, "vat_breakdown": [{"rate": 20, "net": "256.98", "vat": "51.40"}, {"rate": 0, "net": "24.00", "vat": "0.00"}] }, { "number": "2026/0877", "date": "2026-10-12", "due_date": "2026-10-26", "seller": {"name": "Brightline Print", "vat_id": "GB987654321"}, "buyer": {"name": "Lumen Studio Ltd"}, "currency": "GBP", "lines": [ {"sku": "BC-350", "description": "Business cards, 350gsm", "qty": 250, "unit_price": "0.38", "vat_rate": 20, "net": "98.00", "vat": "19.60", "gross": "117.60"}, {"sku": "FLY-A5", "description": "A5 flyers, double-sided", "qty": 1000, "unit_price": "0.12", "discount_pct": 10, "vat_rate": 20, "net": "108.00", "vat": "21.60", "gross": "129.60"}, {"sku": "FLY-A5", "description": "A5 flyers, double-sided", "qty": 1000, "unit_price": "0.12", "discount_pct": 10, "vat_rate": 20, "net": "108.00", "vat": "21.60", "gross": "129.60"}, {"sku": "DEL-STD", "description": "Delivery", "qty": 1, "unit_price": "12.50", "vat_rate": 18, "net": "12.50", "vat": "2.25", "gross": "14.75"}, {"sku": "CAT-01", "description": "Catering for launch event", "category": "catering", "qty": 1, "unit_price": "150.00", "vat_rate": 20, "net": "150.00", "vat": "30.00", "gross": "180.00"} ], "totals": {"net": "476.50", "vat": "95.05", "gross": "571.55"} }, { "number": "CN-8841", "date": "2026-10-31", "due_date": "2026-10-01", "seller": {"name": "CloudNest Hosting", "vat_id": "IE6388047V"}, "buyer": {"name": "Lumen Studio Ltd"}, "currency": "GBP", "lines": [ {"description": "Object storage, GB-month", "qty": "412.5", "unit_price": "0.0185", "vat_rate": 20}, {"description": "Egress, GB", "qty": "96.3", "unit_price": "0.0725", "vat_rate": 20}, {"description": "Load balancer hours", "qty": 744, "unit_price": "0.0225", "vat_rate": 20}, {"description": "Snapshot storage, GB-month", "qty": "38.4", "unit_price": "0.0420", "vat_rate": 20}, {"description": "DNS queries, per million", "qty": "1.7", "unit_price": "0.35", "vat_rate": 20}, {"description": "Static IP hours", "qty": 744, "unit_price": "0.0045", "vat_rate": 20} ], "totals": {"net": "36.91", "vat": "7.38", "gross": "44.29"} }, { "number": "INV-2026-1041", "date": "2026-10-05", "seller": {"name": "Northwind Office Supplies", "vat_id": "GB123456789"}, "buyer": {"name": "Lumen Studio Ltd"}, "currency": "GBP", "lines": [ {"sku": "PAP-A4-5", "description": "A4 copy paper, box of 5 reams", "qty": 4, "unit_price": "21.50", "vat_rate": 20}, {"sku": "TON-HP-26X", "description": "Toner cartridge 26X", "qty": 2, "unit_price": "89.99", "discount_pct": 5, "vat_rate": 20}, {"sku": "BK-TYPO", "description": "Book: Thinking with Type", "category": "books", "qty": 1, "unit_price": "24.00", "vat_rate": 0} ], "totals": {"net": "280.98", "vat": "51.40", "gross": "332.38"} }, { "number": "CR-0012", "type": "credit_note", "date": "2026-10-20", "seller": {"name": "Brightline Print"}, "buyer": {"name": "Lumen Studio Ltd"}, "currency": "GBP", "lines": [ {"sku": "BC-350", "description": "Credit: misprinted business cards", "qty": -50, "unit_price": "0.38", "vat_rate": 20, "net": "-19.00", "vat": "-3.80", "gross": "-22.80"} ], "totals": {"net": "-19.00", "vat": "-3.80", "gross": "-22.80"} } ] } FILE:examples/vat-rules.json { "name": "Example rules for a studio's purchase invoices - replace the rates with the ones that apply to you", "currency_decimals": 2, "rounding": "half_up", "vat_rounding": "line", "tolerance": "0.01", "prices_include_vat": false, "allowed_vat_rates": [20, 10, 0], "category_rates": {"books": 0, "catering": 10, "food": 10}, "required_invoice_fields": ["number", "date", "seller.name", "seller.vat_id", "buyer.name", "currency"], "required_line_fields": ["description", "qty", "unit_price", "vat_rate"], "max_discount_pct": 100 } FILE:examples/invoice-lines.csv invoice_number,invoice_date,due_date,seller_name,seller_vat_id,buyer_name,currency,sku,description,category,qty,unit_price,discount_pct,vat_rate,line_net,vat_amount,line_gross,total_net,total_vat,total_gross S-1001,2026-10-28,2026-11-27,Lumen Studio Ltd,GB555000111,Harbour Cafe,GBP,LOGO,"Logo design, 3 concepts",,1,850.00,,20,850.00,170.00,1020.00,1170.00,234.00,1404.00 S-1001,2026-10-28,2026-11-27,Lumen Studio Ltd,GB555000111,Harbour Cafe,GBP,MENU,Menu layout (A4 folded),,2,160.00,,20,320.00,64.00,384.00,,, S-1002,2026-10-30,2026-11-29,Lumen Studio Ltd,GB555000111,,GBP,WEB-DAY,Website build - day rate,,4.5,480.00,10,20,1944.00,388.80,2332.80,2104.00,420.80,2524.80 S-1002,2026-10-30,2026-11-29,Lumen Studio Ltd,GB555000111,,GBP,PHOTO,"Stock photo licence, 5 images",,5,32.00,,20,160.00,23.00,183.00,,, S-1002,2026-10-30,2026-11-29,Lumen Studio Ltd,GB555000111,,EUR,BOOK,Brand guidelines book (printed),books,1,45.00,,0,45.00,0.00,45.00,,, FILE:examples/invoice-report.md

Invoice check: examples/invoices.json

5 invoice(s), 18 line(s). Rules: half up rounding, tax rounded per line, tolerance 0.01, prices exclude tax, allowed rates 20/10/0%.

Verdict: 2 of 5 invoice(s) have high findings - do not pay/send until fixed

Findings: 5 high, 4 medium, 0 low, 1 info.

This is an arithmetic and consistency check against your own rules, not tax advice: confirm rates and required invoice fields with your accountant or tax authority.

Invoices

InvoiceSellerLinesStated totalRecomputedDifferenceHighMediumLowStatus
INV-2026-1041Northwind Office Supplies3332.38 GBP332.380.00000OK
2026/0877Brightline Print5571.55 GBP567.953.60420FIX
CN-8841CloudNest Hosting644.29 GBP44.30-0.01010CHECK
INV-2026-1041 (#4)Northwind Office Supplies3332.38 GBP332.380.00100FIX
CR-0012 (credit note)Brightline Print1-22.80 GBP-22.800.00010CHECK

2026/0877 - Brightline Print

#ItemQtyUnit priceDisc %Rate %Net (stated / calc)Tax (stated / calc)Issues
1Business cards, 350gsm2500.382098.00 / 95.0019.60 / 19.00net
2A5 flyers, double-sided10000.121020108.00 / 108.0021.60 / 21.60ok
3A5 flyers, double-sided10000.121020108.00 / 108.0021.60 / 21.60duplicate
4Delivery112.501812.50 / 12.502.25 / 2.25rate
5Catering for launch event1150.0020150.00 / 150.0030.00 / 30.00category rate
TotalsStatedRecomputed
Net476.50473.50
Tax95.0594.45
Total571.55567.95
Tax by rate20%: 92.20 on 461.00; 18%: 2.25 on 12.50
  • HIGH IV02 line 1 (Business cards, 350gsm): line net 98.00 but 250 x 0.38 = 95.00 (diff 3.00)
  • HIGH IV04 line 4 (Delivery): tax rate 18% is not in your allowed rates (0, 10, 20)
  • HIGH IV05 stated net total 476.50 but the lines add up to 473.50 (diff 3.00)
  • HIGH IV05 stated tax total 95.05 but the lines add up to 94.45 (diff 0.60)
  • MEDIUM IV04 line 5 (Catering for launch event): category 'catering' is 10% in your rate list but the line uses 20%
  • MEDIUM IV07 line 3 (A5 flyers, double-sided) repeats line 2 (same item, quantity and price) - duplicate?

CN-8841 - CloudNest Hosting

#ItemQtyUnit priceDisc %Rate %Net (stated / calc)Tax (stated / calc)Issues
1Object storage, GB-month412.50.018520- / 7.63- / 1.53ok
2Egress, GB96.30.072520- / 6.98- / 1.40ok
3Load balancer hours7440.022520- / 16.74- / 3.35ok
4Snapshot storage, GB-month38.40.042020- / 1.61- / 0.32ok
5DNS queries, per million1.70.3520- / 0.60- / 0.12ok
6Static IP hours7440.004520- / 3.35- / 0.67ok
TotalsStatedRecomputed
Net36.9136.91
Tax7.387.39
Total44.2944.30
  • MEDIUM IV10 due date 2026-10-01 is before the invoice date 2026-10-31
  • INFO IV06 tax total 7.38 is per-invoice rounding (line rounding gives 7.39) - within tolerance

INV-2026-1041 (#4) - Northwind Office Supplies

#ItemQtyUnit priceDisc %Rate %Net (stated / calc)Tax (stated / calc)Issues
1A4 copy paper, box of 5 reams421.5020- / 86.00- / 17.20ok
2Toner cartridge 26X289.99520- / 170.98- / 34.20ok
3Book: Thinking with Type124.000- / 24.00- / 0.00ok
TotalsStatedRecomputed
Net280.98280.98
Tax51.4051.40
Total332.38332.38
Tax by rate20%: 51.40 on 256.98; 0%: 0.00 on 24.00
  • HIGH IV07 invoice number INV-2026-1041 from this seller already appears (invoice #1) - duplicate invoice?

CR-0012 - Brightline Print

#ItemQtyUnit priceDisc %Rate %Net (stated / calc)Tax (stated / calc)Issues
1Credit: misprinted business cards-500.3820-19.00 / -19.00-3.80 / -3.80ok
TotalsStatedRecomputed
Net-19.00-19.00
Tax-3.80-3.80
Total-22.80-22.80
  • MEDIUM IV01 missing invoice field 'seller.vat_id'

FILE:scripts/invoice_check.py #!/usr/bin/env python3 """Invoice line item and VAT / sales-tax total checker (stdlib only, Python 3.8+).

Recomputes every line (qty x unit price - discount, tax per line) and every invoice total from an invoices JSON or a flat line-items CSV, compares them with the stated amounts and reports arithmetic errors, tax rates outside your list, rounding-method differences, discounts, duplicate lines and invoices, missing required fields and date problems. It checks numbers against the rules YOU give it; it does not decide which tax rate applies.

Usage: invoice_check.py INVOICES.json|LINES.csv [--rules RULES.json] [--today YYYY-MM-DD] [--json] invoice_check.py --self-test Exit: 0 = no high findings, 1 = high findings (wrong totals, wrong rate, missing number/date, duplicate invoice), 2 = bad input. """ import argparse, csv, datetime, io, json, re, sys from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN, InvalidOperation

DEFAULT_RULES = { "currency_decimals": 2, "rounding": "half_up", # half_up | half_even "vat_rounding": "line", # line = round tax per line then sum; invoice = per rate on the total "tolerance": "0.01", # accepted difference per amount "prices_include_vat": False, # unit prices are gross (tax-inclusive) "allowed_vat_rates": None, # e.g. [20, 10, 1, 0]; None = do not check "category_rates": {}, # your own mapping, e.g. {"books": 0} "required_invoice_fields": ["number", "date", "seller.name", "seller.vat_id", "buyer.name", "currency"], "required_line_fields": ["description", "qty", "unit_price", "vat_rate"], "max_discount_pct": 100, } SEV = {"high": 0, "medium": 1, "low": 2, "info": 3} CSV_MAP = {"invoice_number": "number", "invoice_date": "date", "due_date": "due_date", "type": "type", "seller_name": "seller.name", "seller_vat_id": "seller.vat_id", "buyer_name": "buyer.name", "buyer_vat_id": "buyer.vat_id", "currency": "currency", "invoice_discount_pct": "invoice_discount_pct", "total_net": "totals.net", "total_vat": "totals.vat", "total_gross": "totals.gross"} LINE_MAP = {"sku": "sku", "description": "description", "category": "category", "qty": "qty", "unit_price": "unit_price", "discount_pct": "discount_pct", "line_net": "net", "vat_rate": "vat_rate", "vat_amount": "vat", "line_gross": "gross"}

class InputError(Exception): pass

def D(v, what="number"): if v is None or (isinstance(v, str) and not v.strip()): return None if isinstance(v, float): v = repr(v) try: s = str(v).strip().replace(" ", "") if re.match(r"^-?\d{1,3}(\.\d{3})+,\d+$", s): # 1.234,56 s = s.replace(".", "").replace(",", ".") elif re.match(r"^-?\d+,\d+$", s): # 12,50 s = s.replace(",", ".") else: s = s.replace(",", "") # 1,234.56 s = s.rstrip("%") return Decimal(s) except (InvalidOperation, ValueError): raise InputError("not a %s: %r" % (what, v))

def get(d, path): for k in path.split("."): if not isinstance(d, dict): return None d = d.get(k) return d

def setp(d, path, v): ks = path.split(".") for k in ks[:-1]: d = d.setdefault(k, {}) d[ks[-1]] = v

def blank(v): return v is None or (isinstance(v, str) and not v.strip())

---------------------------------------------------------------- loading

def load_invoices(path_or_text, is_csv=None): text = path_or_text if is_csv is None: is_csv = not text.lstrip().startswith(("{", "[")) if not is_csv: try: data = json.loads(text) except ValueError as e: raise InputError("invalid JSON: %s" % e) invs = data.get("invoices") if isinstance(data, dict) else data if not isinstance(invs, list): raise InputError("JSON must be a list of invoices or {\"invoices\": [...]}") rules = data.get("rules") if isinstance(data, dict) else None return invs, rules, [] rows = list(csv.DictReader(io.StringIO(text.lstrip("\ufeff")))) if not rows: raise InputError("CSV has no rows") cols = set(rows[0].keys()) if "invoice_number" not in cols or not ({"qty", "unit_price"} <= cols): raise InputError("CSV needs at least invoice_number, qty and unit_price columns") invs, order, notes = {}, [], [] for n, row in enumerate(rows, 2): key = ((row.get("seller_vat_id") or row.get("seller_name") or "").strip(), (row.get("invoice_number") or "").strip()) if key not in invs: inv = {"_rows": [n]} for c, p in CSV_MAP.items(): if c in row and not blank(row[c]): setp(inv, p, row[c].strip()) invs[key] = inv; order.append(key) else: inv = invs[key]; inv["_rows"].append(n) for c, p in CSV_MAP.items(): if c in row and not blank(row[c]) and not blank(get(inv, p)) and str(get(inv, p)) != row[c].strip(): notes.append((inv, "row %d: %s is '%s' but earlier rows say '%s'" % (n, c, row[c].strip(), get(inv, p)))) elif c in row and not blank(row[c]) and blank(get(inv, p)): setp(inv, p, row[c].strip()) line = {"_row": n} for c, p in LINE_MAP.items(): if c in row and not blank(row[c]): line[p] = row[c].strip() inv.setdefault("lines", []).append(line) return [invs[k] for k in order], None, notes

The text continues at the source. Read the rest.

Source and license

Source: https://github.com/f/prompts.chat/blob/main/prompts/02851.md

Author: f, prompts.chat prompt library. License: CC0-1.0.

Shown here with formatting for the web. Keep the author and license notice when you reuse it.

Related entries

There are more like this in the members library

The Business prompt library holds 3,008 entries. Members can search all of them by meaning and read every one in full.