From eeff95f8956485b19a960c7d455ece5b1ad460b5 Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:03:26 +0100 Subject: [PATCH 01/19] feat(reminders): store reminder texts and mark reminder mails Settings gets a subject and body per language for a payment reminder, and EmailLog a reminder flag, added with ALTER TABLE so the mail log's append-only triggers stay (#114). Co-Authored-By: Claude Opus 5.5 --- .../migrations/0010_mail_reminder_texts.py | 36 +++++++++++++++++ huismus/business/models.py | 8 ++++ .../migrations/0017_emaillog_reminder.py | 33 ++++++++++++++++ huismus/documents/models.py | 3 ++ tests/documents/test_migration_triggers.py | 39 +++++++++++++++++++ 5 files changed, 119 insertions(+) create mode 100644 huismus/business/migrations/0010_mail_reminder_texts.py create mode 100644 huismus/documents/migrations/0017_emaillog_reminder.py 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/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 f57814e..0aaaf98 100644 --- a/huismus/documents/models.py +++ b/huismus/documents/models.py @@ -480,6 +480,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/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() From 319cb94855fa12bec433a7758afbd30195c06d2c Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:03:26 +0100 Subject: [PATCH 02/19] feat(reminders): send a payment reminder for an overdue invoice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Herinnering sturen" is the main action of an overdue invoice. It opens the mail form with the reminder text ({openstaand}, {vervaldatum}) and the invoice PDF. The page shows how many days late the invoice is and when the last reminder went out; the timeline marks reminders. Texts in Instellingen → Mailen, nl and en. Decided by the PO agent, 2026-11-15. Co-Authored-By: Claude Opus 5.5 --- huismus/business/forms.py | 7 +- huismus/documents/mail_texts.py | 32 +++- huismus/documents/mailing.py | 29 +++- huismus/documents/urls.py | 1 + huismus/documents/views.py | 48 +++++- huismus/locale/en/LC_MESSAGES/django.po | 114 ++++++++++--- huismus/locale/nl/LC_MESSAGES/django.po | 103 +++++++++--- huismus/templates/business/topic.html | 2 +- .../templates/documents/_mail_heading.html | 1 + huismus/templates/documents/_timeline.html | 2 + huismus/templates/documents/detail.html | 14 +- huismus/templates/documents/mail.html | 6 +- tests/documents/test_mailing.py | 150 ++++++++++++++++++ tests/e2e/test_browser.py | 43 +++++ tests/e2e/test_every_page.py | 6 + 15 files changed, 496 insertions(+), 62 deletions(-) create mode 100644 huismus/templates/documents/_mail_heading.html diff --git a/huismus/business/forms.py b/huismus/business/forms.py index 82c9356..c2b92db 100644 --- a/huismus/business/forms.py +++ b/huismus/business/forms.py @@ -29,7 +29,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"), diff --git a/huismus/documents/mail_texts.py b/huismus/documents/mail_texts.py index e2bd495..1aa3af3 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,9 @@ from django.utils import translation from django.utils.translation import gettext as _ -KINDS = ["invoice", "credit_note", "quote"] +# "reminder" is no kind of document but a mail about an invoice; it has +# texts of its own, so it is one more kind here. +KINDS = ["invoice", "credit_note", "quote", "reminder"] LANGUAGES = ["nl", "en"] # Every placeholder, and the kinds it belongs to. The names are Dutch in @@ -21,8 +24,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 +44,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..3a8e687 100644 --- a/huismus/documents/mailing.py +++ b/huismus/documents/mailing.py @@ -45,10 +45,17 @@ def _date(value) -> str: return dateformat.format(value, "j F Y") -def default_message(document) -> tuple[str, str]: +def can_remind(document) -> bool: + """A payment reminder (#114) is for an issued invoice that is overdue: + its due date has passed and it isn't fully paid (Document.is_overdue).""" + return document.kind == "invoice" and document.status == "issued" and document.is_overdue + + +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 +63,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 +75,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 +95,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 +132,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/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 e3fb3b9..134ef42 100644 --- a/huismus/documents/views.py +++ b/huismus/documents/views.py @@ -43,7 +43,13 @@ in_tab, matches_search, ) -from .mailing import MAILABLE_STATUSES, default_message, default_recipients, send_document +from .mailing import ( + MAILABLE_STATUSES, + can_remind, + default_message, + default_recipients, + send_document, +) from .models import Document, DocumentLine from .pdf import render_pdf from .preview import render_preview_pdf @@ -455,7 +461,7 @@ 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 too: it has the PDF. last_mail = document.emails.filter(succeeded=True).order_by("-sent_at").first() context = { "document": document, @@ -514,6 +520,14 @@ def _detail_context(document): kind="credit_note", related_document=invoice ).order_by("issue_date", "pk"), "timeline": timeline_events(invoice), + # Payment reminders (#114): how late it is, and when the last + # one went out (a failed one doesn't count). + "days_overdue": ( + (timezone.localdate() - invoice.due_date).days if invoice.is_overdue else None + ), + "last_reminder": invoice.emails.filter(succeeded=True, reminder=True) + .order_by("-sent_at") + .first(), "payment_form": PaymentForm( initial={ "paid_on": timezone.localdate(), @@ -674,6 +688,26 @@ 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. An invoice that isn't (or + no longer is) overdue, say just paid, goes back to its page.""" + document = get_object_or_404(Document, pk=pk, kind="invoice", status="issued") + if not can_remind(document): + 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": @@ -687,13 +721,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} ) @@ -702,6 +741,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/locale/en/LC_MESSAGES/django.po b/huismus/locale/en/LC_MESSAGES/django.po index 858f573..bb47a6e 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-13 15:46+0100\n" +"POT-Creation-Date: 2026-11-15 09:58+0100\n" "PO-Revision-Date: 2026-09-25 08:36+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -213,6 +213,10 @@ msgstr "Credit note" msgid "Offerte" msgstr "Quote" +# +msgid "Herinnering" +msgstr "Reminder" + msgid "onderwerp in het Nederlands" msgstr "subject in Dutch" @@ -435,6 +439,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" @@ -1673,6 +1693,28 @@ 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}." @@ -1693,13 +1735,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" @@ -1859,6 +1894,10 @@ msgstr "succeeded" msgid "fout" msgstr "error" +# +msgid "herinnering" +msgstr "reminder" + msgid "verstuurde e-mail" msgstr "sent e-mail" @@ -1964,6 +2003,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." @@ -3499,13 +3546,10 @@ 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}." -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 " +"{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 and a reminder also {vervaldatum}, for a reminder {openstaand}, for a quote {geldig_tot}." #, python-format msgid "%(counter)s veld heeft aandacht nodig" @@ -4211,6 +4255,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." @@ -4307,6 +4359,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" @@ -4338,6 +4398,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…" @@ -4397,6 +4461,16 @@ msgstr "" msgid "Naar factuur %(number)s" msgstr "To invoice %(number)s" +#, 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 "Laatste herinnering: %(date)s" +msgstr "Last reminder: %(date)s" + msgid "Afgehandeld" msgstr "Settled" @@ -4702,10 +4776,6 @@ msgstr "Clear filters" msgid "betekent: vervaldatum voorbij en nog niet volledig betaald." msgstr "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." @@ -4917,6 +4987,10 @@ msgid_plural "%(count)s bestanden" msgstr[0] "%(count)s file" msgstr[1] "%(count)s files" +#, python-format +msgid "Bonnetje %(name)s" +msgstr "Receipt %(name)s" + msgid "Bonnetje verwijderen" msgstr "Delete receipt" @@ -5043,10 +5117,6 @@ msgstr "Nothing left to process." msgid "Naar Uitgaven" msgstr "Go to Expenses" -#, python-format -msgid "Bonnetje %(name)s" -msgstr "Receipt %(name)s" - msgid "Bonnetje openen" msgstr "Open receipt" diff --git a/huismus/locale/nl/LC_MESSAGES/django.po b/huismus/locale/nl/LC_MESSAGES/django.po index 858aa3a..a6dcc2b 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-13 15:46+0100\n" +"POT-Creation-Date: 2026-11-15 09:58+0100\n" "PO-Revision-Date: 2026-09-25 08:36+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -197,6 +197,9 @@ msgstr "" msgid "Offerte" msgstr "" +msgid "Herinnering" +msgstr "" + msgid "onderwerp in het Nederlands" msgstr "" @@ -411,6 +414,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 "" @@ -1602,30 +1617,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" @@ -1787,6 +1817,9 @@ msgstr "" msgid "fout" msgstr "" +msgid "herinnering" +msgstr "" + msgid "verstuurde e-mail" msgstr "" @@ -1886,6 +1919,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 "" @@ -3286,8 +3327,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 @@ -3940,6 +3982,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 "" @@ -4034,6 +4084,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 "" @@ -4065,6 +4123,9 @@ msgstr "" msgid "uitgegeven op %(date)s" msgstr "" +msgid "Herinnering sturen" +msgstr "" + msgid "Creditnota maken…" msgstr "" @@ -4120,6 +4181,16 @@ msgstr "" msgid "Naar factuur %(number)s" 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" + +#, python-format +msgid "Laatste herinnering: %(date)s" +msgstr "" + msgid "Afgehandeld" msgstr "" @@ -4398,10 +4469,6 @@ msgstr "" msgid "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." @@ -4600,6 +4667,10 @@ msgid_plural "%(count)s bestanden" msgstr[0] "" msgstr[1] "" +#, python-format +msgid "Bonnetje %(name)s" +msgstr "" + msgid "Bonnetje verwijderen" msgstr "" @@ -4722,10 +4793,6 @@ msgstr "" msgid "Naar Uitgaven" msgstr "" -#, python-format -msgid "Bonnetje %(name)s" -msgstr "" - msgid "Bonnetje openen" msgstr "" diff --git a/huismus/templates/business/topic.html b/huismus/templates/business/topic.html index 5895489..9ff2668 100644 --- a/huismus/templates/business/topic.html +++ b/huismus/templates/business/topic.html @@ -145,7 +145,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/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 f430b4e..6b31952 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.is_overdue %} + {% 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,18 @@

