diff --git a/Pipfile b/Pipfile index c552d4e..41dfbf1 100644 --- a/Pipfile +++ b/Pipfile @@ -8,6 +8,7 @@ fastapi = "*" uvicorn = "*" sqlalchemy = "*" bcrypt = "*" +fpdf2 = "*" [dev-packages] pytest = "*" diff --git a/Pipfile.lock b/Pipfile.lock index 3796d45..f7b9116 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -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": [ diff --git a/README.md b/README.md index f277094..a0d9712 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/src/cashbook_app/main.py b/src/cashbook_app/main.py index f3032ea..4bf9696 100644 --- a/src/cashbook_app/main.py +++ b/src/cashbook_app/main.py @@ -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 diff --git a/src/cashbook_app/routers/invoices.py b/src/cashbook_app/routers/invoices.py new file mode 100644 index 0000000..538e3f5 --- /dev/null +++ b/src/cashbook_app/routers/invoices.py @@ -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)}"}) diff --git a/src/cashbook_app/routers/mileage.py b/src/cashbook_app/routers/mileage.py new file mode 100644 index 0000000..fd1cde9 --- /dev/null +++ b/src/cashbook_app/routers/mileage.py @@ -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}\""}) diff --git a/src/cashbook_app/services/invoice_pdf.py b/src/cashbook_app/services/invoice_pdf.py new file mode 100644 index 0000000..5902891 --- /dev/null +++ b/src/cashbook_app/services/invoice_pdf.py @@ -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()) diff --git a/src/invoices.py b/src/invoices.py new file mode 100644 index 0000000..cd9ba8c --- /dev/null +++ b/src/invoices.py @@ -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) diff --git a/src/ledger.py b/src/ledger.py index e4fdc8a..73ffaa2 100644 --- a/src/ledger.py +++ b/src/ledger.py @@ -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]} diff --git a/src/mileage.py b/src/mileage.py new file mode 100644 index 0000000..950a07f --- /dev/null +++ b/src/mileage.py @@ -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") diff --git a/src/static/index.html b/src/static/index.html index 5497963..7d0d15b 100644 --- a/src/static/index.html +++ b/src/static/index.html @@ -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; } @@ -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 = `
No cashbook yet.

`; @@ -400,6 +411,7 @@ function tabsHtml() { ${state.summary.months.map(m => ``).join("")} + ${["invoices", "customers", "mileage"].map(v => ``).join("")} ${state.preview ? `` : ""} `; @@ -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(); })(); + + diff --git a/src/static/invoices.js b/src/static/invoices.js new file mode 100644 index 0000000..97b8492 --- /dev/null +++ b/src/static/invoices.js @@ -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", ` + +
+

New invoice

+
+ + + +
+
+ + +
DescriptionQtyUnit price (excl GST)GSTAmount
+ +
+ + +
+ + +
+
+
+ +
+

Record payment

+
+ + +
+
+ + +
+
+
+ +
+

Business details

+
Shown on every invoice. With a GST number, invoices with GST are titled “Tax invoice”.
+
+ + + + + + + + + + +
+ +
+ + + + +
+
+ + +
+
+
`); + +document.head.insertAdjacentHTML("beforeend", ``); + +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 ? `overdue` : `${i.status}`; + const btn = (act, i, label, cls = "") => ``; + const actions = i => [ + ``, + 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 ` +
+ Invoices +
+ ${[["all", `All (${all.length})`], ["unpaid", `Unpaid (${unpaid.length})`], ["paid", "Paid"]].map(([k, l]) => + ``).join("")} +
+ + + + +
+ ${b.name ? "" : `

Add your (name, GST number, bank account) before sending invoices.

`} +
+
Owed to you
${fmt(owed)}
+
Overdue
${fmt(overdue)}
+
+ ${list.length ? `
+ + ${list.map(i => ` + + + + `).join("")} +
NumberDateCustomerDueGSTTotalStatus
${esc(i.number)}${fmtDate(i.issue_date)}${esc(i.customer_name)}${fmtDate(i.due_date)}${fmt(i.gst)}${fmt(i.total)}${chip(i)}${i.status === "paid" ? `
${fmtDate(i.paid_date)}${i.payments.length ? ` · ${esc(i.payments[0].book)}` : ""}
` : ""}
${actions(i)}
` : `
${all.length ? "No invoices here." : "No invoices yet."}
`} +

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).

