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>
This commit is contained in:
jimmyandClaude Opus 5.5 committed 2026-10-25 18:56:30 +13:00
1 parent 4b3e5f0932
commit 177dfbc0a4
15 files changed
+2208 -10

No files matched your search

+1
View File
@@ -8,6 +8,7 @@ fastapi = "*"
uvicorn = "*"
sqlalchemy = "*"
bcrypt = "*"
fpdf2 = "*"
[dev-packages]
pytest = "*"
Generated
+174 -4
View File
@@ -1,7 +1,7 @@
{
"_meta": {
"hash": {
"sha256": "47119175f9f01a429431ed06baae2e53be90fefd8a53c7a73a273db3ea065845"
"sha256": "83c5a098be61a5bfa7680a062089ff53e8927dac5d618bc2f4194d97c80c7964"
},
"pipfile-spec": 6,
"requires": {},
@@ -116,6 +116,14 @@
"markers": "python_version >= '3.10'",
"version": "==8.5.0"
},
"defusedxml": {
"hashes": [
"sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69",
"sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61"
],
"markers": "python_version >= '2.7' and python_version not in '3.0, 3.1, 3.2, 3.3, 3.4'",
"version": "==0.7.1"
},
"fastapi": {
"hashes": [
"sha256:3785963de305dd09912426cb81f2d230fce98ab3521cdfe97265c8d14983128c",
@@ -125,6 +133,79 @@
"markers": "python_version >= '3.10'",
"version": "==0.162.0"
},
"fonttools": {
"hashes": [
"sha256:0781fe22583529e1e98bb8a3a33040632e202a4c427ed7e65412c41a21b8ebcb",
"sha256:07a2f36b3263faadf5b7b548f62fd3cac401e490189c82b16f7139ac0df91cd4",
"sha256:13d7507252c5a5d7941a5fa1be27d335c378ef07983ea2bb24988bf600eadd5e",
"sha256:1671e5f368b0c136ed9fb62fef26c7e425b4ebb0bb669a1cb7ba453f5bba580b",
"sha256:1be99c1f07fca59510d657ef3eae584b5273fa4e203aff2383b3520744e19536",
"sha256:1f200cd2cf046a5a0b03babe84ebf8bbc12187d5d57f50bc03f24be89e7c1605",
"sha256:2a09d33a9264a6b29efca9dc633b53969aaedb250a9c8521d60f51280cef65ca",
"sha256:2bfab2f5d1d255dec82f4bd082a1c10e77df808e42210890f50a9c30bf91570e",
"sha256:33ae23a531795864fcdbbab91a40c824976e22642c05efca3bd8a0b00630d0e7",
"sha256:36f0fee56227b909c9d1392f17b23803616f1f04efbe020c176d9945cabc0be5",
"sha256:38fc772182ebff3e2ebba7886460476eb65842b601ca0b9221a6a5826136396e",
"sha256:3a19f6d5e1a373f2e4a5bdb9452c8ba212dd9f1e43df2fff042b896e28084e4a",
"sha256:3b34324deb3e09ad648039a0a86d945b83f23a44fe3da74a84e6ada71fe0b650",
"sha256:3cb57e6600ca77c0b1729cf8adc23bc0652633a37f18cfa934d9c7bc3de25519",
"sha256:3fb95166eaebad72f9deb1d0d781f652525f47e4693e553dad3954cf68ed6e9c",
"sha256:4304f03ed7f4ba000a8dcc941ad854bfa52e2f3b6112b8f099b6f431cf98e701",
"sha256:451077d2fc61a2a03f5dca54d84fbb01051ad781f48ea137eff35c775a4cb025",
"sha256:47dba566b4f475b0fb5f83129487c21b6a6a4edc41c0eec52524f969a68a3d45",
"sha256:48696b630069e29b8aa5ea8b034e4f651a2e112073938ec16bd536dadde1debf",
"sha256:4e2c1586b5b6588a47d02e2588170eefdc996b708f2659c44dbe169bd6fcacb5",
"sha256:50c41e30aa2e0130b80d1a58ac0f3ea7c02a854a70dbea1ff8d88e0ce524806f",
"sha256:5377e0e991e3e2be47fd1215414b20c2288b546e5a8c6d80b1a7cde9c72a89e1",
"sha256:592d8f72024dea0408739a92599e4f839b960e1e887b25adc76dc87271fdac76",
"sha256:59f44309ce78851c9621ee88e3f667ca3fbcc89dc0e8641336be3f12ba06bfd4",
"sha256:5ad690ea5bfd8913d1a6e5d5e9825ccf4ed342716e63c2b0d7f490d50235daef",
"sha256:5ccaa87b312219d02cf72a79f1eb2f3ce028882d6fd1b79336141005db83b84e",
"sha256:621b3152b5d0412381b792bacfe410ac1f09c2c4f28a44bd19d26fe7160cfc96",
"sha256:64e56d0d6a39780fee86955c758674538387b18f911ea904a4aae8f8e30fa26f",
"sha256:690ab72d338aa9bf8e5cd9aefb86e0d3c458d8b9de4df041fb7dc2ed4703144e",
"sha256:6c19a770a8d273371a37969003c143eaa629ab893c3db028af8b91d04c6f9a6d",
"sha256:720bcf27727193b0fe1883c2e036dc88e37047916e977f5c3daf6ee4316e9656",
"sha256:72d6d316dffc92eadb771f697f289ea7b60f689580931328905a267bd170f93b",
"sha256:7343cd0ef70edf8be7f4913cb9b55b992fb4e04055b47dcfecddcc2eb045a9d2",
"sha256:768a33bbe6ec5ba8f19979f938752f06d4e614cb554fd47abd7830f2007660e3",
"sha256:775364ac079e2ea7a2eedb5f9172c57b059d638ff79e2bf8d4257e5805713f32",
"sha256:77e0d4096a2ac60aebe43928b5382766df2d148577db8e8ff79b6a50879a6c06",
"sha256:8239e2ca24878715a19f061d065b5721e87da81d145e48b3418f771a469b5a24",
"sha256:846982e89b1861d6c9d7fcd6567aec3fa5a10ad313e7f2076045fcd339cfbd8e",
"sha256:84a3aed005de106fb1794372dace82eca50859d52ae26da4bb6c602480a41250",
"sha256:89ad62d116f45bb45873bb92fd69c14a720ba591cba488044731954a5565e194",
"sha256:8c21073cfe7129aaa070d94f575c1e2a880ae4aae1dcffd5352f174b96d27d16",
"sha256:8c58a8a9ad447bead6f91e5f50b23c0e4988538cdbd9bf2f68952b39f5900a84",
"sha256:916836845e4b1c1447bb61390ffb3cb5f2940fd9f5d6de4685539a81806c7764",
"sha256:952eb091689545d86d16e40f719ed7bb086dd810a07dcc9ea2ca0a81004810a3",
"sha256:9c38fece8156cbda31b42d49c4a187858056a35932b88233b6fb31eaca5cf67f",
"sha256:ad813967410ba6d24a52850df59b164ee17883f17b96a91b4b0ac6e9d7b5a118",
"sha256:ad8b4f7c754a627e91908fa1a1ccc90b489cd2810c0ba16acd26ea2ff5273db7",
"sha256:b274ed3106b8086f237b7dbb1529c28142ba10ae40b9d285be0ae6a44b2946d0",
"sha256:b3ddf350e74508102b33dc6b32984b6dd751359a7c57732bcd39f9d7cb37d71e",
"sha256:bd3239e5709fd4c3343db67245ede46aece610d7f7ef61afb174718122479282",
"sha256:e0ca4c8438dd6320f5850c9bbee3b3980455ee3bac602a9a0299caf9e799a0e8",
"sha256:e2b5d511ea012dce7bd6df12b279b7d7a5b01b019865717d03ae679f4b944fa5",
"sha256:e8a8545cbd58bd29494ffe81e3cb35f8a29332a8e495c42bec334145ce8cd65b",
"sha256:eb3c98cac93aac4b9f6e3ce2008325340b234cc9b0338ca6b513f31962a1e278",
"sha256:f672398385849ff79e7dd50c0a06efe110c8ba23d8890f9b45fbb922bc2f55f6",
"sha256:fc6b6b03aa44f504c8734e62ccc3e4dcda9f4b8213a85aa80742e4d1cc9d96ef",
"sha256:fcb9743140419410161acfe7ec205fb0a8a703acfccb85b586becb5a97c047c9",
"sha256:fd79e36c2968e9fc3e1b082f2ba7dc63ae88a161a3d8ceaa0746b906455f3617"
],
"markers": "python_version >= '3.11'",
"version": "==4.67.0"
},
"fpdf2": {
"hashes": [
"sha256:5b0b3786f5236a2b3cc83c1fee567df17ddd314f8c4e13d820d8f09b617ab4f0",
"sha256:6e1d94af6d6311950a23dec7fb5fc84b000203eb59aee8e76c1e701b12a14976"
],
"index": "pypi",
"markers": "python_version >= '3.10'",
"version": "==2.8.9"
},
"h11": {
"hashes": [
"sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1",
@@ -149,6 +230,95 @@
"markers": "python_version >= '3.10'",
"version": "==1.45.1"
},
"pillow": {
"hashes": [
"sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27",
"sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782",
"sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22",
"sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15",
"sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502",
"sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692",
"sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f",
"sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8",
"sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13",
"sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3",
"sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369",
"sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88",
"sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d",
"sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb",
"sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f",
"sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0",
"sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40",
"sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599",
"sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055",
"sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033",
"sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061",
"sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca",
"sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f",
"sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca",
"sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c",
"sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4",
"sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8",
"sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620",
"sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071",
"sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc",
"sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a",
"sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6",
"sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e",
"sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582",
"sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f",
"sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79",
"sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5",
"sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683",
"sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb",
"sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c",
"sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa",
"sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0",
"sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521",
"sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e",
"sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c",
"sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058",
"sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2",
"sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463",
"sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d",
"sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81",
"sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf",
"sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63",
"sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0",
"sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42",
"sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad",
"sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81",
"sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c",
"sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4",
"sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981",
"sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43",
"sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039",
"sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76",
"sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51",
"sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2",
"sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630",
"sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac",
"sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510",
"sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6",
"sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3",
"sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d",
"sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61",
"sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932",
"sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1",
"sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d",
"sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00",
"sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe",
"sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313",
"sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806",
"sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a",
"sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0",
"sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52",
"sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b",
"sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe"
],
"markers": "python_version >= '3.11'",
"version": "==13.0.0"
},
"pydantic": {
"hashes": [
"sha256:9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454",
@@ -381,11 +551,11 @@
},
"starlette": {
"hashes": [
"sha256:3d931de246ed870e35ce605974440816ef895e592f255d1396cfdf191d4c4318",
"sha256:fd3f159936e882d06c1108f84688f7cda2cf85fc6a592a50edbd175e882c2ddc"
"sha256:478c0ab3b4ced6e82719849c118fa406f0278a3499c1a898cd15cd31bdc38ce4",
"sha256:b8399098d4c1e3522734f7235dc79b1fc967f96cf139c81e0fa30479e0685f9b"
],
"markers": "python_version >= '3.11'",
"version": "==1.9.0"
"version": "==1.10.0"
},
"typing-extensions": {
"hashes": [
+44 -3
View File
@@ -251,6 +251,45 @@ 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
@@ -303,11 +342,13 @@ src/
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 and page routes
services/ accounts, statement files, LibreOffice
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)
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)
+4
View File
@@ -14,6 +14,8 @@ from cashbook_app.db.session import get_engine, get_session_factory
from cashbook_app.routers.auth_routes import router as auth_router
from cashbook_app.routers.books import router as books_router
from cashbook_app.routers.frontend import router as frontend_router
from cashbook_app.routers.invoices import router as invoices_router
from cashbook_app.routers.mileage import router as mileage_router
from cashbook_app.routers.statements import router as statements_router
from cashbook_app.routers.users_admin import router as users_router
from cashbook_app.services import accounts, spreadsheets
@@ -119,6 +121,8 @@ def create_app() -> FastAPI:
app.include_router(users_router)
app.include_router(books_router)
app.include_router(statements_router)
app.include_router(invoices_router)
app.include_router(mileage_router)
return app
+192
View File
@@ -0,0 +1,192 @@
from __future__ import annotations
import re
from urllib.parse import quote
from fastapi import APIRouter, Depends, HTTPException, Request, Response
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
import invoices
import ledger
from cashbook_app.deps import get_ledger, require_user
from cashbook_app.services import invoice_pdf
from cashbook_app.services.invoice_pdf import LogoError
router = APIRouter(prefix="/api", tags=["invoices"], dependencies=[Depends(require_user)])
class BusinessUpdate(BaseModel):
name: str | None = Field(None, max_length=200)
address: str | None = Field(None, max_length=500)
email: str | None = Field(None, max_length=200)
phone: str | None = Field(None, max_length=50)
gst_number: str | None = Field(None, max_length=20)
bank_account: str | None = Field(None, max_length=50)
invoice_prefix: str | None = Field(None, max_length=20)
next_number: int | None = None
payment_terms_days: int | None = Field(None, le=365)
footer: str | None = Field(None, max_length=1000)
class Customer(BaseModel):
name: str = Field(min_length=1, max_length=200)
email: str = Field("", max_length=200)
address: str = Field("", max_length=500)
class Line(BaseModel):
description: str = Field(max_length=500)
qty: float = 1
unit: float
taxable: bool = True
class InvoiceCreate(BaseModel):
customer_id: int
issue_date: str
due_date: str | None = None
lines: list[Line]
notes: str = Field("", max_length=2000)
class InvoiceUpdate(BaseModel):
customer_id: int | None = None
issue_date: str | None = None
due_date: str | None = None
lines: list[Line] | None = None
notes: str | None = Field(None, max_length=2000)
class StatusChange(BaseModel):
status: str
class Payment(BaseModel):
date: str
row: int | None = None # an imported bank line to record it on
def _call(fn, *args, **kwargs):
try:
return fn(*args, **kwargs)
except ledger.NotFound as e:
raise HTTPException(status_code=404, detail=str(e))
except (ValueError, LogoError) as e:
raise HTTPException(status_code=400, detail=str(e))
# --- business ---------------------------------------------------------------
@router.get("/business")
def get_business(conn=Depends(get_ledger)):
return invoices.get_business(conn)
@router.put("/business")
def update_business(body: BusinessUpdate, conn=Depends(get_ledger)):
return _call(invoices.update_business, conn, **body.model_dump(exclude_unset=True, exclude_none=True))
@router.post("/business/logo")
async def upload_logo(request: Request, conn=Depends(get_ledger)):
if int(request.headers.get("content-length") or 0) > invoice_pdf.MAX_LOGO:
raise HTTPException(status_code=413, detail="the logo is too large (2 MB at most)")
name = _call(invoice_pdf.save_logo, await request.body())
invoices.set_logo(conn, name)
return invoices.get_business(conn)
@router.get("/business/logo")
def get_logo(conn=Depends(get_ledger)):
path = invoice_pdf.logo_path(invoices.get_business(conn)["logo_file"])
if path is None:
raise HTTPException(status_code=404, detail="no logo")
return FileResponse(path)
@router.delete("/business/logo")
def delete_logo(conn=Depends(get_ledger)):
invoice_pdf.remove_logo(invoices.set_logo(conn, None))
return invoices.get_business(conn)
# --- customers --------------------------------------------------------------
@router.get("/customers")
def list_customers(conn=Depends(get_ledger)):
return invoices.list_customers(conn)
@router.post("/customers")
def create_customer(body: Customer, conn=Depends(get_ledger)):
return _call(invoices.create_customer, conn, **body.model_dump())
@router.put("/customers/{customer_id}")
def update_customer(customer_id: int, body: Customer, conn=Depends(get_ledger)):
return _call(invoices.update_customer, conn, customer_id, **body.model_dump())
@router.delete("/customers/{customer_id}")
def delete_customer(customer_id: int, conn=Depends(get_ledger)):
_call(invoices.delete_customer, conn, customer_id)
return {"ok": True}
# --- invoices ---------------------------------------------------------------
def _lines(lines):
return None if lines is None else [l.model_dump() for l in lines]
@router.get("/invoices")
def list_invoices(status: str | None = None, customer: int | None = None, conn=Depends(get_ledger)):
return invoices.list_invoices(conn, status, customer)
@router.post("/invoices")
def create_invoice(body: InvoiceCreate, conn=Depends(get_ledger)):
return _call(invoices.create_invoice, conn, body.customer_id, body.issue_date, _lines(body.lines),
due_date=body.due_date, notes=body.notes)
@router.get("/invoices/{invoice_id}")
def get_invoice(invoice_id: int, conn=Depends(get_ledger)):
return _call(invoices.get_invoice, conn, invoice_id)
@router.put("/invoices/{invoice_id}")
def update_invoice(invoice_id: int, body: InvoiceUpdate, conn=Depends(get_ledger)):
return _call(invoices.update_invoice, conn, invoice_id, customer_id=body.customer_id,
issue_date=body.issue_date, due_date=body.due_date, lines=_lines(body.lines), notes=body.notes)
@router.post("/invoices/{invoice_id}/status")
def set_status(invoice_id: int, body: StatusChange, conn=Depends(get_ledger)):
return _call(invoices.set_status, conn, invoice_id, body.status)
@router.get("/invoices/{invoice_id}/matches")
def bank_matches(invoice_id: int, date: str, conn=Depends(get_ledger)):
return _call(invoices.bank_matches, conn, invoice_id, date)
@router.post("/invoices/{invoice_id}/pay")
def pay(invoice_id: int, body: Payment, conn=Depends(get_ledger)):
return _call(invoices.mark_paid, conn, invoice_id, body.date, row=body.row)
@router.post("/invoices/{invoice_id}/unpay")
def unpay(invoice_id: int, conn=Depends(get_ledger)):
return _call(invoices.unmark_paid, conn, invoice_id)
@router.get("/invoices/{invoice_id}/pdf")
def invoice_pdf_file(invoice_id: int, conn=Depends(get_ledger)):
inv = _call(invoices.get_invoice, conn, invoice_id)
data = invoice_pdf.render(inv, invoices.get_business(conn))
filename = f"{inv['number']} {inv['customer_name']}.pdf"
safe = re.sub(r"[^\w.-]", "_", filename)
return Response(data, media_type="application/pdf", headers={
"Content-Disposition": f"attachment; filename=\"{safe}\"; filename*=UTF-8''{quote(filename)}"})
+113
View File
@@ -0,0 +1,113 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Response
from pydantic import BaseModel, Field
import ledger
import mileage
from cashbook_app.deps import get_ledger, require_user
router = APIRouter(prefix="/api", tags=["mileage"], dependencies=[Depends(require_user)])
class VehicleCreate(BaseModel):
name: str = Field(min_length=1, max_length=100)
rego: str = Field("", max_length=20)
class VehicleUpdate(BaseModel):
name: str | None = Field(None, max_length=100)
rego: str | None = Field(None, max_length=20)
active: bool | None = None
class Trip(BaseModel):
vehicle_id: int
date: str
from_place: str = ""
to_place: str = ""
purpose: str = ""
customer: str = ""
odo_start: int | None = Field(None, ge=0)
odo_end: int | None = Field(None, ge=0)
km: float | None = None
business: bool = True
class Rate(BaseModel):
tier1: float
tier2: float
tier1_limit_km: int = 14000
def _call(fn, *args, **kwargs):
try:
return fn(*args, **kwargs)
except ledger.NotFound as e:
raise HTTPException(status_code=404, detail=str(e))
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.get("/vehicles")
def list_vehicles(conn=Depends(get_ledger)):
return mileage.list_vehicles(conn)
@router.post("/vehicles")
def create_vehicle(body: VehicleCreate, conn=Depends(get_ledger)):
return _call(mileage.create_vehicle, conn, body.name, body.rego)
@router.put("/vehicles/{vehicle_id}")
def update_vehicle(vehicle_id: int, body: VehicleUpdate, conn=Depends(get_ledger)):
return _call(mileage.update_vehicle, conn, vehicle_id, **body.model_dump(exclude_unset=True))
@router.delete("/vehicles/{vehicle_id}")
def delete_vehicle(vehicle_id: int, conn=Depends(get_ledger)):
_call(mileage.delete_vehicle, conn, vehicle_id)
return {"ok": True}
@router.get("/trips")
def list_trips(year: int | None = None, vehicle: int | None = None, conn=Depends(get_ledger)):
return mileage.list_trips(conn, year, vehicle)
@router.post("/trips")
def add_trip(body: Trip, conn=Depends(get_ledger)):
return _call(mileage.add_trip, conn, **body.model_dump())
@router.put("/trips/{trip_id}")
def update_trip(trip_id: int, body: Trip, conn=Depends(get_ledger)):
return _call(mileage.update_trip, conn, trip_id, **body.model_dump())
@router.delete("/trips/{trip_id}")
def delete_trip(trip_id: int, conn=Depends(get_ledger)):
_call(mileage.delete_trip, conn, trip_id)
return {"ok": True}
@router.get("/mileage/rates/{year}")
def get_rate(year: int, conn=Depends(get_ledger)):
return mileage.get_rate(conn, year)
@router.put("/mileage/rates/{year}")
def set_rate(year: int, body: Rate, conn=Depends(get_ledger)):
return _call(mileage.set_rate, conn, year, body.tier1, body.tier2, body.tier1_limit_km)
@router.get("/mileage/report")
def report(year: int, conn=Depends(get_ledger)):
return mileage.report(conn, year)
@router.get("/mileage/export")
def export(year: int, conn=Depends(get_ledger)):
filename = f"logbook-{year}-{(year + 1) % 100:02d}.csv"
return Response(mileage.export_csv(conn, year), media_type="text/csv; charset=utf-8",
headers={"Content-Disposition": f"attachment; filename=\"{filename}\""})
+193
View File
@@ -0,0 +1,193 @@
"""Invoice PDFs (fpdf2) and the logo they carry, kept in data/invoices."""
from __future__ import annotations
from datetime import date
from pathlib import Path
from fpdf import FPDF
from cashbook_app import config
MAX_LOGO = 2 * 1024 * 1024
LOGO_EXT = {"image/png": ".png", "image/jpeg": ".jpg"}
LOGO_MAGIC = {b"\x89PNG\r\n\x1a\n": "image/png", b"\xff\xd8\xff": "image/jpeg"}
FONT_DIR = Path("/usr/share/fonts/truetype/dejavu") # fonts-dejavu-core
class LogoError(Exception):
pass
def invoices_dir() -> Path:
path = config.data_dir() / "invoices"
path.mkdir(parents=True, exist_ok=True)
return path
def logo_path(logo_file: str | None) -> Path | None:
if logo_file not in [f"logo{ext}" for ext in LOGO_EXT.values()]:
return None
path = invoices_dir() / logo_file
return path if path.exists() else None
def save_logo(data: bytes) -> str:
"""Write the logo; returns its file name. Only PNG and JPEG, which fpdf can embed."""
if not data:
raise LogoError("the file is empty")
if len(data) > MAX_LOGO:
raise LogoError("the logo is too large (2 MB at most)")
mime = next((m for magic, m in LOGO_MAGIC.items() if data.startswith(magic)), None)
if mime is None:
raise LogoError("the logo must be a PNG or JPEG image")
name = f"logo{LOGO_EXT[mime]}"
for ext in LOGO_EXT.values():
(invoices_dir() / f"logo{ext}").unlink(missing_ok=True)
(invoices_dir() / name).write_bytes(data)
return name
def remove_logo(logo_file: str | None) -> None:
path = logo_path(logo_file)
if path:
path.unlink(missing_ok=True)
def _money(x: float) -> str:
return f"${x:,.2f}"
def _qty(q: float) -> str:
return f"{q:g}"
def _date(iso: str) -> str:
return date.fromisoformat(iso).strftime("%-d %B %Y")
class _Pdf(FPDF):
def __init__(self):
super().__init__(format="A4")
self.set_margins(18, 18, 18)
self.set_auto_page_break(True, 20)
if (FONT_DIR / "DejaVuSans.ttf").exists():
self.add_font("body", "", str(FONT_DIR / "DejaVuSans.ttf"))
self.add_font("body", "B", str(FONT_DIR / "DejaVuSans-Bold.ttf"))
self.family = "body"
else:
self.family = "helvetica" # latin-1 only
def font(self, size, style=""):
self.set_font(self.family, style, size)
def render(invoice: dict, business: dict) -> bytes:
pdf = _Pdf()
pdf.add_page()
width = pdf.epw
grey = (110, 110, 110)
has_gst = invoice["gst"] > 0
title = "TAX INVOICE" if has_gst and business["gst_number"] else "INVOICE"
# header: logo and business on the left, title and numbers on the right
top = pdf.get_y()
logo = logo_path(business.get("logo_file"))
if logo:
pdf.image(str(logo), x=pdf.l_margin, y=top, h=20, keep_aspect_ratio=True)
pdf.set_y(top + 23)
pdf.font(12, "B")
pdf.multi_cell(width * 0.55, 6, business["name"] or "Your business name", new_x="LMARGIN", new_y="NEXT")
pdf.font(9)
pdf.set_text_color(*grey)
for line in [business["address"], business["phone"], business["email"],
f"GST number: {business['gst_number']}" if business["gst_number"] else ""]:
if line:
pdf.multi_cell(width * 0.55, 4.6, line, new_x="LMARGIN", new_y="NEXT")
left_bottom = pdf.get_y()
pdf.set_text_color(0)
pdf.set_xy(pdf.l_margin + width * 0.55, top)
pdf.font(18, "B")
pdf.cell(width * 0.45, 9, title, align="R", new_x="LEFT", new_y="NEXT")
pdf.font(9)
for label, value in [("Invoice number", invoice["number"]), ("Date", _date(invoice["issue_date"])),
("Due", _date(invoice["due_date"]))]:
pdf.set_x(pdf.l_margin + width * 0.55)
pdf.set_text_color(*grey)
pdf.cell(width * 0.25, 5, label, align="R")
pdf.set_text_color(0)
pdf.cell(width * 0.20, 5, value, align="R", new_x="LMARGIN", new_y="NEXT")
pdf.set_y(max(left_bottom, pdf.get_y()) + 8)
# bill to
pdf.font(8, "B")
pdf.set_text_color(*grey)
pdf.cell(0, 5, "BILL TO", new_x="LMARGIN", new_y="NEXT")
pdf.set_text_color(0)
pdf.font(10, "B")
pdf.multi_cell(width * 0.6, 5.5, invoice["customer_name"], new_x="LMARGIN", new_y="NEXT")
pdf.font(9)
for line in [invoice["customer_address"], invoice["customer_email"]]:
if line:
pdf.multi_cell(width * 0.6, 4.6, line, new_x="LMARGIN", new_y="NEXT")
pdf.ln(7)
# lines
mixed = any(not l["taxable"] for l in invoice["lines"]) and has_gst
cols = [("Description", width * 0.52, "L"), ("Qty", width * 0.10, "R"),
("Unit price", width * 0.18, "R"), ("Amount", width * 0.20, "R")]
pdf.set_fill_color(240, 240, 240)
pdf.font(9, "B")
for name, w, align in cols:
pdf.cell(w, 7, name, align=align, fill=True)
pdf.ln()
pdf.font(9)
for l in invoice["lines"]:
desc = l["description"] + (" *" if mixed and not l["taxable"] else "")
y = pdf.get_y()
pdf.multi_cell(cols[0][1], 6, desc, new_x="RIGHT", new_y="TOP")
end_y = pdf.get_y() if pdf.get_y() > y else y
pdf.set_xy(pdf.l_margin + cols[0][1], y)
pdf.cell(cols[1][1], 6, _qty(l["qty"]), align="R")
pdf.cell(cols[2][1], 6, _money(l["unit"]), align="R")
pdf.cell(cols[3][1], 6, _money(l["amount"]), align="R", new_x="LMARGIN", new_y="NEXT")
pdf.set_y(max(end_y, pdf.get_y()))
pdf.set_draw_color(225, 225, 225)
pdf.line(pdf.l_margin, pdf.get_y(), pdf.l_margin + width, pdf.get_y())
pdf.ln(3)
# totals
label_w, value_w = width * 0.30, width * 0.20
rows = [("Subtotal (excl. GST)", invoice["subtotal"])]
if has_gst or business["gst_number"]:
rows.append(("GST 15%" + (f" on {_money(invoice['taxable'])}" if mixed else ""), invoice["gst"]))
for label, value in rows:
pdf.set_x(pdf.l_margin + width - label_w - value_w)
pdf.cell(label_w, 6, label, align="R")
pdf.cell(value_w, 6, _money(value), align="R", new_x="LMARGIN", new_y="NEXT")
pdf.set_x(pdf.l_margin + width - label_w - value_w)
pdf.font(11, "B")
pdf.cell(label_w, 8, "Total NZD", align="R", border="T")
pdf.cell(value_w, 8, _money(invoice["total"]), align="R", border="T", new_x="LMARGIN", new_y="NEXT")
pdf.font(9)
if mixed:
pdf.set_text_color(*grey)
pdf.cell(0, 6, "* No GST on this item", new_x="LMARGIN", new_y="NEXT")
pdf.set_text_color(0)
pdf.ln(8)
# payment details and notes
if business["bank_account"]:
pdf.font(9, "B")
pdf.cell(0, 5, "Payment", new_x="LMARGIN", new_y="NEXT")
pdf.font(9)
pdf.multi_cell(0, 5, f"Please pay by {_date(invoice['due_date'])} to bank account "
f"{business['bank_account']}, using {invoice['number']} as the reference.",
new_x="LMARGIN", new_y="NEXT")
pdf.ln(3)
for text in [invoice["notes"], business["footer"]]:
if text:
pdf.set_text_color(*grey)
pdf.multi_cell(0, 5, text, new_x="LMARGIN", new_y="NEXT")
pdf.ln(2)
return bytes(pdf.output())
+331
View File
@@ -0,0 +1,331 @@
"""Invoices sent to customers: the business they come from, customers, numbering, GST and payment.
Line prices are excluding GST. GST is 15% of the taxable lines' total, rounded half-up to
the cent once per invoice. Marking an invoice paid records the money in the cashbook: it is
matched to the bank line if the statement is already imported, or added as a new row that
the statement import will then recognise. An invoice with taxable and non-taxable lines
becomes two rows (Incl GST and Excl GST), since a cashbook row has one GST type.
"""
from datetime import date, timedelta
from decimal import ROUND_HALF_UP, Decimal
import ledger
STATUSES = ("draft", "sent", "paid", "void")
BUSINESS_FIELDS = ("name", "address", "email", "phone", "gst_number", "bank_account",
"invoice_prefix", "next_number", "payment_terms_days", "footer")
CUSTOMER_FIELDS = ("name", "email", "address")
MATCH_DAYS = 7 # how far an imported bank line's date may be from the payment date
# --- business ---------------------------------------------------------------
def get_business(conn):
with conn:
conn.execute("INSERT OR IGNORE INTO business (id) VALUES (1)")
return dict(conn.execute("SELECT * FROM business WHERE id = 1").fetchone())
def update_business(conn, **fields):
get_business(conn)
for k, v in fields.items():
if k not in BUSINESS_FIELDS:
raise ValueError(f"can't change {k}")
if k in ("next_number", "payment_terms_days"):
v = int(v)
if v < (1 if k == "next_number" else 0):
raise ValueError(f"{k.replace('_', ' ')} is too small")
if k == "next_number" and conn.execute(
"SELECT 1 FROM invoices WHERE number = ?", (_number(get_business(conn)["invoice_prefix"], v),)).fetchone():
raise ValueError("an invoice already has that number")
with conn:
conn.execute(f"UPDATE business SET {k} = ? WHERE id = 1", (v.strip() if isinstance(v, str) else v,))
return get_business(conn)
def set_logo(conn, logo_file):
"""Record the logo's file name; returns the previous one so the caller can remove it."""
old = get_business(conn)["logo_file"]
with conn:
conn.execute("UPDATE business SET logo_file = ? WHERE id = 1", (logo_file,))
return old
def _number(prefix, n):
return f"{prefix}{n:04d}"
# --- customers --------------------------------------------------------------
def list_customers(conn):
return [dict(r) for r in conn.execute(
"SELECT c.*, COUNT(i.id) AS invoices FROM customers c LEFT JOIN invoices i ON i.customer_id = c.id "
"GROUP BY c.id ORDER BY c.name COLLATE NOCASE")]
def get_customer(conn, customer_id):
c = conn.execute("SELECT * FROM customers WHERE id = ?", (customer_id,)).fetchone()
if c is None:
raise ledger.NotFound("no such customer")
return dict(c)
def _customer_fields(fields):
out = {}
for k, v in fields.items():
if k not in CUSTOMER_FIELDS:
raise ValueError(f"can't change {k}")
out[k] = (v or "").strip()
if "name" in out and not out["name"]:
raise ValueError("the customer needs a name")
return out
def create_customer(conn, name, email="", address=""):
f = _customer_fields({"name": name, "email": email, "address": address})
with conn:
cur = conn.execute("INSERT INTO customers (name, email, address) VALUES (?, ?, ?)",
(f["name"], f["email"], f["address"]))
return get_customer(conn, cur.lastrowid)
def update_customer(conn, customer_id, **fields):
get_customer(conn, customer_id)
for k, v in _customer_fields(fields).items():
with conn:
conn.execute(f"UPDATE customers SET {k} = ? WHERE id = ?", (v, customer_id))
return get_customer(conn, customer_id)
def delete_customer(conn, customer_id):
get_customer(conn, customer_id)
if conn.execute("SELECT 1 FROM invoices WHERE customer_id = ?", (customer_id,)).fetchone():
raise ValueError("this customer has invoices, so it can't be deleted")
with conn:
conn.execute("DELETE FROM customers WHERE id = ?", (customer_id,))
# --- amounts ----------------------------------------------------------------
def line_cents(qty, unit_cents):
return int((Decimal(str(qty)) * unit_cents).quantize(Decimal(1), rounding=ROUND_HALF_UP))
def gst_on(taxable_cents):
"""15% GST on an amount excluding GST, rounded half-up to the cent."""
return (taxable_cents * 6 + 20) // 40
def totals(lines):
"""Subtotal, GST and total in cents, from lines with qty, unit_cents and taxable."""
amounts = [(line_cents(l["qty"], l["unit_cents"]), l["taxable"]) for l in lines]
taxable = sum(a for a, t in amounts if t)
exempt = sum(a for a, t in amounts if not t)
gst = gst_on(taxable)
return {"subtotal": taxable + exempt, "taxable": taxable, "exempt": exempt, "gst": gst,
"total": taxable + exempt + gst}
# --- invoices ---------------------------------------------------------------
def _check_lines(lines):
if not lines:
raise ValueError("the invoice needs at least one line")
out = []
for l in lines:
description = (l.get("description") or "").strip()
if not description:
raise ValueError("every line needs a description")
qty = float(l.get("qty", 1))
if qty <= 0:
raise ValueError("quantities must be more than zero")
out.append({"description": description[:500], "qty": qty,
"unit_cents": ledger.cents(float(l.get("unit", 0))), "taxable": bool(l.get("taxable", True))})
if totals(out)["total"] <= 0:
raise ValueError("the invoice total must be more than zero")
return out
def _check_dates(issue_date, due_date, terms):
issued = date.fromisoformat(issue_date) # ValueError if it isn't a date
due = date.fromisoformat(due_date) if due_date else issued + timedelta(days=terms)
if due < issued:
raise ValueError("the due date is before the invoice date")
return issued.isoformat(), due.isoformat()
def _write_lines(conn, invoice_id, lines):
conn.execute("DELETE FROM invoice_lines WHERE invoice_id = ?", (invoice_id,))
conn.executemany(
"INSERT INTO invoice_lines (invoice_id, position, description, qty, unit_cents, taxable) "
"VALUES (?, ?, ?, ?, ?, ?)",
[(invoice_id, i, l["description"], l["qty"], l["unit_cents"], int(l["taxable"]))
for i, l in enumerate(lines)])
def create_invoice(conn, customer_id, issue_date, lines, due_date=None, notes=""):
business = get_business(conn)
customer = get_customer(conn, customer_id)
lines = _check_lines(lines)
issued, due = _check_dates(issue_date, due_date, business["payment_terms_days"])
with conn: # the number is taken in the same transaction, so it's never handed out twice
n = conn.execute("SELECT next_number FROM business WHERE id = 1").fetchone()[0]
while conn.execute("SELECT 1 FROM invoices WHERE number = ?",
(_number(business["invoice_prefix"], n),)).fetchone():
n += 1
cur = conn.execute(
"INSERT INTO invoices (number, customer_id, customer_name, customer_address, customer_email, "
"issue_date, due_date, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(_number(business["invoice_prefix"], n), customer_id, customer["name"], customer["address"],
customer["email"], issued, due, (notes or "").strip()))
conn.execute("UPDATE business SET next_number = ? WHERE id = 1", (n + 1,))
_write_lines(conn, cur.lastrowid, lines)
return get_invoice(conn, cur.lastrowid)
def _invoice(conn, inv):
d = dict(inv)
lines = [dict(l) for l in conn.execute(
"SELECT description, qty, unit_cents, taxable FROM invoice_lines WHERE invoice_id = ? ORDER BY position",
(inv["id"],))]
t = totals(lines)
d["lines"] = [{"description": l["description"], "qty": l["qty"], "unit": l["unit_cents"] / 100,
"taxable": bool(l["taxable"]), "amount": line_cents(l["qty"], l["unit_cents"]) / 100}
for l in lines]
d.update({k: v / 100 for k, v in t.items()})
d["overdue"] = d["status"] == "sent" and d["due_date"] < date.today().isoformat()
d["payments"] = [ledger._brief(ledger._transaction_info(conn, p["transaction_id"])) for p in conn.execute(
"SELECT transaction_id FROM invoice_payments WHERE invoice_id = ? ORDER BY transaction_id", (inv["id"],))]
return d
def get_invoice(conn, invoice_id):
inv = conn.execute("SELECT * FROM invoices WHERE id = ?", (invoice_id,)).fetchone()
if inv is None:
raise ledger.NotFound("no such invoice")
return _invoice(conn, inv)
def list_invoices(conn, status=None, customer_id=None):
where, args = [], []
if status:
where.append("status = ?")
args.append(status)
if customer_id is not None:
where.append("customer_id = ?")
args.append(customer_id)
sql = "SELECT * FROM invoices" + (" WHERE " + " AND ".join(where) if where else "")
return [_invoice(conn, i) for i in conn.execute(sql + " ORDER BY issue_date DESC, id DESC", args)]
def update_invoice(conn, invoice_id, customer_id=None, issue_date=None, due_date=None, lines=None, notes=None):
"""Change a draft. Once sent, only the notes can change."""
inv = get_invoice(conn, invoice_id)
if inv["status"] != "draft" and any(v is not None for v in (customer_id, issue_date, due_date, lines)):
raise ValueError(f"invoice {inv['number']} has been {inv['status']}, so only its notes can change")
with conn:
if customer_id is not None:
c = get_customer(conn, customer_id)
conn.execute("UPDATE invoices SET customer_id = ?, customer_name = ?, customer_address = ?, "
"customer_email = ? WHERE id = ?", (c["id"], c["name"], c["address"], c["email"], invoice_id))
if issue_date is not None or due_date is not None:
issued, due = _check_dates(issue_date or inv["issue_date"], due_date or inv["due_date"], 0)
conn.execute("UPDATE invoices SET issue_date = ?, due_date = ? WHERE id = ?", (issued, due, invoice_id))
if lines is not None:
_write_lines(conn, invoice_id, _check_lines(lines))
if notes is not None:
conn.execute("UPDATE invoices SET notes = ? WHERE id = ?", (notes.strip(), invoice_id))
return get_invoice(conn, invoice_id)
def set_status(conn, invoice_id, status):
"""draft -> sent, sent -> draft (to correct it), draft/sent -> void. Paid goes through mark_paid."""
inv = get_invoice(conn, invoice_id)
allowed = {"draft": ("sent", "void"), "sent": ("draft", "void"), "paid": (), "void": ()}[inv["status"]]
if status not in allowed:
hint = " (undo the payment first)" if inv["status"] == "paid" else ""
raise ValueError(f"invoice {inv['number']} is {inv['status']} and can't be made {status}{hint}")
with conn:
conn.execute("UPDATE invoices SET status = ? WHERE id = ?", (status, invoice_id))
return get_invoice(conn, invoice_id)
# --- payment ----------------------------------------------------------------
def book_for(conn, day):
"""The book whose financial year (1 April - 31 March) contains `day`."""
year = day.year if day.month >= 4 else day.year - 1
b = conn.execute("SELECT * FROM books WHERE start_year = ? ORDER BY id LIMIT 1", (year,)).fetchone()
if b is None:
raise ValueError(f"there's no book for the year starting 1 April {year}; create one first")
return b
def bank_matches(conn, invoice_id, paid_date):
"""Imported money-in lines that could be this invoice's payment: same amount, within MATCH_DAYS,
not already allocated, nearest first."""
inv = get_invoice(conn, invoice_id)
day = date.fromisoformat(paid_date)
rows = conn.execute(
"SELECT t.*, b.name AS book FROM transactions t JOIN books b ON b.id = t.book_id "
"WHERE t.amount_cents = ? AND t.category IS NULL "
"AND t.id NOT IN (SELECT transaction_id FROM invoice_payments)", (ledger.cents(inv["total"]),)).fetchall()
near = [(abs((date.fromisoformat(t["date"]) - day).days), t) for t in rows]
return [{**ledger._brief(t), "days_apart": gap}
for gap, t in sorted(near, key=lambda x: x[0]) if gap <= MATCH_DAYS]
def mark_paid(conn, invoice_id, paid_date, row=None):
"""Record the payment: on bank line `row` if given (see bank_matches), otherwise as new cashbook rows
dated `paid_date` in the book for that date."""
inv = get_invoice(conn, invoice_id)
if inv["status"] not in ("draft", "sent"):
raise ValueError(f"invoice {inv['number']} is {inv['status']}")
paid = date.fromisoformat(paid_date)
taxable_cents = ledger.cents(inv["taxable"] + inv["gst"])
exempt_cents = ledger.cents(inv["exempt"])
parts = [(c, gst) for c, gst in ((taxable_cents, "Incl GST"), (exempt_cents, "Excl GST")) if c]
reference = f"{inv['number']} {inv['customer_name']}"[:200]
with conn:
if row is not None:
t = ledger._transaction_info(conn, row)
if t["amount_cents"] != taxable_cents + exempt_cents:
raise ValueError("that bank line's amount isn't the invoice total")
if conn.execute("SELECT 1 FROM invoice_payments WHERE transaction_id = ?", (row,)).fetchone():
raise ValueError("that bank line is already recorded as another invoice's payment")
(first, gst), rest = parts[0], parts[1:]
conn.execute("UPDATE transactions SET amount_cents = ?, gst = ?, category = 'Sales' WHERE id = ?",
(first, gst, row))
conn.execute("INSERT INTO invoice_payments VALUES (?, ?, 0, ?, ?, ?)",
(invoice_id, row, t["amount_cents"], t["gst"], t["category"]))
book_id, day, reference = t["book_id"], t["date"], t["reference"]
paid_date = t["date"]
else:
book_id, day, rest = book_for(conn, paid)["id"], paid.isoformat(), parts
for amount, gst in rest:
cur = conn.execute(
"INSERT INTO transactions (book_id, date, reference, origin, amount_cents, gst, category, source) "
"VALUES (?, ?, ?, 'Invoice', ?, ?, 'Sales', ?)",
(book_id, day, reference, amount, gst, f"invoice {inv['number']}"))
conn.execute("INSERT INTO invoice_payments (invoice_id, transaction_id, created) VALUES (?, ?, 1)",
(invoice_id, cur.lastrowid))
conn.execute("UPDATE invoices SET status = 'paid', paid_date = ? WHERE id = ?", (paid_date, invoice_id))
return get_invoice(conn, invoice_id)
def unmark_paid(conn, invoice_id):
"""Undo mark_paid: remove the rows it added and put a matched bank line back as it was."""
inv = get_invoice(conn, invoice_id)
if inv["status"] != "paid":
raise ValueError(f"invoice {inv['number']} isn't paid")
with conn:
for p in conn.execute("SELECT * FROM invoice_payments WHERE invoice_id = ?", (invoice_id,)).fetchall():
conn.execute("DELETE FROM invoice_payments WHERE invoice_id = ? AND transaction_id = ?",
(invoice_id, p["transaction_id"]))
if p["created"]:
conn.execute("DELETE FROM transactions WHERE id = ?", (p["transaction_id"],))
else:
conn.execute("UPDATE transactions SET amount_cents = ?, gst = ?, category = ? WHERE id = ?",
(p["orig_amount_cents"], p["orig_gst"], p["orig_category"], p["transaction_id"]))
conn.execute("UPDATE invoices SET status = 'sent', paid_date = NULL WHERE id = ?", (invoice_id,))
return get_invoice(conn, invoice_id)
+105 -1
View File
@@ -47,6 +47,89 @@ CREATE TABLE IF NOT EXISTS transactions (
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS transactions_book_date ON transactions (book_id, date);
CREATE TABLE IF NOT EXISTS business ( -- the one business invoices are sent from
id INTEGER PRIMARY KEY CHECK (id = 1),
name TEXT NOT NULL DEFAULT '',
address TEXT NOT NULL DEFAULT '',
email TEXT NOT NULL DEFAULT '',
phone TEXT NOT NULL DEFAULT '',
gst_number TEXT NOT NULL DEFAULT '',
bank_account TEXT NOT NULL DEFAULT '',
logo_file TEXT, -- file in data/invoices
invoice_prefix TEXT NOT NULL DEFAULT 'INV-',
next_number INTEGER NOT NULL DEFAULT 1,
payment_terms_days INTEGER NOT NULL DEFAULT 14,
footer TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL DEFAULT '',
address TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS invoices (
id INTEGER PRIMARY KEY,
number TEXT NOT NULL UNIQUE,
customer_id INTEGER NOT NULL REFERENCES customers(id),
-- copied from the customer when the invoice is made, so editing the customer doesn't change it
customer_name TEXT NOT NULL,
customer_address TEXT NOT NULL DEFAULT '',
customer_email TEXT NOT NULL DEFAULT '',
issue_date TEXT NOT NULL, -- ISO date
due_date TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'draft' CHECK (status IN ('draft', 'sent', 'paid', 'void')),
notes TEXT NOT NULL DEFAULT '',
paid_date TEXT,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS invoice_lines (
id INTEGER PRIMARY KEY,
invoice_id INTEGER NOT NULL REFERENCES invoices(id) ON DELETE CASCADE,
position INTEGER NOT NULL,
description TEXT NOT NULL,
qty REAL NOT NULL,
unit_cents INTEGER NOT NULL, -- excluding GST
taxable INTEGER NOT NULL DEFAULT 1 -- 0 = no GST on this line
);
-- the transactions a paid invoice was recorded as (two when it has taxable and non-taxable lines)
CREATE TABLE IF NOT EXISTS invoice_payments (
invoice_id INTEGER NOT NULL REFERENCES invoices(id) ON DELETE CASCADE,
transaction_id INTEGER NOT NULL REFERENCES transactions(id) ON DELETE CASCADE,
created INTEGER NOT NULL, -- 1 = added for the invoice, 0 = an imported bank line it was matched to
-- what a matched bank line was before, to put back if the payment is undone
orig_amount_cents INTEGER,
orig_gst TEXT,
orig_category TEXT,
PRIMARY KEY (invoice_id, transaction_id)
);
CREATE TABLE IF NOT EXISTS vehicles (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
rego TEXT NOT NULL DEFAULT '',
active INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS trips (
id INTEGER PRIMARY KEY,
vehicle_id INTEGER NOT NULL REFERENCES vehicles(id),
date TEXT NOT NULL, -- ISO date
from_place TEXT NOT NULL DEFAULT '',
to_place TEXT NOT NULL DEFAULT '',
purpose TEXT NOT NULL DEFAULT '',
customer TEXT NOT NULL DEFAULT '',
odo_start INTEGER,
odo_end INTEGER,
km REAL NOT NULL CHECK (km > 0),
business INTEGER NOT NULL DEFAULT 1, -- 0 = private
CHECK (odo_start IS NULL OR odo_end IS NULL OR odo_end >= odo_start)
);
CREATE INDEX IF NOT EXISTS trips_date ON trips (date);
CREATE TABLE IF NOT EXISTS mileage_rates ( -- IRD kilometre rates, entered per income year
year INTEGER PRIMARY KEY, -- year starting 1 April
tier1_milli INTEGER NOT NULL, -- thousandths of a dollar per km
tier2_milli INTEGER NOT NULL,
tier1_limit_km INTEGER NOT NULL DEFAULT 14000
);
"""
@@ -138,8 +221,13 @@ def month_range(book, sheet):
# --- importing --------------------------------------------------------------
def _existing(conn, book):
# an invoice payment split into taxable and non-taxable rows is one bank line
return Counter((r["date"], r["amount_cents"]) for r in conn.execute(
"SELECT date, amount_cents FROM transactions WHERE book_id = ?", (book["id"],)))
"SELECT date, amount_cents FROM transactions WHERE book_id = ? "
"AND id NOT IN (SELECT transaction_id FROM invoice_payments) "
"UNION ALL SELECT MIN(t.date), SUM(t.amount_cents) FROM invoice_payments p "
"JOIN transactions t ON t.id = p.transaction_id WHERE t.book_id = ? GROUP BY p.invoice_id",
(book["id"], book["id"])))
def _key(t):
@@ -382,3 +470,19 @@ def update_row(conn, book, row_id, gst=None, category=None):
if category and category not in allowed:
raise ValueError(f"unknown category {category!r}")
conn.execute("UPDATE transactions SET category = ? WHERE id = ?", (category or None, row_id))
# --- transactions by id -----------------------------------------------------
def _transaction_info(conn, row_id):
t = conn.execute("SELECT t.*, b.name AS book FROM transactions t JOIN books b ON b.id = t.book_id "
"WHERE t.id = ?", (row_id,)).fetchone()
if t is None:
raise NotFound("no such transaction")
return t
def _brief(t):
return {"row": t["id"], "book": t["book"], "date": t["date"], "reference": t["reference"],
"amount": t["amount_cents"] / 100, "gst": t["gst"], "category": t["category"] or "",
"sheet": SHEETS[date.fromisoformat(t["date"]).month]}
+236
View File
@@ -0,0 +1,236 @@
"""Vehicle logbook and the IRD kilometre-rate claim it supports.
Trips belong to an income year (1 April - 31 March) by date. The claim for a year is worked
out per vehicle: business kilometres up to the tier 1 limit (14,000 km) at the tier 1 rate,
the rest at the tier 2 rate. Rates change every year, so they're entered by hand from IRD's
published figures. This is a report only: nothing is put in the cashbook or tax returns.
"""
import csv
import io
from datetime import date
import ledger
TRIP_FIELDS = ("vehicle_id", "date", "from_place", "to_place", "purpose", "customer",
"odo_start", "odo_end", "km", "business")
def income_year(day):
return day.year if day.month >= 4 else day.year - 1
def year_range(year):
return date(year, 4, 1), date(year + 1, 3, 31)
# --- vehicles ---------------------------------------------------------------
def list_vehicles(conn):
return [dict(r) for r in conn.execute(
"SELECT v.*, COUNT(t.id) AS trips, MAX(t.odo_end) AS last_odometer FROM vehicles v "
"LEFT JOIN trips t ON t.vehicle_id = v.id GROUP BY v.id ORDER BY v.active DESC, v.name COLLATE NOCASE")]
def get_vehicle(conn, vehicle_id):
v = conn.execute("SELECT * FROM vehicles WHERE id = ?", (vehicle_id,)).fetchone()
if v is None:
raise ledger.NotFound("no such vehicle")
return dict(v)
def _vehicle_name(conn, name, vehicle_id=None):
name = (name or "").strip()
if not name:
raise ValueError("the vehicle needs a name")
if conn.execute("SELECT 1 FROM vehicles WHERE name = ? AND id IS NOT ?", (name, vehicle_id)).fetchone():
raise ValueError(f"there's already a vehicle called {name}")
return name
def create_vehicle(conn, name, rego=""):
name = _vehicle_name(conn, name)
with conn:
cur = conn.execute("INSERT INTO vehicles (name, rego) VALUES (?, ?)", (name, (rego or "").strip().upper()))
return get_vehicle(conn, cur.lastrowid)
def update_vehicle(conn, vehicle_id, name=None, rego=None, active=None):
get_vehicle(conn, vehicle_id)
with conn:
if name is not None:
conn.execute("UPDATE vehicles SET name = ? WHERE id = ?", (_vehicle_name(conn, name, vehicle_id), vehicle_id))
if rego is not None:
conn.execute("UPDATE vehicles SET rego = ? WHERE id = ?", (rego.strip().upper(), vehicle_id))
if active is not None:
conn.execute("UPDATE vehicles SET active = ? WHERE id = ?", (int(bool(active)), vehicle_id))
return get_vehicle(conn, vehicle_id)
def delete_vehicle(conn, vehicle_id):
get_vehicle(conn, vehicle_id)
if conn.execute("SELECT 1 FROM trips WHERE vehicle_id = ?", (vehicle_id,)).fetchone():
raise ValueError("this vehicle has trips logged; mark it inactive instead")
with conn:
conn.execute("DELETE FROM vehicles WHERE id = ?", (vehicle_id,))
# --- trips ------------------------------------------------------------------
def _trip(t):
d = dict(t)
d["business"] = bool(d["business"])
return d
def get_trip(conn, trip_id):
t = conn.execute("SELECT t.*, v.name AS vehicle FROM trips t JOIN vehicles v ON v.id = t.vehicle_id "
"WHERE t.id = ?", (trip_id,)).fetchone()
if t is None:
raise ledger.NotFound("no such trip")
return _trip(t)
def list_trips(conn, year=None, vehicle_id=None):
sql, args = "SELECT t.*, v.name AS vehicle FROM trips t JOIN vehicles v ON v.id = t.vehicle_id WHERE 1", []
if year is not None:
start, end = year_range(year)
sql, args = sql + " AND t.date BETWEEN ? AND ?", args + [start.isoformat(), end.isoformat()]
if vehicle_id is not None:
sql, args = sql + " AND t.vehicle_id = ?", args + [vehicle_id]
return [_trip(t) for t in conn.execute(sql + " ORDER BY t.date, t.odo_start, t.id", args)]
def _check_trip(conn, t):
"""Validate and complete a trip's fields; km comes from the odometer when both readings are given."""
get_vehicle(conn, t["vehicle_id"])
t["date"] = date.fromisoformat(t["date"]).isoformat() # ValueError if it isn't a date
for k in ("from_place", "to_place", "purpose", "customer"):
t[k] = (t.get(k) or "").strip()[:200]
start, end = t.get("odo_start"), t.get("odo_end")
t["odo_start"] = int(start) if start not in (None, "") else None
t["odo_end"] = int(end) if end not in (None, "") else None
if t["odo_start"] is not None and t["odo_end"] is not None:
if t["odo_end"] <= t["odo_start"]:
raise ValueError("the end odometer reading must be more than the start")
t["km"] = t["odo_end"] - t["odo_start"]
km = t.get("km")
if km in (None, "") or float(km) <= 0:
raise ValueError("enter the distance, or both odometer readings")
t["km"] = round(float(km), 1)
t["business"] = int(bool(t.get("business", True)))
return t
def warnings(conn, trip):
"""Odometer readings that clash with the vehicle's other trips (allowed, but probably a typo)."""
if trip["odo_start"] is None or trip["odo_end"] is None:
return []
out = []
for o in conn.execute("SELECT * FROM trips WHERE vehicle_id = ? AND id IS NOT ? AND odo_start IS NOT NULL "
"AND odo_end IS NOT NULL", (trip["vehicle_id"], trip.get("id"))):
if trip["odo_start"] < o["odo_end"] and trip["odo_end"] > o["odo_start"]:
out.append(f"the odometer readings overlap the trip on {o['date']} ({o['odo_start']}-{o['odo_end']})")
elif (o["date"] < trip["date"] and o["odo_start"] > trip["odo_end"]) or \
(o["date"] > trip["date"] and o["odo_end"] < trip["odo_start"]):
out.append(f"the odometer readings are out of order with the trip on {o['date']}")
return out
def add_trip(conn, **fields):
t = _check_trip(conn, {k: fields.get(k) for k in TRIP_FIELDS})
with conn:
cur = conn.execute(f"INSERT INTO trips ({', '.join(TRIP_FIELDS)}) VALUES ({', '.join('?' * len(TRIP_FIELDS))})",
[t[k] for k in TRIP_FIELDS])
trip = get_trip(conn, cur.lastrowid)
return {**trip, "warnings": warnings(conn, trip)}
def update_trip(conn, trip_id, **fields):
old = get_trip(conn, trip_id)
t = _check_trip(conn, {k: fields[k] if k in fields else old[k] for k in TRIP_FIELDS})
with conn:
conn.execute(f"UPDATE trips SET {', '.join(f'{k} = ?' for k in TRIP_FIELDS)} WHERE id = ?",
[t[k] for k in TRIP_FIELDS] + [trip_id])
trip = get_trip(conn, trip_id)
return {**trip, "warnings": warnings(conn, trip)}
def delete_trip(conn, trip_id):
get_trip(conn, trip_id)
with conn:
conn.execute("DELETE FROM trips WHERE id = ?", (trip_id,))
# --- rates and the claim ----------------------------------------------------
def get_rate(conn, year):
r = conn.execute("SELECT * FROM mileage_rates WHERE year = ?", (year,)).fetchone()
if r is None:
return None
return {"year": year, "tier1": r["tier1_milli"] / 1000, "tier2": r["tier2_milli"] / 1000,
"tier1_limit_km": r["tier1_limit_km"]}
def set_rate(conn, year, tier1, tier2, tier1_limit_km=14000):
if not (0 < tier1 < 10 and 0 <= tier2 < 10):
raise ValueError("rates are dollars per kilometre, e.g. 1.17")
if tier1_limit_km <= 0:
raise ValueError("the tier 1 limit must be more than zero")
with conn:
conn.execute("INSERT INTO mileage_rates VALUES (?, ?, ?, ?) ON CONFLICT (year) DO UPDATE SET "
"tier1_milli = excluded.tier1_milli, tier2_milli = excluded.tier2_milli, "
"tier1_limit_km = excluded.tier1_limit_km",
(year, round(tier1 * 1000), round(tier2 * 1000), int(tier1_limit_km)))
return get_rate(conn, year)
def report(conn, year):
"""Kilometres and the claim per vehicle for an income year. claim is None while the year has no rate."""
rate = get_rate(conn, year)
by_vehicle = {}
for t in list_trips(conn, year):
v = by_vehicle.setdefault(t["vehicle_id"], {
"vehicle_id": t["vehicle_id"], "vehicle": t["vehicle"], "trips": 0, "business_km": 0.0,
"private_km": 0.0, "odo_first": None, "odo_last": None})
v["trips"] += 1
v["business_km" if t["business"] else "private_km"] += t["km"]
for reading in (t["odo_start"], t["odo_end"]):
if reading is not None:
v["odo_first"] = reading if v["odo_first"] is None else min(v["odo_first"], reading)
v["odo_last"] = reading if v["odo_last"] is None else max(v["odo_last"], reading)
vehicles = []
for v in by_vehicle.values():
total = v["business_km"] + v["private_km"]
v["business_km"], v["private_km"] = round(v["business_km"], 1), round(v["private_km"], 1)
v["business_percent"] = round(100 * v["business_km"] / total, 1) if total else 0.0
v["tier1_km"] = v["tier2_km"] = v["claim"] = None
if rate:
v["tier1_km"] = min(v["business_km"], rate["tier1_limit_km"])
v["tier2_km"] = round(v["business_km"] - v["tier1_km"], 1)
milli = v["tier1_km"] * rate["tier1"] * 1000 + v["tier2_km"] * rate["tier2"] * 1000
v["claim"] = (int(round(milli)) + 5) // 10 / 100 # thousandths -> cents, half-up
vehicles.append(v)
vehicles.sort(key=lambda v: v["vehicle"].lower())
start, end = year_range(year)
claims = [v["claim"] for v in vehicles]
return {
"year": year, "start": start.isoformat(), "end": end.isoformat(), "rate": rate,
"vehicles": vehicles,
"business_km": round(sum(v["business_km"] for v in vehicles), 1),
"private_km": round(sum(v["private_km"] for v in vehicles), 1),
"claim": round(sum(claims), 2) if rate else None,
}
def export_csv(conn, year):
"""The year's logbook as CSV (with a BOM, so Excel reads it as UTF-8)."""
out = io.StringIO()
w = csv.writer(out)
w.writerow(["Date", "Vehicle", "From", "To", "Purpose", "Customer", "Odometer start", "Odometer end",
"Km", "Business/private"])
for t in list_trips(conn, year):
w.writerow([t["date"], t["vehicle"], t["from_place"], t["to_place"], t["purpose"], t["customer"],
t["odo_start"] if t["odo_start"] is not None else "",
t["odo_end"] if t["odo_end"] is not None else "",
f"{t['km']:g}", "Business" if t["business"] else "Private"])
return ("" + out.getvalue()).encode("utf-8")
+23 -2
View File
@@ -29,7 +29,7 @@
header h1 { font-size: 17px; margin: 0 12px 0 0; letter-spacing: .2px; }
header .spacer { flex: 1; }
select, input, button { font: inherit; color: inherit; }
select, input[type=text], input[type=number] {
select, input[type=text], input[type=number], input[type=date] {
background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 5px 8px; }
button { border: 1px solid var(--line); background: var(--panel); border-radius: 6px;
padding: 5px 12px; cursor: pointer; }
@@ -130,6 +130,15 @@
.tax-table tr.tax-head td { font-weight: 700; padding-top: 14px; color: var(--muted); font-size: 12px; text-transform: uppercase; letter-spacing: .4px; }
.tax-input { width: 120px; text-align: right; padding: 3px 6px; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; }
.row-toolbar { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-bottom: 10px; }
.receipt-head { display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; margin-bottom: 8px; }
.receipt-head .grow { flex: 1; min-width: 0; word-break: break-all; }
.receipt-fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 6px 10px; }
.receipt-fields label, dialog .receipt-fields label { font-size: 12px; color: var(--muted); display: flex; flex-direction: column; gap: 2px; margin: 0; }
.receipt-fields input, .receipt-fields select { width: 100%; }
.receipt-fields .wide { grid-column: span 2; }
dialog.wide { width: min(780px, 94vw); }
dialog .check { display: flex; gap: 8px; align-items: center; margin: 8px 0; font-size: 14px; color: var(--text); }
dialog .check input { width: auto; }
</style>
</head>
<body>
@@ -380,6 +389,8 @@ async function doImport() {
function render() {
const main = $("#main");
if (state.view === "statements") { main.innerHTML = (state.summary ? tabsHtml() : "") + renderStatementsPage(); return; }
const pages = { invoices: renderInvoices, customers: renderCustomers, mileage: renderMileage };
if (pages[state.view]) { main.innerHTML = (state.summary ? tabsHtml() : "") + pages[state.view](); return; }
if (state.view === "preview" && state.preview && !state.book) { main.innerHTML = renderPreview(); return; }
if (!state.book) {
main.innerHTML = `<div class="empty-state">No cashbook yet.<br><br><button class="primary" onclick="openNewBook()">Create a cashbook</button></div>`;
@@ -400,6 +411,7 @@ function tabsHtml() {
<button data-view="tax" class="${state.view === "tax" ? "on" : ""}">Income tax</button>
${state.summary.months.map(m => `<button data-sheet="${m.sheet}" class="${state.view === "month" && state.sheet === m.sheet ? "on" : ""} ${m.count ? "" : "empty"}">${m.label.split(" ")[0].slice(0, 3)}</button>`).join("")}
<span style="flex:1"></span>
${["invoices", "customers", "mileage"].map(v => `<button data-view="${v}" class="${state.view === v ? "on" : ""}">${v[0].toUpperCase() + v.slice(1)}</button>`).join("")}
<button data-view="statements" class="${state.view === "statements" ? "on" : ""}">Statements</button>
${state.preview ? `<button data-view="preview" class="${state.view === "preview" ? "on" : ""}">${state.preview.single ? "Statement" : "Import preview"}</button>` : ""}
</div>`;
@@ -713,9 +725,14 @@ window.addEventListener("drop", guard(async e => {
$("#main").addEventListener("click", guard(async e => {
const copy = e.target.closest("[data-copy]");
if (copy) { await navigator.clipboard?.writeText(copy.dataset.copy).catch(() => {}); return toast(`Copied ${copy.dataset.copy}`); }
const b = e.target.closest("[data-sheet],[data-view],[data-act],#importBtn,#cancelPreview,#chooseFiles,#previewBtn2");
const b = e.target.closest("[data-sheet],[data-view],[data-act],[data-inv],[data-mi],#importBtn,#cancelPreview,#chooseFiles,#previewBtn2");
if (!b || b.disabled) return;
if (b.id === "chooseFiles") return $("#uploadInput").click();
if (b.dataset.view === "customers") return loadCustomers();
if (b.dataset.inv) return invoiceAction(b);
if (b.dataset.mi) return mileageAction(b);
if (b.dataset.view === "invoices") return loadInvoices();
if (b.dataset.view === "mileage") return loadMileage();
if (b.id === "previewBtn2") return preview();
if (b.dataset.act === "view") return viewStatement(b.dataset.path);
if (b.dataset.act === "rename") return renameStatement(b.dataset.path);
@@ -728,8 +745,10 @@ $("#main").addEventListener("click", guard(async e => {
if (b.dataset.sheet) return loadMonth(b.dataset.sheet);
}));
$("#main").addEventListener("change", guard(async e => {
if (e.target.id === "invoiceCustomer") { state.invoiceCustomer = e.target.value; return render(); }
if (e.target.id === "onlyUnalloc") { state.onlyUnalloc = e.target.checked; return render(); }
if (e.target.dataset.taxBox) return saveTaxInput(e.target);
if (e.target.dataset.mi) return mileageChange(e.target);
if (e.target.id === "gstFreq") { state.gstFreq = e.target.value; localStorageSet("gstFreq", state.gstFreq); return loadGst(); }
if (e.target.dataset.select) {
e.target.checked ? state.selected.add(e.target.dataset.select) : state.selected.delete(e.target.dataset.select);
@@ -780,5 +799,7 @@ guard(async () => {
await loadStatements();
})();
</script>
<script src="/static/invoices.js"></script>
<script src="/static/mileage.js"></script>
</body>
</html>
+348
View File
@@ -0,0 +1,348 @@
// ---- invoices: business details, customers, invoices and their payment ----
// Uses $, state, call, esc, fmt, fmtDate, plural, toast, guard and render from index.html.
const todayIso = () => { const d = new Date(); return new Date(d - d.getTimezoneOffset() * 6e4).toISOString().slice(0, 10); };
const addDays = (iso, n) => { const d = new Date(iso + "T00:00:00Z"); d.setUTCDate(d.getUTCDate() + n); return d.toISOString().slice(0, 10); };
document.body.insertAdjacentHTML("beforeend", `
<dialog id="invDialog" class="wide">
<form method="dialog" id="invForm">
<h2 style="margin:0 0 4px;font-size:16px" id="invTitle">New invoice</h2>
<div class="receipt-fields" style="margin-top:10px">
<label class="wide">Customer<select id="invCustomer" required></select></label>
<label>Invoice date<input id="invIssue" type="date" required></label>
<label>Due date<input id="invDue" type="date" required></label>
</div>
<div class="scroll" style="margin-top:12px"><table class="inv-lines">
<thead><tr><th>Description</th><th class="num">Qty</th><th class="num">Unit price (excl GST)</th><th title="GST applies to this line">GST</th><th class="num">Amount</th><th></th></tr></thead>
<tbody id="invLines"></tbody>
</table></div>
<button type="button" id="invAddLine" style="margin-top:6px">Add line</button>
<div class="inv-totals" id="invTotals"></div>
<label for="invNotes">Notes on the invoice</label>
<input id="invNotes" type="text" maxlength="2000" placeholder="e.g. Thanks for your business">
<div class="actions" style="justify-content:flex-end">
<button value="cancel" formnovalidate>Cancel</button>
<button value="ok" class="primary" id="invSave">Save draft</button>
</div>
</form>
</dialog>
<dialog id="payDialog">
<form method="dialog">
<h2 style="margin:0 0 4px;font-size:16px">Record payment</h2>
<div class="muted small" id="paySub"></div>
<label for="payDate">Date paid</label>
<input id="payDate" type="date" required>
<div id="payOptions" style="margin-top:8px"></div>
<div class="actions" style="justify-content:flex-end">
<button value="cancel" formnovalidate>Cancel</button>
<button value="ok" class="primary">Mark paid</button>
</div>
</form>
</dialog>
<dialog id="bizDialog" class="wide">
<form method="dialog" id="bizForm">
<h2 style="margin:0 0 4px;font-size:16px">Business details</h2>
<div class="muted small">Shown on every invoice. With a GST number, invoices with GST are titled “Tax invoice”.</div>
<div class="receipt-fields" style="margin-top:10px">
<label class="wide">Business name<input data-biz="name" type="text" maxlength="200"></label>
<label>GST number<input data-biz="gst_number" type="text" maxlength="20" placeholder="123-456-789"></label>
<label>Phone<input data-biz="phone" type="text" maxlength="50"></label>
<label class="wide">Address<textarea data-biz="address" rows="2" maxlength="500"></textarea></label>
<label class="wide">Email<input data-biz="email" type="text" maxlength="200"></label>
<label class="wide">Bank account for payments<input data-biz="bank_account" type="text" maxlength="50" placeholder="01-0000-0000000-00"></label>
<label>Number prefix<input data-biz="invoice_prefix" type="text" maxlength="20"></label>
<label>Next number<input data-biz="next_number" type="number" min="1"></label>
<label>Payment terms (days)<input data-biz="payment_terms_days" type="number" min="0" max="365"></label>
<label class="wide">Footer<input data-biz="footer" type="text" maxlength="1000" placeholder="e.g. Company number, terms"></label>
</div>
<label>Logo (PNG or JPEG)</label>
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">
<img id="bizLogo" alt="Logo" style="max-height:48px;max-width:160px" hidden>
<button type="button" id="bizLogoAdd">Choose image…</button>
<button type="button" id="bizLogoRemove" hidden>Remove</button>
<input id="bizLogoInput" type="file" accept="image/png,image/jpeg" hidden>
</div>
<div class="actions" style="justify-content:flex-end">
<button value="cancel" formnovalidate>Cancel</button>
<button value="ok" class="primary">Save</button>
</div>
</form>
</dialog>`);
document.head.insertAdjacentHTML("beforeend", `<style>
.inv-lines td { padding: 3px 4px; }
.inv-lines input[type=text] { width: 100%; min-width: 200px; }
.inv-lines input[type=number] { width: 90px; text-align: right; }
.inv-totals { display: grid; grid-template-columns: auto auto; justify-content: end; gap: 2px 18px; margin: 10px 4px; font-variant-numeric: tabular-nums; }
.inv-totals div:nth-child(even) { text-align: right; }
.inv-totals .grand { font-weight: 700; font-size: 16px; }
.chip.draft { background: var(--line); color: var(--muted); }
.chip.sent { background: var(--accent-soft); color: var(--accent); }
.chip.paid { background: var(--ok-soft); color: var(--in); }
.chip.void { background: var(--line); color: var(--muted); text-decoration: line-through; }
.chip.overdue { background: var(--bad-soft); color: var(--out); }
.contacts td input, .contacts td textarea { width: 100%; min-width: 120px; }
.contacts td { vertical-align: top; }
dialog textarea { width: 100%; font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--line);
border-radius: 6px; padding: 5px 8px; resize: vertical; }
#payOptions label { display: flex; gap: 8px; align-items: baseline; margin: 6px 0; font-size: 14px; color: var(--text); }
#payOptions input { width: auto; }
</style>`);
async function loadInvoices() {
[state.invoices, state.business, state.customers] = await Promise.all([
call("/api/invoices"), call("/api/business"), call("/api/customers")]);
state.view = "invoices"; render();
}
function renderInvoices() {
const all = state.invoices || [], b = state.business || {};
const filter = state.invoiceFilter || "all";
const unpaid = all.filter(i => i.status === "sent" || i.status === "draft");
const cust = state.invoiceCustomer || "";
const list = (filter === "unpaid" ? unpaid : filter === "paid" ? all.filter(i => i.status === "paid") : all)
.filter(i => !cust || String(i.customer_id) === cust);
const owed = all.filter(i => i.status === "sent").reduce((n, i) => n + i.total, 0);
const overdue = all.filter(i => i.overdue).reduce((n, i) => n + i.total, 0);
const chip = i => i.overdue ? `<span class="chip overdue">overdue</span>` : `<span class="chip ${i.status}">${i.status}</span>`;
const btn = (act, i, label, cls = "") => `<button data-inv="${act}" data-id="${i.id}" class="${cls}">${label}</button>`;
const actions = i => [
`<a href="/api/invoices/${i.id}/pdf" download><button tabindex="-1">PDF</button></a>`,
i.status === "draft" ? btn("edit", i, "Edit") + btn("sent", i, "Mark sent") : "",
i.status === "sent" ? btn("draft", i, "Back to draft") : "",
["draft", "sent"].includes(i.status) ? btn("pay", i, "Paid…", "primary") + btn("void", i, "Void") : "",
i.status === "paid" ? btn("unpay", i, "Undo payment") : "",
].join("");
return `
<div class="row-toolbar">
<strong style="font-size:16px">Invoices</strong>
<div class="tabs" style="margin:0">
${[["all", `All (${all.length})`], ["unpaid", `Unpaid (${unpaid.length})`], ["paid", "Paid"]].map(([k, l]) =>
`<button data-inv="filter" data-filter="${k}" class="${filter === k ? "on" : ""}">${l}</button>`).join("")}
</div>
<select id="invoiceCustomer" title="Show one customer's invoices"><option value="">All customers</option>
${(state.customers || []).map(c => `<option value="${c.id}" ${String(c.id) === cust ? "selected" : ""}>${esc(c.name)}</option>`).join("")}</select>
<span style="flex:1"></span>
<button data-inv="business">Business details</button>
<button data-inv="new" class="primary">New invoice</button>
</div>
${b.name ? "" : `<p class="small" style="color:var(--warn)">Add your <button class="linkish" data-inv="business">business details</button> (name, GST number, bank account) before sending invoices.</p>`}
<div class="stats">
<div class="stat"><div class="k">Owed to you</div><div class="v">${fmt(owed)}</div></div>
<div class="stat"><div class="k">Overdue</div><div class="v ${overdue ? "out" : ""}">${fmt(overdue)}</div></div>
</div>
${list.length ? `<div class="scroll"><table>
<thead><tr><th>Number</th><th>Date</th><th>Customer</th><th>Due</th><th class="num">GST</th><th class="num">Total</th><th>Status</th><th></th></tr></thead>
<tbody>${list.map(i => `<tr style="${i.status === "void" ? "opacity:.55" : ""}">
<td><strong>${esc(i.number)}</strong></td><td>${fmtDate(i.issue_date)}</td><td class="ref">${esc(i.customer_name)}</td>
<td>${fmtDate(i.due_date)}</td><td class="num muted">${fmt(i.gst)}</td><td class="num">${fmt(i.total)}</td>
<td>${chip(i)}${i.status === "paid" ? `<div class="muted small">${fmtDate(i.paid_date)}${i.payments.length ? ` · ${esc(i.payments[0].book)}` : ""}</div>` : ""}</td>
<td><div class="icon-btns" style="max-width:none;flex-wrap:nowrap">${actions(i)}</div></td></tr>`).join("")}</tbody>
</table></div>` : `<div class="empty-state">${all.length ? "No invoices here." : "No invoices yet."}</div>`}
<p class="muted small">Marking an invoice paid records the money in the cashbook as Sales, in the book for the payment date. If the bank statement is already imported, pick the matching deposit so it isn't counted twice; statements imported later recognise the payment. An invoice with both GST and non-GST items is recorded as two rows (Incl GST and Excl GST).</p>`;
}
// -- invoice editor --
function lineRow(l = { description: "", qty: 1, unit: "", taxable: true }) {
return `<tr>
<td><input type="text" data-l="description" value="${esc(l.description)}" maxlength="500" required></td>
<td><input type="number" data-l="qty" value="${l.qty}" step="any" min="0.0001" required></td>
<td><input type="number" data-l="unit" value="${l.unit}" step="0.01" required></td>
<td style="text-align:center"><input type="checkbox" data-l="taxable" ${l.taxable ? "checked" : ""} style="width:auto"></td>
<td class="num" data-amount></td>
<td><button type="button" data-remove title="Remove line">✕</button></td></tr>`;
}
function readLines() {
return [...$("#invLines").rows].map(r => ({
description: r.querySelector("[data-l=description]").value, qty: Number(r.querySelector("[data-l=qty]").value),
unit: Number(r.querySelector("[data-l=unit]").value), taxable: r.querySelector("[data-l=taxable]").checked }));
}
function updateInvTotals() {
const cents = l => Math.round(l.qty * Math.round(l.unit * 100));
const lines = readLines();
[...$("#invLines").rows].forEach((r, i) => r.querySelector("[data-amount]").textContent = fmt(cents(lines[i]) / 100));
const taxable = lines.filter(l => l.taxable).reduce((n, l) => n + cents(l), 0);
const exempt = lines.filter(l => !l.taxable).reduce((n, l) => n + cents(l), 0);
const gst = Math.floor((taxable * 6 + 20) / 40); // same rounding as the server
$("#invTotals").innerHTML = `<div>Subtotal (excl GST)</div><div>${fmt((taxable + exempt) / 100)}</div>
<div>GST 15%${exempt && taxable ? ` on ${fmt(taxable / 100)}` : ""}</div><div>${fmt(gst / 100)}</div>
<div class="grand">Total</div><div class="grand">${fmt((taxable + exempt + gst) / 100)}</div>`;
}
function customerOptions(selected) {
return `<option value="">Choose a customer…</option>` +
(state.customers || []).map(c => `<option value="${c.id}" ${c.id === selected ? "selected" : ""}>${esc(c.name)}</option>`).join("") +
`<option value="new">+ New customer…</option>`;
}
function openInvoice(inv) {
state.editingInvoice = inv || null;
$("#invTitle").textContent = inv ? `Edit ${inv.number}` : "New invoice";
$("#invCustomer").innerHTML = customerOptions(inv?.customer_id);
$("#invIssue").value = inv?.issue_date || todayIso();
$("#invDue").value = inv?.due_date || addDays($("#invIssue").value, state.business?.payment_terms_days ?? 14);
$("#invLines").innerHTML = (inv?.lines || [undefined]).map(lineRow).join("");
$("#invNotes").value = inv?.notes || "";
updateInvTotals();
$("#invDialog").returnValue = ""; $("#invDialog").showModal();
}
$("#invLines").addEventListener("input", updateInvTotals);
$("#invLines").addEventListener("click", e => {
if (!e.target.closest("[data-remove]")) return;
if ($("#invLines").rows.length > 1) e.target.closest("tr").remove();
updateInvTotals();
});
$("#invAddLine").addEventListener("click", () => {
$("#invLines").insertAdjacentHTML("beforeend", lineRow());
$("#invLines").lastElementChild.querySelector("input").focus();
updateInvTotals();
});
$("#invIssue").addEventListener("change", () => {
if (!state.editingInvoice) $("#invDue").value = addDays($("#invIssue").value, state.business?.payment_terms_days ?? 14);
});
$("#invCustomer").addEventListener("change", guard(async e => {
if (e.target.value !== "new") return;
const name = prompt("Customer name");
if (!name?.trim()) { e.target.value = ""; return; }
const c = await call("/api/customers", { name });
state.customers = await call("/api/customers");
e.target.innerHTML = customerOptions(c.id);
toast(`Added ${c.name}. Add their address under Customers.`);
}));
$("#invSave").addEventListener("click", guard(async e => {
e.preventDefault();
if (!$("#invForm").reportValidity()) return;
const body = { customer_id: Number($("#invCustomer").value), issue_date: $("#invIssue").value,
due_date: $("#invDue").value, lines: readLines(), notes: $("#invNotes").value };
const inv = state.editingInvoice
? await call(`/api/invoices/${state.editingInvoice.id}`, body, "PUT")
: await call("/api/invoices", body);
$("#invDialog").close();
toast(state.editingInvoice ? `Saved ${inv.number}` : `Created ${inv.number}. Download the PDF to send it.`);
await loadInvoices();
}));
// -- payment --
async function showPayOptions(inv) {
const matches = await call(`/api/invoices/${inv.id}/matches?date=${$("#payDate").value}`);
$("#payOptions").innerHTML = (matches.length ? `<div class="small muted">Imported deposits of ${fmt(inv.total)} near that date:</div>` : "") +
matches.map((m, i) => `<label><input type="radio" name="payRow" value="${m.row}" ${i === 0 ? "checked" : ""}>
<span>${fmtDate(m.date)} · ${esc(m.reference)} <span class="muted small">${esc(m.book)} · ${m.days_apart ? plural(m.days_apart, "day") + " apart" : "same day"}</span></span></label>`).join("") +
`<label><input type="radio" name="payRow" value="" ${matches.length ? "" : "checked"}>
<span>${matches.length ? "None of these: add" : "Add"} it to the cashbook as a new entry <span class="muted small">(the bank statement isn't imported yet)</span></span></label>`;
}
function openPay(inv) {
state.payingInvoice = inv;
$("#paySub").textContent = `${inv.number} · ${inv.customer_name} · ${fmt(inv.total)}`;
$("#payDate").value = todayIso();
$("#payDialog").returnValue = ""; $("#payDialog").showModal();
return showPayOptions(inv);
}
$("#payDate").addEventListener("change", guard(() => showPayOptions(state.payingInvoice)));
$("#payDialog").addEventListener("close", guard(async () => {
if ($("#payDialog").returnValue !== "ok") return;
const row = document.querySelector("input[name=payRow]:checked")?.value;
const inv = await call(`/api/invoices/${state.payingInvoice.id}/pay`, { date: $("#payDate").value, row: row ? Number(row) : null });
toast(`${inv.number} paid: recorded in ${inv.payments[0]?.book || "the cashbook"}`);
if (state.book) state.summary = await call(`/api/summary?book=${encodeURIComponent(state.book)}`);
await loadInvoices();
}));
// -- customers --
async function loadCustomers() {
[state.customers, state.invoices] = await Promise.all([call("/api/customers"), call("/api/invoices")]);
state.view = "customers"; render();
}
function renderCustomers() {
const list = state.customers || [];
const owed = id => (state.invoices || []).filter(i => i.customer_id === id && i.status === "sent").reduce((n, i) => n + i.total, 0);
return `
<div class="row-toolbar"><strong style="font-size:16px">Customers</strong></div>
${list.length ? `<div class="scroll"><table class="contacts"><thead><tr><th>Name</th><th>Email</th><th>Address</th><th class="num">Owing</th><th></th></tr></thead><tbody>
${list.map(c => `<tr>${["name", "email"].map(k =>
`<td><input type="text" data-cust="${k}" data-id="${c.id}" value="${esc(c[k])}"></td>`).join("")}
<td><textarea rows="2" data-cust="address" data-id="${c.id}">${esc(c.address)}</textarea></td>
<td class="num">${c.invoices ? `<button class="linkish" data-cust-show="${c.id}">${fmt(owed(c.id))}</button><div class="muted small">${plural(c.invoices, "invoice")}</div>` : ""}</td>
<td>${c.invoices ? "" : `<button data-cust-delete="${c.id}">Delete</button>`}</td></tr>`).join("")}
</tbody></table></div><div class="muted small">Changes are saved as you leave each box. Invoices already made keep the details they were made with.</div>`
: `<div class="empty-state" style="padding:20px">No customers yet.</div>`}
<form id="custAdd" class="receipt-fields" style="margin-top:16px;align-items:end">
<label>Name<input id="custName" type="text" required maxlength="200"></label>
<label>Email<input id="custEmail" type="text" maxlength="200"></label>
<label class="wide">Address<textarea id="custAddress" rows="2" maxlength="500"></textarea></label>
<button class="primary">Add customer</button>
</form>`;
}
$("#main").addEventListener("change", guard(async e => {
const k = e.target.dataset.cust; if (!k) return;
const c = state.customers.find(x => x.id === Number(e.target.dataset.id));
await call(`/api/customers/${c.id}`, { name: c.name, email: c.email, address: c.address, [k]: e.target.value }, "PUT");
state.customers = await call("/api/customers");
toast("Saved");
}));
$("#main").addEventListener("click", guard(async e => {
const del = e.target.dataset.custDelete, show = e.target.dataset.custShow;
if (show) { state.invoiceCustomer = show; state.invoiceFilter = "all"; await loadInvoices(); return; }
if (del) { await call(`/api/customers/${del}`, undefined, "DELETE"); await loadCustomers(); }
}));
$("#main").addEventListener("submit", guard(async e => {
if (e.target.id !== "custAdd") return;
e.preventDefault();
await call("/api/customers", { name: $("#custName").value, email: $("#custEmail").value, address: $("#custAddress").value });
await loadCustomers();
}));
// -- business details --
function showLogo() {
const has = !!state.business.logo_file;
$("#bizLogo").hidden = !has; $("#bizLogoRemove").hidden = !has;
if (has) $("#bizLogo").src = `/api/business/logo?t=${Date.now()}`;
}
async function openBusiness() {
state.business = await call("/api/business");
for (const input of document.querySelectorAll("[data-biz]")) input.value = state.business[input.dataset.biz] ?? "";
showLogo();
$("#bizDialog").returnValue = ""; $("#bizDialog").showModal();
}
$("#bizDialog").addEventListener("close", guard(async () => {
if ($("#bizDialog").returnValue !== "ok") return;
const body = {};
for (const input of document.querySelectorAll("[data-biz]")) {
const k = input.dataset.biz, v = input.type === "number" ? Number(input.value) : input.value;
if (v !== state.business[k]) body[k] = v;
}
state.business = await call("/api/business", body, "PUT");
toast("Business details saved");
if (state.view === "invoices") render();
}));
$("#bizLogoAdd").addEventListener("click", () => $("#bizLogoInput").click());
$("#bizLogoInput").addEventListener("change", guard(async e => {
const f = e.target.files[0]; e.target.value = ""; if (!f) return;
const res = await fetch("/api/business/logo", { method: "POST", body: f });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(errorText(data, res));
state.business = data; showLogo();
}));
$("#bizLogoRemove").addEventListener("click", guard(async () => {
state.business = await call("/api/business/logo", undefined, "DELETE"); showLogo();
}));
// buttons with data-inv in the Invoices view
async function invoiceAction(b) {
const id = Number(b.dataset.id), inv = (state.invoices || []).find(i => i.id === id);
switch (b.dataset.inv) {
case "filter": state.invoiceFilter = b.dataset.filter; return render();
case "new": return openInvoice();
case "edit": return openInvoice(inv);
case "business": return openBusiness();
case "pay": return openPay(inv);
case "sent": case "draft": await call(`/api/invoices/${id}/status`, { status: b.dataset.inv }); break;
case "void":
if (!confirm(`Void ${inv.number}? It keeps its number but can't be used again.`)) return;
await call(`/api/invoices/${id}/status`, { status: "void" }); break;
case "unpay":
if (!confirm(`Undo the payment of ${inv.number}? The cashbook entries it made are removed (an imported bank line is put back as it was).`)) return;
await call(`/api/invoices/${id}/unpay`, {});
if (state.book) state.summary = await call(`/api/summary?book=${encodeURIComponent(state.book)}`);
break;
}
await loadInvoices();
}
+203
View File
@@ -0,0 +1,203 @@
// ---- mileage: vehicle logbook and the IRD kilometre-rate claim ----
// Uses $, state, call, esc, fmt, fmtDate, plural, toast, guard, render and todayIso from index.html / invoices.js.
const incomeYear = iso => { const [y, m] = iso.split("-").map(Number); return m >= 4 ? y : y - 1; };
const yearLabel = y => `April ${y} – March ${y + 1}`;
const km = n => Number(n).toLocaleString("en-NZ", { maximumFractionDigits: 1 });
document.body.insertAdjacentHTML("beforeend", `
<dialog id="tripDialog">
<form method="dialog" id="tripForm">
<h2 style="margin:0 0 4px;font-size:16px" id="tripTitle">Add trip</h2>
<div class="receipt-fields" style="margin-top:10px">
<label>Vehicle<select id="tripVehicle" required></select></label>
<label>Date<input id="tripDate" type="date" required></label>
<label>From<input id="tripFrom" type="text" maxlength="200"></label>
<label>To<input id="tripTo" type="text" maxlength="200"></label>
<label class="wide">Purpose<input id="tripPurpose" type="text" maxlength="200" placeholder="e.g. Site visit, supplies pickup"></label>
<label class="wide">Customer<input id="tripCustomer" type="text" maxlength="200" list="tripCustomers"></label>
<label>Odometer start<input id="tripOdoStart" type="number" min="0" step="1"></label>
<label>Odometer end<input id="tripOdoEnd" type="number" min="0" step="1"></label>
<label>Distance (km)<input id="tripKm" type="number" min="0.1" step="0.1"></label>
</div>
<datalist id="tripCustomers"></datalist>
<label class="check"><input type="checkbox" id="tripBusiness" checked> Business trip (untick for private use)</label>
<div class="muted small">Enter both odometer readings and the distance is worked out, or just type the distance.</div>
<div class="actions" style="justify-content:flex-end">
<button value="cancel" formnovalidate>Cancel</button>
<button value="ok" class="primary" id="tripSave">Save trip</button>
</div>
</form>
</dialog>
<dialog id="vehDialog" class="wide">
<div class="receipt-head"><h2 class="grow" style="margin:0;font-size:16px">Vehicles</h2><button id="vehClose">Close</button></div>
<div id="vehBody"></div>
<form id="vehAdd" class="receipt-fields" style="margin-top:12px;align-items:end">
<label class="wide">Name<input id="vehName" type="text" required maxlength="100" placeholder="e.g. Hilux"></label>
<label>Registration<input id="vehRego" type="text" maxlength="20"></label>
<button class="primary">Add vehicle</button>
</form>
</dialog>`);
async function loadMileage(year) {
state.mileageYear = year ?? state.mileageYear ?? incomeYear(todayIso());
const y = state.mileageYear;
[state.vehicles, state.trips, state.mileage] = await Promise.all([
call("/api/vehicles"), call(`/api/trips?year=${y}`), call(`/api/mileage/report?year=${y}`)]);
state.view = "mileage"; render();
}
function renderMileage() {
const r = state.mileage, y = state.mileageYear, trips = state.trips || [], rate = r.rate;
const thisYear = incomeYear(todayIso());
const years = [...new Set([thisYear, thisYear - 1, thisYear - 2, y])].sort((a, b) => b - a);
const vehicleCard = v => `<div class="stat" style="min-width:220px">
<div class="k">${esc(v.vehicle)} · ${plural(v.trips, "trip")}</div>
<div class="v">${v.claim == null ? `${km(v.business_km)} km` : fmt(v.claim)}</div>
<div class="small muted">${km(v.business_km)} km business${v.private_km ? ` · ${km(v.private_km)} km private · ${v.business_percent}% business use` : ""}</div>
${v.claim != null ? `<div class="small muted">${km(v.tier1_km)} km × ${fmt(rate.tier1)}${v.tier2_km ? ` + ${km(v.tier2_km)} km × ${fmt(rate.tier2)}` : ""}</div>` : ""}
${v.odo_first != null ? `<div class="small muted">Odometer ${v.odo_first.toLocaleString()} → ${v.odo_last.toLocaleString()}</div>` : ""}
</div>`;
return `
<div class="row-toolbar">
<strong style="font-size:16px">Mileage</strong>
<select data-mi="year" aria-label="Income year">${years.map(x => `<option value="${x}" ${x === y ? "selected" : ""}>${yearLabel(x)}</option>`).join("")}</select>
<span style="flex:1"></span>
<a href="/api/mileage/export?year=${y}" download style="color:inherit"><button tabindex="-1" ${trips.length ? "" : "disabled"}>Export logbook (CSV)</button></a>
<button data-mi="vehicles">Vehicles (${(state.vehicles || []).length})</button>
<button data-mi="add" class="primary">Add trip</button>
</div>
<div class="gst-card">
<div class="gst-head">
<div><strong>IRD kilometre rates for ${yearLabel(y)}</strong>
<div class="muted small">IRD publishes these each year. Tier 1 is for each vehicle's first business kilometres up to the limit, tier 2 for the rest.</div></div>
<div class="gst-result">${r.claim == null ? "" : `${fmt(r.claim)} claim`}</div>
</div>
<div class="receipt-fields" style="max-width:640px;align-items:end">
<label>Tier 1 ($ per km)<input type="number" step="0.001" min="0" id="rateT1" value="${rate?.tier1 ?? ""}" placeholder="e.g. 1.17"></label>
<label>Tier 2 ($ per km)<input type="number" step="0.001" min="0" id="rateT2" value="${rate?.tier2 ?? ""}" placeholder="e.g. 0.37"></label>
<label>Tier 1 limit (km)<input type="number" step="1" min="1" id="rateLimit" value="${rate?.tier1_limit_km ?? 14000}"></label>
<button data-mi="rate">${rate ? "Update rates" : "Save rates"}</button>
</div>
${rate ? "" : `<div class="small" style="color:var(--warn);margin-top:8px">Enter this year's rates from IRD to see the claim.</div>`}
</div>
${r.vehicles.length ? `<div class="stats">${r.vehicles.map(vehicleCard).join("")}</div>` : ""}
${trips.length ? `<div class="scroll"><table>
<thead><tr><th>Date</th><th>Vehicle</th><th>Trip</th><th>Purpose</th><th>Customer</th><th class="num">Odometer</th><th class="num">Km</th><th></th><th></th></tr></thead>
<tbody>${trips.map(t => `<tr style="${t.business ? "" : "opacity:.7"}">
<td>${fmtDate(t.date)}</td><td>${esc(t.vehicle)}</td>
<td class="ref">${esc(t.from_place)}${t.from_place || t.to_place ? " → " : ""}${esc(t.to_place)}</td>
<td class="ref">${esc(t.purpose)}</td><td>${esc(t.customer)}</td>
<td class="num muted">${t.odo_start != null ? `${t.odo_start.toLocaleString()}–${(t.odo_end ?? "").toLocaleString()}` : ""}</td>
<td class="num">${km(t.km)}</td>
<td>${t.business ? "" : `<span class="chip duplicate">private</span>`}</td>
<td><div class="icon-btns"><button data-mi="edit" data-id="${t.id}">Edit</button><button data-mi="delete" data-id="${t.id}">Delete</button></div></td></tr>`).join("")}</tbody>
<tfoot><tr><td colspan="6">${plural(trips.length, "trip")}</td><td class="num">${km(r.business_km + r.private_km)}</td><td colspan="2"></td></tr></tfoot>
</table></div>` : `<div class="empty-state">No trips logged for ${yearLabel(y)}.${(state.vehicles || []).length ? "" : `<br><br><button class="primary" data-mi="vehicles">Add a vehicle</button>`}</div>`}
<p class="muted small">This is a report for your records and tax return: nothing here changes the cashbook. IRD expects a logbook kept for at least 90 days every three years to set the business-use percentage.</p>`;
}
// -- trip editor --
function lastOdometer(vehicleId) {
return (state.vehicles || []).find(v => v.id === vehicleId)?.last_odometer ?? "";
}
function syncTripKm() {
const s = $("#tripOdoStart").value, e = $("#tripOdoEnd").value;
const both = s !== "" && e !== "";
$("#tripKm").disabled = both;
if (both) $("#tripKm").value = Number(e) > Number(s) ? Number(e) - Number(s) : "";
}
function openTrip(t) {
const vehicles = (state.vehicles || []).filter(v => v.active || v.id === t?.vehicle_id);
if (!vehicles.length) { toast("Add a vehicle first", true); return openVehicles(); }
state.editingTrip = t || null;
$("#tripTitle").textContent = t ? "Edit trip" : "Add trip";
$("#tripVehicle").innerHTML = vehicles.map(v => `<option value="${v.id}" ${v.id === t?.vehicle_id ? "selected" : ""}>${esc(v.name)}${v.rego ? ` (${esc(v.rego)})` : ""}</option>`).join("");
$("#tripDate").value = t?.date || todayIso();
$("#tripFrom").value = t?.from_place || ""; $("#tripTo").value = t?.to_place || "";
$("#tripPurpose").value = t?.purpose || ""; $("#tripCustomer").value = t?.customer || "";
$("#tripOdoStart").value = t ? t.odo_start ?? "" : lastOdometer(Number($("#tripVehicle").value));
$("#tripOdoEnd").value = t?.odo_end ?? "";
$("#tripKm").value = t?.km ?? "";
$("#tripBusiness").checked = t ? t.business : true;
$("#tripCustomers").innerHTML = [...new Set([...(state.customers || []).map(c => c.name), ...(state.trips || []).map(x => x.customer)])]
.filter(Boolean).map(n => `<option value="${esc(n)}">`).join("");
syncTripKm();
$("#tripDialog").returnValue = ""; $("#tripDialog").showModal();
}
$("#tripOdoStart").addEventListener("input", syncTripKm);
$("#tripOdoEnd").addEventListener("input", syncTripKm);
$("#tripVehicle").addEventListener("change", () => {
if (!state.editingTrip) { $("#tripOdoStart").value = lastOdometer(Number($("#tripVehicle").value)); syncTripKm(); }
});
$("#tripSave").addEventListener("click", guard(async e => {
e.preventDefault();
if (!$("#tripForm").reportValidity()) return;
const num = id => $(id).value === "" ? null : Number($(id).value);
const body = { vehicle_id: Number($("#tripVehicle").value), date: $("#tripDate").value,
from_place: $("#tripFrom").value, to_place: $("#tripTo").value, purpose: $("#tripPurpose").value,
customer: $("#tripCustomer").value, odo_start: num("#tripOdoStart"), odo_end: num("#tripOdoEnd"),
km: num("#tripKm"), business: $("#tripBusiness").checked };
const t = state.editingTrip ? await call(`/api/trips/${state.editingTrip.id}`, body, "PUT") : await call("/api/trips", body);
$("#tripDialog").close();
if (t.warnings.length) toast(`Saved, but ${t.warnings.join("; ")}`, true);
else toast(`Saved: ${km(t.km)} km`);
await loadMileage(incomeYear(t.date));
}));
// -- vehicles --
function renderVehicles() {
const list = state.vehicles || [];
$("#vehBody").innerHTML = list.length ? `<div class="scroll"><table><thead><tr><th>Name</th><th>Registration</th><th>In use</th><th></th></tr></thead><tbody>
${list.map(v => `<tr>
<td><input type="text" data-veh="name" data-id="${v.id}" value="${esc(v.name)}" style="width:100%"></td>
<td><input type="text" data-veh="rego" data-id="${v.id}" value="${esc(v.rego)}" style="width:100%"></td>
<td><input type="checkbox" data-veh="active" data-id="${v.id}" ${v.active ? "checked" : ""} style="width:auto"></td>
<td>${v.trips ? `<span class="muted small">${plural(v.trips, "trip")}</span>` : `<button data-veh-delete="${v.id}">Delete</button>`}</td></tr>`).join("")}
</tbody></table></div><div class="muted small">Untick “In use” for a vehicle you no longer have; its trips are kept.</div>`
: `<div class="empty-state" style="padding:20px">No vehicles yet.</div>`;
}
async function openVehicles() {
state.vehicles = await call("/api/vehicles");
renderVehicles(); $("#vehDialog").showModal();
}
$("#vehClose").addEventListener("click", guard(async () => { $("#vehDialog").close(); if (state.view === "mileage") await loadMileage(); }));
$("#vehBody").addEventListener("change", guard(async e => {
const k = e.target.dataset.veh; if (!k) return;
await call(`/api/vehicles/${e.target.dataset.id}`, { [k]: k === "active" ? e.target.checked : e.target.value }, "PUT");
state.vehicles = await call("/api/vehicles");
toast("Saved");
}));
$("#vehBody").addEventListener("click", guard(async e => {
const id = e.target.dataset.vehDelete; if (!id) return;
await call(`/api/vehicles/${id}`, undefined, "DELETE");
state.vehicles = await call("/api/vehicles"); renderVehicles();
}));
$("#vehAdd").addEventListener("submit", guard(async e => {
e.preventDefault();
await call("/api/vehicles", { name: $("#vehName").value, rego: $("#vehRego").value });
$("#vehAdd").reset();
state.vehicles = await call("/api/vehicles"); renderVehicles();
}));
// buttons with data-mi in the Mileage view
async function mileageAction(b) {
const t = (state.trips || []).find(x => x.id === Number(b.dataset.id));
switch (b.dataset.mi) {
case "add": return openTrip();
case "edit": return openTrip(t);
case "vehicles": return openVehicles();
case "delete":
if (!confirm(`Delete the trip on ${fmtDate(t.date)} (${km(t.km)} km)?`)) return;
await call(`/api/trips/${t.id}`, undefined, "DELETE"); break;
case "rate":
if ($("#rateT1").value === "" || $("#rateT2").value === "") throw new Error("Enter both rates");
await call(`/api/mileage/rates/${state.mileageYear}`, { tier1: Number($("#rateT1").value),
tier2: Number($("#rateT2").value), tier1_limit_km: Number($("#rateLimit").value) || 14000 }, "PUT");
toast("Rates saved"); break;
default: return;
}
await loadMileage();
}
function mileageChange(el) {
if (el.dataset.mi === "year") return loadMileage(Number(el.value));
}
+160
View File
@@ -0,0 +1,160 @@
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
+81
View File
@@ -0,0 +1,81 @@
import pytest
@pytest.fixture
def cars(admin):
admin.ute = admin.post("/api/vehicles", json={"name": "Ute", "rego": "abc123"}).json()
admin.van = admin.post("/api/vehicles", json={"name": "Van"}).json()
return admin
def trip(client, vehicle, day, **kw):
r = client.post("/api/trips", json={"vehicle_id": vehicle["id"], "date": day, "purpose": "Site visit", **kw})
assert r.status_code == 200, r.text
return r.json()
def test_odometer_km(cars):
t = trip(cars, cars.ute, "2026-05-01", odo_start=10000, odo_end=10042)
assert (t["km"], t["vehicle"], t["warnings"]) == (42, "Ute", [])
assert cars.ute["rego"] == "ABC123"
bad = {"vehicle_id": cars.ute["id"], "date": "2026-05-02"}
assert cars.post("/api/trips", json={**bad, "odo_start": 10100, "odo_end": 10050}).status_code == 400
assert cars.post("/api/trips", json=bad).status_code == 400 # no distance at all
assert cars.post("/api/trips", json={**bad, "km": 5, "vehicle_id": 999}).status_code == 404
# overlapping readings are kept, with a warning
assert trip(cars, cars.ute, "2026-05-02", odo_start=10030, odo_end=10060)["warnings"]
# km typed directly
assert trip(cars, cars.van, "2026-05-03", km=12.5)["km"] == 12.5
def test_report_tiers_per_vehicle(cars):
r = cars.get("/api/mileage/report?year=2026").json()
assert (r["claim"], r["vehicles"], r["rate"]) == (None, [], None)
trip(cars, cars.ute, "2026-04-01", km=15000)
trip(cars, cars.ute, "2026-06-01", km=1000, business=False)
trip(cars, cars.van, "2027-03-31", km=10000)
trip(cars, cars.van, "2027-04-01", km=999) # next year
r = cars.get("/api/mileage/report?year=2026").json()
assert r["claim"] is None and r["vehicles"][0]["claim"] is None # no rate yet: no claim, not zero
assert cars.put("/api/mileage/rates/2026", json={"tier1": 0, "tier2": 0.3}).status_code == 400
cars.put("/api/mileage/rates/2026", json={"tier1": 1.17, "tier2": 0.37})
r = cars.get("/api/mileage/report?year=2026").json()
ute, van = r["vehicles"]
assert (ute["business_km"], ute["private_km"], ute["business_percent"]) == (15000, 1000, 93.8)
assert (ute["tier1_km"], ute["tier2_km"], ute["claim"]) == (14000, 1000, 16380 + 370)
# the 14,000 km limit is per vehicle
assert (van["tier1_km"], van["tier2_km"], van["claim"]) == (10000, 0, 11700)
assert r["claim"] == 16750 + 11700
assert r["business_km"] == 25000
def test_export_and_vehicle_delete(cars):
trip(cars, cars.ute, "2026-05-01", odo_start=100, odo_end=150, to_place="Hamilton", customer="Client Ltd")
trip(cars, cars.ute, "2026-05-02", km=7, business=False)
r = cars.get("/api/mileage/export?year=2026")
assert r.status_code == 200 and "logbook-2026-27.csv" in r.headers["content-disposition"]
lines = r.content.decode("utf-8-sig").splitlines()
assert lines[1] == "2026-05-01,Ute,,Hamilton,Site visit,Client Ltd,100,150,50,Business"
assert lines[2].endswith(",,,7,Private")
assert cars.delete(f"/api/vehicles/{cars.ute['id']}").status_code == 400
assert cars.put(f"/api/vehicles/{cars.ute['id']}", json={"active": False}).json()["active"] == 0
assert cars.delete(f"/api/vehicles/{cars.van['id']}").status_code == 200
assert cars.post("/api/vehicles", json={"name": "Ute"}).status_code == 400
def test_edit_and_delete_trip(cars):
t = trip(cars, cars.ute, "2026-05-01", km=10)
r = cars.put(f"/api/trips/{t['id']}", json={"vehicle_id": cars.ute["id"], "date": "2026-05-01",
"odo_start": 5, "odo_end": 25})
assert r.json()["km"] == 20
cars.delete(f"/api/trips/{t['id']}")
assert cars.get("/api/trips?year=2026").json() == []
def test_needs_sign_in(client):
assert client.get("/api/trips").status_code == 401
assert client.get("/api/mileage/report?year=2026").status_code == 401