{% translate "Betaalstatus" %}

{% if document.is_overdue %}{% include "documents/_pill_overdue.html" %} {% else %}{{ document.payment_state|payment_state_label|capfirst }}{% endif %}
+ {% if days_overdue is not None or last_reminder %} +

+ {% if days_overdue is not None %}{% blocktranslate count count=days_overdue %}{{ count }} dag te laat{% plural %}{{ count }} dagen te laat{% endblocktranslate %}{% endif %} + {% if days_overdue is not None and last_reminder %}·{% endif %} + {% if last_reminder %}{% blocktranslate with date=last_reminder.sent_at|date:"SHORT_DATE_FORMAT" %}Laatste herinnering: {{ date }}{% endblocktranslate %}{% endif %} +

+ {% 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/tests/documents/test_mailing.py b/tests/documents/test_mailing.py index 3253c1d..ac10c47 100644 --- a/tests/documents/test_mailing.py +++ b/tests/documents/test_mailing.py @@ -629,3 +629,153 @@ 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 diff --git a/tests/e2e/test_browser.py b/tests/e2e/test_browser.py index 170c457..4427f2c 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 diff --git a/tests/e2e/test_every_page.py b/tests/e2e/test_every_page.py index 900c494..ea1c066 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/", From 265a97d872092e80cc1c2d11e4c8668870dcb88c Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:03:26 +0100 Subject: [PATCH 03/19] docs: payment reminders in SPEC M10 and the help (#114) Co-Authored-By: Claude Opus 5.5 --- SPEC.md | 5 +++-- docs/hulp/facturen.en.md | 8 ++++++++ docs/hulp/facturen.nl.md | 9 +++++++++ docs/hulp/functies.en.md | 3 ++- docs/hulp/functies.nl.md | 3 ++- docs/hulp/mailen.en.md | 9 ++++++--- docs/hulp/mailen.nl.md | 9 ++++++--- 7 files changed, 36 insertions(+), 10 deletions(-) diff --git a/SPEC.md b/SPEC.md index 919bfd3..61a32e6 100644 --- a/SPEC.md +++ b/SPEC.md @@ -191,7 +191,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) @@ -407,7 +408,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/docs/hulp/facturen.en.md b/docs/hulp/facturen.en.md index 77d1171..e86889b 100644 --- a/docs/hulp/facturen.en.md +++ b/docs/hulp/facturen.en.md @@ -38,6 +38,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 c0bcb47..7177247 100644 --- a/docs/hulp/facturen.nl.md +++ b/docs/hulp/facturen.nl.md @@ -40,6 +40,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 a677a9b..7645151 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 vervallen 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 vervallen factuur - 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 From cabae1944a2215d4051460c2d6ff9be167faacdc Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:11:12 +0100 Subject: [PATCH 04/19] refactor(reminders): one rule for when an invoice gets a reminder Document.days_overdue is the one check for the button, the line on the page and the form, so they can't drift apart. Review findings. Co-Authored-By: Claude Opus 5.5 --- huismus/documents/mail_texts.py | 5 +++-- huismus/documents/mailing.py | 6 ------ huismus/documents/models.py | 9 +++++++++ huismus/documents/views.py | 18 ++++++++---------- huismus/templates/documents/detail.html | 10 +++++----- tests/documents/test_mailing.py | 11 +++++++++++ tests/e2e/test_browser.py | 3 ++- 7 files changed, 38 insertions(+), 24 deletions(-) diff --git a/huismus/documents/mail_texts.py b/huismus/documents/mail_texts.py index 1aa3af3..a62c332 100644 --- a/huismus/documents/mail_texts.py +++ b/huismus/documents/mail_texts.py @@ -12,8 +12,9 @@ from django.utils import translation from django.utils.translation import gettext as _ -# "reminder" is no kind of document but a mail about an invoice; it has -# texts of its own, so it is one more kind here. +# 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"] diff --git a/huismus/documents/mailing.py b/huismus/documents/mailing.py index 3a8e687..ad6c2b6 100644 --- a/huismus/documents/mailing.py +++ b/huismus/documents/mailing.py @@ -45,12 +45,6 @@ def _date(value) -> str: return dateformat.format(value, "j F Y") -def can_remind(document) -> bool: - """A payment reminder (#114) is for an issued invoice that is overdue: - its due date has passed and it isn't fully paid (Document.is_overdue).""" - return document.kind == "invoice" and document.status == "issued" and document.is_overdue - - 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), diff --git a/huismus/documents/models.py b/huismus/documents/models.py index 0aaaf98..6317fcc 100644 --- a/huismus/documents/models.py +++ b/huismus/documents/models.py @@ -290,6 +290,15 @@ def is_overdue(self): and self.due_date < timezone.localdate() ) + @property + def days_overdue(self): + """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() if self.status not in ALLOWED_STATUSES_BY_KIND[self.kind]: diff --git a/huismus/documents/views.py b/huismus/documents/views.py index 134ef42..d9cbf85 100644 --- a/huismus/documents/views.py +++ b/huismus/documents/views.py @@ -45,7 +45,6 @@ ) from .mailing import ( MAILABLE_STATUSES, - can_remind, default_message, default_recipients, send_document, @@ -461,7 +460,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, a reminder too: it has the PDF. + # 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, @@ -520,11 +520,8 @@ def _detail_context(document): kind="credit_note", related_document=invoice ).order_by("issue_date", "pk"), "timeline": timeline_events(invoice), - # Payment reminders (#114): how late it is, and when the last - # one went out (a failed one doesn't count). - "days_overdue": ( - (timezone.localdate() - invoice.due_date).days if invoice.is_overdue else None - ), + # 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(), @@ -694,10 +691,11 @@ def document_mail(request, pk, kind="invoice"): @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. An invoice that isn't (or - no longer is) overdue, say just paid, goes back to its page.""" + (#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 not can_remind(document): + if document.days_overdue is None: messages.info( request, _("Factuur %(number)s is niet te laat. Er is geen herinnering gestuurd.") diff --git a/huismus/templates/documents/detail.html b/huismus/templates/documents/detail.html index 6b31952..d4ed293 100644 --- a/huismus/templates/documents/detail.html +++ b/huismus/templates/documents/detail.html @@ -20,7 +20,7 @@

{{ 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.is_overdue %} + {% 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 %} @@ -113,10 +113,10 @@

{% translate "Betaalstatus" %}

{% if document.is_overdue %}{% include "documents/_pill_overdue.html" %} {% else %}{{ document.payment_state|payment_state_label|capfirst }}{% endif %}
- {% if days_overdue is not None or last_reminder %} + {% if document.days_overdue is not None or last_reminder %}

- {% if days_overdue is not None %}{% blocktranslate count count=days_overdue %}{{ count }} dag te laat{% plural %}{{ count }} dagen te laat{% endblocktranslate %}{% endif %} - {% if days_overdue is not None and last_reminder %}·{% endif %} + {% if document.days_overdue is not None %}{% blocktranslate count count=document.days_overdue %}{{ count }} dag te laat{% plural %}{{ count }} dagen te laat{% endblocktranslate %}{% endif %} + {% if document.days_overdue is not None and last_reminder %}·{% endif %} {% if last_reminder %}{% blocktranslate with date=last_reminder.sent_at|date:"SHORT_DATE_FORMAT" %}Laatste herinnering: {{ date }}{% endblocktranslate %}{% endif %}

{% endif %} @@ -124,7 +124,7 @@

{% translate "Betaalstatus" %}

{% 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/tests/documents/test_mailing.py b/tests/documents/test_mailing.py index ac10c47..0155c36 100644 --- a/tests/documents/test_mailing.py +++ b/tests/documents/test_mailing.py @@ -779,3 +779,14 @@ def refuse(*args, **kwargs): 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/e2e/test_browser.py b/tests/e2e/test_browser.py index 4427f2c..d290a7e 100644 --- a/tests/e2e/test_browser.py +++ b/tests/e2e/test_browser.py @@ -1360,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}") From d354c0cccda8bdc3fc1b45268256f55596cc0a43 Mon Sep 17 00:00:00 2001 From: Arne Date: Fri, 13 Nov 2026 07:38:44 +0100 Subject: [PATCH 05/19] fix(updates): the Mac app keeps its version when a new one needs a newer macOS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After downloading, the Mac app reads LSMinimumSystemVersion from the new Huismus.app in the .dmg. On an older macOS it installs nothing, not at start and not with the button, and the overview and Instellingen → Updates say which macOS is needed and to update macOS first. 0.1.4 asked macOS 15; a 0.1.3 app on macOS 14 updated itself and didn't open any more. Closes #155 Playbook: n.v.t. — alleen voor Huismus, geen workflow gewijzigd Co-Authored-By: Claude Opus 5.5 --- SPEC.md | 2 +- desktop/app.py | 5 + desktop/updater.py | 30 ++++++ docs/desktop.md | 19 +++- docs/hulp/desktop-app.en.md | 5 + docs/hulp/desktop-app.nl.md | 6 ++ huismus/core/update_views.py | 17 +++- huismus/core/updates.py | 111 +++++++++++++++++++++-- huismus/core/views.py | 8 ++ huismus/locale/en/LC_MESSAGES/django.po | 35 ++++++- huismus/locale/nl/LC_MESSAGES/django.po | 16 +++- huismus/templates/business/updates.html | 4 +- huismus/templates/core/home.html | 4 +- tests/core/test_update_views.py | 62 +++++++++++++ tests/core/test_updates.py | 116 ++++++++++++++++++++++++ tests/desktop/test_updater.py | 43 +++++++++ tests/e2e/test_desktop_app.py | 33 +++++++ 17 files changed, 497 insertions(+), 19 deletions(-) diff --git a/SPEC.md b/SPEC.md index 61a32e6..249cce7 100644 --- a/SPEC.md +++ b/SPEC.md @@ -202,7 +202,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. 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/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/huismus/core/update_views.py b/huismus/core/update_views.py index 2245b73..31546bd 100644 --- a/huismus/core/update_views.py +++ b/huismus/core/update_views.py @@ -96,6 +96,7 @@ def page(request): "whats_new_url": _whats_new_url(), "waiting": updates.waiting() is not None, "downloading": updates.downloading() is not None, + **_needs_macos(), "problem": _problem(code) if code else "", # Then the download by hand, from the release's page. "download_by_hand": code == "not-writable", @@ -132,6 +133,15 @@ def check(request): return redirect("business:updates") +def _needs_macos() -> dict: + """When the new version needs a newer macOS than this Mac has: which, + and this Mac's (issue #155). Then no button.""" + needed = updates.needs_macos() + if not needed: + return {} + return {"needs_macos": updates.macos_label(needed), "this_macos": updates.this_macos()} + + def _whats_new_url() -> str: """On the site, not in this Huismus: the new version brings its own text for Hulp → Wat is er nieuw, so only the site has it before updating.""" @@ -154,13 +164,16 @@ 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.UpdateError as error: - request.session["update_problem"] = str(error) + # A newer macOS is no error: Updates says what to do + # (huismus-intern/besluiten.md, 2026-11-13). + if str(error) != "macos": + request.session["update_problem"] = str(error) return redirect("business:updates") return render(request, "business/updating.html", {"release": release}) return render( diff --git a/huismus/core/updates.py b/huismus/core/updates.py index 19864b7..4afa03b 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 @@ -89,7 +96,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,10 +341,23 @@ 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 + _keep_download(release, path) + + +def _keep_download(release: Release, path: Path) -> str: + """Records the checked file for the next start, with the oldest macOS + it opens on, and returns that minimum.""" + minimum = _read_minimum_os(path) 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, + }, download_failed="", ) + return minimum def _waiting_file(status: Status) -> Path | None: @@ -347,10 +367,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 +387,82 @@ 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. +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, and installing + would fail on that package anyway.""" + 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 needs_macos(minimum: str | None = None) -> str: + """The macOS the downloaded new version needs, as the user reads it + ("15", not "15.0"), when this Mac's is older; "" otherwise. Without + minimum, the one recorded for the available version.""" + if minimum is None: + release = available() + downloaded = load_status().downloaded + if release is None or downloaded.get("version") != release.version: + return "" + minimum = downloaded.get("minimum_os", "") + if not older_macos(this_macos(), minimum): + return "" + return ".".join(str(part) for part in _macos_parts(minimum)) + + 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 +572,10 @@ 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. Kept, so Updates can say which macOS it needs. + if needs_macos(_keep_download(release, package)): + raise UpdateError("macos") try: backup = auto_backups.safety_backup() except auto_backups.SafetyBackupError as error: @@ -520,7 +616,10 @@ def install_at_start() -> bool: install(release) except UpdateError as error: logger.warning("Automatisch bijwerken naar %s lukte niet: %s", release.version, error) - if str(error) == "backup": + if str(error) in ("backup", "macos"): + # Nothing was tried. A failed backup: the overview's backup + # warning says why. A newer macOS: Updates says so, and it's + # installed once macOS is updated. return False update_status(auto_failed=release.version, not_installed=release.version) return False diff --git a/huismus/core/views.py b/huismus/core/views.py index 6f65c69..10523d8 100644 --- a/huismus/core/views.py +++ b/huismus/core/views.py @@ -159,9 +159,17 @@ def _update_notices(request) -> dict: "new_release": updates.available(), "release_waiting": updates.waiting(), "release_downloading": updates.downloading(), + "release_needs_macos": _needs_macos(), } +def _needs_macos() -> str: + """ "15 (Sequoia)" when the new version needs a newer macOS than this + Mac has (issue #155), else "".""" + needed = updates.needs_macos() + return updates.macos_label(needed) if needed else "" + + @login_required @require_POST def updated_seen(request): diff --git a/huismus/locale/en/LC_MESSAGES/django.po b/huismus/locale/en/LC_MESSAGES/django.po index bb47a6e..f6332bf 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 09:58+0100\n" +"POT-Creation-Date: 2026-11-15 10:32+0100\n" "PO-Revision-Date: 2026-09-25 08:36+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -1705,12 +1705,16 @@ msgstr "Dear {naam}," 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." +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." +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," @@ -3549,7 +3553,11 @@ msgid "" "{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 and a reminder also {vervaldatum}, for a reminder {openstaand}, for a quote {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 and a reminder also {vervaldatum}, for " +"a reminder {openstaand}, for a quote {geldig_tot}." #, python-format msgid "%(counter)s veld heeft aandacht nodig" @@ -3587,6 +3595,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." @@ -3933,6 +3952,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 " diff --git a/huismus/locale/nl/LC_MESSAGES/django.po b/huismus/locale/nl/LC_MESSAGES/django.po index a6dcc2b..8a698e4 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 09:58+0100\n" +"POT-Creation-Date: 2026-11-15 10:32+0100\n" "PO-Revision-Date: 2026-09-25 08:36+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -3368,6 +3368,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 "" @@ -3683,6 +3691,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 " diff --git a/huismus/templates/business/updates.html b/huismus/templates/business/updates.html index 1f5ab34..42b5c12 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 24f0c4f..7f8bf9c 100644 --- a/huismus/templates/core/home.html +++ b/huismus/templates/core/home.html @@ -78,7 +78,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/tests/core/test_update_views.py b/tests/core/test_update_views.py index d2f1606..ad16886 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.UpdateError("macos") + + 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..75c77bf 100644 --- a/tests/core/test_updates.py +++ b/tests/core/test_updates.py @@ -427,6 +427,122 @@ 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_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/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. From afbd094574dbe07213e548d082f81781953b1678 Mon Sep 17 00:00:00 2001 From: Arne Date: Fri, 13 Nov 2026 07:40:20 +0100 Subject: [PATCH 06/19] refactor(updates): one label helper, NeedsNewerMacOS, explicit check in install MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From review: needs_macos split from too_old_for, the minimum recorded and checked in three plain lines, and a subclass instead of the string "macos". Also a test for an even newer version that needs the newer macOS too. Playbook: n.v.t. — alleen voor Huismus Co-Authored-By: Claude Opus 5.5 --- huismus/core/update_views.py | 22 ++++------ huismus/core/updates.py | 78 +++++++++++++++++++++------------ huismus/core/views.py | 9 +--- tests/core/test_update_views.py | 2 +- tests/core/test_updates.py | 11 +++++ 5 files changed, 72 insertions(+), 50 deletions(-) diff --git a/huismus/core/update_views.py b/huismus/core/update_views.py index 31546bd..414b751 100644 --- a/huismus/core/update_views.py +++ b/huismus/core/update_views.py @@ -96,7 +96,9 @@ def page(request): "whats_new_url": _whats_new_url(), "waiting": updates.waiting() is not None, "downloading": updates.downloading() is not None, - **_needs_macos(), + # 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", @@ -133,15 +135,6 @@ def check(request): return redirect("business:updates") -def _needs_macos() -> dict: - """When the new version needs a newer macOS than this Mac has: which, - and this Mac's (issue #155). Then no button.""" - needed = updates.needs_macos() - if not needed: - return {} - return {"needs_macos": updates.macos_label(needed), "this_macos": updates.this_macos()} - - def _whats_new_url() -> str: """On the site, not in this Huismus: the new version brings its own text for Hulp → Wat is er nieuw, so only the site has it before updating.""" @@ -169,11 +162,12 @@ def install(request): 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: - # A newer macOS is no error: Updates says what to do - # (huismus-intern/besluiten.md, 2026-11-13). - if str(error) != "macos": - request.session["update_problem"] = str(error) + request.session["update_problem"] = str(error) return redirect("business:updates") return render(request, "business/updating.html", {"release": release}) return render( diff --git a/huismus/core/updates.py b/huismus/core/updates.py index 4afa03b..88f46df 100644 --- a/huismus/core/updates.py +++ b/huismus/core/updates.py @@ -75,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 @@ -341,23 +349,21 @@ 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 - _keep_download(release, path) + _record_download(release, path, _read_minimum_os(path)) -def _keep_download(release: Release, path: Path) -> str: - """Records the checked file for the next start, with the oldest macOS - it opens on, and returns that minimum.""" - minimum = _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, - "minimum_os": minimum, + "minimum_os": minimum_os, }, download_failed="", ) - return minimum def _waiting_file(status: Status) -> Path | None: @@ -397,14 +403,18 @@ def downloading() -> Release | None: # 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. +# 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, and installing - would fail on that package anyway.""" + 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: @@ -448,21 +458,30 @@ def macos_label(version: str) -> str: return f"{version} ({name})" if name else version -def needs_macos(minimum: str | None = None) -> str: - """The macOS the downloaded new version needs, as the user reads it - ("15", not "15.0"), when this Mac's is older; "" otherwise. Without - minimum, the one recorded for the available version.""" - if minimum is None: - release = available() - downloaded = load_status().downloaded - if release is None or downloaded.get("version") != release.version: - return "" - minimum = downloaded.get("minimum_os", "") +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 @@ -573,9 +592,12 @@ def install(release: Release) -> None: 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. Kept, so Updates can say which macOS it needs. - if needs_macos(_keep_download(release, package)): - raise UpdateError("macos") + # 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: @@ -614,12 +636,14 @@ 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) in ("backup", "macos"): - # Nothing was tried. A failed backup: the overview's backup - # warning says why. A newer macOS: Updates says so, and it's - # installed once macOS is updated. + if str(error) == "backup": return False update_status(auto_failed=release.version, not_installed=release.version) return False diff --git a/huismus/core/views.py b/huismus/core/views.py index 10523d8..5a14bf1 100644 --- a/huismus/core/views.py +++ b/huismus/core/views.py @@ -159,17 +159,10 @@ def _update_notices(request) -> dict: "new_release": updates.available(), "release_waiting": updates.waiting(), "release_downloading": updates.downloading(), - "release_needs_macos": _needs_macos(), + "release_needs_macos": updates.needs_macos_label(), } -def _needs_macos() -> str: - """ "15 (Sequoia)" when the new version needs a newer macOS than this - Mac has (issue #155), else "".""" - needed = updates.needs_macos() - return updates.macos_label(needed) if needed else "" - - @login_required @require_POST def updated_seen(request): diff --git a/tests/core/test_update_views.py b/tests/core/test_update_views.py index ad16886..a063c9a 100644 --- a/tests/core/test_update_views.py +++ b/tests/core/test_update_views.py @@ -281,7 +281,7 @@ def test_bijwerken_for_a_newer_macos_is_no_error(desktop, monkeypatch): def asks_15(release): updates.update_status(downloaded={"version": "1.4.0", "path": "", "minimum_os": "15"}) - raise updates.UpdateError("macos") + raise updates.NeedsNewerMacOS with patch("huismus.core.updates.install", side_effect=asks_15): response = desktop.post(reverse("business:updates_install"), follow=True) diff --git a/tests/core/test_updates.py b/tests/core/test_updates.py index 75c77bf..e22395a 100644 --- a/tests/core/test_updates.py +++ b/tests/core/test_updates.py @@ -518,6 +518,17 @@ def test_bijwerken_refuses_a_version_for_a_newer_macos(needs_15, monkeypatch): 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") From 5e5a266a2266ed84b462b7ea4c83d0a4c0269b20 Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 11:03:59 +0100 Subject: [PATCH 07/19] feat(workflow): /regie, one session that steers several milestones The /mijlpaal chain runs one cloud session after another, and cloud sessions don't report back, so the owner had no overview. /regie runs locally, starts up to three /mijlpaal sessions from the board queue (never two on one screen), reads their status files in .git/regie/ and bundles status, questions and screenshots for the owner. Under regie a milestone reports instead of asking or notifying the owner, doesn't release and starts no successor; the regie releases on Wednesday. Playbook: https://github.com/codebyarne/agentic-playbook/pull/27 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/mijlpaal/SKILL.md | 27 +++++- .claude/skills/regie/SKILL.md | 161 +++++++++++++++++++++++++++++++ CLAUDE.md | 9 ++ 3 files changed, 196 insertions(+), 1 deletion(-) create mode 100644 .claude/skills/regie/SKILL.md 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: From 99f29bd50c70d4b53b1eff217c9203535e1c8a2e Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:16:56 +0100 Subject: [PATCH 08/19] feat(expenses): on a phone a new expense starts with the camera (#188) Tapping Uitgave on a phone opens the camera. The photo goes into the tray at once, then a page shows it above the amount, the supplier, the date and the category of one line. Uitgave opslaan makes the expense with the photo on it; Alleen de foto bewaren leaves it for Verwerken. Without a connection the photo stays to send again. Wide screens and no-JS keep the old form. Co-Authored-By: Claude Opus 5.5 --- huismus/core/static/core/app.js | 72 ++++++++ huismus/core/static/core/huismus.css | 10 ++ huismus/expenses/photo_views.py | 109 ++++++++++++ huismus/expenses/urls.py | 5 +- huismus/templates/base.html | 11 ++ huismus/templates/expenses/photo.html | 71 ++++++++ tests/e2e/test_every_page.py | 3 + tests/e2e/test_photo_first.py | 116 +++++++++++++ tests/expenses/test_photo.py | 241 ++++++++++++++++++++++++++ 9 files changed, 637 insertions(+), 1 deletion(-) create mode 100644 huismus/expenses/photo_views.py create mode 100644 huismus/templates/expenses/photo.html create mode 100644 tests/e2e/test_photo_first.py create mode 100644 tests/expenses/test_photo.py diff --git a/huismus/core/static/core/app.js b/huismus/core/static/core/app.js index 4e7c14c..888f793 100644 --- a/huismus/core/static/core/app.js +++ b/huismus/core/static/core/app.js @@ -674,3 +674,75 @@ 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 { + response = await fetch(form.action, { method: "POST", body: data }); + } catch { + response = null; + } + if (!response?.ok) { + cameraToast("camera-offline"); + return; + } + unsent = null; + // Where Huismus sent it: the photo page, or the ordinary form with the + // reason it refused the file. + window.location.assign(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 5fb555e..64b3665 100644 --- a/huismus/core/static/core/huismus.css +++ b/huismus/core/static/core/huismus.css @@ -809,6 +809,16 @@ div.hint-banner:hover { border-color: var(--border); } .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: 40dvh; } +.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; } +.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/expenses/photo_views.py b/huismus/expenses/photo_views.py new file mode 100644 index 0000000..80e17f3 --- /dev/null +++ b/huismus/expenses/photo_views.py @@ -0,0 +1,109 @@ +# 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.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" + + +@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 redirect("expenses:create") + uploaded = form.cleaned_data["file"] + replaced = Attachment.objects.in_tray().filter(pk=_int(request.POST.get("vervangt"))).first() + if replaced is not None: + replaced.file.delete(save=False) + replaced.delete() + receipt = Attachment.objects.create( + file=uploaded, kind="receipt", sha256=sha256_of(uploaded), source=SOURCE + ) + return redirect("expenses:photo", pk=receipt.pk) + + +@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"), + }, + ) + + +def _int(value) -> int | None: + try: + return int(value) + except (TypeError, ValueError): + return None 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/templates/base.html b/huismus/templates/base.html index b9df5bd..28703d6 100644 --- a/huismus/templates/base.html +++ b/huismus/templates/base.html @@ -116,6 +116,17 @@
{% translate "Facturen en uitgaven voor zzp'ers, met of zonder KOR" %}{% translate "Sneltoetsen:" %} N {% translate "nieuw" %}{% block shortcut_search %}{% endblock %}
+{% if user.is_authenticated %} +{% 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.{% endcomment %} + + + +{% endif %} {% include "core/_toasts.html" %} {% endblock %} diff --git a/huismus/templates/expenses/photo.html b/huismus/templates/expenses/photo.html new file mode 100644 index 0000000..9eb1095 --- /dev/null +++ b/huismus/templates/expenses/photo.html @@ -0,0 +1,71 @@ +{% extends "base.html" %} +{% load i18n forms %} + +{% block title %}{% translate "Nieuwe uitgave" %} — Huismus{% endblock %} +{% block content_class %}content-narrow{% endblock %} + +{% block content %} +{% comment %}A new expense on a phone, the photo first (#188, +huismus/expenses/photo_views.py). The photo is in the tray already; the +fields are one line of the ordinary form, the amount first.{% endcomment %} +
+
+ {% translate "Uitgaven" %} +

{% translate "Nieuwe uitgave" %}

+
+
+ +{% form_errors form formset %} + +
+ {% blocktranslate with name=receipt.filename asvar receipt_label %}Bonnetje {{ name }}{% endblocktranslate %} + {% if receipt.is_pdf %} +
{{ receipt.filename }}
+ {% else %} + {{ receipt_label }} + {% endif %} + {% comment %}"Opnieuw": a new photo in place of this one (photo_upload, + vervangt). Its own form: forms can't nest. data-camera: app.js sends it + as soon as it is taken, and says so when Huismus can't be reached. The + old photo goes only once the new one is in.{% endcomment %} +
+ {% csrf_token %} + + + +
+
+ +
+ {% csrf_token %} + {% comment %}Enter saves: the first submit button of a form is the one + Enter clicks, and "Meer regels" comes before the bar.{% endcomment %} + + {{ formset.management_form }} + {{ line_form.id }} +
+ {% translate "Bedrag, zoals je het betaalde" as amount_label %} +
{% field line_form.amount_cents money=True label=amount_label %}
+ {% comment %}Without the KOR every line needs its VAT and its rate + (ExpenseLineForm), right under the amount.{% endcomment %} + {% if "vat_rate" in line_form.fields %} + {% field line_form.vat_info_cents span=3 money=True %} + {% field line_form.vat_rate span=3 %} + {% endif %} + {% field form.supplier %} + {% field form.date span=3 %} + {% field line_form.category span=3 %} +
+ {% comment %}Verwerken for this receipt, with what was typed and one + line more, saving nothing: its "Regel toevoegen" without JS + (process_views._one_more_line).{% endcomment %} +
+
+ + +
+
+{% endblock %} diff --git a/tests/e2e/test_every_page.py b/tests/e2e/test_every_page.py index ea1c066..6d9aad2 100644 --- a/tests/e2e/test_every_page.py +++ b/tests/e2e/test_every_page.py @@ -93,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..8378998 --- /dev/null +++ b/tests/e2e/test_photo_first.py @@ -0,0 +1,116 @@ +# 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 + +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 = [] + page.on("pageerror", lambda error: 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_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..19f5c35 --- /dev/null +++ b/tests/expenses/test_photo.py @@ -0,0 +1,241 @@ +# 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", **extra): + """The photo from the camera, as app.js sends it.""" + return client.post(reverse("expenses:photo_upload"), {"file": _photo(color=color), **extra}) + + +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 From 53c28fc838d1f3824878c9c40d4e96bd32d0ee4f Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:17:51 +0100 Subject: [PATCH 09/19] docs(hulp): an expense with the camera on your phone (#188) Co-Authored-By: Claude Opus 5.5 --- SPEC.md | 3 ++- docs/hulp/telefoon.en.md | 17 +++++++++++++++++ docs/hulp/telefoon.nl.md | 18 ++++++++++++++++++ docs/hulp/uitgaven.en.md | 3 +++ docs/hulp/uitgaven.nl.md | 3 +++ 5 files changed, 43 insertions(+), 1 deletion(-) diff --git a/SPEC.md b/SPEC.md index 249cce7..49d55be 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`). @@ -308,6 +308,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; approved by the owner on 2026-11-15, 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 while it 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, the desktop app 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. 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). From 0db0e0e484839f6200cef0979579fc5a6ac0195a Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:21:00 +0100 Subject: [PATCH 10/19] fix(expenses): Opnieuw only replaces a phone photo, never in the desktop app (#188) Review: the old photo goes only after the new one is in; an error from Huismus says so instead of claiming no connection; closing the camera has its browser test. Co-Authored-By: Claude Opus 5.5 --- SPEC.md | 2 +- huismus/core/static/core/app.js | 9 ++++++--- huismus/expenses/photo_views.py | 21 ++++++++++----------- huismus/templates/base.html | 6 ++++-- tests/e2e/test_photo_first.py | 18 +++++++++++++++++- tests/expenses/test_photo.py | 20 ++++++++++++++++++++ 6 files changed, 58 insertions(+), 18 deletions(-) diff --git a/SPEC.md b/SPEC.md index 49d55be..8a88685 100644 --- a/SPEC.md +++ b/SPEC.md @@ -308,7 +308,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; approved by the owner on 2026-11-15, 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 while it 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, the desktop app and no JS keep the ordinary form. +- **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. diff --git a/huismus/core/static/core/app.js b/huismus/core/static/core/app.js index 888f793..0198cec 100644 --- a/huismus/core/static/core/app.js +++ b/huismus/core/static/core/app.js @@ -724,12 +724,15 @@ async function sendPhoto(form, file) { try { response = await fetch(form.action, { method: "POST", body: data }); } catch { - response = null; - } - if (!response?.ok) { + // 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 sent it: the photo page, or the ordinary form with the // reason it refused the file. diff --git a/huismus/expenses/photo_views.py b/huismus/expenses/photo_views.py index 80e17f3..d8d5e7f 100644 --- a/huismus/expenses/photo_views.py +++ b/huismus/expenses/photo_views.py @@ -47,13 +47,19 @@ def photo_upload(request): messages.error(request, form.errors["file"][0]) return redirect("expenses:create") uploaded = form.cleaned_data["file"] - replaced = Attachment.objects.in_tray().filter(pk=_int(request.POST.get("vervangt"))).first() - if replaced is not None: - replaced.file.delete(save=False) - replaced.delete() 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 redirect("expenses:photo", pk=receipt.pk) @@ -100,10 +106,3 @@ def photo_expense(request, pk): "upload_url": reverse("expenses:photo_upload"), }, ) - - -def _int(value) -> int | None: - try: - return int(value) - except (TypeError, ValueError): - return None diff --git a/huismus/templates/base.html b/huismus/templates/base.html index 28703d6..8d33c57 100644 --- a/huismus/templates/base.html +++ b/huismus/templates/base.html @@ -116,16 +116,18 @@
{% translate "Facturen en uitgaven voor zzp'ers, met of zonder KOR" %}{% translate "Sneltoetsen:" %} N {% translate "nieuw" %}{% block shortcut_search %}{% endblock %}
-{% if user.is_authenticated %} +{% 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.{% endcomment %} +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" %} diff --git a/tests/e2e/test_photo_first.py b/tests/e2e/test_photo_first.py index 8378998..940606a 100644 --- a/tests/e2e/test_photo_first.py +++ b/tests/e2e/test_photo_first.py @@ -11,6 +11,7 @@ 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) @@ -32,7 +33,11 @@ def phone(app, browser, browser_name): context.add_cookies(app.context.cookies()) page = context.new_page() errors = [] - page.on("pageerror", lambda error: errors.append(str(error))) + # 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() @@ -108,6 +113,17 @@ def test_without_a_connection_the_photo_stays_to_send_again(phone): assert Attachment.objects.in_tray().count() == 1 +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/") diff --git a/tests/expenses/test_photo.py b/tests/expenses/test_photo.py index 19f5c35..7ca37c1 100644 --- a/tests/expenses/test_photo.py +++ b/tests/expenses/test_photo.py @@ -239,3 +239,23 @@ def test_alleen_de_foto_bewaren_leaves_it_in_the_tray_and_reads_it(logged_in, mo 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() From 9440a88ba3ccfa8f4ded00244e070bb31a10c98c Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:24:24 +0100 Subject: [PATCH 11/19] style(expenses): a smaller photo, so the amount shows above the bar (#188) Co-Authored-By: Claude Opus 5.5 --- huismus/core/static/core/huismus.css | 4 ++-- huismus/templates/expenses/photo.html | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/huismus/core/static/core/huismus.css b/huismus/core/static/core/huismus.css index 64b3665..861b375 100644 --- a/huismus/core/static/core/huismus.css +++ b/huismus/core/static/core/huismus.css @@ -812,12 +812,12 @@ div.hint-banner:hover { border-color: var(--border); } /* 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: 40dvh; } +.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; } +.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; } diff --git a/huismus/templates/expenses/photo.html b/huismus/templates/expenses/photo.html index 9eb1095..ae75a1f 100644 --- a/huismus/templates/expenses/photo.html +++ b/huismus/templates/expenses/photo.html @@ -65,7 +65,7 @@

{% translate "Nieuwe uitgave" %}

- +
{% endblock %} From 4ee51de7feb8214279ec3cd61de1ae5fb6caeea1 Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:29:49 +0100 Subject: [PATCH 12/19] fix(expenses): a refused photo keeps its reason on the ordinary form (#188) fetch() followed the redirect and used up the message, so the page that opened after it had none. To the camera's upload Huismus now answers with where to go instead of a redirect. Co-Authored-By: Claude Opus 5.5 --- huismus/core/static/core/app.js | 15 +++++++++++---- huismus/expenses/photo_views.py | 20 ++++++++++++++++++-- tests/e2e/test_photo_first.py | 10 ++++++++++ tests/expenses/test_photo.py | 21 ++++++++++++++++++--- 4 files changed, 57 insertions(+), 9 deletions(-) diff --git a/huismus/core/static/core/app.js b/huismus/core/static/core/app.js index 0198cec..2dd7fda 100644 --- a/huismus/core/static/core/app.js +++ b/huismus/core/static/core/app.js @@ -722,7 +722,14 @@ async function sendPhoto(form, file) { data.set("file", file); let response; try { - response = await fetch(form.action, { method: "POST", body: data }); + // 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"); @@ -734,9 +741,9 @@ async function sendPhoto(form, file) { return; } unsent = null; - // Where Huismus sent it: the photo page, or the ordinary form with the - // reason it refused the file. - window.location.assign(response.url); + // 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) => { diff --git a/huismus/expenses/photo_views.py b/huismus/expenses/photo_views.py index d8d5e7f..e282f90 100644 --- a/huismus/expenses/photo_views.py +++ b/huismus/expenses/photo_views.py @@ -16,6 +16,7 @@ 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 @@ -32,6 +33,9 @@ # 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 @@ -45,7 +49,7 @@ def photo_upload(request): # 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 redirect("expenses:create") + 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 @@ -60,7 +64,19 @@ def photo_upload(request): for old in replaced: old.file.delete(save=False) old.delete() - return redirect("expenses:photo", pk=receipt.pk) + 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 diff --git a/tests/e2e/test_photo_first.py b/tests/e2e/test_photo_first.py index 940606a..0cf1287 100644 --- a/tests/e2e/test_photo_first.py +++ b/tests/e2e/test_photo_first.py @@ -113,6 +113,16 @@ def test_without_a_connection_the_photo_stays_to_send_again(phone): 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(): diff --git a/tests/expenses/test_photo.py b/tests/expenses/test_photo.py index 7ca37c1..91eda43 100644 --- a/tests/expenses/test_photo.py +++ b/tests/expenses/test_photo.py @@ -50,9 +50,11 @@ def _photo(name="IMG_0001.jpg", color="red"): return SimpleUploadedFile(name, buffer.getvalue(), content_type="image/jpeg") -def _take(client, color="red", **extra): - """The photo from the camera, as app.js sends it.""" - return client.post(reverse("expenses:photo_upload"), {"file": _photo(color=color), **extra}) +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): @@ -259,3 +261,16 @@ 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() From dc4a5e0ebede8a5942cedd2ea08a0afcf0c24c65 Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 10:41:45 +0100 Subject: [PATCH 13/19] fix(expenses): the receipt on a new expense is no longer called optional A receipt is the proof of an expense. Saving without one still works. Co-Authored-By: Claude Opus 5.5 --- huismus/templates/expenses/form.html | 2 +- tests/expenses/test_views.py | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) 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 From 5a3c594bd2d5c919cd95787541087d34af5a1f2d Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 11:25:03 +0100 Subject: [PATCH 17/19] docs: the next number by hand in SPEC and the help (#141) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Playbook: n.v.t. — alleen voor Huismus, geen workflow gewijzigd Co-Authored-By: Claude Opus 5.5 --- SPEC.md | 3 ++- docs/hulp/beginnen.en.md | 4 +++- docs/hulp/beginnen.nl.md | 4 +++- docs/hulp/facturen.en.md | 10 ++++++++++ docs/hulp/facturen.nl.md | 10 ++++++++++ 5 files changed, 28 insertions(+), 3 deletions(-) diff --git a/SPEC.md b/SPEC.md index 8a88685..f584965 100644 --- a/SPEC.md +++ b/SPEC.md @@ -220,7 +220,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). @@ -360,6 +360,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`. 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/facturen.en.md b/docs/hulp/facturen.en.md index e86889b..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. diff --git a/docs/hulp/facturen.nl.md b/docs/hulp/facturen.nl.md index 7177247..6534e28 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 From 8f45b86d5cef060343e9fd4d6a5116df5abdd55a Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 11:31:23 +0100 Subject: [PATCH 18/19] refactor(numbering): say why unchanged is skipped and what source means; test the import's link (#141) Co-Authored-By: Claude Opus 5.5 --- huismus/business/forms.py | 2 ++ huismus/documents/numbering.py | 5 ++++- huismus/templates/business/_number_formats.html | 3 ++- tests/imports/test_commit.py | 7 +++++++ 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/huismus/business/forms.py b/huismus/business/forms.py index 0e371dd..37e2db3 100644 --- a/huismus/business/forms.py +++ b/huismus/business/forms.py @@ -318,6 +318,8 @@ 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: diff --git a/huismus/documents/numbering.py b/huismus/documents/numbering.py index a183446..fab7c13 100644 --- a/huismus/documents/numbering.py +++ b/huismus/documents/numbering.py @@ -167,7 +167,10 @@ def next_sequence_number_is_fixed(kind: str) -> bool: user continues by hand. A reopened document ("Toch bewerken") keeps its number, so it still counts.""" return Document.objects.filter( - kind__in=_SEQUENCE_DOCUMENT_KINDS[kind], number__isnull=False, source="" + # 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() diff --git a/huismus/templates/business/_number_formats.html b/huismus/templates/business/_number_formats.html index 269754a..476bc46 100644 --- a/huismus/templates/business/_number_formats.html +++ b/huismus/templates/business/_number_formats.html @@ -2,7 +2,8 @@ {% 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.{% endcomment %} +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 %} 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(): From 895455afa29f0178297796fe3c773ddea4fd30e1 Mon Sep 17 00:00:00 2001 From: Arne Date: Sun, 15 Nov 2026 19:07:55 +0100 Subject: [PATCH 19/19] fix(documents): an overdue invoice says how late it is once, in its pill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After bringing huisstijl up to date with main, the payment box repeated the pill's 'N dagen te laat'. It now only shows when the last reminder went. Playbook: n.v.t. — alleen een Huismus-scherm Co-Authored-By: Claude Opus 5.5 --- huismus/locale/en/LC_MESSAGES/django.po | 14 +++++++------- huismus/locale/nl/LC_MESSAGES/django.po | 14 +++++++------- huismus/templates/documents/detail.html | 9 +++------ 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/huismus/locale/en/LC_MESSAGES/django.po b/huismus/locale/en/LC_MESSAGES/django.po index 4fe1732..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 18:56+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" @@ -4618,12 +4618,6 @@ msgstr "To invoice %(number)s" msgid "Betaalstatus" msgstr "Payment status" -#, 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 "Laatste herinnering: %(date)s" msgstr "Last reminder: %(date)s" @@ -6808,6 +6802,12 @@ 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 " diff --git a/huismus/locale/nl/LC_MESSAGES/django.po b/huismus/locale/nl/LC_MESSAGES/django.po index 3811ad0..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 18:56+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" @@ -4319,12 +4319,6 @@ msgstr "" msgid "Betaalstatus" 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" - #, python-format msgid "Laatste herinnering: %(date)s" msgstr "" @@ -6242,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/documents/detail.html b/huismus/templates/documents/detail.html index 04e2b15..85a5dee 100644 --- a/huismus/templates/documents/detail.html +++ b/huismus/templates/documents/detail.html @@ -113,12 +113,9 @@

{% 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 %}
- {% if document.days_overdue is not None or last_reminder %} -

- {% if document.days_overdue is not None %}{% blocktranslate count count=document.days_overdue %}{{ count }} dag te laat{% plural %}{{ count }} dagen te laat{% endblocktranslate %}{% endif %} - {% if document.days_overdue is not None and last_reminder %}·{% endif %} - {% if last_reminder %}{% blocktranslate with date=last_reminder.sent_at|date:"SHORT_DATE_FORMAT" %}Laatste herinnering: {{ date }}{% endblocktranslate %}{% 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 %}