Files
accounts/tests/test_invoices.py
T
jimmyandClaude Opus 5.5 177dfbc0a4 Add invoice generator and mileage logbook
Invoices: business details and logo, saved customers, numbering, GST per
line, PDF download (fpdf2), and marking paid, which records the income in
the book (split into Incl and Excl GST rows when an invoice has both) or
uses an already-imported bank deposit. Statement import treats a split
payment as the one bank line it came from.

Mileage: vehicles and trips with odometer readings, business or private
use, IRD kilometre rates entered per income year, a per-vehicle tier 1/2
claim and a CSV logbook export. Report only: nothing is added to the
cashbook or IR10.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:56:30 +13:00

161 lines
8.0 KiB
Python

import shutil
import subprocess
import pytest
from conftest import SAMPLE_CSV
LINES = [{"description": "Web design", "qty": 2, "unit": 50, "taxable": True},
{"description": "Domain fee (no GST)", "qty": 1, "unit": 50, "taxable": False}]
@pytest.fixture
def biz(admin):
"""A book for 2026, a business and a customer."""
admin.post("/api/books", json={"name": "b", "year": 2026})
r = admin.put("/api/business", json={"name": "Jimmy Ltd", "gst_number": "123-456-789",
"bank_account": "01-0822-0082180-00", "payment_terms_days": 20})
assert r.status_code == 200, r.text
admin.customer = admin.post("/api/customers", json={"name": "Client Ltd", "address": "1 Queen St\nAuckland"}).json()
return admin
def make(client, lines=LINES, **kw):
r = client.post("/api/invoices", json={"customer_id": client.customer["id"], "issue_date": "2026-04-10",
"lines": lines, **kw})
assert r.status_code == 200, r.text
return r.json()
def rows(client, sheet="APR"):
return client.get(f"/api/month?book=b&sheet={sheet}").json()["rows"]
def test_totals_and_numbering(biz):
inv = make(biz)
assert inv["number"] == "INV-0001"
assert (inv["subtotal"], inv["taxable"], inv["exempt"], inv["gst"], inv["total"]) == (150, 100, 50, 15, 165)
assert inv["due_date"] == "2026-04-30" # 20 days' terms
assert inv["status"] == "draft"
assert [l["amount"] for l in inv["lines"]] == [100, 50]
# numbers carry on, and a void invoice keeps its number
biz.post(f"/api/invoices/{inv['id']}/status", json={"status": "void"})
assert make(biz)["number"] == "INV-0002"
# moving the counter onto a used number is refused
assert biz.put("/api/business", json={"next_number": 2}).status_code == 400
biz.put("/api/business", json={"invoice_prefix": "J-", "next_number": 7})
assert make(biz)["number"] == "J-0007"
def test_rounding():
import invoices
# 3 x $33.33 = $99.99, GST 15% = 14.9985 -> 15.00 (half-up, once per invoice)
t = invoices.totals([{"qty": 3, "unit_cents": 3333, "taxable": True},
{"qty": 1.5, "unit_cents": 1001, "taxable": True}]) # 15.015 -> 15.02
assert t["taxable"] == 9999 + 1502
assert t["gst"] == (t["taxable"] * 3 + 10) // 20
assert invoices.gst_on(10) == 2 and invoices.gst_on(3) == 0 # 1.5c rounds up, 0.45c down
def test_validation(biz):
c = biz.customer["id"]
bad = [{"customer_id": c, "issue_date": "2026-04-10", "lines": []},
{"customer_id": c, "issue_date": "nope", "lines": LINES},
{"customer_id": c, "issue_date": "2026-04-10", "due_date": "2026-04-01", "lines": LINES},
{"customer_id": c, "issue_date": "2026-04-10", "lines": [{"description": "", "unit": 5}]},
{"customer_id": c, "issue_date": "2026-04-10", "lines": [{"description": "x", "qty": 0, "unit": 5}]}]
for body in bad:
assert biz.post("/api/invoices", json=body).status_code == 400, body
assert biz.post("/api/invoices", json={**bad[1], "customer_id": 999, "issue_date": "2026-04-10"}).status_code == 404
def test_customer_snapshot_and_locking(biz):
inv = make(biz)
biz.put(f"/api/customers/{biz.customer['id']}", json={"name": "Client Holdings Ltd", "address": "elsewhere"})
assert biz.get(f"/api/invoices/{inv['id']}").json()["customer_name"] == "Client Ltd"
# a draft can be changed; re-choosing the customer picks up the new details
r = biz.put(f"/api/invoices/{inv['id']}", json={"customer_id": biz.customer["id"],
"lines": [{"description": "x", "unit": 10}]})
assert (r.json()["customer_name"], r.json()["total"]) == ("Client Holdings Ltd", 11.5)
biz.post(f"/api/invoices/{inv['id']}/status", json={"status": "sent"})
assert biz.put(f"/api/invoices/{inv['id']}", json={"lines": LINES}).status_code == 400
assert biz.put(f"/api/invoices/{inv['id']}", json={"notes": "Thanks!"}).json()["notes"] == "Thanks!"
assert biz.delete(f"/api/customers/{biz.customer['id']}").status_code == 400
assert biz.post(f"/api/invoices/{inv['id']}/status", json={"status": "paid"}).status_code == 400
def test_pay_adds_rows_and_import_recognises_them(biz):
inv = make(biz)
paid = biz.post(f"/api/invoices/{inv['id']}/pay", json={"date": "2026-04-20"}).json()
assert (paid["status"], paid["paid_date"]) == ("paid", "2026-04-20")
added = [r for r in rows(biz) if r["reference"].startswith("INV-0001")]
assert sorted((r["income"], r["gst"], r["category"]) for r in added) == [(50, "Excl GST", "Sales"),
(115, "Incl GST", "Sales")]
assert biz.get("/api/gst?book=b").json()["periods"][0]["boxes"]["8"] == 15.0
# the bank line for the payment ($165 on the same day) is then seen as already in the book
csv = SAMPLE_CSV.splitlines()[0] + "\nDirect Credit,Client Ltd,INV-0001,,,165.00,20/04/2026,,\n"
path = biz.post("/api/upload?filename=p.csv", content=csv.encode()).json()["path"]
plan = biz.post("/api/preview", json={"book": "b", "statements": [path]}).json()
assert [t["status"] for t in plan] == ["duplicate"]
unpaid = biz.post(f"/api/invoices/{inv['id']}/unpay").json()
assert (unpaid["status"], unpaid["payments"]) == ("sent", [])
assert not [r for r in rows(biz) if r["reference"].startswith("INV-0001")]
def test_pay_on_imported_bank_line(biz):
path = biz.post("/api/upload?filename=s.csv", content=SAMPLE_CSV.encode()).json()["path"]
biz.post("/api/import", json={"book": "b", "statements": [path]})
# SAMPLE_CSV has "Client Ltd" paying $1150.00 on 20 April
inv = make(biz, lines=[{"description": "Consulting", "qty": 10, "unit": 100, "taxable": True}])
[m] = biz.get(f"/api/invoices/{inv['id']}/matches?date=2026-04-18").json()
assert (m["amount"], m["days_apart"]) == (1150, 2)
biz.post(f"/api/invoices/{inv['id']}/pay", json={"date": "2026-04-18", "row": m["row"]})
line = next(r for r in rows(biz) if r["row"] == m["row"])
assert (line["category"], line["gst"], line["income"]) == ("Sales", "Incl GST", 1150)
assert biz.get(f"/api/invoices/{inv['id']}").json()["paid_date"] == "2026-04-20" # the bank's date
biz.post(f"/api/invoices/{inv['id']}/unpay")
line = next(r for r in rows(biz) if r["row"] == m["row"])
assert line["income"] == 1150 and line["category"] == "" # put back as it was imported
def test_pay_needs_a_book(biz):
inv = make(biz)
r = biz.post(f"/api/invoices/{inv['id']}/pay", json={"date": "2025-06-01"})
assert r.status_code == 400 and "no book" in r.json()["detail"]
def test_pdf(biz):
inv = make(biz, notes="Thanks for your business")
r = biz.get(f"/api/invoices/{inv['id']}/pdf")
assert r.status_code == 200 and r.content.startswith(b"%PDF")
assert 'filename="INV-0001_Client_Ltd.pdf"' in r.headers["content-disposition"]
if shutil.which("pdftotext"):
text = subprocess.run(["pdftotext", "-layout", "-", "-"], input=r.content, capture_output=True).stdout.decode()
for s in ("TAX INVOICE", "INV-0001", "Client Ltd", "$165.00", "123-456-789", "No GST on this item"):
assert s in text, s
def test_logo(biz, tmp_path):
from PIL import Image
import io
buf = io.BytesIO()
Image.new("RGB", (40, 20), "red").save(buf, "PNG")
assert biz.post("/api/business/logo", content=b"hello").status_code == 400
assert biz.post("/api/business/logo", content=buf.getvalue()).json()["logo_file"] == "logo.png"
assert biz.get("/api/business/logo").content == buf.getvalue()
assert biz.get(f"/api/invoices/{make(biz)['id']}/pdf").status_code == 200
assert biz.delete("/api/business/logo").json()["logo_file"] is None
assert not (tmp_path / "invoices" / "logo.png").exists()
def test_needs_sign_in(client):
assert client.get("/api/invoices").status_code == 401
assert client.get("/api/business").status_code == 401
assert client.post("/api/customers", json={"name": "x"}).status_code == 401