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 diff --git a/huismus/business/forms.py b/huismus/business/forms.py index c2b92db..37e2db3 100644 --- a/huismus/business/forms.py +++ b/huismus/business/forms.py @@ -5,12 +5,21 @@ from django import forms from django.core.exceptions import ValidationError from django.core.files.uploadedfile import UploadedFile +from django.db import transaction from django.utils.text import format_lazy from django.utils.translation import gettext_lazy as _ from huismus.core.forms import EuroCentsField from huismus.documents import mail_texts -from huismus.documents.numbering import format_number +from huismus.documents.numbering import ( + NumberingError, + check_next_sequence_number, + format_number, + next_sequence_number, + next_sequence_number_is_fixed, + set_next_sequence_number, + year_if_issued_today, +) from . import smtp from .logo import validate_and_sanitize_logo @@ -22,6 +31,22 @@ ) +# Not settings fields: they set the sequence (documents.numbering). Per +# field the kind of sequence, label and help. +NEXT_NUMBER_FIELDS = { + "next_invoice_number": ( + "invoice", + _("Volgnummer van je volgende factuur"), + _("Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste factuur komt."), + ), + "next_quote_number": ( + "quote", + _("Volgnummer van je volgende offerte"), + _("Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste offerte komt."), + ), +} + + # Instellingen → Mailen: a subject and a body per kind and language. MAIL_TEXT_FIELDS = [ (kind, part, language, mail_texts.field_name(kind, part, language)) @@ -254,3 +279,61 @@ def __init__(self, *args, fields, **kwargs): for name in list(self.fields): if name not in fields: del self.fields[name] + # The next number by hand (issue #141), where the fields name it + # (Facturen en nummering, the start's Facturen step), and only for a + # kind Huismus never gave a number yet (invariant 3). + year = year_if_issued_today(self.instance.number_reset_yearly) + self.fixed_sequences = {} + for name, (kind, label, help_text) in NEXT_NUMBER_FIELDS.items(): + if name not in fields: + continue + self.fixed_sequences[kind] = next_sequence_number_is_fixed(kind) + if not self.fixed_sequences[kind]: + self.fields[name] = forms.IntegerField( + label=label, + help_text=help_text, + min_value=1, + # Empty keeps the number as it is. + required=False, + initial=next_sequence_number(kind, year=year), + ) + + def _next_numbers(self): + """(kind, format, year, value) per next-number field in the form, + from what the form saves: the number format and yearly reset may + change in the same save.""" + reset_yearly = self.cleaned_data.get( + "number_reset_yearly", self.instance.number_reset_yearly + ) + year = year_if_issued_today(reset_yearly) + for name, (kind, _label, _help) in NEXT_NUMBER_FIELDS.items(): + value = self.cleaned_data.get(name) + template = self.cleaned_data.get(f"{kind}_number_format") or getattr( + self.instance, f"{kind}_number_format" + ) + if name in self.fields and value is not None: + yield name, kind, template, year, value + + def clean(self): + cleaned = super().clean() + if not self.errors: + for name, kind, template, year, value in self._next_numbers(): + # Unchanged is not a change: no checks, so it never stops + # the rest of the form from saving. + if value == next_sequence_number(kind, year=year): + continue + try: + check_next_sequence_number(kind, template, year=year, value=value) + except NumberingError as error: + self.add_error(name, str(error)) + return cleaned + + def save(self, commit=True): + """With the next numbers, in one transaction: a refusal (an invoice + issued since the check in clean()) leaves the settings unsaved too. + Raises NumberingError then; the view shows it.""" + with transaction.atomic(): + instance = super().save(commit) + for _name, kind, template, year, value in self._next_numbers(): + set_next_sequence_number(kind, template, year=year, value=value) + return instance diff --git a/huismus/business/topics.py b/huismus/business/topics.py index 2ea1825..fa7f3e2 100644 --- a/huismus/business/topics.py +++ b/huismus/business/topics.py @@ -77,6 +77,8 @@ class Topic: "invoice_number_format", "quote_number_format", "number_reset_yearly", + "next_invoice_number", + "next_quote_number", "default_language", "currency", ), diff --git a/huismus/business/views.py b/huismus/business/views.py index 21a6e89..1356dc5 100644 --- a/huismus/business/views.py +++ b/huismus/business/views.py @@ -10,7 +10,7 @@ from huismus.core import help from huismus.core.appearance import theme_of -from huismus.documents.numbering import next_numbers_if_issued_today +from huismus.documents.numbering import NumberingError, next_numbers_if_issued_today from . import smtp, topics from .forms import MAIL_TEXT_FIELDS, MAIL_TEXT_PARTS, MAIL_TEXT_TITLES, SettingsPartForm @@ -48,9 +48,13 @@ def topic_page(request, slug): if request.method == "POST": form = SettingsPartForm(request.POST, request.FILES, instance=instance, fields=topic.fields) if form.is_valid(): - form.save() - messages.success(request, _("Instellingen opgeslagen.")) - return redirect("business:topic", slug=slug) + try: + form.save() + except NumberingError as error: + form.add_error(None, str(error)) + else: + messages.success(request, _("Instellingen opgeslagen.")) + return redirect("business:topic", slug=slug) else: form = SettingsPartForm(instance=instance, fields=topic.fields) diff --git a/huismus/core/onboarding.py b/huismus/core/onboarding.py index 1129541..32302a3 100644 --- a/huismus/core/onboarding.py +++ b/huismus/core/onboarding.py @@ -51,7 +51,13 @@ class Step: "Je betalingstermijn en hoe Huismus je facturen en offertes nummert. " "Meestal is de standaard goed." ), - ("default_payment_terms_days", "invoice_number_format", "quote_number_format"), + ( + "default_payment_terms_days", + "invoice_number_format", + "quote_number_format", + "next_invoice_number", + "next_quote_number", + ), ), Step( "logo", diff --git a/huismus/core/views.py b/huismus/core/views.py index 5a14bf1..7738a1f 100644 --- a/huismus/core/views.py +++ b/huismus/core/views.py @@ -19,7 +19,7 @@ from huismus.business.models import Settings from huismus.documents.listing import expiry_hint from huismus.documents.models import Document -from huismus.documents.numbering import next_numbers_if_issued_today +from huismus.documents.numbering import NumberingError, next_numbers_if_issued_today from huismus.expenses.inbox_views import new_receipts_context from huismus.reports.year_overview import compute_year_overview @@ -240,10 +240,14 @@ def onboarding(request, slug): if request.method == "POST": form = SettingsPartForm(request.POST, request.FILES, instance=instance, fields=step.fields) if form.is_valid(): - form.save() - if index + 1 < len(STEPS): - return redirect("onboarding", STEPS[index + 1].slug) - return redirect("onboarding_done") + try: + form.save() + except NumberingError as error: + form.add_error(None, str(error)) + else: + if index + 1 < len(STEPS): + return redirect("onboarding", STEPS[index + 1].slug) + return redirect("onboarding_done") else: form = SettingsPartForm(instance=instance, fields=step.fields) diff --git a/huismus/documents/numbering.py b/huismus/documents/numbering.py index fd8de8a..fab7c13 100644 --- a/huismus/documents/numbering.py +++ b/huismus/documents/numbering.py @@ -136,13 +136,117 @@ def next_numbers_if_issued_today(settings) -> dict[str, str | None]: ("invoice", "quote"). issue() takes the year of the document's issue date; this assumes today. Without a yearly reset the sequence has no year (Settings.number_reset_yearly).""" - year = timezone.localdate().year if settings.number_reset_yearly else None + year = year_if_issued_today(settings.number_reset_yearly) return { "invoice": peek_next_number("invoice", settings.invoice_number_format, year=year), "quote": peek_next_number("quote", settings.quote_number_format, year=year), } +# Which document kinds take their numbers from a sequence: credit notes +# share the invoice sequence (models.SEQUENCE_KIND_CHOICES). +_SEQUENCE_DOCUMENT_KINDS = {"invoice": ["invoice", "credit_note"], "quote": ["quote"]} + + +def next_sequence_number(kind: str, *, year: int | None) -> int: + """The {seq} the next document of this sequence gets. Reads only.""" + last_value = ( + NumberSequence.objects.filter(kind=kind, year=year) + .values_list("last_value", flat=True) + .first() + ) + return (last_value or 0) + 1 + + +def next_sequence_number_is_fixed(kind: str) -> bool: + """True once Huismus itself gave a document of this kind a number, in + any year. From then on numbers only move by issuing: setting the next + one by hand could leave a gap after a number Huismus gave, also in a + new year's sequence (invariant 3). Imported documents don't count: + their numbers come from the package the user left, which is what the + user continues by hand. A reopened document ("Toch bewerken") keeps its + number, so it still counts.""" + return Document.objects.filter( + # source is empty for a document made in Huismus, set for an imported one. + kind__in=_SEQUENCE_DOCUMENT_KINDS[kind], + number__isnull=False, + source="", + ).exists() + + +def lowest_next_sequence_number(kind: str, template: str, *, year: int | None) -> int: + """Just above the highest {seq} already in this sequence: the numbers + that fit the format, of this year when it resets yearly. Below that the + sequence would reach a number that exists.""" + highest = 0 + documents = Document.objects.filter( + kind__in=_SEQUENCE_DOCUMENT_KINDS[kind], number__isnull=False + ).select_related("contact") + for document in documents: + if year is not None and (document.issue_date is None or document.issue_date.year != year): + continue + customer = (document.contact.customer_number if document.contact else "") or "" + seq = parse_number(template, document.number, year=year, customer=customer) + if seq is not None: + highest = max(highest, seq) + return highest + 1 + + +def check_next_sequence_number(kind: str, template: str, *, year: int | None, value: int) -> None: + """Raise NumberingError if the next {seq} can't be set to `value` + without a gap or a number twice (invariant 3): not once Huismus issued + a document of this kind, not onto or below a number that already + exists. Up and down are both fine before that: nothing was issued from + the sequence yet, so nothing is skipped. Changes nothing; the settings + form shows its errors with it, set_next_sequence_number() checks + again under the write lock.""" + if value < 1: + raise NumberingError(_("Het volgnummer is minstens 1.")) + if next_sequence_number_is_fixed(kind): + raise NumberingError( + _("Je hebt in Huismus al een nummer uitgegeven. Het nummer loopt nu vanzelf door.") + ) + lowest = lowest_next_sequence_number(kind, template, year=year) + if value < lowest: + raise NumberingError( + _("Kies %(lowest)s of hoger. Een lager nummer bestaat al.") % {"lowest": lowest} + ) + if not uses_customer_number(template): + # An existing number that doesn't fit the format (an import) can + # still be hit exactly. With {customer} the number isn't known + # until the customer is; number_for() refuses it then. + number = format_number(template, year=year, seq=value) + if Document.objects.filter(kind__in=_SEQUENCE_DOCUMENT_KINDS[kind], number=number).exists(): + raise NumberingError( + _("Nummer %(number)s bestaat al. Kies een hoger volgnummer.") % {"number": number} + ) + + +def set_next_sequence_number(kind: str, template: str, *, year: int | None, value: int) -> None: + """Set the {seq} of the next document of this sequence by hand (SPEC.md + section 7, "the user sets the next number manually"; issue #141), for + someone continuing the numbers of another package. Raises + NumberingError where check_next_sequence_number() does. Only the + sequence row changes; a number is still given only by + allocate_number(), when issuing.""" + if value == next_sequence_number(kind, year=year): + return + with transaction.atomic(): + # A write first, as in allocate_number(): from here SQLite holds the + # write lock, so no document can be issued between the check and + # the update. Reading first and writing after could instead + # deadlock with a concurrent issue(). + ensure_sequence_row(kind, year) + check_next_sequence_number(kind, template, year=year, value=value) + NumberSequence.objects.filter(kind=kind, year=year).update(last_value=value - 1) + + +def year_if_issued_today(reset_yearly: bool) -> int | None: + """The year of the sequence a document issued today takes; without a + yearly reset the sequence has no year (Settings.number_reset_yearly).""" + return timezone.localdate().year if reset_yearly else None + + _SEQ_PLACEHOLDER = re.compile(r"\{seq(:[^}]*)?\}") diff --git a/huismus/imports/commit.py b/huismus/imports/commit.py index 9f871fd..ae664b1 100644 --- a/huismus/imports/commit.py +++ b/huismus/imports/commit.py @@ -598,7 +598,8 @@ def _continue_numbering( if unparsed: return _( "%(unparsed)s van %(total)s geïmporteerde %(label)s passen niet in het ingestelde " - "nummerformaat. Stel het volgende nummer zelf in bij Instellingen." + "nummerformaat. Stel het volgende nummer zelf in bij Instellingen → Facturen en " + "nummering." ) % {"unparsed": unparsed, "total": len(imported_numbers), "label": label} return "" diff --git a/huismus/locale/en/LC_MESSAGES/django.po b/huismus/locale/en/LC_MESSAGES/django.po index 11ff955..de0d7be 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 11:03+0100\n" +"POT-Creation-Date: 2026-11-15 11:31+0100\n" "PO-Revision-Date: 2026-09-25 08:36+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -204,6 +204,22 @@ msgstr "" "Exempt from VAT under the small business scheme (KOR). No VAT has been " "charged." +msgid "Volgnummer van je volgende factuur" +msgstr "Sequence number of your next invoice" + +msgid "" +"Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste factuur " +"komt." +msgstr "Coming from another package? Enter the sequence number that follows your last invoice." + +msgid "Volgnummer van je volgende offerte" +msgstr "Sequence number of your next quote" + +msgid "" +"Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste offerte " +"komt." +msgstr "Coming from another package? Enter the sequence number that follows your last quote." + msgid "Factuur" msgstr "Invoice" @@ -1914,6 +1930,22 @@ msgstr "A sent e-mail cannot be changed." msgid "[klantnummer]" msgstr "[customer number]" +msgid "Het volgnummer is minstens 1." +msgstr "The sequence number is at least 1." + +msgid "" +"Je hebt in Huismus al een nummer uitgegeven. Het nummer loopt nu vanzelf " +"door." +msgstr "You already issued a number in Huismus. The number now counts up by itself." + +#, python-format +msgid "Kies %(lowest)s of hoger. Een lager nummer bestaat al." +msgstr "Choose %(lowest)s or higher. A lower number already exists." + +#, python-format +msgid "Nummer %(number)s bestaat al. Kies een hoger volgnummer." +msgstr "Number %(number)s already exists. Choose a higher sequence number." + msgid "[nummer volgt]" msgstr "[number to follow]" @@ -2451,10 +2483,9 @@ msgstr "quote numbers" #, python-format msgid "" "%(unparsed)s van %(total)s geïmporteerde %(label)s passen niet in het " -"ingestelde nummerformaat. Stel het volgende nummer zelf in bij Instellingen." -msgstr "" -"%(unparsed)s of %(total)s imported %(label)s don't fit the number format you " -"set. Set the next number yourself in Settings." +"ingestelde nummerformaat. Stel het volgende nummer zelf in bij Instellingen " +"→ Facturen en nummering." +msgstr "%(unparsed)s of %(total)s imported %(label)s don't fit the number format you set. Set the next number yourself in Settings → Invoices and numbering." #, python-format msgid "Uitgave %(number)s" @@ -3074,6 +3105,16 @@ msgstr "Manage" msgid "Instellen" msgstr "Set up" +#, python-format +msgid "Volgende als je vandaag uitgeeft: %(number)s" +msgstr "Next if you issue today: %(number)s" + +msgid "Het nummer loopt vanzelf door sinds je eerste factuur in Huismus." +msgstr "The number now counts up by itself, since your first invoice in Huismus." + +msgid "Het nummer loopt vanzelf door sinds je eerste offerte in Huismus." +msgstr "The number now counts up by itself, since your first quote in Huismus." + msgid "De taal van nieuwe facturen kies je bij Facturen en nummering." msgstr "You choose the language of new invoices under Invoices and numbering." @@ -3493,10 +3534,6 @@ msgstr "days" msgid "Standaard betalingstermijn" msgstr "Default payment term" -#, python-format -msgid "Volgende als je vandaag uitgeeft: %(number)s" -msgstr "Next if you issue today: %(number)s" - #, python-brace-format msgid "" "In een nummerformaat staat {year} voor het jaar, {seq:04d} voor het " diff --git a/huismus/locale/nl/LC_MESSAGES/django.po b/huismus/locale/nl/LC_MESSAGES/django.po index a143f81..6608a16 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 11:03+0100\n" +"POT-Creation-Date: 2026-11-15 11:31+0100\n" "PO-Revision-Date: 2026-09-25 08:36+0200\n" "Last-Translator: \n" "Language-Team: \n" @@ -188,6 +188,22 @@ msgid "" "geen btw in rekening gebracht." msgstr "" +msgid "Volgnummer van je volgende factuur" +msgstr "" + +msgid "" +"Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste factuur " +"komt." +msgstr "" + +msgid "Volgnummer van je volgende offerte" +msgstr "" + +msgid "" +"Kom je uit een ander pakket? Vul het volgnummer in dat na je laatste offerte " +"komt." +msgstr "" + msgid "Factuur" msgstr "" @@ -1832,6 +1848,22 @@ msgstr "" msgid "[klantnummer]" msgstr "" +msgid "Het volgnummer is minstens 1." +msgstr "" + +msgid "" +"Je hebt in Huismus al een nummer uitgegeven. Het nummer loopt nu vanzelf " +"door." +msgstr "" + +#, python-format +msgid "Kies %(lowest)s of hoger. Een lager nummer bestaat al." +msgstr "" + +#, python-format +msgid "Nummer %(number)s bestaat al. Kies een hoger volgnummer." +msgstr "" + msgid "[nummer volgt]" msgstr "" @@ -2335,7 +2367,8 @@ msgstr "" #, python-format msgid "" "%(unparsed)s van %(total)s geïmporteerde %(label)s passen niet in het " -"ingestelde nummerformaat. Stel het volgende nummer zelf in bij Instellingen." +"ingestelde nummerformaat. Stel het volgende nummer zelf in bij Instellingen " +"→ Facturen en nummering." msgstr "" #, python-format @@ -2895,6 +2928,16 @@ msgstr "" msgid "Instellen" msgstr "" +#, python-format +msgid "Volgende als je vandaag uitgeeft: %(number)s" +msgstr "" + +msgid "Het nummer loopt vanzelf door sinds je eerste factuur in Huismus." +msgstr "" + +msgid "Het nummer loopt vanzelf door sinds je eerste offerte in Huismus." +msgstr "" + msgid "De taal van nieuwe facturen kies je bij Facturen en nummering." msgstr "" @@ -3274,10 +3317,6 @@ msgstr "" msgid "Standaard betalingstermijn" msgstr "" -#, python-format -msgid "Volgende als je vandaag uitgeeft: %(number)s" -msgstr "" - #, python-brace-format msgid "" "In een nummerformaat staat {year} voor het jaar, {seq:04d} voor het " diff --git a/huismus/templates/business/_number_formats.html b/huismus/templates/business/_number_formats.html new file mode 100644 index 0000000..476bc46 --- /dev/null +++ b/huismus/templates/business/_number_formats.html @@ -0,0 +1,18 @@ +{% load i18n forms %} +{% comment %}The invoice and quote number formats, each with the next sequence number under it while +Huismus has not given a number of that kind yet (issue #141; business.forms.SettingsPartForm). +A column per kind, so the next number stays under its own format. Used on Instellingen → +Facturen en nummering and in the start's Facturen step; the form's fields must name +next_invoice_number and next_quote_number (topics.py, core/onboarding.py).{% endcomment %} +
+ {% if next_invoice %}{% blocktranslate asvar invoice_next with number=next_invoice %}Volgende als je vandaag uitgeeft: {{ number }}{% endblocktranslate %}{% endif %} + {% field form.invoice_number_format extra_class="mono" help=invoice_next %} + {% if form.fixed_sequences.invoice %}

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

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

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

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