`; +} + +// -- invoice editor -- +function lineRow(l = { description: "", qty: 1, unit: "", taxable: true }) { + return ` + + + + + + `; +} +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 = `
Subtotal (excl GST)
${fmt((taxable + exempt) / 100)}
+
GST 15%${exempt && taxable ? ` on ${fmt(taxable / 100)}` : ""}
${fmt(gst / 100)}
+
Total
${fmt((taxable + exempt + gst) / 100)}
`; +} +function customerOptions(selected) { + return `` + + (state.customers || []).map(c => ``).join("") + + ``; +} +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 ? `
Imported deposits of ${fmt(inv.total)} near that date:
` : "") + + matches.map((m, i) => ``).join("") + + ``; +} +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 ` +
Customers
+ ${list.length ? `
+ ${list.map(c => `${["name", "email"].map(k => + ``).join("")} + + + `).join("")} +
NameEmailAddressOwing
${c.invoices ? `
${plural(c.invoices, "invoice")}
` : ""}
${c.invoices ? "" : ``}
Changes are saved as you leave each box. Invoices already made keep the details they were made with.
` + : `
No customers yet.
`} +
+ + + + +
`; +} +$("#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(); +} diff --git a/src/static/mileage.js b/src/static/mileage.js new file mode 100644 index 0000000..04c3a12 --- /dev/null +++ b/src/static/mileage.js @@ -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", ` + +
+

Add trip

+
+ + + + + + + + + +
+ + +
Enter both odometer readings and the distance is worked out, or just type the distance.
+
+ + +
+
+
+ +

Vehicles

+
+
+ + + +
+
`); + +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 => `
+
${esc(v.vehicle)} · ${plural(v.trips, "trip")}
+
${v.claim == null ? `${km(v.business_km)} km` : fmt(v.claim)}
+
${km(v.business_km)} km business${v.private_km ? ` · ${km(v.private_km)} km private · ${v.business_percent}% business use` : ""}
+ ${v.claim != null ? `
${km(v.tier1_km)} km × ${fmt(rate.tier1)}${v.tier2_km ? ` + ${km(v.tier2_km)} km × ${fmt(rate.tier2)}` : ""}
` : ""} + ${v.odo_first != null ? `
Odometer ${v.odo_first.toLocaleString()} → ${v.odo_last.toLocaleString()}
` : ""} +
`; + return ` +
+ Mileage + + + + + +
+
+
+
IRD kilometre rates for ${yearLabel(y)} +
IRD publishes these each year. Tier 1 is for each vehicle's first business kilometres up to the limit, tier 2 for the rest.
+
${r.claim == null ? "" : `${fmt(r.claim)} claim`}
+
+
+ + + + +
+ ${rate ? "" : `
Enter this year's rates from IRD to see the claim.
`} +
+ ${r.vehicles.length ? `
${r.vehicles.map(vehicleCard).join("")}
` : ""} + ${trips.length ? `
+ + ${trips.map(t => ` + + + + + + + `).join("")} + +
DateVehicleTripPurposeCustomerOdometerKm
${fmtDate(t.date)}${esc(t.vehicle)}${esc(t.from_place)}${t.from_place || t.to_place ? " → " : ""}${esc(t.to_place)}${esc(t.purpose)}${esc(t.customer)}${t.odo_start != null ? `${t.odo_start.toLocaleString()}–${(t.odo_end ?? "").toLocaleString()}` : ""}${km(t.km)}${t.business ? "" : `private`}
${plural(trips.length, "trip")}${km(r.business_km + r.private_km)}
` : `
No trips logged for ${yearLabel(y)}.${(state.vehicles || []).length ? "" : `

`}
`} +

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.

`; +} + +// -- 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 => ``).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 => `