Files
accounts/README.md
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

407 lines
18 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Accounts
A small web app (FastAPI) for keeping a New Zealand business cashbook from ANZ bank
statements. Books are kept in a SQLite database, and can be exported to the standard
cashbook spreadsheet layout (one sheet per month, April–March) as Excel or
LibreOffice files, or as CSV. People sign in with their own accounts, and
administrators manage who has access.
- Import ANZ statements: **CSV exports** from internet banking or **PDF statements**
(including a PDF holding several monthly statements).
- Upload statements by drag-and-drop, then view, download, rename or remove them.
Each one shows how much of it is already in the selected book.
- Preview an import before it happens. Transactions already in the book are skipped,
matched on date and amount, so a CSV and a PDF of the same period don't double up.
- Review each month and set the GST type (Incl GST, Zero-rated, Excl GST) and the
income or expense category per transaction.
- See the year at a glance, and get the **GST return** figures (IRD GST101A boxes
5–15) for each filing period, with due dates.
- **Income tax:** company return (IR4) and financial statements summary (IR10)
figures for the year, from the cashbook plus year-end amounts you type in.
- **Export** a book as an Excel (.xlsx) or LibreOffice (.ods) cashbook spreadsheet,
with formulas, GST and category columns and the summary sheet, or as a CSV of all
transactions.
- **Accounts:** sign-in with personal accounts. Administrators invite people, reset
passwords and manage who's an administrator (see [Accounts](#accounts)).
Everything runs on your machine; nothing is sent anywhere.
## Running it
### Docker Compose (recommended)
One-time setup: create the data folder as the user who should own the books (uid
1000 by default), and copy the example settings.
```bash
mkdir -p data
```
```bash
cp .env.example .env
```
Then start it:
```bash
docker compose up -d --build
```
Open <http://127.0.0.1:8765>. The first time, it asks you to create the
administrator account. Stop it with `docker compose down`, and check it with
`docker compose ps` (it reports `healthy`) or `docker compose logs`.
**What the compose file sets up**
- **Data:** `./data` is mounted at `/data`. It holds the database (`cashbook.db`:
books and accounts) and `statements/`, where uploads go. Back up this folder.
- **Network:** published on `127.0.0.1:8765` only.
- **Lockdown:**
- read-only container filesystem, with scratch space only in `/tmp` (tmpfs);
- no Linux capabilities and `no-new-privileges`;
- runs as a non-root user.
- **Operations:** a health check on `/healthz`, rotated logs (3 × 10 MB) and
`restart: unless-stopped`.
**Settings** go in `.env` next to `compose.yaml` (see `.env.example`). Keep it
private (`chmod 600 .env`); it's git-ignored.
| Variable | Default | Purpose |
|---|---|---|
| `AUTH_ENABLED` | `true` | require sign-in; `false` lets anyone who can reach the port in |
| `AUTH_REGISTER_OPEN` | `true` | allow creating accounts at `/register` |
| `AUTH_INVITE_ONLY` | `true` | …but only with an invite link |
| `AUTH_SESSION_DAYS` | `14` | how long a sign-in lasts |
| `BOOTSTRAP_ADMIN_USERNAME` / `_PASSWORD` | | create this administrator on first start, instead of in the browser |
| `PUBLIC_BASE_URL`, `SMTP_*` | | email invites (see `.env.example`) |
| `CASHBOOK_USER` | `1000:1000` | uid:gid to run as; it should own `data/`. Use `0:0` with rootless Docker, which maps container root to you. |
| `CASHBOOK_BIND` | `127.0.0.1` | host address to publish on |
| `CASHBOOK_PORT` | `8765` | host port |
| `CASHBOOK_ALLOWED_HOSTS` | | extra host names you open the app by, comma-separated; see below |
| `FORWARDED_ALLOW_IPS` | `127.0.0.1` | proxies trusted to say the request came over HTTPS |
**Reaching it from other machines:** keep it on `127.0.0.1` and put a reverse proxy
with HTTPS in front (Caddy, nginx, Traefik). Set `FORWARDED_ALLOW_IPS` to the proxy's
address, so sign-in cookies are marked secure. On a trusted network you can instead
set `CASHBOOK_BIND=0.0.0.0` and open `http://server-ip:8765`. Passwords then cross the
network unencrypted.
To block other websites from making changes through your sign-in, the app refuses
changes whose page address doesn't match the server's host name. It checks the
`Host` and `X-Forwarded-Host` headers. Caddy passes the original host through. With
nginx, add `proxy_set_header Host $host;`. Otherwise, list the name you use in
`CASHBOOK_ALLOWED_HOSTS`. A refused request shows up in `docker compose logs` with
the reason. A Caddy example:
```
cashbook.example.com {
reverse_proxy 127.0.0.1:8765
}
```
To also list ANZ exports from a folder on the host, add a `compose.override.yaml`.
It's git-ignored too.
```yaml
services:
cashbook:
volumes:
- /path/to/anz:/statements:ro
```
### Without Docker
Needs Python 3, `pdftotext` for PDF statements, and LibreOffice's UNO bridge for
spreadsheet export and migration. On Debian/Ubuntu:
```bash
sudo apt install libreoffice-calc python3-uno poppler-utils pipenv
```
The virtualenv needs the system site packages, so it can see LibreOffice's `uno`:
```bash
pipenv --site-packages --python /usr/bin/python3 install --dev
```
```bash
pipenv run dev
```
That serves <http://127.0.0.1:8765> and reloads on code changes. Settings come from
`.env` in the same way. `CASHBOOK_DATA` sets the data folder (default `./data`), and
`CASHBOOK_STATEMENTS` adds statement folders, separated by `:`.
Run the tests with:
```bash
pipenv run test
```
## Accounts
With `AUTH_ENABLED=true` (the default), everyone signs in with their own username
and password. Everyone signed in can see and change the books. Administrators can
also manage people from **Users** in the menu at the top right.
- **First run:** with no accounts yet, the sign-in page offers to create the
administrator account. Alternatively, set `BOOTSTRAP_ADMIN_USERNAME` and
`BOOTSTRAP_ADMIN_PASSWORD` and it's created on first start.
- **Inviting people:** on the Users page, create an invite link and send it. Each
link works once and expires after 1, 7 or 30 days. It can make the new person an
administrator. With `SMTP_*` set and an email address given, the link is emailed.
Pending invites can be revoked. Set `AUTH_INVITE_ONLY=false` to let anyone create
an account, or `AUTH_REGISTER_OPEN=false` to stop new accounts entirely.
- **Managing people:** rename, reset a password, make or remove an administrator,
or delete an account. You can't delete or demote yourself, and there's always at
least one administrator.
- **Passwords:** at least 8 characters, stored as bcrypt hashes. Use **Change
password** in the menu. Changing or resetting a password signs that account out
on every other device.
- **Sessions:** a sign-in lasts `AUTH_SESSION_DAYS` days, in an `httponly`,
`SameSite=Lax` cookie that's marked secure over HTTPS. **Sign out** ends it.
- **Brute force:** after 5 wrong passwords for a username or from an address within
15 minutes, sign-in is refused for a while.
## Using it
1. **New book…** creates a book for a financial year (April to March). If you've
ticked a PDF statement covering 31 March, the opening balance is filled in from it.
2. Add statements (drop them on the page, or **Add…**), tick them, and **Preview import**.
3. Check the preview: new rows, rows already in the book, and rows outside the book's
year (these are skipped). Then import. The database is backed up to
`data/cashbook.db.bak` first.
4. Go through each month: fix GST settings and allocate categories. **Only unallocated**
filters to what still needs doing.
5. Open **GST return**, pick your filing frequency, and enter the boxes into myIR
(see below).
6. **Export** gives you the book as a spreadsheet for your accountant or IRD records.
GST on the Year and month pages is 3/23 of each GST-inclusive amount, rounded to the
cent per transaction, the same as the spreadsheet. Exported spreadsheets show
zero-rated rows as Excl GST, since the template only has those two types.
### GST return
The **GST return** tab shows, for each filing period, the figures for boxes 5–15 of
the GST return (GST101A). These use the payments basis, with periods lined up to a
31 March balance date: six-monthly (Apr–Sep, Oct–Mar), two-monthly (Apr–May …
Feb–Mar) or monthly. It also shows each period's due date: the 28th of the following
month, except 7 May for periods ending in March and 15 January for November. Click a
figure to copy it.
What goes where depends on each transaction's GST type:
| GST type | Use for | On the return |
|---|---|---|
| Incl GST | sales and purchases at 15% GST | money in → Box 5; money out → Box 11 |
| Zero-rated | 0% GST supplies, such as services exported to overseas clients | money in → Box 5 and Box 6 |
| Excl GST | no GST: transfers, drawings, wages, interest, overseas purchases | left out |
Boxes 8 and 12 are 3/23 of the totals, as myIR calculates them, so they can differ by
a cent from the per-transaction GST on the Year page. Adjustments (boxes 9 and 13)
aren't tracked, so add any from your calculation sheet. The page lists anything to
check before filing: transactions not yet allocated, and money in or out left off the
return. Refunds from suppliers come in as Excl GST money in. If you claimed GST on
the original purchase, that GST needs a debit adjustment in Box 9.
These figures are worked out from your records and aren't tax advice. Check them
before you file.
### Income tax (IR4 and IR10)
The **Income tax** tab works out the company income tax return (IR4) and the
financial statements summary (IR10) for the book's year, box by box. Box numbers
follow IRD's IR10 (March 2026) and IR4 (2026) forms. Check them against the form
for the year you're filing.
**IR10.** The cashbook fills these boxes from allocated transactions, excluding GST:
| Cashbook category | IR10 box |
|---|---|
| Sales | 2 Sales and/or services |
| Interest | 7 Interest received |
| Grants, Sundry (income) | 10 Other income |
| Purchases | 4 Purchases |
| ACC & Insurance | 14 Insurance (move ACC levies to box 24) |
| Rent | 18 Rental, lease and licence payments |
| Wages | 22 Salaries and wages |
| Motor vehicle, Bank fees, Telephone & Power, Postage & Stationery, Sundry | 24 Other expenses |
| Drawings | 57 Drawings |
| Funds Intr., Loan repmt | not income or expenses |
| Closing bank balance | 31 Cash and deposits |
Anything the cashbook can't know you type in: stock, depreciation, debtors and
creditors, fixed assets, loans, tax adjustments and the other information boxes. For
boxes the cashbook fills, what you type is added to its figure, so you can move or
correct amounts. Totals (gross profit, net profit, total assets, owners' equity …)
are calculated. Unallocated transactions are left out, and the page says how much
there is.
The cashbook is on a cash basis, and bank interest arrives after RWT, so add the RWT
to box 7 to make it the gross interest.
**IR4.** Business profit (box 20B) comes from IR10 box 29, less the income reported
separately (interest, dividends, schedular and overseas income). You enter RWT and
other tax credits, donations, losses brought forward and provisional tax paid. Tax is
28% of taxable income in whole dollars, and the page shows the refund or tax to pay.
It assumes a New Zealand resident company with no residential property, Māori
authority, partnership or trust income, and no taxable property sales.
Entered amounts are saved per book in the database. These figures are worked out
from your records and aren't tax advice.
### Sending invoices
**Invoices** makes the invoices you send to customers, as PDFs.
- **Business details:** set your name, address, GST number, bank account, logo (PNG or
JPEG), payment terms and invoice numbering once. The logo is stored in `data/invoices`.
- **Customers:** saved for reuse. An invoice keeps the customer's details from when it
was made, so later edits to the customer don't change invoices already sent.
- **Numbers:** invoices are numbered in order (`INV-0001`, ...) when they're created.
Numbers are never reused, and a voided invoice keeps its number.
- **GST:** prices are entered excluding GST. Untick *GST* on a line for items with no GST
(for example costs passed on at cost). GST is 15% of the taxable lines, rounded once per
invoice. With a GST number, invoices that charge GST are titled *Tax invoice*.
- **Status:** a draft can be edited. Once it's marked sent, only its notes can change. Move
it back to draft to correct it, or void it.
- **Paid:** marking an invoice paid records the money in the book for the payment date,
as *Sales*. If that bank statement is already imported, pick the matching deposit, and
the bank line is used instead of adding a new one. Otherwise a new row is added, and a
statement imported later recognises it (same date and amount) as already in the book.
An invoice with GST and non-GST items becomes two rows, *Incl GST* and *Excl GST*, so
the GST return is right. *Undo payment* removes the rows it added, or puts a matched bank
line back as it was.
### Mileage
**Mileage** is a vehicle logbook. It works out the claim at IRD's kilometre rates.
- Add your vehicles, then log each trip: date, from and to, purpose, customer, and either
both odometer readings or the distance. The next trip's start reading defaults to the
last one. Readings that overlap another trip are saved with a warning.
- Untick *Business trip* for private use, so the business-use percentage is shown.
- Enter IRD's tier 1 and tier 2 rates for each income year (April to March). They
change every year, so none are built in. Tier 1 covers each vehicle's first 14,000
business km in the year, and tier 2 the rest.
- **Export logbook (CSV)** downloads the year's trips for your records.
Mileage is a report only. It doesn't add anything to the cashbook or the IR10, so
reimbursements you pay yourself from the bank aren't counted twice.
### Books kept in spreadsheets
Earlier versions kept each book as an `.ods` file in `data/`. At startup the app copies
any such spreadsheet into the database as a book named after the file, once, and
leaves the file alone. Rows split across several categories come in as unallocated,
and the log says which ones. To migrate files by hand:
```bash
python3 src/migrate.py data/cashbook-2026-27.ods
```
### How transactions are classified
These are starting guesses to review, not tax advice:
- NZ card purchases and payments out: **Incl GST**, unallocated.
- Overseas purchases (with a foreign currency amount), bank fees, transfers and money
in: **Excl GST**.
- Bank fees go to *Bank fees*.
- Transfers to and from your own accounts (`OWN_ACCOUNT_PREFIX` in
`src/statements.py`) go to *Drawings* (out) or *Funds Intr.* (in).
Income that is a GST-able sale needs changing to **Incl GST** by hand, otherwise it
won't count in the GST summary.
## Command line
```bash
python3 src/new_book.py cashbook-2026-27 --year 2026 --opening-balance 74.70
```
```bash
python3 src/anz_import.py cashbook-2026-27 data/statements/statement.pdf
```
```bash
python3 src/export.py cashbook-2026-27 cashbook-2026-27.xlsx
```
The export format comes from the file extension: `.xlsx`, `.ods` or `.csv`.
Transactions outside a book's year are skipped on import. All of these take
`--data DIR` (default `./data`).
## Layout
```
src/
app.py entry point (uvicorn app:app --app-dir src)
cashbook_app/ the FastAPI app
main.py app setup, security middleware, startup
config.py settings from the environment / .env
deps.py current user, admin check, database connections
routers/ auth, users, books, statements, invoices, mileage and page routes
services/ accounts, statement files, invoice PDFs, LibreOffice
db/, schemas/ account tables (SQLAlchemy) and request/response models
static/ the web pages (cashbook, sign-in, register, users), invoices.js, mileage.js
ledger.py SQLite storage: books, transactions, GST and summaries
invoices.py customers, invoices, numbering, GST and recording payments
mileage.py vehicle logbook and the kilometre-rate claim
tax.py IR10 and IR4 figures
statements.py reads ANZ CSV and PDF statements, GST/category guesses
export.py exports a book to .xlsx/.ods/.csv (also a CLI)
cashbook.py writes and reads the spreadsheet layout
migrate.py copies .ods cashbooks into the database (also a CLI)
office.py runs a private headless LibreOffice (for spreadsheets)
new_book.py creates a book (CLI)
anz_import.py imports statements (CLI)
template.ods blank cashbook template, used for exports
tests/ pytest suite (pipenv run test)
data/ cashbook.db and statements (git-ignored)
```
`data/` is in `.gitignore`: books, backups and bank statements are never committed.
Removed statements go to `data/statements/.trash`.
## Licence
### Cashbook template
`src/template.ods` is adapted from a free cashbook spreadsheet published by the
New Zealand Government. Its instructions refer to downloading it "from our website"
and to newzealand.govt.nz, and it was created in 2008. It appears to be the Inland
Revenue (IRD) cashbook template, but the original download page couldn't be confirmed.
Inland Revenue publishes its Crown copyright material under the
[Creative Commons Attribution 4.0 International licence](https://creativecommons.org/licenses/by/4.0/)
([IRD copyright statement](https://www.ird.govt.nz/about-this-site/conditions-of-use/copyright)).
You may reuse and adapt it, including commercially, if you:
- acknowledge the source and its Crown copyright status,
- reproduce it accurately and say what was changed,
- don't use it in a misleading or derogatory way.
The licence excludes logos, emblems, trademarks, design elements and photography.
The template contains none of these.
Attribution: *Cashbook template © Crown copyright, New Zealand Government (Inland
Revenue), licensed under CC BY 4.0. Modified: all transaction data and the opening
balance cleared.*
If you confirm the template came from a different agency, check that agency's terms.
Some, such as business.govt.nz, use the non-commercial
[CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/) licence instead.
### Code
Copyright (C) 2026 jimmy
The code is licensed under the GNU Affero General Public License v3.0; see
[LICENSE](LICENSE). It's free software: you can redistribute and modify it under
the AGPL. If you run a modified version as a network service, you must offer its
source code to the people who use it. It comes with no warranty.
The template is covered by its own CC BY 4.0 licence above, not the AGPL.