{{ topic.title }}

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

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

diff --git a/huismus/templates/core/onboarding.html b/huismus/templates/core/onboarding.html index 8b25f33..d4db936 100644 --- a/huismus/templates/core/onboarding.html +++ b/huismus/templates/core/onboarding.html @@ -54,10 +54,7 @@

{{ step.title }}

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

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

{% elif step.slug == "logo" %} diff --git a/huismus/templates/imports/_report_section.html b/huismus/templates/imports/_report_section.html index dfadab3..d9885d5 100644 --- a/huismus/templates/imports/_report_section.html +++ b/huismus/templates/imports/_report_section.html @@ -99,7 +99,7 @@ {% endif %} {% if r.numbering_note %} -
{% translate "Nummering" %}{{ r.numbering_note }}
+
{% translate "Nummering" %}{{ r.numbering_note }} {% translate "Facturen en nummering" %} →
{% endif %} diff --git a/tests/business/test_next_number_field.py b/tests/business/test_next_number_field.py new file mode 100644 index 0000000..6167a44 --- /dev/null +++ b/tests/business/test_next_number_field.py @@ -0,0 +1,127 @@ +# SPDX-FileCopyrightText: 2026 Huismus contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +"""The next number by hand on Facturen en nummering and in the start's +Facturen step (issue #141). The rules themselves: tests/documents/test_next_number.py.""" + +from datetime import date + +import pytest +from django.urls import reverse +from django.utils import timezone + +from huismus.documents.issuing import issue +from huismus.documents.numbering import next_sequence_number +from tests.business.test_views import _login, _valid_form_data +from tests.documents.test_issuing import _settings +from tests.documents.test_next_number import _draft, _imported + +pytestmark = pytest.mark.django_db + +PAGE = reverse("business:topic", args=["facturen"]) +YEAR = timezone.localdate().year + + +def _facturen(**overrides): + names = ( + "default_payment_terms_days", + "invoice_number_format", + "quote_number_format", + "number_reset_yearly", + "default_language", + "currency", + ) + data = {name: value for name, value in _valid_form_data().items() if name in names} + data.update({"next_invoice_number": "1", "next_quote_number": "1"}) + data.update(overrides) + return data + + +def test_the_page_shows_the_next_sequence_numbers(client): + _login(client) + page = client.get(PAGE).content.decode() + + assert 'name="next_invoice_number"' in page + assert 'name="next_quote_number"' in page + assert "Volgnummer van je volgende factuur" in page + + +def test_saving_sets_the_next_invoice_number(client): + _login(client) + response = client.post(PAGE, _facturen(next_invoice_number="43", next_quote_number="12")) + + assert response.status_code == 302 + assert next_sequence_number("invoice", year=YEAR) == 43 + assert next_sequence_number("quote", year=YEAR) == 12 + page = client.get(PAGE).content.decode() + assert f"Volgende als je vandaag uitgeeft: {YEAR}-0043" in page + assert 'value="43"' in page + + +def test_the_new_format_counts_in_the_same_save(client): + # Format and number in one save: the existing-number check uses the + # format being saved. + _login(client) + _imported(f"F-{YEAR}-0043", issue_date=date(YEAR, 1, 2)) + + response = client.post( + PAGE, _facturen(invoice_number_format="F-{year}-{seq:04d}", next_invoice_number="40") + ) + + assert "Kies 44 of hoger" in response.content.decode() + assert next_sequence_number("invoice", year=YEAR) == 1 + + +def test_a_refused_number_saves_nothing_else(client): + _login(client) + _imported(f"{YEAR}-0050", issue_date=date(YEAR, 1, 2)) + + response = client.post( + PAGE, _facturen(next_invoice_number="50", default_payment_terms_days="30") + ) + + assert response.status_code == 200 + assert response.context["form"].errors["next_invoice_number"] + assert client.get(PAGE).context["form"]["default_payment_terms_days"].value() != 30 + + +def test_once_an_invoice_is_issued_the_field_is_gone(client): + _login(client) + _settings() + issue(_draft(issue_date=timezone.localdate())) + + page = client.get(PAGE).content.decode() + + assert 'name="next_invoice_number"' not in page + assert "Het nummer loopt vanzelf door sinds je eerste factuur in Huismus." in page + assert 'name="next_quote_number"' in page + # Saving the rest still works, and a sent field is ignored. + response = client.post(PAGE, _facturen(next_invoice_number="99")) + assert response.status_code == 302 + assert next_sequence_number("invoice", year=YEAR) == 2 + + +def test_the_start_has_the_field_too(client): + _login(client) + step = reverse("onboarding", args=["facturen"]) + assert 'name="next_invoice_number"' in client.get(step).content.decode() + + response = client.post( + step, + { + "default_payment_terms_days": "14", + "invoice_number_format": "{year}-{seq:04d}", + "quote_number_format": "OFF-{year}-{seq:04d}", + "next_invoice_number": "128", + "next_quote_number": "1", + }, + ) + + assert response.status_code == 302 + assert next_sequence_number("invoice", year=YEAR) == 128 + + +def test_in_english(client): + _login(client) + page = client.get(PAGE, headers={"accept-language": "en"}).content.decode() + + assert "Sequence number of your next invoice" in page diff --git a/tests/documents/test_next_number.py b/tests/documents/test_next_number.py new file mode 100644 index 0000000..663e4be --- /dev/null +++ b/tests/documents/test_next_number.py @@ -0,0 +1,246 @@ +# SPDX-FileCopyrightText: 2026 Huismus contributors +# SPDX-License-Identifier: AGPL-3.0-or-later +"""Setting the next number by hand (issue #141): for someone who comes from +another package without an import. Invariant 3 decides what may: never a +gap within what Huismus issued, never a number twice.""" + +from concurrent.futures import ThreadPoolExecutor +from datetime import date + +import pytest +from django.db import connections + +from huismus.contacts.models import Contact +from huismus.documents.issuing import issue +from huismus.documents.models import Document, DocumentLine, NumberSequence +from huismus.documents.numbering import ( + NumberingError, + next_sequence_number, + next_sequence_number_is_fixed, + set_next_sequence_number, +) +from huismus.documents.quoting import send_quote +from huismus.documents.reopening import reopen +from tests.documents.test_issuing import _settings +from tests.support import clean_up_issued_documents_for_flush + +pytestmark = pytest.mark.django_db + +FORMAT = "{year}-{seq:04d}" + + +def _draft(kind="invoice", *, issue_date=date(2026, 3, 1), **fields): + document = Document.objects.create( + kind=kind, + status="draft", + contact=Contact.objects.create(company_name="Klant BV"), + issue_date=issue_date, + **fields, + ) + DocumentLine.objects.create( + document=document, description="Consult", quantity="1", unit_price_cents=10000 + ) + return document + + +def _imported(number, *, kind="invoice", issue_date=date(2026, 2, 1)): + """An issued document as the Moneybird import leaves it: its own + number, source set, the sequence moved past it.""" + return Document.objects.create( + kind=kind, + status="issued" if kind != "quote" else "sent", + contact=Contact.objects.create(company_name="Oude klant BV"), + number=number, + issue_date=issue_date, + source="moneybird", + external_id=number, + total_cents=100000, + ) + + +def test_an_empty_sequence_starts_at_one(): + assert next_sequence_number("invoice", year=2026) == 1 + assert not next_sequence_number_is_fixed("invoice") + + +def test_the_first_invoice_gets_the_number_that_was_set(): + _settings() + set_next_sequence_number("invoice", FORMAT, year=2026, value=43) + + assert next_sequence_number("invoice", year=2026) == 43 + assert issue(_draft()).number == "2026-0043" + assert issue(_draft()).number == "2026-0044" + + +def test_the_same_value_writes_nothing(): + set_next_sequence_number("invoice", FORMAT, year=2026, value=1) + + assert not NumberSequence.objects.exists() + + +def test_once_huismus_issued_an_invoice_the_number_is_fixed(): + # Raising it now would leave a gap after 2026-0001 (invariant 3). + _settings() + issue(_draft()) + + assert next_sequence_number_is_fixed("invoice") + with pytest.raises(NumberingError): + set_next_sequence_number("invoice", FORMAT, year=2026, value=43) + assert next_sequence_number("invoice", year=2026) == 2 + + +def test_a_credit_note_fixes_the_invoice_sequence_too(): + _settings() + invoice = _imported("2026-0042") + NumberSequence.objects.create(kind="invoice", year=2026, last_value=42) + issue(_draft("credit_note", related_document=invoice)) + + assert next_sequence_number_is_fixed("invoice") + + +def test_a_reopened_invoice_still_counts(): + # "Toch bewerken" makes it a draft again, with its number kept. + _settings() + reopen(issue(_draft())) + + assert next_sequence_number_is_fixed("invoice") + + +def test_last_year_s_invoice_fixes_the_new_year_s_sequence_too(): + # Else someone who already invoices in Huismus could skip numbers + # at the start of a new year. + _settings(number_reset_yearly=True) + issue(_draft(issue_date=date(2025, 12, 30))) + + with pytest.raises(NumberingError): + set_next_sequence_number("invoice", FORMAT, year=2026, value=10) + assert next_sequence_number("invoice", year=2026) == 1 + + +def test_without_a_yearly_reset_any_invoice_fixes_it(): + _settings(number_reset_yearly=False, invoice_number_format="F{seq:05d}") + issue(_draft(issue_date=date(2024, 5, 1))) + + assert next_sequence_number_is_fixed("invoice") + + +def test_imported_invoices_do_not_fix_it(): + # After an import whose numbers didn't fit the format, the import + # message sends the user here. + _imported("430033") + NumberSequence.objects.create(kind="invoice", year=2026, last_value=0) + + assert not next_sequence_number_is_fixed("invoice") + set_next_sequence_number("invoice", FORMAT, year=2026, value=34) + assert next_sequence_number("invoice", year=2026) == 34 + + +def test_it_never_goes_onto_or_below_an_existing_number(): + # The import already continued after 2026-0042; 40 would give + # 2026-0042 a second time two invoices later. + _imported("2026-0042") + NumberSequence.objects.create(kind="invoice", year=2026, last_value=42) + + with pytest.raises(NumberingError, match="43"): + set_next_sequence_number("invoice", FORMAT, year=2026, value=40) + assert next_sequence_number("invoice", year=2026) == 43 + + +def test_a_typo_can_be_set_back_lower(): + # 430 instead of 43: nothing was issued from it, so lower is no gap. + set_next_sequence_number("invoice", FORMAT, year=2026, value=430) + set_next_sequence_number("invoice", FORMAT, year=2026, value=43) + + assert next_sequence_number("invoice", year=2026) == 43 + + +def test_last_year_s_imported_numbers_do_not_limit_this_year(): + _imported("2025-0042", issue_date=date(2025, 6, 1)) + + set_next_sequence_number("invoice", FORMAT, year=2026, value=5) + assert next_sequence_number("invoice", year=2026) == 5 + + +def test_an_imported_customer_number_limits_the_sequence(): + _settings(invoice_number_format="{customer}{seq:04d}", number_reset_yearly=False) + document = _imported("580097") + Contact.objects.filter(pk=document.contact_id).update(customer_number="58") + + with pytest.raises(NumberingError, match="98"): + set_next_sequence_number("invoice", "{customer}{seq:04d}", year=None, value=90) + + +def test_a_number_that_already_exists_is_refused(): + _imported("2026-0050") + + with pytest.raises(NumberingError): + set_next_sequence_number("invoice", FORMAT, year=2026, value=50) + assert next_sequence_number("invoice", year=2026) == 1 + + +def test_an_existing_quote_number_does_not_block_an_invoice_number(): + _imported("2026-0050", kind="quote") + + set_next_sequence_number("invoice", FORMAT, year=2026, value=50) + assert next_sequence_number("invoice", year=2026) == 50 + + +def test_zero_is_refused(): + with pytest.raises(NumberingError): + set_next_sequence_number("invoice", FORMAT, year=2026, value=0) + + +def test_quotes_have_their_own_sequence(): + _settings() + issue(_draft()) + + set_next_sequence_number("quote", FORMAT, year=2026, value=7) + assert next_sequence_number("quote", year=2026) == 7 + assert send_quote(_draft("quote")).number.endswith("2026-0007") + assert next_sequence_number_is_fixed("quote") + + +def test_with_a_customer_number_the_sequence_still_counts(): + # Moneybird's own numbering: customer 58, sequence 97 is "580097". + _settings(invoice_number_format="{customer}{seq:04d}", number_reset_yearly=False) + set_next_sequence_number("invoice", "{customer}{seq:04d}", year=None, value=97) + + draft = _draft() + Contact.objects.filter(pk=draft.contact_id).update(customer_number="58") + draft.refresh_from_db() + assert issue(draft).number == "580097" + + +@pytest.mark.django_db(transaction=True) +def test_setting_it_while_invoices_are_issued_leaves_no_gap(): + # Either the number is set before the first invoice, or it is refused: + # never set halfway, which would leave a gap after what was issued. + _settings() + drafts = [_draft() for _ in range(8)] + + def issue_one(document): + try: + return issue(document).number + finally: + connections.close_all() + + def set_it(): + try: + set_next_sequence_number("invoice", FORMAT, year=2026, value=100) + return True + except NumberingError: + return False + finally: + connections.close_all() + + try: + with ThreadPoolExecutor(max_workers=9) as pool: + setting = pool.submit(set_it) + numbers = list(pool.map(issue_one, drafts)) + was_set = setting.result() + + sequence = sorted(int(number.split("-")[1]) for number in numbers) + first = 100 if was_set else 1 + assert sequence == list(range(first, first + len(drafts))) + finally: + clean_up_issued_documents_for_flush() diff --git a/tests/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():