diff --git a/.claude/skills/mijlpaal/SKILL.md b/.claude/skills/mijlpaal/SKILL.md index 9130717..2cf29ac 100644 --- a/.claude/skills/mijlpaal/SKILL.md +++ b/.claude/skills/mijlpaal/SKILL.md @@ -9,6 +9,31 @@ Eén onderwerp, van plan tot release. Je werkt door tot het af is of tot iets op de **escalatielijst** (`CLAUDE.md`, "Autonoom werken") staat. Een productvraag of een design gaat naar de `product-owner`-agent, niet naar de eigenaar. +## Onder regie + +Staat in je opdracht de regel `Regie: ja`, dan heeft `/regie` je gestart +(`.claude/skills/regie/`). Er lopen dan andere mijlpalen naast je, en de +eigenaar praat met de regie, niet met jou. Alles hieronder blijft gelden, met +deze verschillen: + +- **Rapport.** Houd je stand bij in + `"$(git rev-parse --path-format=absolute --git-common-dir)/regie/.md"`, + met de eerste regel en de standen die `/regie` beschrijft (`BEZIG`, `VRAAG`, + `FLOW`, `KLAAR`, `VAST`). Werk het bij als je stand verandert, en zet die eerste + regel ook bovenaan je laatste bericht van elke beurt. Screenshots voor de + eigenaar kopieer je naar `regie//` ernaast. +- **Vragen aan de eigenaar (stap 9 en "Flow voorleggen")**: geen AskUserQuestion + en geen SendUserFile. Zet de vraag of de flow in je rapport, stand `VRAAG` of + `FLOW`, ga door met wat er niet van afhangt, en rond je beurt af. Het antwoord + komt via de regie, als bericht in deze sessie. +- **Geen release (stap 7).** Mergen wel, zoals altijd. De release doet de regie. +- **Melden (stap 8)**: geen pushmelding aan de eigenaar. Stand `KLAAR` in je + rapport, met wat de gebruiker merkt en de PO-besluiten. De regel in + `huismus-intern/STATUS.md` blijft. +- **Geen opvolger (stap 10).** De regie kiest het volgende werk. +- **Botsing.** Merk je dat een andere lopende mijlpaal hetzelfde scherm of een + migratie raakt: stand `VAST`, met welk issue en waarom. + ## 1. Begin - Eigen worktree en branch vanaf de nieuwste `origin/main` (`CLAUDE.md`, @@ -150,7 +175,7 @@ sessie, maar geef het door aan een nieuwe: later nog een keer wakker wordt. Zonder `create_session` (een lokale sessie): noem het volgende onderwerp in -je melding en start niets. +je melding en start niets. Onder regie sla je deze stap over (zie "Onder regie"). Wacht je onderwerp op de eigenaar (stap 9) en hangt het volgende er niet van af, dan mag je de opvolger al starten: geef je issue eerst het label `wacht`, zodat de diff --git a/.claude/skills/regie/SKILL.md b/.claude/skills/regie/SKILL.md new file mode 100644 index 0000000..bab1a21 --- /dev/null +++ b/.claude/skills/regie/SKILL.md @@ -0,0 +1,161 @@ +--- +name: regie +description: Stuurt een paar mijlpalen van Huismus tegelijk aan vanuit één gesprek met de eigenaar. Start per issue uit de wachtrij een lokale sessie met /mijlpaal, ontvangt hun rapporten en bundelt status, vragen en screenshots voor de eigenaar. Gebruik als de eigenaar zegt "/regie", "regie", "werk de wachtrij af" of "doe meerdere dingen tegelijk". +--- + +# /regie [aantal] + +Jij bent de regie. De eigenaar praat alleen met jou, vaak vanaf de telefoon +(Remote Control). Jij bouwt zelf niets: elke mijlpaal draait in een eigen lokale +sessie met `/mijlpaal`, in een eigen worktree. Jij houdt het overzicht, geeft +vragen door en start het volgende werk. + +`aantal` is hoeveel mijlpalen er tegelijk lopen. Standaard 3. Meer geeft vooral +botsingen (vertaalbestanden, migratienummers, hetzelfde scherm). + +Houd je eigen gesprek dun: lees geen code, geen diffs en geen lange logs. Alles +wat je nodig hebt, staat in de rapporten, op het bord en in de PR-status. Een +volle regie wordt traag, en dan stuurt niemand meer. + +## Het rapport van een mijlpaal + +Elke sessie die jij start, schrijft haar stand in één bestand per issue: + +``` +"$(git rev-parse --path-format=absolute --git-common-dir)/regie/.md" +``` + +Dat is de map `.git/regie/` van de hoofdmap, die alle worktrees delen. Git volgt +hem nooit, dus er komt niets van in een commit. Screenshots staan ernaast, in +`regie//`. Het bestand begint met één regel: + +``` +# : <één zin in producttaal> +``` + +`STAND` is een van: + +- `BEZIG`: loopt, niets nodig. +- `VRAAG`: wacht op de eigenaar. Daaronder de vraag, het advies en wat de + sessie intussen doet. +- `FLOW`: een grote wijziging met UI wacht op goedkeuring (`CLAUDE.md`, "Flow + voorleggen"). Daaronder de stappen, elk met één zin en de paden van de + screenshots (telefoon en desktop). +- `KLAAR`: gemerged naar `main`. Daaronder wat de gebruiker merkt en de + besluiten van de PO-agent. +- `VAST`: komt niet verder zonder hulp (poort blijft rood, conflict, iets + buiten de code). Daaronder wat er mis is. + +Dezelfde eerste regel staat bovenaan het laatste bericht van die sessie, zodat +hij ook in de korte melding past die jij van de app krijgt (die wordt na +400 tekens afgekapt). Het bestand is de bron; de melding is de wekker. + +## 1. Begin + +1. Zet Remote Control voor jezelf aan (`set_remote_control`, `self`), als hij + nog niet aanstaat. +2. Lees wat er al loopt: + - de map `.git/regie/` (rapporten van eerdere rondes, ook van een vorige + regie); + - je gekoppelde sessies (`list_sessions` met `linked: true`); + - de open PR's (`gh pr list`); + - het bord: wat op `In Progress` staat. + Een issue met een rapport dat niet `KLAAR` is, telt als lopend. Hoort het bij + een sessie die niet aan jou gekoppeld is (een vorige regie), dan meldt die + niet aan jou. Lees zijn rapport dan zelf bij elke ronde. +3. Stop zonder iets te starten als er een open issue met het label `pauze` is + (`CLAUDE.md`, "Backlog: GitHub Issues"). Meld wat er nog loopt. + +## 2. Kiezen + +Neem van boven naar beneden van het bord, tot er `aantal` lopen: + +``` +gh project item-list 1 --owner codebyarne --limit 500 --format json --jq '[.items[] | select(.content.type == "Issue" and .status == "Todo" and ((.labels // []) | any(. == "wacht" or . == "idee" or . == "pauze") | not))][0:10][] | "#\(.content.number) \(.title)"' +``` + +Sla een issue over (het blijft staan, voor de volgende ronde) als het: + +- hetzelfde scherm, dezelfde template of view raakt als iets wat al loopt; +- een migratie nodig heeft terwijl een andere lopende mijlpaal er ook een maakt; +- afhangt van een issue dat nog loopt. + +Twijfel je, laat het dan wachten. Na elkaar is trager, maar botsen kost meer. +Een release-PR (`chore(release)`) telt niet als mijlpaal en loopt nooit naast +een andere release. + +## 3. Starten + +Per gekozen issue één sessie met `start_session`: + +- `initiation` `user_asked` (de eigenaar vroeg om `/regie`), `context` `fresh`, + `use_worktree` true, `target` `local`; +- `name` `m-`, `title` `Mijlpaal #: `; +- `permission_mode` gelijk aan die van jou (laat weg om te erven); +- `prompt`, precies zo: + + ``` + /mijlpaal # + Regie: ja + ``` + +- `background`: dat deze sessie door de regie is gestart, dat er andere + mijlpalen naast lopen (noem hun issues en schermen), en dat ze rapporteert + zoals `/mijlpaal` onder "Onder regie" zegt. + +Kijk daarna met `get_session` of de nieuwe sessie Remote Control heeft +(`remoteControlState`). Staat hij uit, zet hem dan aan met `set_remote_control`, +zodat de eigenaar er ook vanaf de telefoon in kan. + +## 4. Elke ronde + +Je wordt wakker als een sessie een beurt afrondt (een ``) +of als de eigenaar iets zegt. Lees dan de rapporten die veranderd zijn en doe +per stand: + +- `BEZIG`: niets. Niet melden, niet porren. +- `VRAAG`: geef de vraag door aan de eigenaar, met het advies van de sessie + als eerste optie. Bundel vragen die tegelijk binnenkomen in één bericht, + maar elke vraag apart en met het issue erbij. Antwoordt de eigenaar, stuur + het antwoord dan met `SendMessage` naar die sessie (`to` is haar + `local_…`-id), met de woorden van de eigenaar letterlijk erbij. +- `FLOW`: stuur de screenshots op volgorde met `SendUserFile`, elk met de zin + uit het rapport, en vraag of het zo live mag. Goedgekeurd of niet: geef het + letterlijk door aan de sessie. +- `KLAAR`: controleer met `gh pr view` dat de PR echt gemerged is. Zo ja: meld + het in één zin en vul de vrije plek met het volgende issue (stap 2 en 3). + Een rapport is een bewering, geen bewijs. +- `VAST`: meld het in producttaal, met wat de sessie probeerde en jouw advies. + Los het niet zelf op in de code. + +Sluit elke ronde af met een kort overzicht, één regel per mijlpaal: + +``` +#201 Bon bij uitgave · BEZIG · bouwt de browsertest +#204 Btw-rapport per kwartaal · VRAAG · zie hierboven +#207 Importeren uit e-Boekhouden · KLAAR · staat op main +``` + +Een vraag die alleen de PO-agent hoeft te beantwoorden, komt niet bij jou: die +handelt de sessie zelf af. Krijg je er toch een, stuur hem terug met "vraag de +`product-owner`-agent". + +## 5. Releases + +Mijlpalen onder regie maken geen release. Dat doet de regie, volgens `CLAUDE.md`, +"Releases": op woensdag, als er die week iets anders dan documentatie op `main` +kwam en CI op `main` groen is. Start daarvoor één sessie (`name` `release`, +`prompt` met de release-stappen uit `docs/desktop.md`, "Een release maken"), op +een moment dat geen andere sessie aan het mergen is. Meld de eigenaar welke +versie klaarstaat en wat erin zit, in gewone taal. + +## 6. Stoppen en overdragen + +- Een `pauze`-issue of een lege wachtrij: start niets nieuws, laat lopende + mijlpalen afmaken, en meld wanneer de laatste klaar is. +- Na een stuk of tien mijlpalen, of als je merkt dat je traag wordt: zeg tegen + de eigenaar dat een verse `/regie` kan beginnen. De rapporten in + `.git/regie/` nemen het over. Sessies van jou blijven aan jou melden, dus de + nieuwe regie leest hun rapport zelf (stap 1). +- Een `KLAAR`-sessie mag weg. Vraag de eigenaar of je ze mag archiveren + (`archive_session`), en doe het pas na een ja. diff --git a/CLAUDE.md b/CLAUDE.md index 33c2532..19654cc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -353,6 +353,15 @@ een sessie traag. Na het melden start `/mijlpaal` zelf een nieuwe cloudsessie voor het volgende issue uit de wachtrij (zie "Backlog"; stap 10 van de skill). Een open issue met het label `pauze` of een lege wachtrij stopt de keten. +**Meer tegelijk: `/regie`.** Wil de eigenaar meerdere mijlpalen tegelijk en één +gesprek voor het overzicht, dan begint die met `/regie` (`.claude/skills/regie/`) in een +lokale sessie. De regie start per issue uit de wachtrij een lokale sessie met +`/mijlpaal` (standaard drie tegelijk, nooit twee op hetzelfde scherm), krijgt hun +rapporten, en bundelt status, vragen en screenshots voor de eigenaar. Mijlpalen +onder regie starten geen opvolger en maken geen release; dat doet de regie. +Lokaal, omdat cloudsessies niet terugmelden. Nieuwe sessies op de Mac van de +eigenaar staan standaard op Remote Control, zodat het ook vanaf de telefoon gaat. + **Escalatielijst.** Alleen dit vraag je aan de eigenaar zelf, in producttaal en met een advies: diff --git a/SPEC.md b/SPEC.md index e3748a9..ef82d4a 100644 --- a/SPEC.md +++ b/SPEC.md @@ -86,7 +86,7 @@ One table for quotes, invoices and credit notes. `document` FK, `paid_on`, `amount_cents`, `method`, `note`. Payment state (unpaid, partial, paid, credited) is derived, not stored: an invoice is settled by its payments plus the issued credit notes against it; "credited" when the credit notes alone cover the total. Outstanding = invoice total − issued credit notes − payments. ### Attachment -`document` or `expense` FK, `file`, `kind` (`original_pdf`, `receipt`, `other`), `sha256`, `source`. Never both. Neither only for a receipt waiting for an expense, fetched from the receipts folder (`source` `bonnetjesmap`, M20). +`document` or `expense` FK, `file`, `kind` (`original_pdf`, `receipt`, `other`), `sha256`, `source`. Never both. Neither only for a receipt waiting for an expense, fetched from the receipts folder (`source` `bonnetjesmap`, M20) or taken with a phone's camera (`source` `telefoon`, M20). ### Expense `date`, `supplier`, `description`, `amount_cents` (**gross amount paid**, always stored gross: invariant 7 of CLAUDE.md), `vat_info_cents` (under the KOR informational; with the KOR off the input VAT, decided by the owner 2026-11-06, not built yet: issue "Voorbelasting op uitgaven"), `source`, `external_id`. Has lines, as in Moneybird (decided 2026-11-02, `huismus-intern/besluiten.md`): `amount_cents` and `vat_info_cents` are the sums of its lines, stored by one function (`huismus/expenses/lines.py`). @@ -201,7 +201,8 @@ Huismus mails an issued invoice, an issued credit note or a quote that has been - **Every attempt is logged** in `EmailLog`, with the error when it failed (never the password), and shown on the document's timeline: the invoice timeline gains mails, and credit notes and quotes get a timeline of their own (created, issued or sent, mails). - **Mailing changes nothing about the document**: no status, snapshot, number or total (invariants 1 and 4). A draft quote is sent first, then mailed: two steps. - Sending happens in the request, with a timeout; there is no queue (principle 6). Tests use Django's locmem mail backend and never send real mail. -- Out of scope: recurring invoices, payment reminders, AI/MCP access, retrying in the background, configurable default texts. +- **Payment reminder** (added 2026-11-15, #114): an issued invoice that is overdue (due date passed, not fully paid) has "Herinnering sturen" as the main action of its page, and "Betaling registreren" turns secondary there. It opens the same mail form, filled with the reminder text (its own subject and body per language in the same settings screen, with `{openstaand}`, what is still open after payments and credit notes, and `{vervaldatum}`), with the invoice's PDF attached. The page says how many days the invoice is overdue and when the last reminder that went out was sent; the timeline marks reminders as such (`EmailLog.reminder`). An invoice that is not overdue gets none: the form sends you back to the invoice. Never automatic, and no collection costs or interest. +- Out of scope: recurring invoices, automatic reminders, AI/MCP access, retrying in the background, configurable default texts. *Done when:* mailing works against a real SMTP server from the running container, tests cover the log, the attachment and the untouched document, there is an e2e test for the button, strings exist in Dutch and English, and `docs/hulp/mailen.*.md` explains both setups, including how to make a Gmail app password (M17). ### M11 — Desktop app (macOS and Windows) @@ -211,7 +212,7 @@ Beside the Docker/Pi route, not replacing it: Huismus as an ordinary desktop app - **Login is optional on the desktop, off by default.** The laptop's own lock protects it; whoever wants a password sets one in Settings. Without a login, the server only accepts requests carrying a random token that the app hands its own window at every start, so a browser tab or another program on the same computer cannot use it. The window's first request trades the token for a cookie, so forms, CSRF and HTMX work as they do now. The token stays required when a password is set. On Docker/Pi a login stays required. Built 2026-10-29 (design D6; choices: `huismus-intern/besluiten.md`): Instellingen → Wachtwoord sets, changes or turns off the password; changing and turning off need the current one, and wrong guesses count towards the login limit. With a password the app's login page asks only the password, at every start. - **First start is the onboarding**: business details, then importing the Moneybird export (section 1) or skipping it, then the dashboard with its checklist (M8). Setting a password is offered there too: the done page of the step-by-step start (M13) links to Wachtwoord, in the desktop app only. - **Signing.** Windows: signed for free through SignPath Foundation (decided 2026-11-12; until then not signed, as decided 2026-10-27), which signs open source projects with a certificate in its own name and asks for a code signing policy on the site (Meebouwen › Ondertekening, linked from the foot of every page) and a manual approval of every release by the maintainer. Signing the installer is enough: SmartScreen only checks the downloaded file. The workflow follows once SignPath has accepted the project and set it up. macOS: signed with an Apple Developer ID and notarized by Apple (decided 2026-11-12, the owner pays the € 99 a year), because the unsigned app needs a detour through System Settings that many users give up on. `release.yml` signs and notarizes once the owner has run `scripts/mac-ondertekenen.sh` (`docs/desktop.md`, "Ondertekenen op de Mac"); until then the macOS app carries only a free ad-hoc signature, without which it will not start on Apple Silicon. The download page explains, in Dutch and English, the one-time step on first opening: on macOS System Settings → Privacy & Security → "Open Anyway" (the step links straight to that screen), on Windows "More info" → "Run anyway". After the first notarized release the macOS step goes away. -- **Updates.** The app checks GitHub Releases for a new version, downloads it in the background and installs it by itself the next time it opens, before the user can work (the owner's decision, 2026-11-04; `huismus-intern/besluiten.md`); a button in Settings → Updates updates right away, and "Nu zoeken" there looks for a new version right away instead of waiting for the daily look (on Docker too; the owner's request, 2026-11-05). A version that fails to install automatically is tried once; after that only the button tries it again. The check only fetches the public release list and can be turned off in Settings. Before an update is applied the app makes a backup (`manage.py backup`, M7); the migrations run after. If they fail, the app says so and offers to restore that backup. After a new version, in the app and on Docker alike, the overview shows a blue notice "Huismus is bijgewerkt naar ." with a link to Hulp → Wat is er nieuw and a close button, until it is closed or that page is opened; the last version seen is kept in the update status file next to the database, not in a backup. A new administration and the sample data get no notice; an administration from before the notice gets it once (issue #149; `huismus-intern/besluiten.md`, 2026-11-12). Built 2026-10-29 for macOS (choices: `huismus-intern/besluiten.md`; how it works: `docs/desktop.md`): a release offers `Huismus--macos.dmg`, which `release.yml` builds on a version tag on an Apple Silicon runner and checks with `--check` before it is published (the tag must equal the version in `pyproject.toml`; the app needs macOS 15 or later, the Homebrew Pango it carries is built for that); the download must match the SHA-256 GitHub lists for it; the app replaces itself through a small script after it has closed. Built 2026-10-29 for Windows (choices: `huismus-intern/besluiten.md`, "Windows-app: bouwkeuzes"): a release offers `Huismus--windows.exe` as well, an Inno Setup installer that installs per user in `%LOCALAPPDATA%\Programs\Huismus` without asking for administrator rights; on Windows the app looks only for that file, and updating runs it without any window from a small PowerShell script after the app has closed. `release.yml` publishes a release only once both apps are built and checked (on Windows the installed app) and the release test in the window passed on both; a trial build by hand (workflow_dispatch) builds and tests both apps with a version one patch above the latest release, and publishes nothing (2026-11-13; before, it built only Windows). Windows 10 or later, x64 only; WebView2 is not installed along: when it is missing, the app asks in a Windows message whether to download it from Microsoft, then closes. Opened a second time on Windows, the app brings the open window forward. The app carries its own root certificates (certifi) for HTTPS, so the update check and "Hoe gebruik je Huismus?" also work on a Mac without Homebrew; `--check` checks that (2026-11-02). +- **Updates.** The app checks GitHub Releases for a new version, downloads it in the background and installs it by itself the next time it opens, before the user can work (the owner's decision, 2026-11-04; `huismus-intern/besluiten.md`); a button in Settings → Updates updates right away, and "Nu zoeken" there looks for a new version right away instead of waiting for the daily look (on Docker too; the owner's request, 2026-11-05). A version that fails to install automatically is tried once; after that only the button tries it again. On a Mac the app first reads the downloaded app's `LSMinimumSystemVersion`; when this Mac's macOS is older, it installs nothing (not at start, not with the button), keeps the file, and the overview and Settings → Updates say which macOS is needed and to update macOS first; after that it installs as usual. An unreadable package holds nothing back (issue #155; `huismus-intern/besluiten.md`, 2026-11-13). The check only fetches the public release list and can be turned off in Settings. Before an update is applied the app makes a backup (`manage.py backup`, M7); the migrations run after. If they fail, the app says so and offers to restore that backup. After a new version, in the app and on Docker alike, the overview shows a blue notice "Huismus is bijgewerkt naar ." with a link to Hulp → Wat is er nieuw and a close button, until it is closed or that page is opened; the last version seen is kept in the update status file next to the database, not in a backup. A new administration and the sample data get no notice; an administration from before the notice gets it once (issue #149; `huismus-intern/besluiten.md`, 2026-11-12). Built 2026-10-29 for macOS (choices: `huismus-intern/besluiten.md`; how it works: `docs/desktop.md`): a release offers `Huismus--macos.dmg`, which `release.yml` builds on a version tag on an Apple Silicon runner and checks with `--check` before it is published (the tag must equal the version in `pyproject.toml`; the app needs macOS 15 or later, the Homebrew Pango it carries is built for that); the download must match the SHA-256 GitHub lists for it; the app replaces itself through a small script after it has closed. Built 2026-10-29 for Windows (choices: `huismus-intern/besluiten.md`, "Windows-app: bouwkeuzes"): a release offers `Huismus--windows.exe` as well, an Inno Setup installer that installs per user in `%LOCALAPPDATA%\Programs\Huismus` without asking for administrator rights; on Windows the app looks only for that file, and updating runs it without any window from a small PowerShell script after the app has closed. `release.yml` publishes a release only once both apps are built and checked (on Windows the installed app) and the release test in the window passed on both; a trial build by hand (workflow_dispatch) builds and tests both apps with a version one patch above the latest release, and publishes nothing (2026-11-13; before, it built only Windows). Windows 10 or later, x64 only; WebView2 is not installed along: when it is missing, the app asks in a Windows message whether to download it from Microsoft, then closes. Opened a second time on Windows, the app brings the open window forward. The app carries its own root certificates (certifi) for HTTPS, so the update check and "Hoe gebruik je Huismus?" also work on a Mac without Homebrew; `--check` checks that (2026-11-02). - **Microsoft Store** (the owner registered a free developer account and reserved the name on 2026-11-13; choices: `huismus-intern/besluiten.md`, 2026-11-13; how it works: `docs/desktop.md`, "Microsoft Store"). The same `Huismus.exe` also goes to the Microsoft Store as an MSIX package, which Microsoft signs, beside the installer on GitHub Releases. `release.yml` builds it with the Windows app (`scripts/build-msix.sh`, manifest from `desktop/msix.py`, the reserved identity from repository secrets), installs a copy signed with a throwaway certificate and runs `--check` inside the package; the package is kept with the run, not on the release, and submitted by hand in Partner Center. The first submission is the owner's to make or approve. The app knows it runs from the package and leaves updating to the Store: it never looks at GitHub, downloads or installs a version, ignores and clears what the installer left in the update status, and Settings → Updates says only "De Microsoft Store werkt Huismus bij." (card without on/off). When a new version from the Store brings migrations an existing administration lacks, the app makes a backup before them, as before its own updates, and failing migrations offer it back. The manifest turns off file system virtualization (`unvirtualizedResources`), so the administration stays in `%APPDATA%\Huismus` for both versions and uninstalling keeps it; Windows 10 2004 or later. Help, download page and "Wat is er nieuw" follow once the Store page is live. - **Backups.** Once a day, the app writes a backup archive to a folder the user picks once (iCloud Drive, OneDrive, Dropbox, a USB drive). The live database never goes into a synced folder, only the archives. The dashboard shows when the last backup was, and warns after a failed backup (folder unreachable or full) and after 7 days without one. Restoring is a button in the app, on top of `manage.py restore`: it first backs up the current state, and the app serves no pages while it restores. Built 2026-10-29 (choices: `huismus-intern/besluiten.md`; how it works: `docs/desktop.md`): the folder and the status belong to the computer and are not in a backup; a backup from a newer version is refused. Since M15 step 2 a backup can also go, encrypted, straight to Dropbox or WebDAV. - **Release test in the window** (proposed 2026-11-07; the owner decided the same day to build it, and a failing test stops the release; issue #117). `--check` starts everything except the window, from the built app. A further job in `release.yml` tests what a user gets, on the same GitHub runners (a fresh virtual machine per run, nothing to rent). macOS: install from the `.dmg` as a user would. Windows: the app the installer put in place. Then open the app with its window on an empty administration, walk through the onboarding, make and issue one invoice, download its PDF, and keep a screenshot of each step with the release run. On Windows Playwright drives the app's own WebView2 window, with remote debugging switched on for the test only. On macOS Playwright cannot attach to a WKWebView, so it drives the same server while the test checks from a screenshot that the window opened. The test needs the window's token without that token reaching other programs outside the test. It also updates from the previous release's download and checks that the data stayed and a backup was made first. Together this replaces those steps of the check by hand in *Done when*. Built 2026-11-13 (choices: `huismus-intern/besluiten.md`; how it works: `docs/desktop.md`, "Een release maken"): jobs `macos-window-test` and `windows-window-test` run `scripts/window-test-mac.sh` and `scripts/window-test-windows.sh` with `scripts/window_test.py`, and `publish` needs both. The token: on macOS the test makes one and hands it to that one app process (`HUISMUS_RELEASE_TEST_TOKEN`, only one of 32 characters or more counts, taken out of the app's environment at once, masked in the run's log, never in a screenshot); on Windows the test needs none, and only its own environment switches remote debugging on, on 127.0.0.1 (`WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS`; the app never sets it). The update: the previous release, installed from its own download, gets records from its own `demo_data` (its source at that tag), and the new build is put in place as a version it downloaded and checked; it then installs it at its next start through its own path. Afterwards each kind and status of document, and the expenses, have the same count and total to the cent as before, so does the backup from before the update, and the overview says "Huismus is bijgewerkt naar .". Not tested there: looking the release up at GitHub and downloading it (the release is not online yet); that, on one platform, stays a check by hand at each release. The warnings for an unsigned app (Gatekeeper, SmartScreen) only appear for a real download and stay a check by hand. No paid service: browser-testing services hardly test native desktop apps, and desktop test suites (Ranorex, TestComplete, Squish) are too heavy for a hobby project. @@ -229,7 +230,7 @@ Decided 2026-10-28 (the owner's request; details by the product-owner agent, `hu ### M13 — Step-by-step start Decided 2026-10-28 (the owner's request; details by the product-owner agent, `huismus-intern/besluiten.md`). Huismus can be started without a Moneybird export. The welcome card on the empty overview offers two choices: "Stap voor stap beginnen" first, as the primary button, and "Importeren uit Moneybird" second, as a secondary one (besluit 2026-11-03), with the checklist (M8) below; nothing redirects. -- `/welkom/` walks through four steps, each a part of the settings page with its validation (a plain POST, no JS needed): **Bedrijf** (the fields the settings require, plus legal form, phone, website and VAT number as optional), **KOR** (switch, text, limit and warning percentage, M12), **Facturen** (payment terms, invoice and quote number format, with "Volgende als je vandaag uitgeeft: …") and **Logo** (upload, or skip). A step saves only its own fields; "Terug" goes to the previous step. Then a done page with the sparrow: "Eerste klant toevoegen" and "Naar het overzicht". +- `/welkom/` walks through four steps, each a part of the settings page with its validation (a plain POST, no JS needed): **Bedrijf** (the fields the settings require, plus legal form, phone, website and VAT number as optional), **KOR** (switch, text, limit and warning percentage, M12), **Facturen** (payment terms, invoice and quote number format, with "Volgende als je vandaag uitgeeft: …", and the next sequence number of each as on Facturen en nummering, section 7) and **Logo** (upload, or skip). A step saves only its own fields; "Terug" goes to the previous step. Then a done page with the sparrow: "Eerste klant toevoegen" and "Naar het overzicht". - It always starts at step 1 with the saved values filled in; nothing records which steps were done. `/welkom/` stays reachable by its address, but only the empty overview links to it. - The KOR text field gets the same suggestion as on the settings page (since M1); the wizard adds no text of its own. - Not in this milestone: a step for the language or the first customer, a round after a Moneybird import, and a password step (M11: in the desktop app the done page links to Wachtwoord instead). @@ -317,6 +318,7 @@ Decided by the owner on 2026-11-04 (`huismus-intern/backlog.md`); build choices - **Never paid twice:** a receipt counts as read once the service answered, whatever the answer, and after a timeout (3 minutes; the work may have been done). Errors where the service did no work (unreachable, key refused, unknown model, busy or out of credit, a server error) are red above the tray and on Bonnetjes lezen, not on the overview, and the receipts wait for the next look. - **What the user sees:** under each receipt in the tray "Huismus leest dit bonnetje…" while it waits for its turn, or "Niet gelezen: " when it stayed (a similar expense links to it); "Uitgave maken" stays. On the overview, below "n nieuwe bonnetjes" (which then counts only receipts that stay in the tray, or wait while the service fails), "n nieuwe uitgaven om na te kijken" with "Bekijken →" to Verwerken, counted from the last visit to Verwerken or the Nakijken list. While reading, nothing else changes on the overview. Code: `huismus/expenses/reading.py`, which `expenses.inbox` calls after each look. - **Verwerken** (`/uitgaven/verwerken/`, `huismus/expenses/process_views.py`; decided by the product-owner agent on 2026-11-06, `huismus-intern/besluiten.md`, "Verwerken: één stapel, het bonnetje groot naast de velden"). One stack of everything that waits, one at a time: first the expenses to check (the order of Nakijken, date newest first), then the receipts without an expense (the tray's order, newest first), whether Huismus left them with a reason, is still reading them, or no service is set up (`huismus/expenses/batch.py`). Reached by the button "Verwerken (n)" on Uitgaven (n the whole stack, gone at 0; "Bonnetjes (n)" stays), "Bekijken →" of "n nieuwe uitgaven om na te kijken" on the overview, "Uitgave maken" in the tray, and "Klopt"/"Overslaan" on an expense's own page. On a wide screen (the 980px breakpoint) the receipt is large on the left, half the width, staying in view while the fields scroll: a photo whole, a PDF in the browser's own viewer with every page (the file may be framed by Huismus's own pages only, `X-Frame-Options: SAMEORIGIN`; app.js sets the frame's address on a wide screen only). On a phone the receipt is above the fields, a photo at most half the screen high, a PDF as its name (an iPhone shows only the first page of a frame); everywhere "Bonnetje openen" opens the file in a new tab. No PDF rendering on the server. An expense without a receipt shows "Geen bonnetje bij deze uitgave." with the expense page's upload. On the right the expense page's fields and lines: an expense with its notice ("Huismus las dit bonnetje met …" or the assistant's) and **Klopt**; a receipt with empty fields, the tray's line ("Niet gelezen: …" or "Huismus leest dit bonnetje…") in that same notice (none without one) and **Opslaan**. Both save through the expense page's code, take the mark away and go on to the next one (the first after this one in the stack as it was, else the top one left); **Overslaan** goes there without saving. At the top "3 van 24": the ones done in this round plus where this one is in what is left, of the ones done plus what is left; the number done (`?klaar=`, a hidden field in the form) counts only Klopt and Opslaan and is never stored. An error stays on the same item with the same count; "Regel toevoegen" without JS shows the same item with one line more, saving nothing. After the last one, or with nothing to do, "Niets meer te verwerken." and "Naar Uitgaven". No "Verwijderen" here: in the tray or on the expense. With the KOR off, VAT per line stays required, via Klopt and via Opslaan. The new-expense form without a receipt is unchanged; `/uitgaven/nieuw/?bonnetje=` opens Verwerken at that receipt. +- **The photo first, on a phone** (#188; the step chosen by the owner on 2026-11-15 with the new house style, build choices by the product-owner agent the same day, `huismus-intern/besluiten.md`). On a phone (JS: `(max-width: 760px) and (pointer: coarse)`) every link to the new-expense form opens the camera instead (`capture="environment"`); cancelling it opens the ordinary form, a browser that doesn't say "cancel" leaves the user where they tapped. The photo is sent at once with "Bonnetje uploaden…" (`/uitgaven/nieuw/foto/`, `huismus/expenses/photo_views.py`) and goes into the tray (`source` `telefoon`), so walking away never loses it; a refused file (too big, not a receipt) goes to the ordinary form with the upload's reason. Without a connection the page stays, with "Huismus is niet bereikbaar. Probeer het opnieuw als je verbinding hebt." and "Opnieuw proberen", which sends the same photo again. Then `/uitgaven/nieuw/foto//`, "Nieuwe uitgave": the photo with "Opnieuw" (a new photo; the old one goes only once the new one is in, and only a photo taken this way that still waits in the tray), then one line: "Bedrag, zoals je het betaalde" (large), without the KOR "Btw" and "Btw-tarief" right under it, "Leverancier", "Datum" (today) and "Categorie". **Uitgave opslaan** saves through Verwerken's code, the receipt onto the expense, and goes to Uitgaven ("Uitgave opgeslagen."); **Alleen de foto bewaren** leaves it in the tray, starts Bonnetjes lezen if that is on, and goes to Uitgaven ("Bonnetje bewaard. Je vindt het bij Verwerken."). "Meer regels of een omschrijving" opens Verwerken at that receipt with what was typed and one line more, saving nothing. A wide screen or a mouse, the desktop app (never, even in a narrow window on a touch screen) and no JS keep the ordinary form. - Not in part 2: a scheduled task in the Claude app, a notice from macOS or Windows (`huismus-intern/backlog.md`). *Done when:* tests cover fetching (new, the same twice, a name taken in `Opgehaald`, files left with a reason, a file still syncing, a folder that's gone, saving or moving failing, the sample data), Dropbox and WebDAV against the fakes (the folder, unlinking, backups leaving it alone; on WebDAV also a name taken in `Opgehaald`, a file still being written, a refused password), the pages, making an expense from a receipt, looking sooner (a new file in a folder, the minute's wait, a skipped file once, a folder gone, the restore gate, Dropbox's wait against the fake with backoff and a forgotten cursor), the notice (new, seen, singular, off, sample data, only reading), and HEIC (a JPG with the original's name, upright and without metadata, at most 4032 px, the same JPG every time so it is fetched once and a failed move only moves next time, a damaged one or one of too many pixels left with a reason, the upload field); the pages are in `test_every_page.py`; a browser test sets up a folder, picks up now and makes an expense; strings exist in Dutch and English; `docs/hulp/bonnetjes.*.md` explains it. *Part 2:* tests cover the list, a photo (smaller, upright, PNG with transparency), a PDF with text, a scanned PDF, an unreadable PDF, an image of too many pixels, other attachments refused, and the receipt going onto the expense or nothing saved; `docs/hulp/bonnetjes.*.md` and `ai-assistenten.*.md` explain it. *Part 2b:* tests cover the mark from `add_expense`, the pill, the button and its count, the filter, "Klopt" (onward, the last one, an error keeps the mark), "Overslaan", the order, and saving; browser tests check three expenses with "Klopt" and "Overslaan", and three receipts made into expenses one after the other. *Verwerken:* tests cover the order of the stack, next after a save and round again, the count with `klaar`, Klopt, Opslaan with the receipt, Overslaan, an error, "Regel toevoegen" without JS, the KOR off, an expense without a receipt and its upload, items gone meanwhile, the empty stack, the PDF frame header, and English; browser tests process a photo, a PDF and a receipt at 1440 px (beside the fields, in view while scrolling, the PDF in a frame) and at 390 px (above the fields, no frame); the pages are in `test_every_page.py` with the demo receipts (`huismus/core/demo_receipts.py`). *Part 3:* tests against a fake service (never a real one) cover the page (a known service filled in, the address and key rules, saving tested first, the key never shown, kept when left empty, testing, turning off, left out of backups), and reading (an expense with the mark and the receipt, each reason to leave a receipt, VAT without the KOR, a duplicate, failures that retry and a timeout that doesn't, a receipt taken meanwhile, the sample data); browser tests choose a service and see a receipt become an expense; `docs/hulp/bonnetjes.*.md` and `ai-assistenten.*.md` explain it. @@ -368,6 +370,7 @@ Collect **anonymised sample exports** (contacts, invoices per invoice/per line, - **The customer as on the document.** An imported invoice or quote's contact snapshot takes the customer's name, address, e-mail, phone, VAT and KvK number from the document's own row in the export (as they were then), on top of the contact as it is now. A line keeps the unit of Moneybird's `aantal` ("2,5 uur" → unit "uur"; "x" is no unit). Only for documents imported from now on: a re-import never changes an imported document. - **Original PDF is the legal record.** When a PDF ZIP is provided, attach the matching PDF as `original_pdf`; the UI shows it as the primary document for imported invoices. A re-rendered PDF is offered separately and labelled as such. - **Numbering continues.** After import, the sequence continues after the highest imported number, using the configured number format. A format holds `{year}`, `{seq}` and `{customer}` (the contact's customer number), so Moneybird's default numbering (`{customer}{seq:04d}`: customer 58, sequence 97 is `580097`, one sequence across all customers) continues unchanged. Issuing refuses a contact without a customer number when the format needs one, and a number that already exists; either refusal leaves no gap. If existing numbers cannot be parsed against the format, the user sets the next number manually. +- **The next number by hand** (issue #141; product-owner agent 2026-11-15, `huismus-intern/besluiten.md`). For someone who comes from another package without an import, or whose imported numbers don't fit the format. Instellingen → Facturen en nummering and the start's Facturen step have, under each number format, "Volgnummer van je volgende factuur" / "… offerte": the `{seq}` the next one gets, in the sequence of today (this year's with a yearly reset), filled in with what it is now; empty or unchanged changes nothing. Only the sequence row changes; a number is still given only when issuing (invariant 2). Allowed only while Huismus itself has given no number to a document of that kind (invoices and credit notes together; quotes), in any year, imported ones not counted and a reopened one counted: after that the field is gone and the line says "Het nummer loopt vanzelf door sinds je eerste factuur in Huismus." Before that it may go up or down, but not to or below the highest `{seq}` already in the sequence that fits the format ("Kies 43 of hoger. Een lager nummer bestaat al."), nor onto a number that exists. Checked again under the write lock when saving, in one transaction with the other settings (`huismus/documents/numbering.py`, `set_next_sequence_number`). The import's numbering notice links to this page. - **Settings from the export.** The web dry run proposes settings from the export itself, for the user to check instead of type: business details from the UBL of the newest invoice (a business moves and changes accounts over the years), the most common payment term, and Moneybird's number format `{customer}{seq:04d}` when every invoice and quote number follows it. The dry run applies the proposal inside its rolled-back transaction, so its report shows the result (numbering continuing); "commit" validates what the user confirmed like the settings page does, and saves it in the import's own transaction, before importing. Where a current setting differs, the dry run shows it. The CLI leaves Settings alone. - **UBL as a cross-check, and the source of the lines** (decided 2026-11-02, `huismus-intern/besluiten.md`, "Moneybird-import: de UBL als tweede bron voor de regels" and its confirmation). A sent invoice's UBL (`sales_invoices_ubl_archive/.xml`, same export) *fits* when its number, date, subtotal, VAT and total equal the invoice export's, it has as many lines as the line export, and no line has a discount of its own. Then Huismus takes each line's description, quantity, price without VAT and VAT rate from the UBL, and the unit from the line export in the same order; this always applies, also where the Excel lines add up. Where prices included VAT in Moneybird, the Excel line export gives the price with VAT and the UBL without, so this is what puts the right prices on those invoices. The totals stay Moneybird's own from the invoice export and are checked to the cent as before. Compared, `_x000D_` in Excel counts as a line break. A discount on the whole invoice in the UBL (an `AllowanceCharge`, or `AllowanceTotalAmount` not 0) puts the invoice under "Korting", lines at the price before discount, as for a discount in the Excel export. In the dry run, under "UBL-bestanden" in the invoices block (only when the export has UBL files): a UBL that doesn't fit (which fields; the Excel lines stay), a line of a fitting UBL that differs in more than a price including VAT (which fields; the UBL lines are taken), and an invoice already in Huismus whose lines differ from its UBL (it isn't changed; "Toch bewerken" is the way to fix it). These count as points to check and stop nothing. How many invoices had prices including VAT is always said; when nothing is reported, one line says the UBL files match. A UBL that can't be read (broken XML, another root element than `Invoice`, no number) and a UBL without an invoice in the export are named under "Let op". Reading and comparing: `huismus/imports/ubl.py`. - **Moneybird's own reports as a cross-check** (decided 2026-11-02, `huismus-intern/besluiten.md`, "Moneybird-import: controle tegen Moneybirds omzetrapport" and its addition on the tolerance). Per export, the dry run compares the invoices as Huismus has them after importing (issued, of that export, including ones already there) with two reports in the same export: revenue per contact per month (`RevenueByContact`: the contact's current name, revenue excluding VAT by invoice date) and the year's sales invoice revenue and VAT in the VAT overview (`Tax Overview`, all rates together). Moneybird rounds these reports per line, differently from its invoices, so a difference of at most one cent per invoice line of Huismus in that cell (or that year) counts as equal; where Huismus has no invoice every cent counts. A difference is listed under "Moneybirds eigen rapporten" in the invoices block and counts as a point to check; it never stops the import, since every invoice is already checked to the cent against the invoice export. When everything matches, one line says so; without either report nothing is shown. A report in a layout Huismus doesn't know is named under "Let op" and not compared. Not compared: the debtor report (its meaning can't be derived from the export), the purchase side of the VAT overview, the split per rate and Moneybird's own "Totaal" row. Reading: `huismus/imports/reports.py`; comparing: `huismus/imports/report_check.py`. @@ -417,7 +420,7 @@ Collect **anonymised sample exports** (contacts, invoices per invoice/per line, ## 12. Later / out of scope for v1 -Peppol, multi-currency. Decided by the owner on 2026-11-07 and now in scope, each with its own issue: recurring invoices (#82), time tracking (#80, #81), bank statement import as a file (CAMT.053 or MT940, #77), payment reminders (#114), a profit and loss statement per year (#109), and importing from other packages (#108). Decided by the owner on 2026-11-13 (`huismus-intern/besluiten.md`, "Sprintplanning") and in scope, after the ones above: a UBL e-invoice attached to an invoice, made locally (#169; sending through Peppol stays with the central server, #64), simple mileage records without a computed allowance (#125), investments and depreciation after the profit and loss statement (#124), a summary for the ICP return with its source first (#168), and saved articles to pick as invoice lines (#167). +Peppol, multi-currency. Decided by the owner on 2026-11-07 and now in scope, each with its own issue: recurring invoices (#82), time tracking (#80, #81), bank statement import as a file (CAMT.053 or MT940, #77), payment reminders (#114, now in M10), a profit and loss statement per year (#109), and importing from other packages (#108). Decided by the owner on 2026-11-13 (`huismus-intern/besluiten.md`, "Sprintplanning") and in scope, after the ones above: a UBL e-invoice attached to an invoice, made locally (#169; sending through Peppol stays with the central server, #64), simple mileage records without a computed allowance (#125), investments and depreciation after the profit and loss statement (#124), a summary for the ICP return with its source first (#168), and saved articles to pick as invoice lines (#167). ## 13. Open questions diff --git a/desktop/app.py b/desktop/app.py index bc53574..7e93b44 100644 --- a/desktop/app.py +++ b/desktop/app.py @@ -127,6 +127,11 @@ def boot(self): updates.installer = self.install_update updates.precheck = self.check_replaceable + if sys.platform == "darwin": + # Never a new version that wouldn't open on this macOS (issue #155). + from desktop import updater + + updates.minimum_os = updater.minimum_macos if updates.install_at_start(): # A version downloaded earlier: installed before anyone works # (huismus-intern/besluiten.md, 2026-11-04). The window closes. diff --git a/desktop/updater.py b/desktop/updater.py index d767222..93caae2 100644 --- a/desktop/updater.py +++ b/desktop/updater.py @@ -14,9 +14,13 @@ Then the window closes. Only tested by hand, on a Mac and on Windows (SPEC.md M11, "Done when"). + +Before that, on macOS, minimum_macos reads which macOS the downloaded app +needs, so core.updates never installs one that wouldn't open (issue #155). """ import os +import plistlib import re import shlex import subprocess @@ -90,6 +94,32 @@ def installed_app() -> Path | None: return app_bundle() +def minimum_macos(package: Path) -> str: + """The LSMinimumSystemVersion of Huismus.app in the downloaded .dmg, + like "15.0"; "" when it names none. Mounted read-only and out of + sight, as the install script does; an error when that fails + (core.updates then holds nothing back).""" + with tempfile.TemporaryDirectory(prefix="huismus-dmg-") as mount: + subprocess.run( + ["hdiutil", "attach", "-nobrowse", "-readonly", "-mountpoint", mount, str(package)], + check=True, + capture_output=True, + timeout=120, + ) + try: + return minimum_macos_of(Path(mount) / "Huismus.app") + finally: + subprocess.run(["hdiutil", "detach", mount, "-quiet"], capture_output=True, timeout=60) + + +def minimum_macos_of(app: Path) -> str: + """The LSMinimumSystemVersion in app's Info.plist, "" without one.""" + with (app / "Contents" / "Info.plist").open("rb") as file: + info = plistlib.load(file) + minimum = info.get("LSMinimumSystemVersion", "") + return minimum if isinstance(minimum, str) else "" + + def script(package: Path, sha256: str, app: Path, pid: int) -> str: if not re.fullmatch(r"[0-9a-f]{64}", sha256): raise ValueError("geen SHA-256") diff --git a/docs/desktop.md b/docs/desktop.md index 8f25a40..7ec461c 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -126,13 +126,27 @@ paar seconden opnieuw op (htmx, zoals de back-uprij). Daarna zegt hij op het ove vóórdat het venster Huismus laat zien, installeert de app hem (`updates.install_at_start`): nooit midden in een sessie. "Bijwerken naar 1.4.0" op Instellingen → Updates doet hetzelfde meteen, na bevestiging. + +Op de Mac leest de app na het downloaden welke macOS de nieuwe versie minstens +vraagt: `desktop/updater.py` koppelt het `.dmg` alleen-lezen aan en leest +`LSMinimumSystemVersion` uit `Huismus.app/Contents/Info.plist` +(`updates.minimum_os`, issue #155). Is deze macOS ouder, dan blijft de huidige +versie staan: niet bij het openen, niet met de knop. Het overzicht zegt +"Huismus 1.4.0 is er, maar vraagt macOS 15 (Sequoia) of nieuwer…", Updates +zegt hoe je macOS bijwerkt en heeft geen knop. Het bestand blijft liggen; na +de macOS-update installeert de app hem bij het volgende openen zoals altijd. +Is het `.dmg` niet te lezen, dan houdt de app niets tegen en schrijft hij een +regel in het logbestand. Zo ging het mis bij 0.1.4: die vroeg macOS 15, en een +0.1.3-app op macOS 14 werkte zichzelf bij en opende daarna niet meer. + Installeren gaat zo: 1. kan de app zichzelf hier niet vervangen (niet in een app, map niet schrijfbaar), dan stopt hij vóór er iets gebeurt (`updates.precheck`); 2. gebruikt Huismus het klaarstaande bestand (nog eens gecontroleerd), of downloadt het naar `.huismus-update` en controleert de SHA-256 (klopt die - niet, of ontbreekt hij: niets installeren); + niet, of ontbreekt hij: niets installeren), en leest hij op de Mac nog + een keer welke macOS de nieuwe versie vraagt (te oud: niets installeren); 3. maakt hij een back-up, in de gekozen map of anders in `Huismus back-ups`; 4. schrijft hij in `update-status.json` van welke naar welke versie en waar de back-up staat, start hij een klein script (`desktop/updater.py`) en @@ -412,7 +426,8 @@ run, de screenshots 30 dagen, en er komt niets online. De Pango-pakketten van Homebrew op die runner zijn gebouwd voor macOS 15 (Sequoia). De app vraagt daarom minstens macOS 15 (`LSMinimumSystemVersion` in `desktop/huismus.spec`); op een oudere macOS zegt macOS dat hij daar niet -werkt. GitHub heeft geen runner voor macOS 14 meer, dus 14 is niet te testen +werkt, en een app die zichzelf bijwerkt, laat zo'n versie staan (zie +Bijwerken hierboven). GitHub heeft geen runner voor macOS 14 meer, dus 14 is niet te testen (huismus-intern/besluiten.md, 2026-11-13). Elke Apple Silicon-Mac kan macOS 15 draaien. diff --git a/docs/hulp/beginnen.en.md b/docs/hulp/beginnen.en.md index b485517..1a47a99 100644 --- a/docs/hulp/beginnen.en.md +++ b/docs/hulp/beginnen.en.md @@ -14,7 +14,9 @@ Huismus needs for your first invoice: 2. **KOR:** whether you use the small business scheme (KOR), and if so the text that goes under your invoices. More in [KOR and VAT](kor-en-btw.en.md). 3. **Invoices:** your default payment term and how Huismus numbers your - invoices and quotes. The default is usually fine. + invoices and quotes. The default is usually fine. Coming from another + package? Enter the sequence number that follows your last invoice, so + your numbers carry on. 4. **Logo:** your logo goes at the top of your invoices and quotes. This can wait. diff --git a/docs/hulp/beginnen.nl.md b/docs/hulp/beginnen.nl.md index 6f35d7d..6a02cd2 100644 --- a/docs/hulp/beginnen.nl.md +++ b/docs/hulp/beginnen.nl.md @@ -15,7 +15,9 @@ in wat Huismus nodig heeft voor je eerste factuur: die onder je facturen komt. Meer daarover in [KOR en btw](kor-en-btw.nl.md). 3. **Facturen:** je standaard betalingstermijn en hoe Huismus je facturen - en offertes nummert. Meestal is de standaard goed. + en offertes nummert. Meestal is de standaard goed. Kom je uit een ander + pakket, vul dan het volgnummer in dat na je laatste factuur komt. Dan + lopen je nummers door. 4. **Logo:** je logo komt bovenaan je facturen en offertes. Dit kan ook later. diff --git a/docs/hulp/desktop-app.en.md b/docs/hulp/desktop-app.en.md index c0f3234..51937cc 100644 --- a/docs/hulp/desktop-app.en.md +++ b/docs/hulp/desktop-app.en.md @@ -97,6 +97,11 @@ you're working. Don't want to wait? Choose **Check now** under **Settings → Updates**, or **Update to …** when there's already a new version, and confirm. +If a new version needs a newer macOS than your Mac has, Huismus keeps your +current version. The overview and **Settings → Updates** say which macOS it +needs. Update macOS in **System Settings → General → Software Update**; the +next time you open Huismus, it installs the new version. + If updating doesn't work, the window says so, with the buttons **Restore backup** and **Save log file**. Then install the previous version again. diff --git a/docs/hulp/desktop-app.nl.md b/docs/hulp/desktop-app.nl.md index 768cd25..7d01ef5 100644 --- a/docs/hulp/desktop-app.nl.md +++ b/docs/hulp/desktop-app.nl.md @@ -99,6 +99,12 @@ Terwijl je werkt, wordt Huismus nooit bijgewerkt. Wil je niet wachten? Kies dan bij **Instellingen → Updates** **Nu zoeken**, of **Bijwerken naar …** als er al een nieuwe versie is, en bevestig. +Vraagt een nieuwe versie een nieuwere macOS dan je Mac heeft, dan laat Huismus +je huidige versie staan. Het overzicht en **Instellingen → Updates** zeggen +welke macOS nodig is. Werk macOS bij via **Systeeminstellingen → Algemeen → +Software-update**; de volgende keer dat je Huismus opent, wordt de nieuwe +versie geïnstalleerd. + Lukt het bijwerken niet, dan zegt het venster dat, met de knoppen **Back-up terugzetten** en **Logbestand bewaren**. Installeer daarna de vorige versie opnieuw. diff --git a/docs/hulp/facturen.en.md b/docs/hulp/facturen.en.md index 77d1171..7e41d78 100644 --- a/docs/hulp/facturen.en.md +++ b/docs/hulp/facturen.en.md @@ -30,6 +30,16 @@ the number the invoice will get. With **Issue for good**: Then download the PDF with **PDF**, or mail it with **Mail**. See [Mail](mailen.en.md). +## Carrying on from another package + +Coming from another package? Then you want your numbers to carry on. Go to +**Settings → Invoices and numbering** and under **Sequence number of your +next invoice** enter the number that follows your last invoice. If your last +invoice was 2026-0042, enter 43. Quotes work the same way. + +You can do this until your first invoice in Huismus. After that the number +counts up by itself, so your series has no gap. + ## Payments The invoice shows its payment status: unpaid, partly paid, paid or overdue. @@ -38,6 +48,14 @@ filled in with what's still open. A partial payment works too. The overview shows how much is open in total and which invoices are late. +## Sending a reminder + +When an invoice is late, the invoice shows by how many days, and **Send +reminder** is at the top. You get a mail with the invoice attached and a +text that says what's still open. Change what you like and click **Send**. +After that, the invoice shows when you sent the last reminder. Huismus never +sends a reminder by itself. You set the text under [Mail](mailen.en.md). + ## Correcting something You don't change an issued invoice anymore. If something's wrong, make a diff --git a/docs/hulp/facturen.nl.md b/docs/hulp/facturen.nl.md index 098a6fd..6642041 100644 --- a/docs/hulp/facturen.nl.md +++ b/docs/hulp/facturen.nl.md @@ -31,6 +31,16 @@ bedrag en het nummer dat de factuur krijgt. Met **Definitief uitgeven**: Daarna download je de pdf met **PDF**, of mail je hem met **Mailen**. Zie [Mailen](mailen.nl.md). +## Doornummeren na een ander pakket + +Kom je uit een ander pakket? Dan wil je dat je nummers doorlopen. Ga naar +**Instellingen → Facturen en nummering** en vul bij **Volgnummer van je +volgende factuur** het getal in dat na je laatste factuur komt. Was je +laatste factuur 2026-0042, dan vul je 43 in. Voor offertes werkt het net zo. + +Dit kan tot je eerste factuur in Huismus. Daarna loopt het nummer vanzelf +door, zodat er geen gat in je reeks komt. + ## Betalingen Op de factuur zie je de betaalstatus: onbetaald, deels betaald, betaald of @@ -40,6 +50,15 @@ staat al ingevuld met wat er nog openstaat. Een deel betalen kan ook. Het overzicht laat zien wat er in totaal openstaat en welke facturen te laat zijn. +## Een herinnering sturen + +Is een factuur te laat, dan zie je op de factuur hoeveel dagen, en staat +bovenaan **Herinnering sturen**. Je krijgt een mail met de factuur als +bijlage en een tekst die zegt wat er nog openstaat. Pas aan wat je wilt en +klik op **Versturen**. Daarna zie je op de factuur wanneer je de laatste +herinnering stuurde. Huismus stuurt nooit zelf een herinnering. De tekst stel +je in bij [Mailen](mailen.nl.md). + ## Iets corrigeren Een uitgegeven factuur verander je niet meer. Klopt er iets niet, maak dan diff --git a/docs/hulp/functies.en.md b/docs/hulp/functies.en.md index 09a4bd7..e0b3c89 100644 --- a/docs/hulp/functies.en.md +++ b/docs/hulp/functies.en.md @@ -11,6 +11,8 @@ server. [Invoices](facturen.en.md). - **Tracking payments**, also in parts. The overview shows what's outstanding and what's overdue. +- **Sending a reminder** for an invoice that's late, with the invoice + attached. - **Credit notes** to correct an issued invoice. - **Quotes** that you send and turn into an invoice with one click. See [Quotes](offertes.en.md). @@ -76,7 +78,6 @@ server. This is on the list. The order may still change, and there's no date. - Reading your bank statement, so you see which invoice is paid -- Mailing a payment reminder for an overdue invoice - Tracking hours, and invoicing them - Recurring invoices, such as the same one every month - A profit and loss statement per year diff --git a/docs/hulp/functies.nl.md b/docs/hulp/functies.nl.md index b6028b1..f5e3300 100644 --- a/docs/hulp/functies.nl.md +++ b/docs/hulp/functies.nl.md @@ -11,6 +11,8 @@ eigen server. [Facturen](facturen.nl.md). - **Betalingen** bijhouden, ook in delen. Op het overzicht zie je wat openstaat en wat te laat is. +- **Een herinnering sturen** bij een factuur die te laat is, met de factuur + als bijlage. - **Creditnota's** om een uitgegeven factuur te corrigeren. - **Offertes** die je verzendt en met één klik omzet naar een factuur. Zie [Offertes](offertes.nl.md). @@ -76,7 +78,6 @@ eigen server. Dit staat op de lijst. De volgorde kan nog veranderen, en er is geen datum. - Je bankafschrift inlezen, zodat je ziet welke factuur betaald is -- Een betaalherinnering mailen bij een factuur die te laat is - Uren bijhouden, en daar een factuur van maken - Periodieke facturen, zoals elke maand dezelfde - Een winst-en-verliesrekening per jaar diff --git a/docs/hulp/mailen.en.md b/docs/hulp/mailen.en.md index cb7450a..7ebba6c 100644 --- a/docs/hulp/mailen.en.md +++ b/docs/hulp/mailen.en.md @@ -2,7 +2,8 @@ You mail an invoice, credit note or quote straight from Huismus, with the PDF attached. You can do that once the invoice or credit note is issued, or -the quote is sent. The mail goes through your own Gmail or the mail server +the quote is sent. When an invoice is late, you also send a reminder, with +the invoice attached. The mail goes through your own Gmail or the mail server of your own domain. No other service sits in between. Mailing doesn't change the document. Every attempt goes on the document's @@ -74,7 +75,8 @@ you leave "Sender" empty, Huismus mails from your business e-mail address. Every mail starts with a subject and a text you set yourself, under **Settings → Mail → Standard texts**. There's a text for each kind of -document (invoice, credit note, quote), in Dutch and in English. A document +document (invoice, credit note, quote) and for a reminder, in Dutch and in +English. A document in English gets the English text. Before you send a mail, you can still change all of it. @@ -87,7 +89,8 @@ names, in the English texts too: | `{bedrag}` | the document's total | | `{naam}` | the customer's first name, or else the customer's name | | `{bedrijf}` | your business name | -| `{vervaldatum}` | only on an invoice: the due date | +| `{vervaldatum}` | only on an invoice and a reminder: the due date | +| `{openstaand}` | only on a reminder: what's still open | | `{geldig_tot}` | only on a quote: until when it's valid | You can't save a typo such as `{klant}`. That way it never ends up in a diff --git a/docs/hulp/mailen.nl.md b/docs/hulp/mailen.nl.md index bb2c93e..99101f9 100644 --- a/docs/hulp/mailen.nl.md +++ b/docs/hulp/mailen.nl.md @@ -2,7 +2,8 @@ Je mailt een factuur, creditnota of offerte rechtstreeks vanuit Huismus, met de pdf als bijlage. Dat kan zodra de factuur of creditnota is uitgegeven, of -de offerte verzonden. De mail gaat via je eigen Gmail of via de mailserver +de offerte verzonden. Is een factuur te laat, dan stuur je ook een +herinnering, met de factuur als bijlage. De mail gaat via je eigen Gmail of via de mailserver van je eigen domein. Er zit geen andere dienst tussen. Mailen verandert niets aan het document. Elke poging komt op de tijdlijn van @@ -76,7 +77,8 @@ je "Afzender" leeg, dan mailt Huismus vanaf het e-mailadres van je bedrijf. Elke mail begint met een onderwerp en een tekst die je zelf instelt, bij **Instellingen → Mailen → Standaardteksten**. Er is een tekst per soort -document (factuur, creditnota, offerte), in het Nederlands en in het Engels. +document (factuur, creditnota, offerte) en voor een herinnering, in het +Nederlands en in het Engels. Een Engels document krijgt de Engelse tekst. Voordat je een mail verstuurt, kun je alles nog aanpassen. @@ -88,7 +90,8 @@ Met invulplekken zet Huismus de gegevens van het document in de tekst: | `{bedrag}` | het totaal, bijvoorbeeld € 850,00 | | `{naam}` | de voornaam van de klant, of anders de naam van de klant | | `{bedrijf}` | de naam van je bedrijf | -| `{vervaldatum}` | alleen bij een factuur: de vervaldatum | +| `{vervaldatum}` | alleen bij een factuur en een herinnering: de vervaldatum | +| `{openstaand}` | alleen bij een herinnering: wat er nog openstaat | | `{geldig_tot}` | alleen bij een offerte: tot wanneer hij geldig is | Een tikfout zoals `{klant}` kun je niet opslaan. Zo komt hij nooit in een diff --git a/docs/hulp/telefoon.en.md b/docs/hulp/telefoon.en.md index d10964d..b91bf61 100644 --- a/docs/hulp/telefoon.en.md +++ b/docs/hulp/telefoon.en.md @@ -29,6 +29,23 @@ home screen there's **Share**: use it to mail the PDF or save it to Files. In the browser there's **Download**, and **Share** too if the browser can share files. +## An expense with the camera + +Tap **+** and then **Expense**, or **New expense** under Expenses: the camera +opens. Take a photo of the receipt. Huismus keeps it at once. Then fill in the +amount, then the supplier, the date and the category, and tap **Save +expense**. + +No time? Tap **Just keep the photo**. The receipt then waits under +**Process** on the Expenses page, where you make it into an expense later. +Photo didn't work out? Tap **Retake**. + +Can't reach Huismus, for example in a shop without your VPN? The photo stays +on your screen. Tap **Try again** once you're connected. + +Rather use a photo from your library or a PDF? Close the camera: you get the +ordinary form. + ## What's on your phone Your records aren't on it. Everything stays on the server, and the app only diff --git a/docs/hulp/telefoon.nl.md b/docs/hulp/telefoon.nl.md index e47f4f2..dfbb672 100644 --- a/docs/hulp/telefoon.nl.md +++ b/docs/hulp/telefoon.nl.md @@ -29,6 +29,24 @@ beginscherm staat daar **Delen**: zo mail je de pdf of bewaar je hem in Bestanden. In de browser staat er **Downloaden**, en als de browser kan delen ook **Delen**. +## Een uitgave met de camera + +Tik op **+** en dan op **Uitgave**, of op **Nieuwe uitgave** bij Uitgaven: de +camera gaat open. Maak een foto van het bonnetje. Huismus bewaart hem meteen. +Daarna vul je het bedrag in, dan de leverancier, de datum en de categorie, en +tik je op **Uitgave opslaan**. + +Geen tijd? Tik op **Alleen de foto bewaren**. Het bonnetje staat dan bij +**Verwerken** op de pagina Uitgaven, en daar maak je er later een uitgave van. +Is de foto mislukt, tik dan op **Opnieuw**. + +Huismus is niet bereikbaar, bijvoorbeeld in de winkel zonder VPN? Dan blijft de +foto op je scherm staan. Tik op **Opnieuw proberen** als je weer verbinding +hebt. + +Wil je liever een foto uit je fotobibliotheek of een pdf? Sluit dan de camera: +je krijgt het gewone formulier. + ## Wat er op je telefoon staat Niets van je administratie. Alles blijft op de server, en de app laat alleen diff --git a/docs/hulp/uitgaven.en.md b/docs/hulp/uitgaven.en.md index b87c356..0ee2485 100644 --- a/docs/hulp/uitgaven.en.md +++ b/docs/hulp/uitgaven.en.md @@ -29,6 +29,9 @@ or a PDF. Huismus keeps a HEIC photo as a JPG. For a new expense you can do this **Save**. An expense can have more than one receipt: add the others after saving. +On your phone a new expense starts with the camera. See [On your +phone](telefoon.en.md). + Receipts from the road can also go in a folder that Huismus picks up itself. See [Receipts on the road](bonnetjes.en.md). diff --git a/docs/hulp/uitgaven.nl.md b/docs/hulp/uitgaven.nl.md index 2b7e211..09c9a75 100644 --- a/docs/hulp/uitgaven.nl.md +++ b/docs/hulp/uitgaven.nl.md @@ -30,6 +30,9 @@ HEIC) of een pdf. Een HEIC-foto bewaart Huismus als JPG. Bij een nieuwe uitgave **Opslaan** klikt. Een uitgave kan meer bonnetjes hebben: de rest voeg je toe na het opslaan. +Op je telefoon begint een nieuwe uitgave met de camera. Zie [Op je +telefoon](telefoon.nl.md). + Bonnetjes van onderweg kun je ook in een map zetten die Huismus zelf ophaalt. Zie [Bonnetjes onderweg](bonnetjes.nl.md). diff --git a/huismus/business/forms.py b/huismus/business/forms.py index 82c9356..37e2db3 100644 --- a/huismus/business/forms.py +++ b/huismus/business/forms.py @@ -5,12 +5,21 @@ from django import forms from django.core.exceptions import ValidationError from django.core.files.uploadedfile import UploadedFile +from django.db import transaction from django.utils.text import format_lazy from django.utils.translation import gettext_lazy as _ from huismus.core.forms import EuroCentsField from huismus.documents import mail_texts -from huismus.documents.numbering import format_number +from huismus.documents.numbering import ( + NumberingError, + check_next_sequence_number, + format_number, + next_sequence_number, + next_sequence_number_is_fixed, + set_next_sequence_number, + year_if_issued_today, +) from . import smtp from .logo import validate_and_sanitize_logo @@ -22,6 +31,22 @@ ) +# Not settings fields: they set the sequence (documents.numbering). Per +# field the kind of sequence, label and help. +NEXT_NUMBER_FIELDS = { + "next_invoice_number": ( + "invoice", + _("Volgnummer van je volgende factuur"), + _("Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste factuur komt."), + ), + "next_quote_number": ( + "quote", + _("Volgnummer van je volgende offerte"), + _("Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste offerte komt."), + ), +} + + # Instellingen → Mailen: a subject and a body per kind and language. MAIL_TEXT_FIELDS = [ (kind, part, language, mail_texts.field_name(kind, part, language)) @@ -29,7 +54,12 @@ for language in mail_texts.LANGUAGES for part in ("subject", "body") ] -MAIL_TEXT_TITLES = {"invoice": _("Factuur"), "credit_note": _("Creditnota"), "quote": _("Offerte")} +MAIL_TEXT_TITLES = { + "invoice": _("Factuur"), + "credit_note": _("Creditnota"), + "quote": _("Offerte"), + "reminder": _("Herinnering"), +} MAIL_TEXT_PARTS = { ("subject", "nl"): _("onderwerp in het Nederlands"), ("body", "nl"): _("tekst in het Nederlands"), @@ -249,3 +279,61 @@ def __init__(self, *args, fields, **kwargs): for name in list(self.fields): if name not in fields: del self.fields[name] + # The next number by hand (issue #141), where the fields name it + # (Facturen en nummering, the start's Facturen step), and only for a + # kind Huismus never gave a number yet (invariant 3). + year = year_if_issued_today(self.instance.number_reset_yearly) + self.fixed_sequences = {} + for name, (kind, label, help_text) in NEXT_NUMBER_FIELDS.items(): + if name not in fields: + continue + self.fixed_sequences[kind] = next_sequence_number_is_fixed(kind) + if not self.fixed_sequences[kind]: + self.fields[name] = forms.IntegerField( + label=label, + help_text=help_text, + min_value=1, + # Empty keeps the number as it is. + required=False, + initial=next_sequence_number(kind, year=year), + ) + + def _next_numbers(self): + """(kind, format, year, value) per next-number field in the form, + from what the form saves: the number format and yearly reset may + change in the same save.""" + reset_yearly = self.cleaned_data.get( + "number_reset_yearly", self.instance.number_reset_yearly + ) + year = year_if_issued_today(reset_yearly) + for name, (kind, _label, _help) in NEXT_NUMBER_FIELDS.items(): + value = self.cleaned_data.get(name) + template = self.cleaned_data.get(f"{kind}_number_format") or getattr( + self.instance, f"{kind}_number_format" + ) + if name in self.fields and value is not None: + yield name, kind, template, year, value + + def clean(self): + cleaned = super().clean() + if not self.errors: + for name, kind, template, year, value in self._next_numbers(): + # Unchanged is not a change: no checks, so it never stops + # the rest of the form from saving. + if value == next_sequence_number(kind, year=year): + continue + try: + check_next_sequence_number(kind, template, year=year, value=value) + except NumberingError as error: + self.add_error(name, str(error)) + return cleaned + + def save(self, commit=True): + """With the next numbers, in one transaction: a refusal (an invoice + issued since the check in clean()) leaves the settings unsaved too. + Raises NumberingError then; the view shows it.""" + with transaction.atomic(): + instance = super().save(commit) + for _name, kind, template, year, value in self._next_numbers(): + set_next_sequence_number(kind, template, year=year, value=value) + return instance diff --git a/huismus/business/migrations/0010_mail_reminder_texts.py b/huismus/business/migrations/0010_mail_reminder_texts.py new file mode 100644 index 0000000..5ca7ba4 --- /dev/null +++ b/huismus/business/migrations/0010_mail_reminder_texts.py @@ -0,0 +1,36 @@ +# Generated by Django 5.2.17 on 2026-11-15 08:56 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("business", "0009_feedback_sent"), + ] + + operations = [ + migrations.AddField( + model_name="settings", + name="mail_reminder_body_en", + field=models.TextField(blank=True, verbose_name="tekst herinnering (engels)"), + ), + migrations.AddField( + model_name="settings", + name="mail_reminder_body_nl", + field=models.TextField(blank=True, verbose_name="tekst herinnering (nederlands)"), + ), + migrations.AddField( + model_name="settings", + name="mail_reminder_subject_en", + field=models.CharField( + blank=True, max_length=300, verbose_name="onderwerp herinnering (engels)" + ), + ), + migrations.AddField( + model_name="settings", + name="mail_reminder_subject_nl", + field=models.CharField( + blank=True, max_length=300, verbose_name="onderwerp herinnering (nederlands)" + ), + ), + ] diff --git a/huismus/business/models.py b/huismus/business/models.py index 384edae..0be03b8 100644 --- a/huismus/business/models.py +++ b/huismus/business/models.py @@ -147,6 +147,14 @@ class Settings(TimestampedModel): _("onderwerp offerte (engels)"), max_length=300, blank=True ) mail_quote_body_en = models.TextField(_("tekst offerte (engels)"), blank=True) + mail_reminder_subject_nl = models.CharField( + _("onderwerp herinnering (nederlands)"), max_length=300, blank=True + ) + mail_reminder_body_nl = models.TextField(_("tekst herinnering (nederlands)"), blank=True) + mail_reminder_subject_en = models.CharField( + _("onderwerp herinnering (engels)"), max_length=300, blank=True + ) + mail_reminder_body_en = models.TextField(_("tekst herinnering (engels)"), blank=True) # Hoe gebruik je Huismus? (huismus.core.feedback): the organisation last # sent, to fill in next time, and whether the done page still asks. diff --git a/huismus/business/topics.py b/huismus/business/topics.py index 3be721d..599c388 100644 --- a/huismus/business/topics.py +++ b/huismus/business/topics.py @@ -77,6 +77,8 @@ class Topic: "invoice_number_format", "quote_number_format", "number_reset_yearly", + "next_invoice_number", + "next_quote_number", "default_language", "currency", ), diff --git a/huismus/business/views.py b/huismus/business/views.py index c3fdb9f..280b893 100644 --- a/huismus/business/views.py +++ b/huismus/business/views.py @@ -10,7 +10,7 @@ from huismus.core import help from huismus.core.appearance import theme_of -from huismus.documents.numbering import next_numbers_if_issued_today +from huismus.documents.numbering import NumberingError, next_numbers_if_issued_today from . import smtp, topics from .forms import MAIL_TEXT_FIELDS, MAIL_TEXT_PARTS, MAIL_TEXT_TITLES, SettingsPartForm @@ -48,9 +48,13 @@ def topic_page(request, slug): if request.method == "POST": form = SettingsPartForm(request.POST, request.FILES, instance=instance, fields=topic.fields) if form.is_valid(): - form.save() - messages.success(request, _("Instellingen opgeslagen.")) - return redirect("business:topic", slug=slug) + try: + form.save() + except NumberingError as error: + form.add_error(None, str(error)) + else: + messages.success(request, _("Instellingen opgeslagen.")) + return redirect("business:topic", slug=slug) else: form = SettingsPartForm(instance=instance, fields=topic.fields) diff --git a/huismus/core/onboarding.py b/huismus/core/onboarding.py index 1129541..32302a3 100644 --- a/huismus/core/onboarding.py +++ b/huismus/core/onboarding.py @@ -51,7 +51,13 @@ class Step: "Je betalingstermijn en hoe Huismus je facturen en offertes nummert. " "Meestal is de standaard goed." ), - ("default_payment_terms_days", "invoice_number_format", "quote_number_format"), + ( + "default_payment_terms_days", + "invoice_number_format", + "quote_number_format", + "next_invoice_number", + "next_quote_number", + ), ), Step( "logo", diff --git a/huismus/core/static/core/app.js b/huismus/core/static/core/app.js index b721535..914f248 100644 --- a/huismus/core/static/core/app.js +++ b/huismus/core/static/core/app.js @@ -675,3 +675,85 @@ function showReceiptPdfs(root) { wideScreen.addEventListener("change", () => showReceiptPdfs(document)); if (window.htmx) window.htmx.onLoad(showReceiptPdfs); else showReceiptPdfs(document); + +// The photo first (#188, expenses/photo_views.py): on a phone, a link to the +// new-expense form opens the camera instead. The photo is sent at once; +// Huismus puts it with the receipts and opens the page with the amount. +// Cancelling the camera opens the ordinary form, where a photo from the +// library, a PDF or no receipt at all is possible. On a wide screen, in the +// desktop app and without JS, the link is the ordinary form. +const phone = window.matchMedia("(max-width: 760px) and (pointer: coarse)"); + +// Capture, and no further: htmx's boost listens on the link itself. +document.addEventListener( + "click", + (event) => { + const camera = document.getElementById("camera"); + const link = event.target.closest?.("a[href]"); + if (!camera || !link || !phone.matches || event.defaultPrevented) return; + if (link.pathname !== camera.dataset.newExpense || link.search) return; + event.preventDefault(); + event.stopPropagation(); + link.closest("[popover]")?.hidePopover(); + const input = camera.querySelector("input[type=file]"); + input.value = ""; + // Browsers that don't say "cancel" leave the user where they tapped. + input.oncancel = () => window.location.assign(link.href); + input.click(); + }, + true, +); + +// A photo taken, from that hidden form or from "Opnieuw" on the photo page: +// sent with fetch, so a failed connection leaves the photo here to send +// again. A photo from the camera isn't always in the library too: a +// browser error page would lose it. +let unsent = null; + +function cameraToast(id) { + for (const toast of document.querySelectorAll("[data-camera-toast]")) toast.remove(); + const template = document.getElementById(id); + if (template) document.getElementById("toasts")?.append(template.content.cloneNode(true)); +} + +async function sendPhoto(form, file) { + unsent = { form, file }; + cameraToast("camera-busy"); + const data = new FormData(form); + data.set("file", file); + let response; + try { + // The header asks Huismus to say where to go (X-Huismus-Go) rather than + // to redirect: following a redirect here would use up the next page's + // message, such as why it refused the file (expenses/photo_views.py). + response = await fetch(form.action, { + method: "POST", + body: data, + headers: { "X-Huismus-Camera": "1" }, + }); + } catch { + // No answer at all: no connection with Huismus. + cameraToast("camera-offline"); + return; + } + if (!response.ok) { + // Huismus answered, with an error. + cameraToast("camera-failed"); + return; + } + unsent = null; + // Where Huismus sends it: the photo page, or the ordinary form with the + // reason it refused the file. Signed out meanwhile: the login page. + window.location.assign(response.headers.get("X-Huismus-Go") || response.url); +} + +document.addEventListener("change", (event) => { + const input = event.target; + if (!input.matches?.("input[type=file][data-camera]") || !input.files.length) return; + input.oncancel = null; + sendPhoto(input.form, input.files[0]); +}); + +document.addEventListener("click", (event) => { + if (event.target.closest?.("[data-camera-retry]") && unsent) sendPhoto(unsent.form, unsent.file); +}); diff --git a/huismus/core/static/core/huismus.css b/huismus/core/static/core/huismus.css index e74d125..f4072fc 100644 --- a/huismus/core/static/core/huismus.css +++ b/huismus/core/static/core/huismus.css @@ -888,6 +888,16 @@ div.hint-banner > form { position: relative; z-index: 1; } .process-receipt { position: static; } .process-img { max-height: 50dvh; } } +/* A new expense on a phone, the photo first (#188, expenses/photo.html): + the photo with "Opnieuw" on it, then the amount, large. */ +.photo-shot { position: relative; padding: var(--s-3); } +.photo-shot .process-img { max-height: min(30dvh, 260px); } +.photo-again { position: absolute; right: var(--s-5); bottom: var(--s-5); } +.amount-xl .input { height: 60px; font-size: var(--fs-2xl); font-weight: var(--fw-semibold); } +.amount-xl .money::before { font-size: var(--fs-lg); } +/* Its bar: "Uitgave opslaan" with "Alleen de foto bewaren" under it. */ +.actionbar.photo-actions { flex-direction: column; align-items: stretch; flex-wrap: nowrap; gap: 2px; } +.actionbar.photo-actions .btn { flex: none; } .report { background: var(--surface); border: 1px solid var(--border); border-radius: var(--r-lg); box-shadow: var(--sh-1); overflow: hidden; } .report + .report { margin-top: var(--s-3); } diff --git a/huismus/core/update_views.py b/huismus/core/update_views.py index 2245b73..414b751 100644 --- a/huismus/core/update_views.py +++ b/huismus/core/update_views.py @@ -96,6 +96,9 @@ def page(request): "whats_new_url": _whats_new_url(), "waiting": updates.waiting() is not None, "downloading": updates.downloading() is not None, + # A newer macOS needed (issue #155): then no button. + "needs_macos": updates.needs_macos_label(), + "this_macos": updates.this_macos(), "problem": _problem(code) if code else "", # Then the download by hand, from the release's page. "download_by_hand": code == "not-writable", @@ -154,11 +157,15 @@ def _docker(release) -> dict: def install(request): _desktop_only() release = updates.available() - if release is None: + if release is None or updates.needs_macos(): return redirect("business:updates") if request.method == "POST": try: updates.install(release) + except updates.NeedsNewerMacOS: + # No error: Updates says what to do (huismus-intern/besluiten.md, + # 2026-11-13). + return redirect("business:updates") except updates.UpdateError as error: request.session["update_problem"] = str(error) return redirect("business:updates") diff --git a/huismus/core/updates.py b/huismus/core/updates.py index 19864b7..88f46df 100644 --- a/huismus/core/updates.py +++ b/huismus/core/updates.py @@ -15,6 +15,12 @@ they fail, the shell offers to restore that backup (huismus-intern/besluiten.md, 2026-11-04). +On a Mac a new version may ask a newer macOS than this one has (0.1.4 asked +15 instead of 14). After downloading, the shell reads the minimum from the +new app (minimum_os, desktop/updater.py); on an older macOS the current +version stays and Instellingen → Updates says to update macOS first +(needs_macos; issue #155). + Whether to look and what was found belong to this computer, like the backup folder: a small file next to the database that no backup carries (UPDATE_STATUS_FILE_NAME). @@ -30,6 +36,7 @@ import json import logging import os +import platform import re import sys import threading @@ -68,6 +75,14 @@ class UpdateError(Exception): why; core.update_views turns it into a sentence.""" +class NeedsNewerMacOS(UpdateError): + """The new version needs a newer macOS than this Mac has: no error to + the user, Instellingen → Updates says what to do (issue #155).""" + + def __init__(self): + super().__init__("macos") + + @dataclass class Release: version: str @@ -89,7 +104,7 @@ class Status: # get installed (desktop/app.py). not_installed: str = "" # The checked file that waits for the next start (prepare): version, - # path, sha256. + # path, sha256, minimum_os (the oldest macOS it opens on, "" if unknown). downloaded: dict = field(default_factory=dict) # When downloading last failed (ISO timestamp): tried again a day later. download_failed: str = "" @@ -334,8 +349,19 @@ def prepare(now: datetime | None = None) -> None: logger.info("Downloaden van %s lukte niet: %s", release.version, error) update_status(download_failed=now.isoformat()) return + _record_download(release, path, _read_minimum_os(path)) + + +def _record_download(release: Release, path: Path, minimum_os: str) -> None: + """The checked file for the next start, with the oldest macOS it opens + on ("" if unknown).""" update_status( - downloaded={"version": release.version, "path": str(path), "sha256": release.sha256}, + downloaded={ + "version": release.version, + "path": str(path), + "sha256": release.sha256, + "minimum_os": minimum_os, + }, download_failed="", ) @@ -347,10 +373,11 @@ def _waiting_file(status: Status) -> Path | None: def waiting() -> Release | None: """The new version that is downloaded and will be installed at the - next start: what the overview and Updates say "staat klaar" about.""" + next start: what the overview and Updates say "staat klaar" about. + Not while it needs a newer macOS (needs_macos).""" release = available() status = load_status() - if release is None or status.auto_failed == release.version: + if release is None or status.auto_failed == release.version or needs_macos(): return None if status.downloaded.get("version") != release.version or not _waiting_file(status): return None @@ -366,11 +393,95 @@ def downloading() -> Release | None: status = load_status() if release is None or status.auto_failed == release.version or status.download_failed: return None - if not settings.DESKTOP: + if not settings.DESKTOP or needs_macos(): return None return None if waiting() is not None else release +# -- A newer macOS ------------------------------------------------------------ + +# Set by the desktop shell on a Mac (desktop/app.py, App.boot): a function +# that reads the oldest macOS a downloaded package opens on +# (LSMinimumSystemVersion), "" when it names none. None on Windows, in +# Docker and in tests: then nothing is held back. App.boot sets it before +# the hourly thread's first prepare(); install() reads the package again +# anyway, so a minimum missed then is found before anything changes. +minimum_os = None + + +def _read_minimum_os(package: Path) -> str: + """The minimum from minimum_os, or "" when there is no reader or it + can't read the package. Then updating goes as before, with a line in + the log (huismus-intern/besluiten.md, 2026-11-13): a .dmg that can't be + mounted here can't be installed by desktop/updater.py either, and that + script then opens the old app again.""" + if minimum_os is None: + return "" + try: + return minimum_os(package) or "" + except Exception: + logger.exception("Huismus kon niet lezen welke macOS %s nodig heeft", package) + return "" + + +def this_macos() -> str: + """This Mac's macOS version, like "14.6.1"; "" anywhere else.""" + return platform.mac_ver()[0] if sys.platform == "darwin" else "" + + +def _macos_parts(version: str) -> tuple[int, ...] | None: + parts = version.split(".") + if not all(part.isdigit() for part in parts): + return None + while len(parts) > 1 and parts[-1] == "0": + parts.pop() + return tuple(int(part) for part in parts) + + +def older_macos(this: str, minimum: str) -> bool: + """True when this macOS is older than minimum. False when either is + unknown: then nothing is held back.""" + this_parts, minimum_parts = _macos_parts(this), _macos_parts(minimum) + if this_parts is None or minimum_parts is None: + return False + return this_parts < minimum_parts + + +# The names macOS shows next to its number, for "macOS 15 (Sequoia)" +# (huismus-intern/besluiten.md, 2026-11-13). Another number gets no name. +MACOS_NAMES = {"15": "Sequoia", "26": "Tahoe"} + + +def macos_label(version: str) -> str: + """ "15 (Sequoia)" for "15", or the number alone.""" + name = MACOS_NAMES.get(version) + return f"{version} ({name})" if name else version + + +def too_old_for(minimum: str) -> str: + """minimum as the user reads it ("15", not "15.0") when this Mac's + macOS is older; "" otherwise.""" + if not older_macos(this_macos(), minimum): + return "" + return ".".join(str(part) for part in _macos_parts(minimum)) + + +def needs_macos() -> str: + """The macOS the downloaded new version needs when this Mac's is + older ("15"); "" otherwise, also when nothing is downloaded.""" + release = available() + downloaded = load_status().downloaded + if release is None or downloaded.get("version") != release.version: + return "" + return too_old_for(downloaded.get("minimum_os", "")) + + +def needs_macos_label() -> str: + """needs_macos as the overview and Updates show it: "15 (Sequoia)".""" + needed = needs_macos() + return macos_label(needed) if needed else "" + + def start_hourly_thread() -> threading.Thread: """On Docker: a look for a new version when the server starts and then once a day, if it's on. gunicorn calls this once in its one worker @@ -480,6 +591,13 @@ def install(release: Release) -> None: precheck() waiting_file = _downloaded(release) package = waiting_file or download(release, _update_folder()) + # Read again, also for a file downloaded ahead: the last check before + # anything changes. Recorded first, so Updates can say which macOS it + # needs and the file is used once macOS is updated. + minimum = _read_minimum_os(package) + _record_download(release, package, minimum) + if too_old_for(minimum): + raise NeedsNewerMacOS try: backup = auto_backups.safety_backup() except auto_backups.SafetyBackupError as error: @@ -518,6 +636,11 @@ def install_at_start() -> bool: return False try: install(release) + except NeedsNewerMacOS: + # Not tried: Updates says so, and it's installed once macOS is + # updated. waiting() already leaves it out; this is a macOS updated + # backwards or a minimum read only now. + return False except UpdateError as error: logger.warning("Automatisch bijwerken naar %s lukte niet: %s", release.version, error) if str(error) == "backup": diff --git a/huismus/core/views.py b/huismus/core/views.py index 7b41889..0a89e24 100644 --- a/huismus/core/views.py +++ b/huismus/core/views.py @@ -19,7 +19,7 @@ from huismus.business.models import Settings from huismus.documents.listing import expiry_hint from huismus.documents.models import Document -from huismus.documents.numbering import next_numbers_if_issued_today +from huismus.documents.numbering import NumberingError, next_numbers_if_issued_today from huismus.expenses.inbox_views import new_receipts_context from huismus.reports.year_overview import compute_year_overview @@ -162,6 +162,7 @@ def _update_notices(request) -> dict: "new_release": updates.available(), "release_waiting": updates.waiting(), "release_downloading": updates.downloading(), + "release_needs_macos": updates.needs_macos_label(), } @@ -242,10 +243,14 @@ def onboarding(request, slug): if request.method == "POST": form = SettingsPartForm(request.POST, request.FILES, instance=instance, fields=step.fields) if form.is_valid(): - form.save() - if index + 1 < len(STEPS): - return redirect("onboarding", STEPS[index + 1].slug) - return redirect("onboarding_done") + try: + form.save() + except NumberingError as error: + form.add_error(None, str(error)) + else: + if index + 1 < len(STEPS): + return redirect("onboarding", STEPS[index + 1].slug) + return redirect("onboarding_done") else: form = SettingsPartForm(instance=instance, fields=step.fields) diff --git a/huismus/documents/mail_texts.py b/huismus/documents/mail_texts.py index e2bd495..a62c332 100644 --- a/huismus/documents/mail_texts.py +++ b/huismus/documents/mail_texts.py @@ -1,8 +1,9 @@ # SPDX-FileCopyrightText: 2026 Huismus contributors # SPDX-License-Identifier: AGPL-3.0-or-later -"""The text a mail starts from (SPEC.md M10): per kind of document and per -language, set in Instellingen → Mailen, or the standard text below when -that setting is empty. Placeholders like {nummer} are filled in per +"""The text a mail starts from (SPEC.md M10): per kind of document, plus +the payment reminder for an overdue invoice (#114), and per language, set +in Instellingen → Mailen, or the standard text below when that setting is +empty. Placeholders like {nummer} are filled in per document; the user can still change everything per mail. """ @@ -11,7 +12,10 @@ from django.utils import translation from django.utils.translation import gettext as _ -KINDS = ["invoice", "credit_note", "quote"] +# The kinds of mail text, not Document.kind: one per kind of document, plus +# "reminder", a payment reminder about an invoice (#114) with texts of its +# own. {nummer}, {bedrag}, {naam} and {bedrijf} work in all of them. +KINDS = ["invoice", "credit_note", "quote", "reminder"] LANGUAGES = ["nl", "en"] # Every placeholder, and the kinds it belongs to. The names are Dutch in @@ -21,8 +25,9 @@ "bedrag": KINDS, "naam": KINDS, "bedrijf": KINDS, - "vervaldatum": ["invoice"], + "vervaldatum": ["invoice", "reminder"], "geldig_tot": ["quote"], + "openstaand": ["reminder"], } DATE_PLACEHOLDERS = {"vervaldatum", "geldig_tot"} _PLACEHOLDER = re.compile(r"\{(\w+)\}") @@ -40,7 +45,25 @@ def standard_text(kind: str, part: str, language: str) -> str: "invoice": _("Factuur {nummer} van {bedrijf}"), "credit_note": _("Creditnota {nummer} van {bedrijf}"), "quote": _("Offerte {nummer} van {bedrijf}"), + "reminder": _("Herinnering: factuur {nummer} van {bedrijf}"), }[kind] + if kind == "reminder": + return ( + _("Beste {naam},") + + "\n\n" + + _( + "Van factuur {nummer} staat nog {openstaand} open. " + "De vervaldatum was {vervaldatum}. In de bijlage vind je de factuur." + ) + + "\n\n" + + _( + "Wil je het bedrag zo snel mogelijk overmaken? " + "Heb je al betaald, dan kun je deze mail vergeten." + ) + + "\n\n" + + _("Met vriendelijke groet,") + + "\n{bedrijf}\n" + ) attached = { "invoice": _("In de bijlage vind je factuur {nummer} van {bedrag}."), "credit_note": _("In de bijlage vind je creditnota {nummer} van {bedrag}."), diff --git a/huismus/documents/mailing.py b/huismus/documents/mailing.py index 3fc0d96..ad6c2b6 100644 --- a/huismus/documents/mailing.py +++ b/huismus/documents/mailing.py @@ -45,10 +45,11 @@ def _date(value) -> str: return dateformat.format(value, "j F Y") -def default_message(document) -> tuple[str, str]: +def default_message(document, *, reminder=False) -> tuple[str, str]: """Subject and body to start from: the mail text from the settings for this kind and language, or the standard text (documents.mail_texts), - filled in from the document.""" + filled in from the document. With reminder, the text of a payment + reminder for the invoice.""" customer = document.contact_snapshot or {} values = { "nummer": document.number, @@ -56,6 +57,10 @@ def default_message(document) -> tuple[str, str]: "bedrag": money(document.total_cents), "naam": customer.get("first_name") or customer.get("display_name", ""), } + kind = document.kind + if reminder: + kind = "reminder" + values["openstaand"] = money(document.outstanding_cents) with translation.override(document.language): if document.due_date: values["vervaldatum"] = _date(document.due_date) @@ -64,8 +69,8 @@ def default_message(document) -> tuple[str, str]: business = Settings.load() language = document.language if document.language in mail_texts.LANGUAGES else "nl" subject, body = ( - getattr(business, mail_texts.field_name(document.kind, part, language)) - or mail_texts.standard_text(document.kind, part, language) + getattr(business, mail_texts.field_name(kind, part, language)) + or mail_texts.standard_text(kind, part, language) for part in ("subject", "body") ) return mail_texts.fill(subject, values), mail_texts.fill(body, values) @@ -84,9 +89,12 @@ def attachment(document) -> tuple[str, bytes]: return f"{document.number}.pdf", content -def send_document(document, *, to: list[str], subject: str, body: str, bcc_self: bool): - """Mail the document and log the attempt. Returns the EmailLog; a - failure is in its `error`, not raised.""" +def send_document( + document, *, to: list[str], subject: str, body: str, bcc_self: bool, reminder=False +): + """Mail the document and log the attempt, as a payment reminder if + reminder is set. Returns the EmailLog; a failure is in its `error`, + not raised.""" business = Settings.load() sender = smtp.sender(business) bcc = [sender] if bcc_self else [] @@ -118,4 +126,5 @@ def send_document(document, *, to: list[str], subject: str, body: str, bcc_self: attachment_sha256=hashlib.sha256(content).hexdigest() if content else "", succeeded=not error, error=error, + reminder=reminder, ) diff --git a/huismus/documents/migrations/0017_emaillog_reminder.py b/huismus/documents/migrations/0017_emaillog_reminder.py new file mode 100644 index 0000000..db65d5a --- /dev/null +++ b/huismus/documents/migrations/0017_emaillog_reminder.py @@ -0,0 +1,33 @@ +# SPDX-FileCopyrightText: 2026 Huismus contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +# A mail can be a payment reminder (#114). Every mail sent before was not. +# +# The column is added with ALTER TABLE instead of Django's AddField, as in +# 0015: for a NOT NULL column SQLite's schema editor rebuilds the table, and +# dropping it would take the mail log's append-only triggers (0010) along. +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("documents", "0016_vat_rows"), + ] + + operations = [ + migrations.SeparateDatabaseAndState( + database_operations=[ + migrations.RunSQL( + sql="ALTER TABLE documents_emaillog " + "ADD COLUMN reminder bool NOT NULL DEFAULT 0", + reverse_sql="ALTER TABLE documents_emaillog DROP COLUMN reminder", + ), + ], + state_operations=[ + migrations.AddField( + model_name="emaillog", + name="reminder", + field=models.BooleanField(default=False, verbose_name="herinnering"), + ), + ], + ), + ] diff --git a/huismus/documents/models.py b/huismus/documents/models.py index 32a27f2..6317fcc 100644 --- a/huismus/documents/models.py +++ b/huismus/documents/models.py @@ -292,12 +292,12 @@ def is_overdue(self): @property def days_overdue(self): - """How many days past the due date an overdue invoice is; 0 when it - isn't overdue. Derived, like is_overdue.""" - if self.due_date is None or self.payment_state not in ("unpaid", "partial"): - return 0 - # One reading of today, so the count can't disagree with itself at midnight. - return max((timezone.localdate() - self.due_date).days, 0) + """How many days past its due date an overdue issued invoice is + ("12 dagen te laat"), or None when it isn't one: no reminder (#114) + for anything else.""" + if self.kind != "invoice" or self.status != "issued" or not self.is_overdue: + return None + return (timezone.localdate() - self.due_date).days def clean(self): super().clean() @@ -489,6 +489,9 @@ class EmailLog(TimestampedModel): attachment_sha256 = models.CharField(_("sha256 van de bijlage"), max_length=64) succeeded = models.BooleanField(_("gelukt")) error = models.TextField(_("fout"), blank=True) + # A payment reminder for an overdue invoice (#114), not the invoice + # itself: the same PDF, another text, and its own line on the page. + reminder = models.BooleanField(_("herinnering"), default=False) class Meta: verbose_name = _("verstuurde e-mail") diff --git a/huismus/documents/numbering.py b/huismus/documents/numbering.py index fd8de8a..fab7c13 100644 --- a/huismus/documents/numbering.py +++ b/huismus/documents/numbering.py @@ -136,13 +136,117 @@ def next_numbers_if_issued_today(settings) -> dict[str, str | None]: ("invoice", "quote"). issue() takes the year of the document's issue date; this assumes today. Without a yearly reset the sequence has no year (Settings.number_reset_yearly).""" - year = timezone.localdate().year if settings.number_reset_yearly else None + year = year_if_issued_today(settings.number_reset_yearly) return { "invoice": peek_next_number("invoice", settings.invoice_number_format, year=year), "quote": peek_next_number("quote", settings.quote_number_format, year=year), } +# Which document kinds take their numbers from a sequence: credit notes +# share the invoice sequence (models.SEQUENCE_KIND_CHOICES). +_SEQUENCE_DOCUMENT_KINDS = {"invoice": ["invoice", "credit_note"], "quote": ["quote"]} + + +def next_sequence_number(kind: str, *, year: int | None) -> int: + """The {seq} the next document of this sequence gets. Reads only.""" + last_value = ( + NumberSequence.objects.filter(kind=kind, year=year) + .values_list("last_value", flat=True) + .first() + ) + return (last_value or 0) + 1 + + +def next_sequence_number_is_fixed(kind: str) -> bool: + """True once Huismus itself gave a document of this kind a number, in + any year. From then on numbers only move by issuing: setting the next + one by hand could leave a gap after a number Huismus gave, also in a + new year's sequence (invariant 3). Imported documents don't count: + their numbers come from the package the user left, which is what the + user continues by hand. A reopened document ("Toch bewerken") keeps its + number, so it still counts.""" + return Document.objects.filter( + # source is empty for a document made in Huismus, set for an imported one. + kind__in=_SEQUENCE_DOCUMENT_KINDS[kind], + number__isnull=False, + source="", + ).exists() + + +def lowest_next_sequence_number(kind: str, template: str, *, year: int | None) -> int: + """Just above the highest {seq} already in this sequence: the numbers + that fit the format, of this year when it resets yearly. Below that the + sequence would reach a number that exists.""" + highest = 0 + documents = Document.objects.filter( + kind__in=_SEQUENCE_DOCUMENT_KINDS[kind], number__isnull=False + ).select_related("contact") + for document in documents: + if year is not None and (document.issue_date is None or document.issue_date.year != year): + continue + customer = (document.contact.customer_number if document.contact else "") or "" + seq = parse_number(template, document.number, year=year, customer=customer) + if seq is not None: + highest = max(highest, seq) + return highest + 1 + + +def check_next_sequence_number(kind: str, template: str, *, year: int | None, value: int) -> None: + """Raise NumberingError if the next {seq} can't be set to `value` + without a gap or a number twice (invariant 3): not once Huismus issued + a document of this kind, not onto or below a number that already + exists. Up and down are both fine before that: nothing was issued from + the sequence yet, so nothing is skipped. Changes nothing; the settings + form shows its errors with it, set_next_sequence_number() checks + again under the write lock.""" + if value < 1: + raise NumberingError(_("Het volgnummer is minstens 1.")) + if next_sequence_number_is_fixed(kind): + raise NumberingError( + _("Je hebt in Huismus al een nummer uitgegeven. Het nummer loopt nu vanzelf door.") + ) + lowest = lowest_next_sequence_number(kind, template, year=year) + if value < lowest: + raise NumberingError( + _("Kies %(lowest)s of hoger. Een lager nummer bestaat al.") % {"lowest": lowest} + ) + if not uses_customer_number(template): + # An existing number that doesn't fit the format (an import) can + # still be hit exactly. With {customer} the number isn't known + # until the customer is; number_for() refuses it then. + number = format_number(template, year=year, seq=value) + if Document.objects.filter(kind__in=_SEQUENCE_DOCUMENT_KINDS[kind], number=number).exists(): + raise NumberingError( + _("Nummer %(number)s bestaat al. Kies een hoger volgnummer.") % {"number": number} + ) + + +def set_next_sequence_number(kind: str, template: str, *, year: int | None, value: int) -> None: + """Set the {seq} of the next document of this sequence by hand (SPEC.md + section 7, "the user sets the next number manually"; issue #141), for + someone continuing the numbers of another package. Raises + NumberingError where check_next_sequence_number() does. Only the + sequence row changes; a number is still given only by + allocate_number(), when issuing.""" + if value == next_sequence_number(kind, year=year): + return + with transaction.atomic(): + # A write first, as in allocate_number(): from here SQLite holds the + # write lock, so no document can be issued between the check and + # the update. Reading first and writing after could instead + # deadlock with a concurrent issue(). + ensure_sequence_row(kind, year) + check_next_sequence_number(kind, template, year=year, value=value) + NumberSequence.objects.filter(kind=kind, year=year).update(last_value=value - 1) + + +def year_if_issued_today(reset_yearly: bool) -> int | None: + """The year of the sequence a document issued today takes; without a + yearly reset the sequence has no year (Settings.number_reset_yearly).""" + return timezone.localdate().year if reset_yearly else None + + _SEQ_PLACEHOLDER = re.compile(r"\{seq(:[^}]*)?\}") diff --git a/huismus/documents/urls.py b/huismus/documents/urls.py index 9a3a452..8faff31 100644 --- a/huismus/documents/urls.py +++ b/huismus/documents/urls.py @@ -34,6 +34,7 @@ name="original_pdf_embed", ), path("/mailen/", views.document_mail, name="mail"), + path("/herinnering/", views.document_reminder, name="reminder"), ] # Quotes, mounted at offertes/ in huismus/config/urls.py under its own "quotes" diff --git a/huismus/documents/views.py b/huismus/documents/views.py index 691609e..cb91155 100644 --- a/huismus/documents/views.py +++ b/huismus/documents/views.py @@ -45,7 +45,12 @@ in_tab, matches_search, ) -from .mailing import MAILABLE_STATUSES, default_message, default_recipients, send_document +from .mailing import ( + MAILABLE_STATUSES, + default_message, + default_recipients, + send_document, +) from .models import Document, DocumentLine from .pdf import render_pdf from .preview import render_preview_pdf @@ -458,7 +463,8 @@ def document_reopen_undo(request, pk): def _detail_context(document): """The read-only page of an issued invoice or credit note.""" - # Only a mail that went out counts. + # Only a mail that went out counts. A reminder counts too: it carries + # the same PDF, so the customer has the invoice as it was then. last_mail = document.emails.filter(succeeded=True).order_by("-sent_at").first() context = { "document": document, @@ -517,6 +523,11 @@ def _detail_context(document): kind="credit_note", related_document=invoice ).order_by("issue_date", "pk"), "timeline": timeline_events(invoice), + # When the last payment reminder went out (#114); a failed one + # doesn't count. + "last_reminder": invoice.emails.filter(succeeded=True, reminder=True) + .order_by("-sent_at") + .first(), "payment_form": PaymentForm( initial={ "paid_on": timezone.localdate(), @@ -677,6 +688,27 @@ def document_mail(request, pk, kind="invoice"): document = get_object_or_404(Document, pk=pk, kind__in=kinds) if document.status not in MAILABLE_STATUSES[document.kind]: raise Http404 + return _mail_page(request, document, reminder=False) + + +@login_required +def document_reminder(request, pk): + """The same mail form, as a payment reminder for an overdue invoice + (#114): another text, logged as a reminder. Only an issued invoice has + one; one that isn't (or no longer is) overdue, say just paid, goes back + to its page instead of an error.""" + document = get_object_or_404(Document, pk=pk, kind="invoice", status="issued") + if document.days_overdue is None: + messages.info( + request, + _("Factuur %(number)s is niet te laat. Er is geen herinnering gestuurd.") + % {"number": document.number}, + ) + return redirect(_edit_url(document)) + return _mail_page(request, document, reminder=True) + + +def _mail_page(request, document, *, reminder): configured = smtp.is_configured(Settings.load()) failed = None if request.method == "POST": @@ -690,13 +722,18 @@ def document_mail(request, pk, kind="invoice"): subject=form.cleaned_data["subject"], body=form.cleaned_data["body"], bcc_self=form.cleaned_data["bcc_self"], + reminder=reminder, ) if log.succeeded: - messages.success(request, _("Gemaild naar %(to)s.") % {"to": log.to}) + if reminder: + sent = _("Herinnering gestuurd naar %(to)s.") + else: + sent = _("Gemaild naar %(to)s.") + messages.success(request, sent % {"to": log.to}) return redirect(_edit_url(document)) failed = log else: - subject, body = default_message(document) + subject, body = default_message(document, reminder=reminder) form = MailForm( initial={"to": default_recipients(document), "subject": subject, "body": body} ) @@ -705,6 +742,7 @@ def document_mail(request, pk, kind="invoice"): "documents/mail.html", { "document": document, + "reminder": reminder, "form": form, "mail_configured": configured, "failed": failed, diff --git a/huismus/expenses/photo_views.py b/huismus/expenses/photo_views.py new file mode 100644 index 0000000..e282f90 --- /dev/null +++ b/huismus/expenses/photo_views.py @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: 2026 Huismus contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +"""A new expense on a phone, the photo first (#188; huismus-intern/besluiten.md, +2026-11-15, "Nieuwe huisstijl", and the plan of #188). + +On a phone app.js turns "Uitgave" into the camera. The photo is sent to +photo_upload(), which puts it in the tray at once, as a receipt from the +receipts folder would be: walking away never loses it. photo_expense() +then shows it above the few fields of one line, the amount first. "Uitgave +opslaan" makes the expense with the receipt on it, as Verwerken does; +"Alleen de foto bewaren" leaves it in the tray, where Verwerken has it. + +Without JS, or on a wide screen, "Uitgave" is the ordinary form +(views._expense_form); nothing here is needed for that. +""" + +from django.contrib import messages +from django.contrib.auth.decorators import login_required +from django.http import HttpResponse +from django.shortcuts import redirect, render +from django.urls import reverse +from django.utils import timezone +from django.utils.translation import gettext as _ + +from huismus.core.models import Attachment + +from . import batch, reading +from .adding import RECEIPT_GONE +from .forms import ExpenseForm, ExpenseLineFormSet, ReceiptUploadForm +from .models import Expense +from .receipts import sha256_of +from .views import TrayReceiptGone, all_valid, save_expense + +# Attachment.source of a photo taken here. +SOURCE = "telefoon" +# The request header app.js sends the photo with, and the response header +# with the page to open (_go). +CAMERA, GO = "X-Huismus-Camera", "X-Huismus-Go" + + +@login_required +def photo_upload(request): + """The photo from the camera, into the tray. With `vervangt` + ("Opnieuw"), the photo it replaces goes, if it still waits.""" + if request.method != "POST": + return redirect("expenses:create") + form = ReceiptUploadForm(request.POST, request.FILES) + if not form.is_valid(): + # The form's own reason: "Dit bonnetje is groter dan 10 MB. …". The + # ordinary form can take a photo from the library or a PDF. + messages.error(request, form.errors["file"][0]) + return _go(request, reverse("expenses:create")) + uploaded = form.cleaned_data["file"] + receipt = Attachment.objects.create( + file=uploaded, kind="receipt", sha256=sha256_of(uploaded), source=SOURCE + ) + # The old one goes only now the new one is in. Only a photo taken here + # that still waits in the tray: one on an expense meanwhile (another + # tab) or one from the receipts folder stays. Anything else than a + # number replaces nothing. + replaces = request.POST.get("vervangt", "") + if replaces.isdigit(): + replaced = Attachment.objects.in_tray().filter(source=SOURCE, pk=int(replaces)) + for old in replaced: + old.file.delete(save=False) + old.delete() + return _go(request, reverse("expenses:photo", kwargs={"pk": receipt.pk})) + + +def _go(request, url): + """Where the page goes next. To app.js's upload (the header CAMERA) a + 204 with the address: had fetch() followed a redirect, it would have + shown the next page's message to nobody, and the page that opens after + it wouldn't have it any more. To a plain form, a redirect.""" + if CAMERA not in request.headers: + return redirect(url) + response = HttpResponse(status=204) + response[GO] = url + return response + + +@login_required +def photo_expense(request, pk): + """The photo above the amount, where, date and category of one line.""" + receipt = Attachment.objects.in_tray().filter(pk=pk).first() + if receipt is None: + # Made into an expense or removed meanwhile, in another tab. + messages.error(request, str(RECEIPT_GONE)) + return redirect("expenses:list") + if request.method == "POST" and "alleen_foto" in request.POST: + # It is in the tray already. Read now, if the AI service is on. + reading.read_in_background() + messages.success(request, _("Bonnetje bewaard. Je vindt het bij Verwerken.")) + return redirect("expenses:list") + + # A new expense's amount 0 lasts only until save_lines() sets it. + instance = Expense(amount_cents=0) + if request.method == "POST": + form = ExpenseForm(request.POST, instance=instance) + formset = ExpenseLineFormSet(request.POST, instance=instance, prefix="lines") + if all_valid(form, formset): + try: + save_expense(form, formset, tray_receipt=receipt) + except TrayReceiptGone: + messages.error(request, str(RECEIPT_GONE)) + return redirect("expenses:list") + messages.success(request, _("Uitgave opgeslagen.")) + return redirect("expenses:list") + else: + form = ExpenseForm(instance=instance, initial={"date": timezone.localdate()}) + formset = ExpenseLineFormSet(instance=instance, prefix="lines") + return render( + request, + "expenses/photo.html", + { + "receipt": receipt, + "form": form, + "formset": formset, + "line_form": formset.forms[0], + # More lines or a description: the whole form, in Verwerken. + "full_form_url": batch.Item(batch.RECEIPT, receipt.pk).url(), + "upload_url": reverse("expenses:photo_upload"), + }, + ) diff --git a/huismus/expenses/urls.py b/huismus/expenses/urls.py index 8184223..0d53f5b 100644 --- a/huismus/expenses/urls.py +++ b/huismus/expenses/urls.py @@ -3,13 +3,16 @@ from django.urls import path from django.views.generic import RedirectView -from . import inbox_views, process_views, views +from . import inbox_views, photo_views, process_views, views app_name = "expenses" urlpatterns = [ path("", views.expense_list, name="list"), path("nieuw/", views.expense_create, name="create"), + # On a phone, the photo first (#188). + path("nieuw/foto/", photo_views.photo_upload, name="photo_upload"), + path("nieuw/foto//", photo_views.photo_expense, name="photo"), path("verwerken/", process_views.process, name="process"), path( "verwerken///", diff --git a/huismus/imports/commit.py b/huismus/imports/commit.py index 9f871fd..ae664b1 100644 --- a/huismus/imports/commit.py +++ b/huismus/imports/commit.py @@ -598,7 +598,8 @@ def _continue_numbering( if unparsed: return _( "%(unparsed)s van %(total)s geïmporteerde %(label)s passen niet in het ingestelde " - "nummerformaat. Stel het volgende nummer zelf in bij Instellingen." + "nummerformaat. Stel het volgende nummer zelf in bij Instellingen → Facturen en " + "nummering." ) % {"unparsed": unparsed, "total": len(imported_numbers), "label": label} return "" diff --git a/huismus/locale/en/LC_MESSAGES/django.po b/huismus/locale/en/LC_MESSAGES/django.po index dfd8f6c..dae01a8 100644 --- a/huismus/locale/en/LC_MESSAGES/django.po +++ b/huismus/locale/en/LC_MESSAGES/django.po @@ -4,7 +4,7 @@ msgid "" msgstr "" "Project-Id-Version: huismus\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-15 17:45+0100\n" +"POT-Creation-Date: 2026-11-15 19:01+0100\n" "PO-Revision-Date: 2026-09-25 08:36+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -204,6 +204,26 @@ msgstr "" "Exempt from VAT under the small business scheme (KOR). No VAT has been " "charged." +msgid "Volgnummer van je volgende factuur" +msgstr "Sequence number of your next invoice" + +msgid "" +"Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste factuur " +"komt." +msgstr "" +"Coming from another package? Enter the sequence number that follows your " +"last invoice." + +msgid "Volgnummer van je volgende offerte" +msgstr "Sequence number of your next quote" + +msgid "" +"Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste offerte " +"komt." +msgstr "" +"Coming from another package? Enter the sequence number that follows your " +"last quote." + msgid "Factuur" msgstr "Invoice" @@ -213,6 +233,10 @@ msgstr "Credit note" msgid "Offerte" msgstr "Quote" +# +msgid "Herinnering" +msgstr "Reminder" + msgid "onderwerp in het Nederlands" msgstr "subject in Dutch" @@ -435,6 +459,22 @@ msgstr "quote subject (English)" msgid "tekst offerte (engels)" msgstr "quote text (English)" +# +msgid "onderwerp herinnering (nederlands)" +msgstr "reminder subject (Dutch)" + +# +msgid "tekst herinnering (nederlands)" +msgstr "reminder text (Dutch)" + +# +msgid "onderwerp herinnering (engels)" +msgstr "reminder subject (English)" + +# +msgid "tekst herinnering (engels)" +msgstr "reminder text (English)" + msgid "organisatie" msgstr "organisation" @@ -1709,6 +1749,32 @@ msgstr "Credit note {nummer} from {bedrijf}" msgid "Offerte {nummer} van {bedrijf}" msgstr "Quote {nummer} from {bedrijf}" +#, python-brace-format +msgid "Herinnering: factuur {nummer} van {bedrijf}" +msgstr "Reminder: invoice {nummer} from {bedrijf}" + +#, python-brace-format +msgid "Beste {naam}," +msgstr "Dear {naam}," + +#, python-brace-format +msgid "" +"Van factuur {nummer} staat nog {openstaand} open. De vervaldatum was " +"{vervaldatum}. In de bijlage vind je de factuur." +msgstr "" +"Invoice {nummer} still has {openstaand} outstanding. It was due on " +"{vervaldatum}. You'll find the invoice attached." + +msgid "" +"Wil je het bedrag zo snel mogelijk overmaken? Heb je al betaald, dan kun je " +"deze mail vergeten." +msgstr "" +"Could you transfer the amount as soon as possible? If you've already paid, " +"please ignore this email." + +msgid "Met vriendelijke groet," +msgstr "Kind regards," + #, python-brace-format msgid "In de bijlage vind je factuur {nummer} van {bedrag}." msgstr "Attached is invoice {nummer} for {bedrag}." @@ -1729,13 +1795,6 @@ msgstr "Please pay by {vervaldatum}." msgid "De offerte is geldig tot {geldig_tot}." msgstr "The quote is valid until {geldig_tot}." -#, python-brace-format -msgid "Beste {naam}," -msgstr "Dear {naam}," - -msgid "Met vriendelijke groet," -msgstr "Kind regards," - msgid "offerte" msgstr "quote" @@ -1895,6 +1954,10 @@ msgstr "succeeded" msgid "fout" msgstr "error" +# +msgid "herinnering" +msgstr "reminder" + msgid "verstuurde e-mail" msgstr "sent e-mail" @@ -1907,6 +1970,23 @@ msgstr "A sent e-mail cannot be changed." msgid "[klantnummer]" msgstr "[customer number]" +msgid "Het volgnummer is minstens 1." +msgstr "The sequence number is at least 1." + +msgid "" +"Je hebt in Huismus al een nummer uitgegeven. Het nummer loopt nu vanzelf " +"door." +msgstr "" +"You already issued a number in Huismus. The number now counts up by itself." + +#, python-format +msgid "Kies %(lowest)s of hoger. Een lager nummer bestaat al." +msgstr "Choose %(lowest)s or higher. A lower number already exists." + +#, python-format +msgid "Nummer %(number)s bestaat al. Kies een hoger volgnummer." +msgstr "Number %(number)s already exists. Choose a higher sequence number." + msgid "[nummer volgt]" msgstr "[number to follow]" @@ -2000,6 +2080,14 @@ msgstr "Payment recorded." msgid "De betaling is niet opgeslagen. Kijk het bedrag en de datum na." msgstr "The payment wasn't saved. Check the amount and the date." +#, python-format +msgid "Factuur %(number)s is niet te laat. Er is geen herinnering gestuurd." +msgstr "Invoice %(number)s isn't overdue. No reminder was sent." + +#, python-format +msgid "Herinnering gestuurd naar %(to)s." +msgstr "Reminder sent to %(to)s." + #, python-format msgid "Gemaild naar %(to)s." msgstr "Mailed to %(to)s." @@ -2192,12 +2280,15 @@ msgstr "expense line" msgid "uitgaveregels" msgstr "expense lines" -msgid "Uitgave nagekeken." -msgstr "Expense checked." +msgid "Bonnetje bewaard. Je vindt het bij Verwerken." +msgstr "Receipt saved. You'll find it under Process." msgid "Uitgave opgeslagen." msgstr "Expense saved." +msgid "Uitgave nagekeken." +msgstr "Expense checked." + msgid "Niet gelezen: dit lijkt geen bonnetje." msgstr "Not read: this doesn't look like a receipt." @@ -2430,10 +2521,11 @@ msgstr "quote numbers" #, python-format msgid "" "%(unparsed)s van %(total)s geïmporteerde %(label)s passen niet in het " -"ingestelde nummerformaat. Stel het volgende nummer zelf in bij Instellingen." +"ingestelde nummerformaat. Stel het volgende nummer zelf in bij Instellingen " +"→ Facturen en nummering." msgstr "" "%(unparsed)s of %(total)s imported %(label)s don't fit the number format you " -"set. Set the next number yourself in Settings." +"set. Set the next number yourself in Settings → Invoices and numbering." #, python-format msgid "Uitgave %(number)s" @@ -2967,6 +3059,18 @@ msgstr "Shortcuts:" msgid "nieuw" msgstr "new" +msgid "Bonnetje uploaden…" +msgstr "Uploading receipt…" + +msgid "Huismus is niet bereikbaar. Probeer het opnieuw als je verbinding hebt." +msgstr "Can't reach Huismus. Try again when you're connected." + +msgid "Opnieuw proberen" +msgstr "Try again" + +msgid "Het uploaden is mislukt. Probeer het nog een keer." +msgstr "The upload failed. Please try once more." + msgid "Niet gekoppeld" msgstr "Not connected" @@ -3056,6 +3160,17 @@ msgstr "Manage" msgid "Instellen" msgstr "Set up" +#, python-format +msgid "Volgende als je vandaag uitgeeft: %(number)s" +msgstr "Next if you issue today: %(number)s" + +msgid "Het nummer loopt vanzelf door sinds je eerste factuur in Huismus." +msgstr "" +"The number now counts up by itself, since your first invoice in Huismus." + +msgid "Het nummer loopt vanzelf door sinds je eerste offerte in Huismus." +msgstr "The number now counts up by itself, since your first quote in Huismus." + msgid "De taal van nieuwe facturen kies je bij Facturen en nummering." msgstr "You choose the language of new invoices under Invoices and numbering." @@ -3475,10 +3590,6 @@ msgstr "days" msgid "Standaard betalingstermijn" msgstr "Default payment term" -#, python-format -msgid "Volgende als je vandaag uitgeeft: %(number)s" -msgstr "Next if you issue today: %(number)s" - #, python-brace-format msgid "" "In een nummerformaat staat {year} voor het jaar, {seq:04d} voor het " @@ -3547,13 +3658,14 @@ msgstr "Standard texts" msgid "" "Hiermee begint elke mail. Per mail kun je hem nog aanpassen. Maak je een " "veld leeg, dan gebruikt Huismus zijn eigen tekst. Invulplekken: {nummer}, " -"{bedrag}, {naam} en {bedrijf}; bij een factuur ook {vervaldatum}, bij een " -"offerte {geldig_tot}." +"{bedrag}, {naam} en {bedrijf}; bij een factuur en een herinnering ook " +"{vervaldatum}, bij een herinnering {openstaand}, bij een offerte " +"{geldig_tot}." msgstr "" "Every mail starts with this. You can still change it per mail. Leave a field " "empty and Huismus uses its own text. Placeholders: {nummer}, {bedrag}, " -"{naam} and {bedrijf}; for an invoice also {vervaldatum}, for a quote " -"{geldig_tot}." +"{naam} and {bedrijf}; for an invoice and a reminder also {vervaldatum}, for " +"a reminder {openstaand}, for a quote {geldig_tot}." #, python-format msgid "%(counter)s veld heeft aandacht nodig" @@ -3591,6 +3703,17 @@ msgstr "You're using Huismus %(version)s." msgid "Nieuwe versie downloaden" msgstr "Download the new version" +#, python-format +msgid "" +"Deze versie vraagt macOS %(macos)s of nieuwer. Je Mac heeft macOS " +"%(this_macos)s. Werk eerst macOS bij via Systeeminstellingen → Algemeen → " +"Software-update. Daarna installeert Huismus de nieuwe versie de volgende " +"keer dat je hem opent." +msgstr "" +"This version needs macOS %(macos)s or later. Your Mac has macOS " +"%(this_macos)s. Update macOS first in System Settings → General → Software " +"Update. Then Huismus installs the new version the next time you open it." + msgid "Hij wordt geïnstalleerd als je Huismus opnieuw opent." msgstr "It will be installed the next time you open Huismus." @@ -3934,6 +4057,14 @@ msgstr "Huismus was updated to %(version)s." msgid "Wat is er nieuw" msgstr "What's new" +#, python-format +msgid "" +"Huismus %(version)s is er, maar vraagt macOS %(macos)s of nieuwer. Werk " +"eerst macOS bij." +msgstr "" +"Huismus %(version)s is out, but needs macOS %(macos)s or later. Update macOS " +"first." + #, python-format msgid "" "Huismus %(version)s staat klaar. Hij wordt geïnstalleerd als je Huismus " @@ -4049,9 +4180,6 @@ msgid "" msgstr "" "This device can't connect to Huismus. Check your Wi-Fi or VPN and try again." -msgid "Opnieuw proberen" -msgstr "Try again" - #, python-format msgid "Stap %(number)s van %(total)s" msgstr "Step %(number)s of %(total)s" @@ -4268,6 +4396,14 @@ msgstr "Unit price" msgid "Regel verwijderen" msgstr "Remove line" +#, python-format +msgid "Herinnering voor factuur %(number)s" +msgstr "Reminder for invoice %(number)s" + +#, python-format +msgid "%(kind)s %(number)s mailen" +msgstr "Mail %(kind)s %(number)s" + msgid "Vervaldatum voorbij en nog niet volledig betaald." msgstr "Past the due date and not fully paid yet." @@ -4377,6 +4513,14 @@ msgstr "Reopened for editing" msgid "Betaling %(amount)s" msgstr "Payment %(amount)s" +#, python-format +msgid "Herinnering gestuurd naar %(to)s" +msgstr "Reminder sent to %(to)s" + +#, python-format +msgid "Herinnering sturen mislukt naar %(to)s" +msgstr "Sending the reminder to %(to)s failed" + #, python-format msgid "Gemaild naar %(to)s" msgstr "Mailed to %(to)s" @@ -4408,6 +4552,10 @@ msgstr "Imported" msgid "uitgegeven op %(date)s" msgstr "issued on %(date)s" +# +msgid "Herinnering sturen" +msgstr "Send reminder" + msgid "Creditnota maken…" msgstr "Create credit note…" @@ -4470,6 +4618,10 @@ msgstr "To invoice %(number)s" msgid "Betaalstatus" msgstr "Payment status" +#, python-format +msgid "Laatste herinnering: %(date)s" +msgstr "Last reminder: %(date)s" + msgid "Afgehandeld" msgstr "Settled" @@ -4766,10 +4918,6 @@ msgstr "Clear filters" msgid "Te laat betekent: vervaldatum voorbij en nog niet volledig betaald." msgstr "Late means: past the due date and not fully paid yet." -#, python-format -msgid "%(kind)s %(number)s mailen" -msgstr "Mail %(kind)s %(number)s" - #, python-format msgid "" "Stel bij Instellingen in hoe Huismus mailt." @@ -5095,6 +5243,24 @@ msgstr "No expense matches your search and filters." msgid "betekent dat er een bonnetje bij de uitgave zit." msgstr "means the expense has a receipt." +msgid "Opnieuw" +msgstr "Retake" + +msgid "Foto versturen" +msgstr "Send photo" + +msgid "Bedrag, zoals je het betaalde" +msgstr "Amount, as you paid it" + +msgid "Meer regels of een omschrijving" +msgstr "More lines or a description" + +msgid "Uitgave opslaan" +msgstr "Save expense" + +msgid "Alleen de foto bewaren" +msgstr "Just keep the photo" + msgid "Verwerken" msgstr "Process" @@ -6636,6 +6802,51 @@ msgstr "" "If you have a Raspberry Pi, a NAS, your own server or a VPS, you can also " "run Huismus in Docker. That is for people who are handy with that." +#, python-format +#~ msgid "%(count)s dag te laat" +#~ msgid_plural "%(count)s dagen te laat" +#~ msgstr[0] "%(count)s day overdue" +#~ msgstr[1] "%(count)s days overdue" + +#, python-format +#~ msgid "" +#~ "%(unparsed)s van %(total)s geïmporteerde %(label)s passen niet in het " +#~ "ingestelde nummerformaat. Stel het volgende nummer zelf in bij " +#~ "Instellingen." +#~ msgstr "" +#~ "%(unparsed)s of %(total)s imported %(label)s don't fit the number format " +#~ "you set. Set the next number yourself in Settings." + +#, python-brace-format +#~ msgid "" +#~ "Hiermee begint elke mail. Per mail kun je hem nog aanpassen. Maak je een " +#~ "veld leeg, dan gebruikt Huismus zijn eigen tekst. Invulplekken: {nummer}, " +#~ "{bedrag}, {naam} en {bedrijf}; bij een factuur ook {vervaldatum}, bij een " +#~ "offerte {geldig_tot}." +#~ msgstr "" +#~ "Every mail starts with this. You can still change it per mail. Leave a " +#~ "field empty and Huismus uses its own text. Placeholders: {nummer}, " +#~ "{bedrag}, {naam} and {bedrijf}; for an invoice also {vervaldatum}, for a " +#~ "quote {geldig_tot}." + +#~ msgid "Nog geen dienst gekozen" +#~ msgstr "No service chosen yet" + +#, python-format +#~ msgid "waarvan %(count)s vervallen" +#~ msgid_plural "waarvan %(count)s vervallen" +#~ msgstr[0] "of which %(count)s overdue" +#~ msgstr[1] "of which %(count)s overdue" + +#~ msgid "Vervallen" +#~ msgstr "Overdue" + +#~ msgid "betekent: vervaldatum voorbij en nog niet volledig betaald." +#~ msgstr "means: past the due date and not fully paid yet." + +#~ msgid "Nieuwe categorie, bijvoorbeeld Verzekeringen" +#~ msgstr "New category, e.g. Insurance" + #~ msgid "Je krijgt nog" #~ msgstr "Still to receive" diff --git a/huismus/locale/nl/LC_MESSAGES/django.po b/huismus/locale/nl/LC_MESSAGES/django.po index f8cfa62..a3d8495 100644 --- a/huismus/locale/nl/LC_MESSAGES/django.po +++ b/huismus/locale/nl/LC_MESSAGES/django.po @@ -5,7 +5,7 @@ msgid "" msgstr "" "Project-Id-Version: huismus\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-15 17:45+0100\n" +"POT-Creation-Date: 2026-11-15 19:01+0100\n" "PO-Revision-Date: 2026-09-25 08:36+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -188,6 +188,22 @@ msgid "" "geen btw in rekening gebracht." msgstr "" +msgid "Volgnummer van je volgende factuur" +msgstr "" + +msgid "" +"Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste factuur " +"komt." +msgstr "" + +msgid "Volgnummer van je volgende offerte" +msgstr "" + +msgid "" +"Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste offerte " +"komt." +msgstr "" + msgid "Factuur" msgstr "" @@ -197,6 +213,9 @@ msgstr "" msgid "Offerte" msgstr "" +msgid "Herinnering" +msgstr "" + msgid "onderwerp in het Nederlands" msgstr "" @@ -411,6 +430,18 @@ msgstr "" msgid "tekst offerte (engels)" msgstr "" +msgid "onderwerp herinnering (nederlands)" +msgstr "" + +msgid "tekst herinnering (nederlands)" +msgstr "" + +msgid "onderwerp herinnering (engels)" +msgstr "" + +msgid "tekst herinnering (engels)" +msgstr "" + msgid "organisatie" msgstr "" @@ -1638,30 +1669,45 @@ msgid "Offerte {nummer} van {bedrijf}" msgstr "" #, python-brace-format -msgid "In de bijlage vind je factuur {nummer} van {bedrag}." +msgid "Herinnering: factuur {nummer} van {bedrijf}" msgstr "" #, python-brace-format -msgid "In de bijlage vind je creditnota {nummer} van {bedrag}." +msgid "Beste {naam}," msgstr "" #, python-brace-format -msgid "In de bijlage vind je offerte {nummer} van {bedrag}." +msgid "" +"Van factuur {nummer} staat nog {openstaand} open. De vervaldatum was " +"{vervaldatum}. In de bijlage vind je de factuur." +msgstr "" + +msgid "" +"Wil je het bedrag zo snel mogelijk overmaken? Heb je al betaald, dan kun je " +"deze mail vergeten." +msgstr "" + +msgid "Met vriendelijke groet," msgstr "" #, python-brace-format -msgid "Wil je hem uiterlijk {vervaldatum} betalen?" +msgid "In de bijlage vind je factuur {nummer} van {bedrag}." msgstr "" #, python-brace-format -msgid "De offerte is geldig tot {geldig_tot}." +msgid "In de bijlage vind je creditnota {nummer} van {bedrag}." msgstr "" #, python-brace-format -msgid "Beste {naam}," +msgid "In de bijlage vind je offerte {nummer} van {bedrag}." msgstr "" -msgid "Met vriendelijke groet," +#, python-brace-format +msgid "Wil je hem uiterlijk {vervaldatum} betalen?" +msgstr "" + +#, python-brace-format +msgid "De offerte is geldig tot {geldig_tot}." msgstr "" msgid "offerte" @@ -1823,6 +1869,9 @@ msgstr "" msgid "fout" msgstr "" +msgid "herinnering" +msgstr "" + msgid "verstuurde e-mail" msgstr "" @@ -1835,6 +1884,22 @@ msgstr "" msgid "[klantnummer]" msgstr "" +msgid "Het volgnummer is minstens 1." +msgstr "" + +msgid "" +"Je hebt in Huismus al een nummer uitgegeven. Het nummer loopt nu vanzelf " +"door." +msgstr "" + +#, python-format +msgid "Kies %(lowest)s of hoger. Een lager nummer bestaat al." +msgstr "" + +#, python-format +msgid "Nummer %(number)s bestaat al. Kies een hoger volgnummer." +msgstr "" + msgid "[nummer volgt]" msgstr "" @@ -1922,6 +1987,14 @@ msgstr "" msgid "De betaling is niet opgeslagen. Kijk het bedrag en de datum na." msgstr "" +#, python-format +msgid "Factuur %(number)s is niet te laat. Er is geen herinnering gestuurd." +msgstr "" + +#, python-format +msgid "Herinnering gestuurd naar %(to)s." +msgstr "" + #, python-format msgid "Gemaild naar %(to)s." msgstr "" @@ -2108,12 +2181,15 @@ msgstr "" msgid "uitgaveregels" msgstr "" -msgid "Uitgave nagekeken." +msgid "Bonnetje bewaard. Je vindt het bij Verwerken." msgstr "" msgid "Uitgave opgeslagen." msgstr "" +msgid "Uitgave nagekeken." +msgstr "" + msgid "Niet gelezen: dit lijkt geen bonnetje." msgstr "" @@ -2324,7 +2400,8 @@ msgstr "" #, python-format msgid "" "%(unparsed)s van %(total)s geïmporteerde %(label)s passen niet in het " -"ingestelde nummerformaat. Stel het volgende nummer zelf in bij Instellingen." +"ingestelde nummerformaat. Stel het volgende nummer zelf in bij Instellingen " +"→ Facturen en nummering." msgstr "" #, python-format @@ -2803,6 +2880,18 @@ msgstr "" msgid "nieuw" msgstr "" +msgid "Bonnetje uploaden…" +msgstr "" + +msgid "Huismus is niet bereikbaar. Probeer het opnieuw als je verbinding hebt." +msgstr "" + +msgid "Opnieuw proberen" +msgstr "" + +msgid "Het uploaden is mislukt. Probeer het nog een keer." +msgstr "" + msgid "Niet gekoppeld" msgstr "" @@ -2887,6 +2976,16 @@ msgstr "" msgid "Instellen" msgstr "" +#, python-format +msgid "Volgende als je vandaag uitgeeft: %(number)s" +msgstr "" + +msgid "Het nummer loopt vanzelf door sinds je eerste factuur in Huismus." +msgstr "" + +msgid "Het nummer loopt vanzelf door sinds je eerste offerte in Huismus." +msgstr "" + msgid "De taal van nieuwe facturen kies je bij Facturen en nummering." msgstr "" @@ -3266,10 +3365,6 @@ msgstr "" msgid "Standaard betalingstermijn" msgstr "" -#, python-format -msgid "Volgende als je vandaag uitgeeft: %(number)s" -msgstr "" - #, python-brace-format msgid "" "In een nummerformaat staat {year} voor het jaar, {seq:04d} voor het " @@ -3334,8 +3429,9 @@ msgstr "" msgid "" "Hiermee begint elke mail. Per mail kun je hem nog aanpassen. Maak je een " "veld leeg, dan gebruikt Huismus zijn eigen tekst. Invulplekken: {nummer}, " -"{bedrag}, {naam} en {bedrijf}; bij een factuur ook {vervaldatum}, bij een " -"offerte {geldig_tot}." +"{bedrag}, {naam} en {bedrijf}; bij een factuur en een herinnering ook " +"{vervaldatum}, bij een herinnering {openstaand}, bij een offerte " +"{geldig_tot}." msgstr "" #, python-format @@ -3374,6 +3470,14 @@ msgstr "" msgid "Nieuwe versie downloaden" msgstr "" +#, python-format +msgid "" +"Deze versie vraagt macOS %(macos)s of nieuwer. Je Mac heeft macOS " +"%(this_macos)s. Werk eerst macOS bij via Systeeminstellingen → Algemeen → " +"Software-update. Daarna installeert Huismus de nieuwe versie de volgende " +"keer dat je hem opent." +msgstr "" + msgid "Hij wordt geïnstalleerd als je Huismus opnieuw opent." msgstr "" @@ -3686,6 +3790,12 @@ msgstr "" msgid "Wat is er nieuw" msgstr "" +#, python-format +msgid "" +"Huismus %(version)s is er, maar vraagt macOS %(macos)s of nieuwer. Werk " +"eerst macOS bij." +msgstr "" + #, python-format msgid "" "Huismus %(version)s staat klaar. Hij wordt geïnstalleerd als je Huismus " @@ -3796,9 +3906,6 @@ msgid "" "en probeer het opnieuw." msgstr "" -msgid "Opnieuw proberen" -msgstr "" - #, python-format msgid "Stap %(number)s van %(total)s" msgstr "" @@ -3997,6 +4104,14 @@ msgstr "" msgid "Regel verwijderen" msgstr "" +#, python-format +msgid "Herinnering voor factuur %(number)s" +msgstr "" + +#, python-format +msgid "%(kind)s %(number)s mailen" +msgstr "" + msgid "Vervaldatum voorbij en nog niet volledig betaald." msgstr "" @@ -4104,6 +4219,14 @@ msgstr "" msgid "Betaling %(amount)s" msgstr "" +#, python-format +msgid "Herinnering gestuurd naar %(to)s" +msgstr "" + +#, python-format +msgid "Herinnering sturen mislukt naar %(to)s" +msgstr "" + #, python-format msgid "Gemaild naar %(to)s" msgstr "" @@ -4135,6 +4258,9 @@ msgstr "" msgid "uitgegeven op %(date)s" msgstr "" +msgid "Herinnering sturen" +msgstr "" + msgid "Creditnota maken…" msgstr "" @@ -4193,6 +4319,10 @@ msgstr "" msgid "Betaalstatus" msgstr "" +#, python-format +msgid "Laatste herinnering: %(date)s" +msgstr "" + msgid "Afgehandeld" msgstr "" @@ -4462,10 +4592,6 @@ msgstr "" msgid "Te laat betekent: vervaldatum voorbij en nog niet volledig betaald." msgstr "" -#, python-format -msgid "%(kind)s %(number)s mailen" -msgstr "" - #, python-format msgid "" "Stel bij Instellingen in hoe Huismus mailt." @@ -4774,6 +4900,24 @@ msgstr "" msgid "betekent dat er een bonnetje bij de uitgave zit." msgstr "" +msgid "Opnieuw" +msgstr "" + +msgid "Foto versturen" +msgstr "" + +msgid "Bedrag, zoals je het betaalde" +msgstr "" + +msgid "Meer regels of een omschrijving" +msgstr "" + +msgid "Uitgave opslaan" +msgstr "" + +msgid "Alleen de foto bewaren" +msgstr "" + msgid "Verwerken" msgstr "" @@ -6092,3 +6236,9 @@ msgid "" "Heb je een Raspberry Pi, een NAS, een eigen server of een VPS, dan kun je " "Huismus ook in Docker draaien. Dat is voor wie daar handig mee is." msgstr "" + +#, python-format +#~ msgid "%(count)s dag te laat" +#~ msgid_plural "%(count)s dagen te laat" +#~ msgstr[0] "%(count)s dag te laat" +#~ msgstr[1] "%(count)s dagen te laat" diff --git a/huismus/templates/base.html b/huismus/templates/base.html index 4e6576a..1343330 100644 --- a/huismus/templates/base.html +++ b/huismus/templates/base.html @@ -111,6 +111,19 @@
{% translate "Facturen en uitgaven voor zzp'ers, met of zonder KOR" %}{% translate "Sneltoetsen:" %} N {% translate "nieuw" %}{% block shortcut_search %}{% endblock %}
+{% if user.is_authenticated and not desktop %} +{% comment %}On a phone every "Uitgave" opens the camera, and the photo goes +here (#188; app.js, "The photo first"; expenses/photo_views.py). Without JS +this stays hidden and unused: the link goes to the ordinary form. Never in +the desktop app, even in a narrow window on a touch screen.{% endcomment %} + + + + +{% endif %} {% include "core/_toasts.html" %} {% endblock %} diff --git a/huismus/templates/business/_number_formats.html b/huismus/templates/business/_number_formats.html new file mode 100644 index 0000000..476bc46 --- /dev/null +++ b/huismus/templates/business/_number_formats.html @@ -0,0 +1,18 @@ +{% load i18n forms %} +{% comment %}The invoice and quote number formats, each with the next sequence number under it while +Huismus has not given a number of that kind yet (issue #141; business.forms.SettingsPartForm). +A column per kind, so the next number stays under its own format. Used on Instellingen → +Facturen en nummering and in the start's Facturen step; the form's fields must name +next_invoice_number and next_quote_number (topics.py, core/onboarding.py).{% endcomment %} +
+ {% if next_invoice %}{% blocktranslate asvar invoice_next with number=next_invoice %}Volgende als je vandaag uitgeeft: {{ number }}{% endblocktranslate %}{% endif %} + {% field form.invoice_number_format extra_class="mono" help=invoice_next %} + {% if form.fixed_sequences.invoice %}

{% translate "Het nummer loopt vanzelf door sinds je eerste factuur in Huismus." %}

+ {% else %}{% field form.next_invoice_number extra_class="num" %}{% endif %} +
+
+ {% if next_quote %}{% blocktranslate asvar quote_next with number=next_quote %}Volgende als je vandaag uitgeeft: {{ number }}{% endblocktranslate %}{% endif %} + {% field form.quote_number_format extra_class="mono" help=quote_next %} + {% if form.fixed_sequences.quote %}

{% translate "Het nummer loopt vanzelf door sinds je eerste offerte in Huismus." %}

+ {% else %}{% field form.next_quote_number extra_class="num" %}{% endif %} +
diff --git a/huismus/templates/business/topic.html b/huismus/templates/business/topic.html index 687d9c5..36fc0cf 100644 --- a/huismus/templates/business/topic.html +++ b/huismus/templates/business/topic.html @@ -73,10 +73,7 @@

{{ topic.title }}

{% translate "dagen" as days_unit %} {% translate "Standaard betalingstermijn" as terms_label %} {% field form.default_payment_terms_days span=2 extra_class="num" suffix=days_unit label=terms_label %} - {% if next_invoice_number %}{% blocktranslate asvar invoice_next with number=next_invoice_number %}Volgende als je vandaag uitgeeft: {{ number }}{% endblocktranslate %}{% endif %} - {% field form.invoice_number_format span=2 extra_class="mono" help=invoice_next %} - {% if next_quote_number %}{% blocktranslate asvar quote_next with number=next_quote_number %}Volgende als je vandaag uitgeeft: {{ number }}{% endblocktranslate %}{% endif %} - {% field form.quote_number_format span=2 extra_class="mono" help=quote_next %} + {% include "business/_number_formats.html" with next_invoice=next_invoice_number next_quote=next_quote_number %}

{% translate "In een nummerformaat staat {year} voor het jaar, {seq:04d} voor het volgnummer met vier cijfers en {customer} voor het klantnummer." %}

@@ -145,7 +142,7 @@

{{ topic.title }}

{% endif %}

{% translate "Standaardteksten" %}

-

{% translate "Hiermee begint elke mail. Per mail kun je hem nog aanpassen. Maak je een veld leeg, dan gebruikt Huismus zijn eigen tekst. Invulplekken: {nummer}, {bedrag}, {naam} en {bedrijf}; bij een factuur ook {vervaldatum}, bij een offerte {geldig_tot}." %}

+

{% translate "Hiermee begint elke mail. Per mail kun je hem nog aanpassen. Maak je een veld leeg, dan gebruikt Huismus zijn eigen tekst. Invulplekken: {nummer}, {bedrag}, {naam} en {bedrijf}; bij een factuur en een herinnering ook {vervaldatum}, bij een herinnering {openstaand}, bij een offerte {geldig_tot}." %}

{% for block in mail_text_blocks %}
diff --git a/huismus/templates/business/updates.html b/huismus/templates/business/updates.html index 78031bd..093e58d 100644 --- a/huismus/templates/business/updates.html +++ b/huismus/templates/business/updates.html @@ -26,7 +26,7 @@

{% translate "Updates" %}

{% blocktranslate with version=release.version %}Huismus {{ version }} is er{% endblocktranslate %}

- {% if waiting %}

{% translate "Hij wordt geïnstalleerd als je Huismus opnieuw opent." %}

{% elif downloading %}

{% translate "Hij wordt nu gedownload. Daarna wordt hij geïnstalleerd als je Huismus opnieuw opent." %}

{% endif %} + {% if needs_macos %}

{% blocktranslate with macos=needs_macos %}Deze versie vraagt macOS {{ macos }} of nieuwer. Je Mac heeft macOS {{ this_macos }}. Werk eerst macOS bij via Systeeminstellingen → Algemeen → Software-update. Daarna installeert Huismus de nieuwe versie de volgende keer dat je hem opent.{% endblocktranslate %}

{% elif waiting %}

{% translate "Hij wordt geïnstalleerd als je Huismus opnieuw opent." %}

{% elif downloading %}

{% translate "Hij wordt nu gedownload. Daarna wordt hij geïnstalleerd als je Huismus opnieuw opent." %}

{% endif %}

{% blocktranslate with version=release.version %}Wat is er nieuw in {{ version }}?{% endblocktranslate %}

{% if docker %} {% comment %}Docker: no button, Huismus says what to type (core.update_views._docker).{% endcomment %} @@ -38,7 +38,7 @@

{% blocktranslate with version=release.version %}Huismus {{ version }} is er
docker compose pull
 docker compose up -d

{% translate "Meer over bijwerken in Docker" %}

- {% else %} + {% elif not needs_macos %} {% endif %}

diff --git a/huismus/templates/core/home.html b/huismus/templates/core/home.html index 56b5b72..9a266cb 100644 --- a/huismus/templates/core/home.html +++ b/huismus/templates/core/home.html @@ -80,7 +80,9 @@

{{ greeting }}{% if user.first_name %}, {{ user.first_name }}{% endif %}

- {% if release_waiting %} + {% if release_needs_macos %} + {% blocktranslate with version=new_release.version macos=release_needs_macos %}Huismus {{ version }} is er, maar vraagt macOS {{ macos }} of nieuwer. Werk eerst macOS bij.{% endblocktranslate %} + {% elif release_waiting %} {% blocktranslate with version=new_release.version %}Huismus {{ version }} staat klaar. Hij wordt geïnstalleerd als je Huismus opnieuw opent.{% endblocktranslate %} {% elif release_downloading %} {% blocktranslate with version=new_release.version %}Huismus {{ version }} is gevonden en wordt gedownload.{% endblocktranslate %} diff --git a/huismus/templates/core/onboarding.html b/huismus/templates/core/onboarding.html index 8b25f33..d4db936 100644 --- a/huismus/templates/core/onboarding.html +++ b/huismus/templates/core/onboarding.html @@ -54,10 +54,7 @@

{{ step.title }}

{% translate "dagen" as days_unit %} {% translate "Standaard betalingstermijn" as terms_label %} {% field form.default_payment_terms_days span=2 extra_class="num" suffix=days_unit label=terms_label %} - {% if next_numbers.invoice %}{% blocktranslate asvar invoice_next with number=next_numbers.invoice %}Volgende als je vandaag uitgeeft: {{ number }}{% endblocktranslate %}{% endif %} - {% field form.invoice_number_format span=2 extra_class="mono" help=invoice_next %} - {% if next_numbers.quote %}{% blocktranslate asvar quote_next with number=next_numbers.quote %}Volgende als je vandaag uitgeeft: {{ number }}{% endblocktranslate %}{% endif %} - {% field form.quote_number_format span=2 extra_class="mono" help=quote_next %} + {% include "business/_number_formats.html" with next_invoice=next_numbers.invoice next_quote=next_numbers.quote %}

{% translate "In een nummerformaat staat {year} voor het jaar, {seq:04d} voor het volgnummer met vier cijfers en {customer} voor het klantnummer." %}

{% elif step.slug == "logo" %} diff --git a/huismus/templates/documents/_mail_heading.html b/huismus/templates/documents/_mail_heading.html new file mode 100644 index 0000000..cac03c9 --- /dev/null +++ b/huismus/templates/documents/_mail_heading.html @@ -0,0 +1 @@ +{% load i18n %}{% comment %}The title of the mail page: "Factuur 2026-0012 mailen", or for a payment reminder (#114) "Herinnering voor factuur 2026-0012".{% endcomment %}{% if reminder %}{% blocktranslate with number=document.number %}Herinnering voor factuur {{ number }}{% endblocktranslate %}{% else %}{% blocktranslate asvar heading with kind=document.get_kind_display number=document.number %}{{ kind }} {{ number }} mailen{% endblocktranslate %}{{ heading|capfirst }}{% endif %} \ No newline at end of file diff --git a/huismus/templates/documents/_timeline.html b/huismus/templates/documents/_timeline.html index 76575ce..cafc97c 100644 --- a/huismus/templates/documents/_timeline.html +++ b/huismus/templates/documents/_timeline.html @@ -13,6 +13,8 @@

{% translate "Tijdlijn" %}

{% elif event.kind == "declined" %}
{% translate "Afgewezen" %}
{% elif event.kind == "reopened" %}
{% translate "Heropend om te bewerken" %}
{% elif event.kind == "payment" %}
{% blocktranslate with amount=event.payment.amount_cents|money %}Betaling {{ amount }}{% endblocktranslate %}
+ {% elif event.kind == "email" and event.email.reminder and event.email.succeeded %}
{% blocktranslate with to=event.email.to %}Herinnering gestuurd naar {{ to }}{% endblocktranslate %}
+ {% elif event.kind == "email" and event.email.reminder %}
{% blocktranslate with to=event.email.to %}Herinnering sturen mislukt naar {{ to }}{% endblocktranslate %}
{{ event.email.plain_error }}
{{ event.email.error }}
{% elif event.kind == "email" and event.email.succeeded %}
{% blocktranslate with to=event.email.to %}Gemaild naar {{ to }}{% endblocktranslate %}
{% elif event.kind == "email" %}
{% blocktranslate with to=event.email.to %}Mailen mislukt naar {{ to }}{% endblocktranslate %}
{{ event.email.plain_error }}
{{ event.email.error }}
{% elif event.kind == "credit_note" %}{% endif %} diff --git a/huismus/templates/documents/detail.html b/huismus/templates/documents/detail.html index b39ae5b..85a5dee 100644 --- a/huismus/templates/documents/detail.html +++ b/huismus/templates/documents/detail.html @@ -20,6 +20,10 @@

{{ document.get_kind_display|capfirst }} {{ document.number }}

{{ customer.display_name }} · {% blocktranslate with date=document.issue_date|date:"SHORT_DATE_FORMAT" %}uitgegeven op {{ date }}{% endblocktranslate %}
+ {% if document.days_overdue is not None %} + {% comment %}The main action of an overdue invoice (#114, owner 2026-11-15).{% endcomment %} + {% translate "Herinnering sturen" %} + {% endif %} {% if document.kind == "invoice" and credited_cents < document.total_cents %} {% endif %} @@ -109,10 +113,15 @@

{% translate "Betaalstatus" %}

{% if document.is_overdue %}{% include "documents/_pill_overdue.html" with doc=document full=True %} {% else %}{{ document.payment_state|payment_state_label|capfirst }}{% endif %}
+ {% comment %}How late it is stands in the pill above; here only when the last reminder went.{% endcomment %} + {% if last_reminder %} +

{% blocktranslate with date=last_reminder.sent_at|date:"SHORT_DATE_FORMAT" %}Laatste herinnering: {{ date }}{% endblocktranslate %}

+ {% endif %}
{% with invoice=document %}{% include "documents/_credit_room.html" %}{% endwith %} {% if outstanding_cents > 0 %} - + {% comment %}Secondary on an overdue invoice: there the reminder is the main action.{% endcomment %} + {% endif %} diff --git a/huismus/templates/documents/mail.html b/huismus/templates/documents/mail.html index 0324b9a..b5087de 100644 --- a/huismus/templates/documents/mail.html +++ b/huismus/templates/documents/mail.html @@ -1,14 +1,14 @@ {% extends "base.html" %} {% load i18n forms %} -{% block title %}{% blocktranslate asvar heading with kind=document.get_kind_display number=document.number %}{{ kind }} {{ number }} mailen{% endblocktranslate %}{{ heading|capfirst }} — Huismus{% endblock %} +{% block title %}{% include "documents/_mail_heading.html" %} — Huismus{% endblock %} {% block content %} -{% comment %}Mailing a document (SPEC.md M10): a plain POST form, works without JS. Nothing here changes the document.{% endcomment %} +{% comment %}Mailing a document (SPEC.md M10), or a payment reminder for an overdue invoice (#114): a plain POST form, works without JS. Nothing here changes the document.{% endcomment %}
{{ document.get_kind_display|capfirst }} {{ document.number }} -

{% blocktranslate asvar heading with kind=document.get_kind_display number=document.number %}{{ kind }} {{ number }} mailen{% endblocktranslate %}{{ heading|capfirst }}

+

{% include "documents/_mail_heading.html" %}

diff --git a/huismus/templates/expenses/form.html b/huismus/templates/expenses/form.html index 8620bf6..042903b 100644 --- a/huismus/templates/expenses/form.html +++ b/huismus/templates/expenses/form.html @@ -93,7 +93,7 @@

{% translate "Dit bonnetje verw Bonnetjes section above the form, with its own upload.{% endcomment %} {% if new_receipt_form %}{% with field=new_receipt_form.file %}
-

{% translate "Bonnetje" %} ({% translate "optioneel" %})

+

{% translate "Bonnetje" %}

{% endif %} {% if r.numbering_note %} -
{% translate "Nummering" %}{{ r.numbering_note }}
+
{% translate "Nummering" %}{{ r.numbering_note }} {% translate "Facturen en nummering" %} →
{% endif %}

diff --git a/tests/business/test_next_number_field.py b/tests/business/test_next_number_field.py new file mode 100644 index 0000000..6167a44 --- /dev/null +++ b/tests/business/test_next_number_field.py @@ -0,0 +1,127 @@ +# SPDX-FileCopyrightText: 2026 Huismus contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +"""The next number by hand on Facturen en nummering and in the start's +Facturen step (issue #141). The rules themselves: tests/documents/test_next_number.py.""" + +from datetime import date + +import pytest +from django.urls import reverse +from django.utils import timezone + +from huismus.documents.issuing import issue +from huismus.documents.numbering import next_sequence_number +from tests.business.test_views import _login, _valid_form_data +from tests.documents.test_issuing import _settings +from tests.documents.test_next_number import _draft, _imported + +pytestmark = pytest.mark.django_db + +PAGE = reverse("business:topic", args=["facturen"]) +YEAR = timezone.localdate().year + + +def _facturen(**overrides): + names = ( + "default_payment_terms_days", + "invoice_number_format", + "quote_number_format", + "number_reset_yearly", + "default_language", + "currency", + ) + data = {name: value for name, value in _valid_form_data().items() if name in names} + data.update({"next_invoice_number": "1", "next_quote_number": "1"}) + data.update(overrides) + return data + + +def test_the_page_shows_the_next_sequence_numbers(client): + _login(client) + page = client.get(PAGE).content.decode() + + assert 'name="next_invoice_number"' in page + assert 'name="next_quote_number"' in page + assert "Volgnummer van je volgende factuur" in page + + +def test_saving_sets_the_next_invoice_number(client): + _login(client) + response = client.post(PAGE, _facturen(next_invoice_number="43", next_quote_number="12")) + + assert response.status_code == 302 + assert next_sequence_number("invoice", year=YEAR) == 43 + assert next_sequence_number("quote", year=YEAR) == 12 + page = client.get(PAGE).content.decode() + assert f"Volgende als je vandaag uitgeeft: {YEAR}-0043" in page + assert 'value="43"' in page + + +def test_the_new_format_counts_in_the_same_save(client): + # Format and number in one save: the existing-number check uses the + # format being saved. + _login(client) + _imported(f"F-{YEAR}-0043", issue_date=date(YEAR, 1, 2)) + + response = client.post( + PAGE, _facturen(invoice_number_format="F-{year}-{seq:04d}", next_invoice_number="40") + ) + + assert "Kies 44 of hoger" in response.content.decode() + assert next_sequence_number("invoice", year=YEAR) == 1 + + +def test_a_refused_number_saves_nothing_else(client): + _login(client) + _imported(f"{YEAR}-0050", issue_date=date(YEAR, 1, 2)) + + response = client.post( + PAGE, _facturen(next_invoice_number="50", default_payment_terms_days="30") + ) + + assert response.status_code == 200 + assert response.context["form"].errors["next_invoice_number"] + assert client.get(PAGE).context["form"]["default_payment_terms_days"].value() != 30 + + +def test_once_an_invoice_is_issued_the_field_is_gone(client): + _login(client) + _settings() + issue(_draft(issue_date=timezone.localdate())) + + page = client.get(PAGE).content.decode() + + assert 'name="next_invoice_number"' not in page + assert "Het nummer loopt vanzelf door sinds je eerste factuur in Huismus." in page + assert 'name="next_quote_number"' in page + # Saving the rest still works, and a sent field is ignored. + response = client.post(PAGE, _facturen(next_invoice_number="99")) + assert response.status_code == 302 + assert next_sequence_number("invoice", year=YEAR) == 2 + + +def test_the_start_has_the_field_too(client): + _login(client) + step = reverse("onboarding", args=["facturen"]) + assert 'name="next_invoice_number"' in client.get(step).content.decode() + + response = client.post( + step, + { + "default_payment_terms_days": "14", + "invoice_number_format": "{year}-{seq:04d}", + "quote_number_format": "OFF-{year}-{seq:04d}", + "next_invoice_number": "128", + "next_quote_number": "1", + }, + ) + + assert response.status_code == 302 + assert next_sequence_number("invoice", year=YEAR) == 128 + + +def test_in_english(client): + _login(client) + page = client.get(PAGE, headers={"accept-language": "en"}).content.decode() + + assert "Sequence number of your next invoice" in page diff --git a/tests/core/test_update_views.py b/tests/core/test_update_views.py index 7e01bd1..e3b2061 100644 --- a/tests/core/test_update_views.py +++ b/tests/core/test_update_views.py @@ -228,6 +228,68 @@ def test_a_failed_update_says_why_on_the_updates_page(desktop, code, sentence): assert 'id="bijwerken-mislukt"' in page and sentence in page +# -- A version for a newer macOS (issue #155; huismus-intern/besluiten.md, 2026-11-13) + + +@pytest.fixture +def needs_15(desktop, monkeypatch, tmp_path): + """1.4.0 downloaded ahead, asking macOS 15.0, on a Mac with 14.6.""" + package = tmp_path / "Huismus-1.4.0-macos.dmg" + package.write_bytes(b"dmg") + updates.update_status( + available=RELEASE, + downloaded={ + "version": "1.4.0", + "path": str(package), + "sha256": RELEASE["sha256"], + "minimum_os": "15.0", + }, + ) + monkeypatch.setattr(updates, "this_macos", lambda: "14.6") + return desktop + + +def test_the_overview_says_to_update_macos_first(needs_15): + page = _overview(needs_15) + assert "Huismus 1.4.0 is er, maar vraagt macOS 15 (Sequoia) of nieuwer." in page + assert "Werk eerst macOS bij." in page + assert "staat klaar" not in page and "wordt gedownload" not in page + + +def test_updates_says_which_macos_and_offers_no_button(needs_15): + page = needs_15.get(reverse("business:updates")).content.decode() + assert "Deze versie vraagt macOS 15 (Sequoia) of nieuwer. Je Mac heeft macOS 14.6." in page + assert "Systeeminstellingen → Algemeen → Software-update" in page + assert "Wat is er nieuw in 1.4.0?" in page + assert "Bijwerken naar 1.4.0" not in page + assert needs_15.get(reverse("business:updates_install")).url == reverse("business:updates") + + +def test_in_english_too(needs_15): + needs_15.cookies["django_language"] = "en" + assert "Huismus 1.4.0 is out, but needs macOS 15 (Sequoia) or later." in _overview(needs_15) + page = needs_15.get(reverse("business:updates")).content.decode() + assert "This version needs macOS 15 (Sequoia) or later. Your Mac has macOS 14.6." in page + + +def test_bijwerken_for_a_newer_macos_is_no_error(desktop, monkeypatch): + # Not downloaded ahead (looking happened, downloading not yet): the + # button finds out, and Updates then says what to do, without a red + # message (huismus-intern/besluiten.md, 2026-11-13). + updates.update_status(available=RELEASE) + monkeypatch.setattr(updates, "this_macos", lambda: "14.6") + + def asks_15(release): + updates.update_status(downloaded={"version": "1.4.0", "path": "", "minimum_os": "15"}) + raise updates.NeedsNewerMacOS + + with patch("huismus.core.updates.install", side_effect=asks_15): + response = desktop.post(reverse("business:updates_install"), follow=True) + page = response.content.decode() + assert 'id="bijwerken-mislukt"' not in page + assert "Deze versie vraagt macOS 15 (Sequoia) of nieuwer." in page + + # -- "Huismus is bijgewerkt" (issue #149; huismus-intern/besluiten.md, 2026-11-12) UPDATED = "Huismus is bijgewerkt naar 1.3.0." diff --git a/tests/core/test_updates.py b/tests/core/test_updates.py index 5c7535c..e22395a 100644 --- a/tests/core/test_updates.py +++ b/tests/core/test_updates.py @@ -427,6 +427,133 @@ def test_after_a_failed_automatic_install_it_doesnt_say_downloading(found): assert updates.downloading() is None +# -- A version for a newer macOS (issue #155) ----------------------------------- +# 0.1.4 asked macOS 15 instead of 14; a 0.1.3 app on macOS 14 updated itself +# and didn't open any more. The Mac app now reads the downloaded app's +# LSMinimumSystemVersion first (desktop/updater.py) and leaves the current +# version in place on an older macOS. + + +@pytest.fixture +def needs_15(found, monkeypatch): + """1.4.0 found on a Mac with macOS 14.6.1, and it asks macOS 15.0.""" + read = [] + monkeypatch.setattr(updates, "minimum_os", lambda package: read.append(package) or "15.0") + monkeypatch.setattr(updates, "this_macos", lambda: "14.6.1") + return read + + +def test_macos_versions_compare_as_numbers(): + assert updates.older_macos("14.6.1", "15.0") + assert updates.older_macos("10.15", "10.9") is False + assert updates.older_macos("15", "15.0") is False + assert updates.older_macos("15.0.1", "15.0") is False + assert updates.older_macos("26.1", "15.0") is False + assert updates.older_macos("15.7", "26") is True + # Unknown: as before, nothing is held back. + assert updates.older_macos("", "15.0") is False + assert updates.older_macos("14.6", "") is False + assert updates.older_macos("14.6", "fifteen") is False + + +def test_the_minimum_macos_is_read_after_downloading(needs_15): + updates.prepare() + + assert needs_15 == [Path(updates.load_status().downloaded["path"])] + assert updates.load_status().downloaded["minimum_os"] == "15.0" + + +def test_a_version_for_a_newer_macos_waits_and_says_which(needs_15): + updates.prepare() + + assert updates.needs_macos() == "15" + assert updates.waiting() is None + assert updates.downloading() is None + # Kept: it's installed once macOS is up to date. + assert Path(updates.load_status().downloaded["path"]).exists() + + +def test_a_version_for_a_newer_macos_is_not_installed_at_start(needs_15, monkeypatch): + updates.prepare() + handed = [] + monkeypatch.setattr(updates, "installer", lambda *args: handed.append(args)) + + with patch("huismus.core.auto_backups.safety_backup") as backup: + assert updates.install_at_start() is False + + assert handed == [] + backup.assert_not_called() + status = updates.load_status() + # Not a failure: nothing to say "niet gelukt" about, and it's tried + # again after macOS is updated. + assert status.not_installed == "" and status.auto_failed == "" + + +@pytest.mark.django_db(transaction=True) +def test_after_updating_macos_it_is_installed_at_start(needs_15, monkeypatch): + updates.prepare() + monkeypatch.setattr(updates, "this_macos", lambda: "15.1") + handed = [] + monkeypatch.setattr(updates, "installer", lambda *args: handed.append(args)) + + assert updates.needs_macos() == "" + assert updates.install_at_start() is True + assert handed + + +def test_bijwerken_refuses_a_version_for_a_newer_macos(needs_15, monkeypatch): + # Not downloaded ahead: the button downloads and reads it itself. + handed = [] + monkeypatch.setattr(updates, "installer", lambda *args: handed.append(args)) + + with ( + patch("huismus.core.auto_backups.safety_backup") as backup, + pytest.raises(updates.UpdateError, match="macos"), + ): + updates.install(updates.available()) + + assert handed == [] and updates.load_status().pending == {} + backup.assert_not_called() + # Kept, so the page can say which macOS it needs. + assert updates.needs_macos() == "15" + + +def test_an_even_newer_version_for_a_newer_macos_replaces_the_waiting_one(needs_15): + # Replacing the file itself: test_a_newer_release_replaces_the_waiting_one. + updates.prepare() + updates.update_status(available=updates.load_status().available | {"version": "1.5.0"}) + + updates.prepare() + + assert updates.load_status().downloaded["version"] == "1.5.0" + assert updates.needs_macos() == "15" and updates.waiting() is None + + +def test_an_app_that_cant_be_read_is_installed_as_before(found, monkeypatch): + def unreadable(package): + raise OSError("hdiutil failed") + + monkeypatch.setattr(updates, "minimum_os", unreadable) + monkeypatch.setattr(updates, "this_macos", lambda: "14.6.1") + updates.prepare() + + assert updates.needs_macos() == "" + assert updates.waiting() is not None + + +def test_a_macos_is_named_as_the_mac_names_it(): + assert updates.macos_label("15") == "15 (Sequoia)" + assert updates.macos_label("26") == "26 (Tahoe)" + assert updates.macos_label("27.1") == "27.1" + + +def test_without_a_minimum_reader_nothing_is_held_back(found, monkeypatch): + # Windows and Docker register none (desktop/app.py). + monkeypatch.setattr(updates, "this_macos", lambda: "14.6.1") + updates.prepare() + assert updates.needs_macos() == "" and updates.waiting() is not None + + # -- Docker: only a notice ------------------------------------------------------ # Huismus in Docker looks for a new version too and says so on the overview, # but never downloads or replaces anything: updating is the user's own diff --git a/tests/desktop/test_updater.py b/tests/desktop/test_updater.py index ff468fc..f983a52 100644 --- a/tests/desktop/test_updater.py +++ b/tests/desktop/test_updater.py @@ -4,6 +4,7 @@ what can run without a Mac. Replacing Huismus.app itself is checked by hand on a Mac (SPEC.md M11, "Done when").""" +import plistlib import subprocess from pathlib import Path, PureWindowsPath from unittest.mock import MagicMock, patch @@ -24,6 +25,7 @@ def _shell_hooks(monkeypatch): # never left behind for other tests. monkeypatch.setattr(updates, "installer", None) monkeypatch.setattr(updates, "precheck", None) + monkeypatch.setattr(updates, "minimum_os", None) def test_the_install_script_is_valid_shell_and_quotes_its_paths(tmp_path): @@ -49,6 +51,38 @@ def test_the_install_script_is_valid_shell_and_quotes_its_paths(tmp_path): updater.script(Path("/tmp/x.dmg"), "'; rm -rf ~; '", Path("/Applications/Huismus.app"), 1) +def _app_with(tmp_path, info): + contents = tmp_path / "Huismus.app" / "Contents" + contents.mkdir(parents=True) + with (contents / "Info.plist").open("wb") as file: + plistlib.dump(info, file) + return tmp_path / "Huismus.app" + + +def test_the_minimum_macos_comes_from_the_new_apps_info_plist(tmp_path): + # As desktop/huismus.spec writes it (issue #155). + app = _app_with(tmp_path, {"CFBundleName": "Huismus", "LSMinimumSystemVersion": "15.0"}) + assert updater.minimum_macos_of(app) == "15.0" + assert updater.minimum_macos_of(_app_with(tmp_path / "old", {})) == "" + + +def test_the_dmg_is_mounted_read_only_and_always_detached(tmp_path): + calls = [] + + def hdiutil(args, **kwargs): + calls.append(args) + if args[1] == "attach": + _app_with(Path(args[args.index("-mountpoint") + 1]), {"LSMinimumSystemVersion": "15.0"}) + return subprocess.CompletedProcess(args, 0) + + with patch("subprocess.run", side_effect=hdiutil): + assert updater.minimum_macos(tmp_path / "Huismus-1.4.0-macos.dmg") == "15.0" + + attach, detach = calls + assert "-readonly" in attach and "-nobrowse" in attach + assert detach[:2] == ["hdiutil", "detach"] + + def test_outside_a_packaged_app_there_is_nothing_to_replace(): assert updater.app_bundle() is None @@ -237,6 +271,15 @@ def test_at_start_a_waiting_version_is_installed_before_the_window_opens(data_di thread.assert_not_called() # no backup or check in a closing app +@pytest.mark.parametrize("platform, reader", [("darwin", updater.minimum_macos), ("win32", None)]) +def test_only_the_mac_app_reads_which_macos_a_version_needs( + data_dir, monkeypatch, platform, reader +): + monkeypatch.setattr("sys.platform", platform) + _booted(data_dir, installs=True) + assert updates.minimum_os is reader + + def test_without_a_waiting_version_the_window_opens_as_always(data_dir, monkeypatch): monkeypatch.setenv("HUISMUS_WINDOW_TOKEN", "t") shell, _, _ = _booted(data_dir, installs=False) diff --git a/tests/documents/test_mailing.py b/tests/documents/test_mailing.py index 3253c1d..0155c36 100644 --- a/tests/documents/test_mailing.py +++ b/tests/documents/test_mailing.py @@ -629,3 +629,164 @@ def test_the_mail_page_says_when_the_customer_wants_post(client_in): response = client_in.get(_mail_url(invoice)) assert "per post" in response.content.decode() + + +# --- Payment reminders (#114) --- + + +def _reminder_url(document): + return reverse("documents:reminder", args=[document.pk]) + + +def _remind(client, document, **data): + fields = {"to": "sanne@example.invalid", "subject": "Herinnering", "body": "Nog open.", **data} + return client.post(_reminder_url(document), fields) + + +def test_a_reminder_goes_out_with_the_invoice_pdf_and_is_logged_as_one(client_in): + invoice = _invoice() # due 15 March 2026, so overdue + + response = _remind(client_in, invoice) + + assert response.status_code == 302 + assert response.url == reverse("documents:edit", args=[invoice.pk]) + [message] = mail.outbox + assert message.attachments[0][0] == f"{invoice.number}.pdf" + [log] = EmailLog.objects.all() + assert log.reminder is True + assert log.succeeded + + +def test_an_ordinary_mail_is_no_reminder(client_in): + _post(client_in, _invoice()) + + assert EmailLog.objects.get().reminder is False + + +def test_a_reminder_leaves_the_invoice_as_it_was(client_in): + invoice = _invoice() + before = _as_stored(invoice) + + _remind(client_in, invoice) + + assert _as_stored(invoice) == before + + +def test_the_reminder_text_says_what_is_still_open(client_in): + from huismus.documents.models import Payment + + invoice = _invoice(language="nl") + Payment.objects.create(document=invoice, paid_on=datetime.date(2026, 3, 20), amount_cents=35000) + + initial = client_in.get(_reminder_url(invoice)).context["form"].initial + + assert initial["subject"] == f"Herinnering: factuur {invoice.number} van Voorbeeld BV" + assert initial["body"].startswith("Beste Sanne,") + assert "€\u00a0500,00" in initial["body"] # 850 minus the 350 paid + assert "15 maart 2026" in initial["body"] + assert initial["body"].rstrip().endswith("Voorbeeld BV") + + +def test_an_english_invoice_gets_the_english_reminder(client_in): + invoice = _invoice(language="en") + + initial = client_in.get(_reminder_url(invoice)).context["form"].initial + + assert initial["subject"] == f"Reminder: invoice {invoice.number} from Voorbeeld BV" + assert initial["body"].startswith("Dear Sanne,") + assert "15 March 2026" in initial["body"] + + +def test_the_reminder_text_from_the_settings_is_filled_in(client_in, business_settings): + business_settings.mail_reminder_subject_nl = "Nog open: {nummer}" + business_settings.mail_reminder_body_nl = "{openstaand} van {bedrag}, sinds {vervaldatum}." + business_settings.save() + invoice = _invoice(language="nl") + + initial = client_in.get(_reminder_url(invoice)).context["form"].initial + + assert initial["subject"] == f"Nog open: {invoice.number}" + assert initial["body"] == "€\u00a0850,00 van €\u00a0850,00, sinds 15 maart 2026." + + +@pytest.mark.parametrize("kind", ["draft", "credit_note", "quote"]) +def test_only_an_issued_invoice_has_a_reminder_form(client_in, kind): + if kind == "draft": + document = _draft() + elif kind == "credit_note": + document = issue(_draft(kind="credit_note", related_document=_invoice())) + else: + document = _quote() + + assert client_in.get(_reminder_url(document)).status_code == 404 + assert _remind(client_in, document).status_code == 404 + assert mail.outbox == [] + + +@pytest.mark.parametrize("state", ["paid", "not_due"]) +def test_an_invoice_that_is_not_overdue_gets_no_reminder(client_in, state): + from huismus.documents.models import Payment + + if state == "paid": + invoice = _invoice() + Payment.objects.create( + document=invoice, paid_on=datetime.date(2026, 3, 20), amount_cents=85000 + ) + else: + invoice = _invoice(due_date=datetime.date(2099, 1, 1)) + page = reverse("documents:edit", args=[invoice.pk]) + + for response in (client_in.get(_reminder_url(invoice)), _remind(client_in, invoice)): + assert (response.status_code, response.url) == (302, page) + assert mail.outbox == [] + shown = client_in.get(page).content.decode() + assert f"Factuur {invoice.number} is niet te laat. Er is geen herinnering gestuurd." in shown + + +def test_the_reminder_button_is_only_on_an_overdue_invoice(client_in): + overdue = _invoice() + not_due = _invoice(due_date=datetime.date(2099, 1, 1)) + + def page(document): + return client_in.get(reverse("documents:edit", args=[document.pk])).content.decode() + + assert _reminder_url(overdue) in page(overdue) + assert _reminder_url(not_due) not in page(not_due) + + +def test_the_invoice_shows_the_last_reminder_and_how_late_it_is(client_in): + invoice = _invoice(due_date=datetime.date.today() - datetime.timedelta(days=12)) + + page = client_in.get(reverse("documents:edit", args=[invoice.pk])).content.decode() + assert "12 dagen te laat" in page + assert "Laatste herinnering" not in page + + _remind(client_in, invoice) + page = client_in.get(reverse("documents:edit", args=[invoice.pk])).content.decode() + assert "Laatste herinnering" in page + assert "Herinnering gestuurd naar sanne@example.invalid" in page + + +def test_a_failed_reminder_is_not_the_last_reminder(client_in, monkeypatch): + def refuse(*args, **kwargs): + raise smtplib.SMTPAuthenticationError(535, b"nee") + + monkeypatch.setattr("django.core.mail.EmailMessage.send", refuse) + invoice = _invoice() + + _remind(client_in, invoice) + + page = client_in.get(reverse("documents:edit", args=[invoice.pk])).content.decode() + assert "Laatste herinnering" not in page + assert "Herinnering sturen mislukt naar sanne@example.invalid" in page + + +def test_only_an_overdue_issued_invoice_counts_its_days_overdue(): + invoice = _invoice(due_date=datetime.date.today() - datetime.timedelta(days=1)) + credit_note = issue(_draft(kind="credit_note", related_document=_invoice())) + + assert invoice.days_overdue == 1 + assert _invoice(due_date=datetime.date(2099, 1, 1)).days_overdue is None + assert _draft().days_overdue is None + assert credit_note.days_overdue is None + assert _quote().days_overdue is None diff --git a/tests/documents/test_migration_triggers.py b/tests/documents/test_migration_triggers.py index 060e91a..9861602 100644 --- a/tests/documents/test_migration_triggers.py +++ b/tests/documents/test_migration_triggers.py @@ -111,3 +111,42 @@ def test_adding_reverse_charge_keeps_the_triggers_and_issued_documents(): executor = MigrationExecutor(connection) executor.migrate(executor.loader.graph.leaf_nodes()) clean_up_issued_documents_for_flush() + + +def test_marking_reminders_keeps_the_mail_log_and_its_triggers(): + """0017 adds a column to the mail log without rebuilding it (#114).""" + before = ("documents", "0016_vat_rows") + after = ("documents", "0017_emaillog_reminder") + executor = MigrationExecutor(connection) + executor.migrate([before]) + old_apps = executor.loader.project_state([before]).apps + document = old_apps.get_model("documents", "Document").objects.create( + kind="invoice", status="draft" + ) + old_apps.get_model("documents", "EmailLog").objects.create( + document=document, + to="sanne@example.invalid", + subject="Factuur", + attachment_name="2026-0001.pdf", + attachment_sha256="", + succeeded=True, + ) + + executor = MigrationExecutor(connection) + executor.migrate([after]) + + assert { + "documents_emaillog_append_only_update", + "documents_emaillog_append_only_delete", + } <= _triggers() + EmailLog = executor.loader.project_state([after]).apps.get_model("documents", "EmailLog") + kept = EmailLog.objects.get() + assert (kept.subject, kept.reminder) == ("Factuur", False) + with pytest.raises(Exception, match="immutable"): + EmailLog.objects.update(reminder=True) + + from tests.support import clean_up_issued_documents_for_flush + + executor = MigrationExecutor(connection) + executor.migrate(executor.loader.graph.leaf_nodes()) + clean_up_issued_documents_for_flush() diff --git a/tests/documents/test_next_number.py b/tests/documents/test_next_number.py new file mode 100644 index 0000000..663e4be --- /dev/null +++ b/tests/documents/test_next_number.py @@ -0,0 +1,246 @@ +# SPDX-FileCopyrightText: 2026 Huismus contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Setting the next number by hand (issue #141): for someone who comes from +another package without an import. Invariant 3 decides what may: never a +gap within what Huismus issued, never a number twice.""" + +from concurrent.futures import ThreadPoolExecutor +from datetime import date + +import pytest +from django.db import connections + +from huismus.contacts.models import Contact +from huismus.documents.issuing import issue +from huismus.documents.models import Document, DocumentLine, NumberSequence +from huismus.documents.numbering import ( + NumberingError, + next_sequence_number, + next_sequence_number_is_fixed, + set_next_sequence_number, +) +from huismus.documents.quoting import send_quote +from huismus.documents.reopening import reopen +from tests.documents.test_issuing import _settings +from tests.support import clean_up_issued_documents_for_flush + +pytestmark = pytest.mark.django_db + +FORMAT = "{year}-{seq:04d}" + + +def _draft(kind="invoice", *, issue_date=date(2026, 3, 1), **fields): + document = Document.objects.create( + kind=kind, + status="draft", + contact=Contact.objects.create(company_name="Klant BV"), + issue_date=issue_date, + **fields, + ) + DocumentLine.objects.create( + document=document, description="Consult", quantity="1", unit_price_cents=10000 + ) + return document + + +def _imported(number, *, kind="invoice", issue_date=date(2026, 2, 1)): + """An issued document as the Moneybird import leaves it: its own + number, source set, the sequence moved past it.""" + return Document.objects.create( + kind=kind, + status="issued" if kind != "quote" else "sent", + contact=Contact.objects.create(company_name="Oude klant BV"), + number=number, + issue_date=issue_date, + source="moneybird", + external_id=number, + total_cents=100000, + ) + + +def test_an_empty_sequence_starts_at_one(): + assert next_sequence_number("invoice", year=2026) == 1 + assert not next_sequence_number_is_fixed("invoice") + + +def test_the_first_invoice_gets_the_number_that_was_set(): + _settings() + set_next_sequence_number("invoice", FORMAT, year=2026, value=43) + + assert next_sequence_number("invoice", year=2026) == 43 + assert issue(_draft()).number == "2026-0043" + assert issue(_draft()).number == "2026-0044" + + +def test_the_same_value_writes_nothing(): + set_next_sequence_number("invoice", FORMAT, year=2026, value=1) + + assert not NumberSequence.objects.exists() + + +def test_once_huismus_issued_an_invoice_the_number_is_fixed(): + # Raising it now would leave a gap after 2026-0001 (invariant 3). + _settings() + issue(_draft()) + + assert next_sequence_number_is_fixed("invoice") + with pytest.raises(NumberingError): + set_next_sequence_number("invoice", FORMAT, year=2026, value=43) + assert next_sequence_number("invoice", year=2026) == 2 + + +def test_a_credit_note_fixes_the_invoice_sequence_too(): + _settings() + invoice = _imported("2026-0042") + NumberSequence.objects.create(kind="invoice", year=2026, last_value=42) + issue(_draft("credit_note", related_document=invoice)) + + assert next_sequence_number_is_fixed("invoice") + + +def test_a_reopened_invoice_still_counts(): + # "Toch bewerken" makes it a draft again, with its number kept. + _settings() + reopen(issue(_draft())) + + assert next_sequence_number_is_fixed("invoice") + + +def test_last_year_s_invoice_fixes_the_new_year_s_sequence_too(): + # Else someone who already invoices in Huismus could skip numbers + # at the start of a new year. + _settings(number_reset_yearly=True) + issue(_draft(issue_date=date(2025, 12, 30))) + + with pytest.raises(NumberingError): + set_next_sequence_number("invoice", FORMAT, year=2026, value=10) + assert next_sequence_number("invoice", year=2026) == 1 + + +def test_without_a_yearly_reset_any_invoice_fixes_it(): + _settings(number_reset_yearly=False, invoice_number_format="F{seq:05d}") + issue(_draft(issue_date=date(2024, 5, 1))) + + assert next_sequence_number_is_fixed("invoice") + + +def test_imported_invoices_do_not_fix_it(): + # After an import whose numbers didn't fit the format, the import + # message sends the user here. + _imported("430033") + NumberSequence.objects.create(kind="invoice", year=2026, last_value=0) + + assert not next_sequence_number_is_fixed("invoice") + set_next_sequence_number("invoice", FORMAT, year=2026, value=34) + assert next_sequence_number("invoice", year=2026) == 34 + + +def test_it_never_goes_onto_or_below_an_existing_number(): + # The import already continued after 2026-0042; 40 would give + # 2026-0042 a second time two invoices later. + _imported("2026-0042") + NumberSequence.objects.create(kind="invoice", year=2026, last_value=42) + + with pytest.raises(NumberingError, match="43"): + set_next_sequence_number("invoice", FORMAT, year=2026, value=40) + assert next_sequence_number("invoice", year=2026) == 43 + + +def test_a_typo_can_be_set_back_lower(): + # 430 instead of 43: nothing was issued from it, so lower is no gap. + set_next_sequence_number("invoice", FORMAT, year=2026, value=430) + set_next_sequence_number("invoice", FORMAT, year=2026, value=43) + + assert next_sequence_number("invoice", year=2026) == 43 + + +def test_last_year_s_imported_numbers_do_not_limit_this_year(): + _imported("2025-0042", issue_date=date(2025, 6, 1)) + + set_next_sequence_number("invoice", FORMAT, year=2026, value=5) + assert next_sequence_number("invoice", year=2026) == 5 + + +def test_an_imported_customer_number_limits_the_sequence(): + _settings(invoice_number_format="{customer}{seq:04d}", number_reset_yearly=False) + document = _imported("580097") + Contact.objects.filter(pk=document.contact_id).update(customer_number="58") + + with pytest.raises(NumberingError, match="98"): + set_next_sequence_number("invoice", "{customer}{seq:04d}", year=None, value=90) + + +def test_a_number_that_already_exists_is_refused(): + _imported("2026-0050") + + with pytest.raises(NumberingError): + set_next_sequence_number("invoice", FORMAT, year=2026, value=50) + assert next_sequence_number("invoice", year=2026) == 1 + + +def test_an_existing_quote_number_does_not_block_an_invoice_number(): + _imported("2026-0050", kind="quote") + + set_next_sequence_number("invoice", FORMAT, year=2026, value=50) + assert next_sequence_number("invoice", year=2026) == 50 + + +def test_zero_is_refused(): + with pytest.raises(NumberingError): + set_next_sequence_number("invoice", FORMAT, year=2026, value=0) + + +def test_quotes_have_their_own_sequence(): + _settings() + issue(_draft()) + + set_next_sequence_number("quote", FORMAT, year=2026, value=7) + assert next_sequence_number("quote", year=2026) == 7 + assert send_quote(_draft("quote")).number.endswith("2026-0007") + assert next_sequence_number_is_fixed("quote") + + +def test_with_a_customer_number_the_sequence_still_counts(): + # Moneybird's own numbering: customer 58, sequence 97 is "580097". + _settings(invoice_number_format="{customer}{seq:04d}", number_reset_yearly=False) + set_next_sequence_number("invoice", "{customer}{seq:04d}", year=None, value=97) + + draft = _draft() + Contact.objects.filter(pk=draft.contact_id).update(customer_number="58") + draft.refresh_from_db() + assert issue(draft).number == "580097" + + +@pytest.mark.django_db(transaction=True) +def test_setting_it_while_invoices_are_issued_leaves_no_gap(): + # Either the number is set before the first invoice, or it is refused: + # never set halfway, which would leave a gap after what was issued. + _settings() + drafts = [_draft() for _ in range(8)] + + def issue_one(document): + try: + return issue(document).number + finally: + connections.close_all() + + def set_it(): + try: + set_next_sequence_number("invoice", FORMAT, year=2026, value=100) + return True + except NumberingError: + return False + finally: + connections.close_all() + + try: + with ThreadPoolExecutor(max_workers=9) as pool: + setting = pool.submit(set_it) + numbers = list(pool.map(issue_one, drafts)) + was_set = setting.result() + + sequence = sorted(int(number.split("-")[1]) for number in numbers) + first = 100 if was_set else 1 + assert sequence == list(range(first, first + len(drafts))) + finally: + clean_up_issued_documents_for_flush() diff --git a/tests/documents/test_payments.py b/tests/documents/test_payments.py index 17f10ea..4fcfd5d 100644 --- a/tests/documents/test_payments.py +++ b/tests/documents/test_payments.py @@ -121,11 +121,11 @@ def test_days_overdue_counts_from_the_due_date(): assert _issued_invoice(due_date=YESTERDAY).days_overdue == 1 -def test_days_overdue_is_zero_when_not_overdue(): - assert _issued_invoice(due_date=TODAY).days_overdue == 0 +def test_days_overdue_is_none_when_not_overdue(): + assert _issued_invoice(due_date=TODAY).days_overdue is None paid = _issued_invoice(total_line_cents=10000, due_date=YESTERDAY) Payment.objects.create(document=paid, paid_on=TODAY, amount_cents=10000) - assert paid.days_overdue == 0 + assert paid.days_overdue is None def test_paid_invoice_past_its_due_date_is_not_overdue(): diff --git a/tests/e2e/test_browser.py b/tests/e2e/test_browser.py index 6cd2586..114a2ac 100644 --- a/tests/e2e/test_browser.py +++ b/tests/e2e/test_browser.py @@ -1232,6 +1232,49 @@ def test_an_issued_invoice_is_mailed_from_its_page_and_lands_on_the_timeline( assert message.attachments[0][0] == f"{invoice.number}.pdf" +def test_an_overdue_invoice_gets_a_reminder_from_its_page(app, contact, settings): + # #114: the reminder is the main action of an overdue invoice, goes out + # with the invoice PDF, and the page then says when it went. + import datetime + + from django.core import mail + + from huismus.documents.issuing import issue + from huismus.documents.models import DocumentLine + + _mail_set_up(settings) + contact.email = "bakker@example.invalid" + contact.save() + invoice = Document.objects.create( + kind="invoice", + status="draft", + contact=contact, + issue_date=datetime.date.today() - datetime.timedelta(days=42), + due_date=datetime.date.today() - datetime.timedelta(days=12), + ) + DocumentLine.objects.create(document=invoice, description="Brood", unit_price_cents=1250) + issue(invoice) + app.goto(f"{app.base}/facturen/{invoice.pk}/") + expect(app.get_by_text("12 dagen te laat")).to_be_visible() + + app.locator(".page-head").get_by_role("link", name="Herinnering sturen").click() + + expect(app.locator("h1")).to_have_text(f"Herinnering voor factuur {invoice.number}") + expect(app.get_by_label("Onderwerp")).to_have_value( + f"Herinnering: factuur {invoice.number} van Voorbeeld BV" + ) + app.locator(".actionbar").get_by_role("button", name="Versturen").click() + + expect(app).to_have_url(f"{app.base}/facturen/{invoice.pk}/") + expect(app.get_by_text("Herinnering gestuurd naar bakker@example.invalid.")).to_be_visible() + expect(app.locator(".timeline")).to_contain_text( + "Herinnering gestuurd naar bakker@example.invalid" + ) + expect(app.get_by_text("Laatste herinnering:")).to_be_visible() + [message] = mail.outbox + assert message.attachments[0][0] == f"{invoice.number}.pdf" + + def test_on_a_phone_a_sent_quote_is_mailed_from_behind_meer(app, contact, settings): from django.core import mail @@ -1317,7 +1360,8 @@ def test_a_mail_text_changed_in_the_settings_is_where_the_mail_starts(app, conta _mail_set_up(settings) app.goto(f"{app.base}/instellingen/mailen/") - app.locator("details", has_text="Factuur").locator("summary").click() + # Exactly "Factuur": the block Herinnering mentions invoices too. + app.locator("details summary").filter(has=app.get_by_text("Factuur", exact=True)).click() subject = app.get_by_label("Onderwerp in het Nederlands").first expect(subject).to_have_value("Factuur {nummer} van {bedrijf}") subject.fill("Rekening {nummer}") diff --git a/tests/e2e/test_desktop_app.py b/tests/e2e/test_desktop_app.py index 7445570..5d890cb 100644 --- a/tests/e2e/test_desktop_app.py +++ b/tests/e2e/test_desktop_app.py @@ -234,6 +234,39 @@ def test_a_downloaded_version_waits_for_the_next_start(desktop, tmp_path, monkey expect(app.locator("#nieuwe-versie")).to_have_count(0) +@pytest.mark.parametrize("width", [360, 1440]) +def test_a_version_for_a_newer_macos_says_to_update_macos_first( + desktop, tmp_path, monkeypatch, width +): + """Issue #155: 0.1.4 asked macOS 15, and a 0.1.3 app on macOS 14 updated + itself and didn't open any more. Now the downloaded app is read first; + the banner turns from "wordt gedownload" into what to do, by itself.""" + from huismus.core import updates + + app = desktop + app.set_viewport_size({"width": width, "height": 800}) + _fake_release(tmp_path, monkeypatch) + monkeypatch.setattr(updates, "minimum_os", lambda package: "15.0") + monkeypatch.setattr(updates, "this_macos", lambda: "14.6") + updates.check() + + app.goto(app.base + "/") + expect(app.locator("#nieuwe-versie")).to_contain_text("wordt gedownload") + updates.prepare() + expect(app.locator("#nieuwe-versie")).to_contain_text( + "Huismus 1.4.0 is er, maar vraagt macOS 15 (Sequoia) of nieuwer. Werk eerst macOS bij." + ) + assert _overflow(app) <= 1 + + app.locator("#nieuwe-versie").click() + expect(app.locator("#eerst-macos")).to_contain_text( + "Deze versie vraagt macOS 15 (Sequoia) of nieuwer. Je Mac heeft macOS 14.6." + ) + expect(app.get_by_role("link", name="Wat is er nieuw in 1.4.0?")).to_be_visible() + expect(app.get_by_role("link", name="Bijwerken naar 1.4.0")).to_have_count(0) + assert _overflow(app) <= 1 + + def test_set_a_password_then_turn_it_off(desktop): # Wachtwoord (design D6): the fields show once the switch is on, with # CSS only; then the app asks it when it opens, until it is turned off. diff --git a/tests/e2e/test_every_page.py b/tests/e2e/test_every_page.py index 900c494..6d9aad2 100644 --- a/tests/e2e/test_every_page.py +++ b/tests/e2e/test_every_page.py @@ -51,6 +51,10 @@ def _pages(): documents = Document.objects.all() issued = _first(documents.filter(kind="invoice", status="issued"), "invoice") sent_quote = _first(documents.filter(kind="quote", status="sent"), "quote") + overdue = next( + (d for d in documents.filter(kind="invoice", status="issued") if d.is_overdue), None + ) + assert overdue is not None, "huismus/core/demo_history.py has no overdue invoice" pages = [ "/", "/facturen/", @@ -58,6 +62,8 @@ def _pages(): f"/facturen/{_first(documents.filter(kind='invoice', status='draft'), 'draft').pk}/", f"/facturen/{issued.pk}/", f"/facturen/{issued.pk}/mailen/", + f"/facturen/{overdue.pk}/", + f"/facturen/{overdue.pk}/herinnering/", f"/facturen/{issued.pk}/pdf/bekijken/", f"/offertes/{_first(documents.filter(kind='quote', status='sent'), 'quote').pk}/mailen/", f"/offertes/{sent_quote.pk}/pdf/bekijken/", @@ -87,6 +93,9 @@ def _pages(): f"/uitgaven/verwerken/bonnetje/{receipt.pk}/" for receipt in Attachment.objects.in_tray() ), + # A new expense on a phone, the photo first (#188): any receipt in + # the tray can be that photo. + *(f"/uitgaven/nieuw/foto/{receipt.pk}/" for receipt in Attachment.objects.in_tray()[:1]), "/rapporten/jaaroverzicht/", # The VAT return (SPEC.md M21, part 4): a year of the history, with # imports and lines without a rate under "Niet meegeteld". diff --git a/tests/e2e/test_photo_first.py b/tests/e2e/test_photo_first.py new file mode 100644 index 0000000..0cf1287 --- /dev/null +++ b/tests/e2e/test_photo_first.py @@ -0,0 +1,142 @@ +# SPDX-FileCopyrightText: 2026 Huismus contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +"""A new expense on a phone, the photo first (#188; app.js, "The photo +first"; huismus/expenses/photo_views.py): "Uitgave" opens the camera, the +photo goes into the tray, then the amount. Without a connection the photo +stays to send again. On a wide screen "Uitgave" is the ordinary form.""" + +import pytest +from playwright.sync_api import expect + +from huismus.core.demo_receipts import _photo +from huismus.core.models import Attachment +from huismus.expenses.models import Expense +from tests.e2e.conftest import IGNORED + +pytestmark = pytest.mark.django_db(transaction=True) + +PHOTO = { + "name": "IMG_3001.jpg", + "mimeType": "image/jpeg", + "buffer": _photo(["KANTOORCENTRUM", "TOTAAL 48,95"], "JPEG"), +} + + +@pytest.fixture +def phone(app, browser, browser_name): + """The logged-in user on a phone 390 px wide with touch.""" + args = {"viewport": {"width": 390, "height": 844}, "has_touch": True, "locale": "nl-NL"} + # Firefox has no mobile mode in Playwright; touch it does have. + if browser_name != "firefox": + args["is_mobile"] = True + context = browser.new_context(**args) + context.add_cookies(app.context.cookies()) + page = context.new_page() + errors = [] + # The same JavaScript errors as the app fixture lets pass. + page.on( + "pageerror", + lambda error: None if any(n in str(error) for n in IGNORED) else errors.append(str(error)), + ) + page.base = app.base + yield page + context.close() + assert errors == [], f"JavaScript errors: {errors}" + + +def _camera(page, tap): + """Taps `tap`, which must open the camera, and takes PHOTO.""" + with page.expect_file_chooser() as chooser: + tap() + assert chooser.value.element.get_attribute("capture") == "environment" + chooser.value.set_files(PHOTO) + + +def test_on_a_phone_uitgave_opens_the_camera_then_the_amount(phone): + phone.goto(phone.base + "/uitgaven/") + phone.locator(".tabbar .fab").tap() + _camera(phone, lambda: phone.locator("#plus-menu a", has_text="Uitgave").tap()) + + expect(phone.locator("h1")).to_have_text("Nieuwe uitgave") + expect(phone.get_by_role("img", name="Bonnetje IMG_3001.jpg")).to_be_visible() + assert Attachment.objects.in_tray().count() == 1 + # The amount first, with the number keyboard. + amount = phone.get_by_label("Bedrag, zoals je het betaalde") + expect(amount).to_have_attribute("inputmode", "decimal") + amount.fill("48,95") + # Without the KOR (as here) the VAT and its rate too, right under it. + phone.get_by_label("Btw", exact=True).fill("8,50") + phone.get_by_label("Btw-tarief").select_option("21") + phone.get_by_label("Leverancier").fill("Kantoorcentrum Zuid") + phone.get_by_role("button", name="Uitgave opslaan").tap() + + expect(phone).to_have_url(phone.base + "/uitgaven/") + expect(phone.locator("#toasts")).to_contain_text("Uitgave opgeslagen.") + expense = Expense.objects.get() + assert expense.amount_cents == 4895 + assert expense.attachments.get().filename == "IMG_3001.jpg" + assert not Attachment.objects.in_tray().exists() + + +def test_opnieuw_and_only_the_photo(phone): + phone.goto(phone.base + "/uitgaven/") + _camera(phone, lambda: phone.get_by_role("link", name="Nieuwe uitgave").first.tap()) + expect(phone.locator("h1")).to_have_text("Nieuwe uitgave") + first = Attachment.objects.get().pk + + _camera(phone, lambda: phone.locator(".photo-again label").tap()) + expect(phone).not_to_have_url(phone.base + f"/uitgaven/nieuw/foto/{first}/") + assert Attachment.objects.in_tray().count() == 1 + assert Attachment.objects.get().pk != first + + phone.get_by_role("button", name="Alleen de foto bewaren").tap() + kept = "Bonnetje bewaard. Je vindt het bij Verwerken." + expect(phone.locator("#toasts")).to_contain_text(kept) + expect(phone.get_by_role("link", name="Verwerken (1)")).to_be_visible() + assert not Expense.objects.exists() + + +def test_without_a_connection_the_photo_stays_to_send_again(phone): + phone.goto(phone.base + "/uitgaven/") + phone.context.set_offline(True) + _camera(phone, lambda: phone.get_by_role("link", name="Nieuwe uitgave").first.tap()) + + expect(phone.locator("#toasts")).to_contain_text( + "Huismus is niet bereikbaar. Probeer het opnieuw als je verbinding hebt." + ) + expect(phone).to_have_url(phone.base + "/uitgaven/") + assert not Attachment.objects.exists() + + phone.context.set_offline(False) + phone.get_by_role("button", name="Opnieuw proberen").tap() + expect(phone.locator("h1")).to_have_text("Nieuwe uitgave") + assert Attachment.objects.in_tray().count() == 1 + + +def test_a_refused_photo_opens_the_ordinary_form_with_the_reason(phone, monkeypatch): + # Found in the screenshots, 2026-11-15: the reason was gone. + monkeypatch.setattr("huismus.expenses.receipts.MAX_RECEIPT_BYTES", 10) + phone.goto(phone.base + "/uitgaven/") + _camera(phone, lambda: phone.get_by_role("link", name="Nieuwe uitgave").first.tap()) + expect(phone).to_have_url(phone.base + "/uitgaven/nieuw/") + expect(phone.locator("#toasts")).to_contain_text("groter dan") + assert not Attachment.objects.exists() + + +def test_closing_the_camera_opens_the_ordinary_form(phone): + phone.goto(phone.base + "/uitgaven/") + with phone.expect_file_chooser(): + phone.get_by_role("link", name="Nieuwe uitgave").first.tap() + # What the browser does when the camera is closed without a photo. + phone.locator("#camera input[type=file]").dispatch_event("cancel") + expect(phone).to_have_url(phone.base + "/uitgaven/nieuw/") + expect(phone.get_by_text("Sleep een bonnetje hierheen")).to_be_visible() + assert not Attachment.objects.exists() + + +def test_on_a_wide_screen_uitgave_is_the_ordinary_form(app): + app.set_viewport_size({"width": 1440, "height": 900}) + app.goto(app.base + "/uitgaven/") + app.get_by_role("link", name="Nieuwe uitgave").first.click() + expect(app).to_have_url(app.base + "/uitgaven/nieuw/") + expect(app.get_by_text("Sleep een bonnetje hierheen")).to_be_visible() diff --git a/tests/expenses/test_photo.py b/tests/expenses/test_photo.py new file mode 100644 index 0000000..91eda43 --- /dev/null +++ b/tests/expenses/test_photo.py @@ -0,0 +1,276 @@ +# SPDX-FileCopyrightText: 2026 Huismus contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +"""A new expense on a phone, the photo first (#188, +huismus/expenses/photo_views.py): the photo goes into the tray at once, +then the amount, where, date and category of one line. The camera itself +(app.js) is tests/e2e/test_photo_first.py.""" + +import datetime +import io + +import pytest +from django.contrib.auth import get_user_model +from django.core.files.uploadedfile import SimpleUploadedFile +from django.urls import reverse +from django.utils import timezone +from PIL import Image + +from huismus.business.models import Settings +from huismus.core.models import Attachment +from huismus.expenses import photo_views, reading +from huismus.expenses.models import Expense, ExpenseCategory + +pytestmark = pytest.mark.django_db + + +def _kor(on): + business = Settings.load() + business.kor_enabled = on + business.save() + + +@pytest.fixture(autouse=True) +def kor_on(settings, tmp_path): + settings.DATA_DIR = tmp_path / "data" + settings.MEDIA_ROOT = settings.DATA_DIR + settings.DATA_DIR.mkdir() + _kor(True) + + +@pytest.fixture +def logged_in(client): + get_user_model().objects.create_user(username="freelancer", password="s3cret-pass") + client.login(username="freelancer", password="s3cret-pass") + return client + + +def _photo(name="IMG_0001.jpg", color="red"): + buffer = io.BytesIO() + Image.new("RGB", (8, 8), color=color).save(buffer, format="JPEG") + return SimpleUploadedFile(name, buffer.getvalue(), content_type="image/jpeg") + + +def _take(client, color="red", headers=None, **extra): + """The photo from the camera, as the form without JS sends it.""" + return client.post( + reverse("expenses:photo_upload"), {"file": _photo(color=color), **extra}, headers=headers + ) + + +def _form(**extra): + return { + "date": "2026-11-07", + "supplier": "Kantoorcentrum Zuid", + "description": "", + "lines-TOTAL_FORMS": "1", + "lines-INITIAL_FORMS": "0", + "lines-MIN_NUM_FORMS": "1", + "lines-MAX_NUM_FORMS": "1000", + "lines-0-description": "", + "lines-0-amount_cents": "48,95", + "lines-0-vat_info_cents": "", + "lines-0-category": "", + **extra, + } + + +# --- The photo ----------------------------------------------------------- + + +def test_the_photo_goes_into_the_tray_at_once(logged_in): + response = _take(logged_in) + receipt = Attachment.objects.in_tray().get() + assert receipt.source == photo_views.SOURCE and receipt.sha256 + assert response.url == reverse("expenses:photo", args=[receipt.pk]) + + +def test_a_receipt_that_is_too_big_goes_to_the_ordinary_form_with_the_reason( + logged_in, monkeypatch +): + monkeypatch.setattr("huismus.expenses.receipts.MAX_RECEIPT_BYTES", 10) + response = _take(logged_in) + assert response.url == reverse("expenses:create") + assert not Attachment.objects.exists() + page = logged_in.get(response.url).content.decode() + assert "groter dan" in page + + +def test_without_a_post_it_is_the_ordinary_form(logged_in): + assert logged_in.get(reverse("expenses:photo_upload")).url == reverse("expenses:create") + + +def test_opnieuw_replaces_the_photo(logged_in): + _take(logged_in) + first = Attachment.objects.get() + response = _take(logged_in, color="blue", vervangt=str(first.pk)) + second = Attachment.objects.get() + assert second.pk != first.pk + assert response.url == reverse("expenses:photo", args=[second.pk]) + assert not first.file.storage.exists(first.file.name) + + +def test_opnieuw_never_removes_a_receipt_that_is_on_an_expense(logged_in): + _take(logged_in) + receipt = Attachment.objects.get() + logged_in.post(reverse("expenses:photo", args=[receipt.pk]), _form()) + _take(logged_in, vervangt=str(receipt.pk)) + receipt.refresh_from_db() + assert receipt.expense is not None + assert Attachment.objects.count() == 2 + + +# --- The page ------------------------------------------------------------ + + +def test_the_page_shows_the_photo_the_amount_first_and_today(logged_in): + _take(logged_in) + receipt = Attachment.objects.get() + page = logged_in.get(reverse("expenses:photo", args=[receipt.pk])).content.decode() + assert f'src="{receipt.file.url}"' in page + assert "Opnieuw" in page + assert page.index('name="lines-0-amount_cents"') < page.index('name="supplier"') + assert page.index('name="supplier"') < page.index('name="date"') + assert f'value="{timezone.localdate().isoformat()}"' in page + assert "Bedrag, zoals je het betaalde" in page + # The app's own labels, not "Waar" and "Soort" of the design (PO, #188). + assert "Leverancier" in page and "Categorie" in page + assert "Uitgave opslaan" in page and "Alleen de foto bewaren" in page + assert page.index("Uitgave opslaan") < page.index("Alleen de foto bewaren") + + +def test_meer_regels_opens_verwerken_with_what_was_typed_and_saves_nothing(logged_in): + _take(logged_in) + receipt = Attachment.objects.get() + page = logged_in.get(reverse("expenses:photo", args=[receipt.pk])).content.decode() + process_url = reverse("expenses:process_item", args=["bonnetje", receipt.pk]) + assert f'formaction="{process_url}"' in page + + # The button posts the form there, as its "Regel toevoegen" without JS. + response = logged_in.post(process_url, _form(regel_toevoegen="1")) + + page = response.content.decode() + assert response.status_code == 200 + assert 'value="Kantoorcentrum Zuid"' in page and 'value="48,95"' in page + assert 'name="lines-1-amount_cents"' in page + assert not Expense.objects.exists() + assert Attachment.objects.in_tray().get() == receipt + + +def test_without_the_kor_it_asks_the_vat_and_the_rate(logged_in): + _kor(False) + _take(logged_in) + receipt = Attachment.objects.get() + page = logged_in.get(reverse("expenses:photo", args=[receipt.pk])).content.decode() + assert 'name="lines-0-vat_info_cents"' in page and 'name="lines-0-vat_rate"' in page + # Right under the amount. + assert page.index('name="lines-0-vat_rate"') < page.index('name="supplier"') + + response = logged_in.post(reverse("expenses:photo", args=[receipt.pk]), _form()) + assert response.status_code == 200 + assert "Vul het btw-bedrag in." in response.content.decode() + assert not Expense.objects.exists() + + +def test_a_receipt_gone_meanwhile_goes_to_uitgaven_with_the_reason(logged_in): + _take(logged_in) + receipt = Attachment.objects.get() + url = reverse("expenses:photo", args=[receipt.pk]) + receipt.delete() + response = logged_in.get(url) + assert response.url == reverse("expenses:list") + page = logged_in.get(response.url).content.decode() + assert "Dit bonnetje staat niet meer bij de bonnetjes zonder uitgave." in page + + +# --- Saving -------------------------------------------------------------- + + +def test_uitgave_opslaan_makes_the_expense_with_the_photo_on_it(logged_in): + office = ExpenseCategory.objects.create(name="Kantoor", sort_order=1) + _take(logged_in) + receipt = Attachment.objects.get() + + response = logged_in.post( + reverse("expenses:photo", args=[receipt.pk]), _form(**{"lines-0-category": office.pk}) + ) + + assert response.url == reverse("expenses:list") + expense = Expense.objects.get() + assert expense.amount_cents == 4895 + assert expense.supplier == "Kantoorcentrum Zuid" + assert expense.date == datetime.date(2026, 11, 7) + assert expense.lines.get().category == office + assert not expense.needs_review + receipt.refresh_from_db() + assert receipt.expense == expense + assert not Attachment.objects.in_tray().exists() + assert "Uitgave opgeslagen." in logged_in.get(response.url).content.decode() + + +def test_without_an_amount_nothing_is_saved_and_the_photo_stays(logged_in): + _take(logged_in) + receipt = Attachment.objects.get() + response = logged_in.post( + reverse("expenses:photo", args=[receipt.pk]), _form(**{"lines-0-amount_cents": ""}) + ) + assert response.status_code == 200 + assert not Expense.objects.exists() + assert Attachment.objects.in_tray().get() == receipt + + +def test_alleen_de_foto_bewaren_leaves_it_in_the_tray_and_reads_it(logged_in, monkeypatch): + started = [] + monkeypatch.setattr(reading, "read_in_background", lambda: started.append(True)) + _take(logged_in) + receipt = Attachment.objects.get() + + response = logged_in.post( + reverse("expenses:photo", args=[receipt.pk]), + _form(**{"lines-0-amount_cents": "", "alleen_foto": "1"}), + ) + + assert response.url == reverse("expenses:list") + assert Attachment.objects.in_tray().get() == receipt + assert not Expense.objects.exists() + assert started == [True] + page = logged_in.get(response.url).content.decode() + assert "Bonnetje bewaard. Je vindt het bij Verwerken." in page + assert "Verwerken (1)" in page + + +def test_both_need_a_login(client): + assert client.post(reverse("expenses:photo_upload")).status_code == 302 + assert "/login/" in client.get(reverse("expenses:photo", args=[1])).url + + +def test_a_vervangt_that_is_no_number_replaces_nothing(logged_in): + _take(logged_in) + _take(logged_in, color="blue", vervangt="nee") + assert Attachment.objects.in_tray().count() == 2 + + +def test_opnieuw_never_removes_a_receipt_from_the_receipts_folder(logged_in): + _take(logged_in) + folder = Attachment.objects.get() + Attachment.objects.filter(pk=folder.pk).update(source="bonnetjesmap") + _take(logged_in, color="blue", vervangt=str(folder.pk)) + assert Attachment.objects.in_tray().count() == 2 + + +def test_the_desktop_app_has_no_camera(logged_in, settings): + assert 'id="camera"' in logged_in.get(reverse("expenses:list")).content.decode() + settings.DESKTOP = True + assert 'id="camera"' not in logged_in.get(reverse("expenses:list")).content.decode() + + +def test_to_app_js_it_says_where_to_go_instead_of_redirecting(logged_in, monkeypatch): + # fetch() would follow a redirect and use up the next page's message. + response = _take(logged_in, headers={"X-Huismus-Camera": "1"}) + receipt = Attachment.objects.get() + assert response.status_code == 204 + assert response["X-Huismus-Go"] == reverse("expenses:photo", args=[receipt.pk]) + + monkeypatch.setattr("huismus.expenses.receipts.MAX_RECEIPT_BYTES", 10) + response = _take(logged_in, color="blue", headers={"X-Huismus-Camera": "1"}) + assert response["X-Huismus-Go"] == reverse("expenses:create") + assert "groter dan" in logged_in.get(response["X-Huismus-Go"]).content.decode() diff --git a/tests/expenses/test_views.py b/tests/expenses/test_views.py index 4a1b190..84bbb6c 100644 --- a/tests/expenses/test_views.py +++ b/tests/expenses/test_views.py @@ -479,3 +479,11 @@ def test_category_edit_with_an_empty_name_keeps_the_row_open_with_the_error(clie assert response.status_code == 200 assert response.context["editing_pk"] == category.pk assert 'aria-invalid="true"' in response.content.decode() + + +def test_the_receipt_on_a_new_expense_is_not_called_optional(client): + # A receipt is the proof of an expense (the owner, 2026-11-15): the + # form doesn't ask for one, but doesn't call it optional either. + _login(client) + page = client.get(reverse("expenses:create")).content.decode() + assert "

Bonnetje

" in page diff --git a/tests/imports/test_commit.py b/tests/imports/test_commit.py index 27c5631..17914e8 100644 --- a/tests/imports/test_commit.py +++ b/tests/imports/test_commit.py @@ -4,6 +4,8 @@ from pathlib import Path import pytest +from django.template.loader import render_to_string +from django.urls import reverse from huismus.business.models import Settings from huismus.contacts.models import Contact, ContactPerson @@ -270,6 +272,11 @@ def test_real_moneybird_numbers_do_not_fit_the_default_format(): assert report.numbering_note != "" assert NumberSequence.objects.count() == 0 + # The report says where: the next number by hand (issue #141). + section = render_to_string( + "imports/_report_section.html", {"r": {"numbering_note": report.numbering_note}} + ) + assert reverse("business:topic", args=["facturen"]) in section def test_an_apparent_payment_with_no_paid_on_date_is_reported_not_dropped():