Utgående faktura
This content is not available in your language yet.
Salgsdokument per bokføringsforskriften §5-1: gap-free invoice numbers, KID, and automatic posting to ledger + reskontro. Invoices are immutable once issued (insert-only for the app role) — a mistake is corrected with a kreditnota, never an edit, mirroring the ledger’s reversing-voucher rule.
Guarantees
Section titled “Guarantees”- Fortløpende nummerering: the invoice number comes from a counter
bumped in the same transaction as the ledger posting
(
post_voucher_in), so a failed issue rolls back both — no gaps in invoice numbers or voucher numbers, ever. Tested: a rejected invoice attempt does not burn a number. - KID: derived from the invoice number (8 digits + MOD10 check,
regnmed-core::invoice::invoice_kid), unique per company. OCR innbetalinger resolve their invoice by KID at import and the payment list shows which invoice each payment settles (auto-posting of payments is a later, opt-in step — the bank statement is the posting source until then, avoiding double-posting). - Posting: debit receivable (with the customer — hash v2 covers the
party), credit each revenue line with its VAT code, credit summed VAT.
Line VAT uses the dated rate valid on the invoice date. Amounts:
integer øre,
quantity_milli × unit_price_ore / 1000rounded half away from zero. - Kreditnota: same lines negated (signs flow through the whole
computation),
credits_invoice_idlinks the pair, and the two receivable entries are auto-matched in reskontro for whatever remained open. Double-crediting is rejected.
Salgsdokumentet som PDF (#32)
Section titled “Salgsdokumentet som PDF (#32)”- Deterministic, hand-rolled renderer (
regnmed-core::pdf+fakturapdf): the three standard PDF fonts (no embedding), WinAnsi/CP1252 for æøå og typografi, ~3 KB per invoice, no rendering engine (frugality). Same input → byte-identical output forever. - Stored at issue time, in the issuing transaction, as an attachment on the invoice’s voucher — the document the customer receives is part of oppbevaringen from the moment the invoice exists, hash-checked on every download like all dokumentasjon. Serving is a DB read; nothing renders on the request path.
- Contents per bokføringsforskriften §5-1-1: nummer/dato, selger med orgnr (påtegningene under), kjøper, leveringstidspunkt (og -sted), linjer, mva spesifisert i NOK per sats, forfall, KID og kontonummer. Begge parters adresse er påkrevd (§5-1-2) — utstedelsen nekter uten dem, siden fakturaen er uforanderlig i det den finnes og et manglende felt bare kan rettes ved å kreditere og gjøre om.
Registreringsstatus (§5-1-2, #81)
Section titled “Registreringsstatus (§5-1-2, #81)”“MVA” etter orgnr og påtegningen “Foretaksregisteret” hører til
REGISTRERINGEN, ikke til dokumentet. De ble utledet — vat_ore != 0
respektive orgform in (AS, ASA) — og begge utledningene er gale i
vanlige tilfeller: en registrert selger som fakturerer eksport eller
fritatt omsetning fikk ingen “MVA”, og ANS/DA, NUF og næringsdrivende
ENK er registreringspliktige i Foretaksregisteret uten å være AS.
Statusen er nå lagret i company_registrering (migration 0056),
datert og innsettings-bar etter mønsteret fra sats og vat_rate:
oppslag = nyeste rad med valid_from <= dokumentets dato. Dateringen
er ikke teoretisk — tilbud og ordrebekreftelser rendres on demand, så
uten den ville et gammelt tilbud fått dagens status neste gang noen
lastet det ned.
- Onboarding henter begge flaggene og forretningsadressen fra
Enhetsregisteret (
kilde='brreg'). - Korrigering:
POST …/settings/registrering(admin) skriver en ny datert rad; den forrige blir stående som det som gjaldt da. Én rad per dato: samme status på nytt er en no-op, men en ANNEN status for en dato som alt har en rad nektes med datoen i meldingen. Før svarte den OK og forkastet endringen i stillhet (on conflict do nothing), så en rettelse samme dag ble aldri lagret. - Eksisterende selskaper ble backfillet med den gamle utledningen
løftet fra per-dokument til per-selskap, merket
kilde='migrert'— en ANTAKELSE, og portalen ber om at den bekreftes. - Ingen rad = ingen påtegning: vi hevder ikke en registrering vi ikke har belegg for.
Det samme oppslaget styrer cac:PartyTaxScheme i EHF-en.
Fra #99 styrer det også om en mva-kode kan brukes i det hele tatt — ikke bare hva dokumentet SIER, men hva det får gjøre. Regelen står i docs/mva.md.
KID krever bankavtale (#104)
Section titled “KID krever bankavtale (#104)”KID er ikke en egenskap ved fakturanummeret, men ved en OCR-/KID-avtale med banken. regnmed regnet før ut en KID for hver faktura og trykte den alltid — og en KID på et salgsdokument er en INSTRUKS til betaleren om hvordan betalingen skal merkes. Uten avtale kan den instruksen ikke følges: betalerens bank tilbyr ikke KID mot kontoen, eller avviser betalingen.
Det traff det første ekte selskapet som fakturerte i regnmed — et nystartet AS har sjelden OCR-avtale fra dag én.
Statusen er lagret på selskapet (company.kid_avtale, migrasjon 0061),
redigerbar stamdata ved siden av bank_account, og av som standard:
vi hevder ikke en bankavtale vi ikke har belegg for, samme regel som
registreringsstatusen over. Uten avtale:
- faktura- og kreditnota-PDF-en skriver ingen KID-linje
(
FakturaPdfInput.kiderOption<String>), - purringen gjentar ingen KID,
- EHF-en bærer ingen
cbc:PaymentID.
invoice.kid BEREGNES OG LAGRES uansett: OCR-importen slår opp faktura
på KID (#7), så verdien må finnes selv når dokumentet ikke viser den.
Det samme gjelder den lagrede purreraden — det er gjengivelsen som
utelater KID-en, ikke regnskapet som glemmer den.
Dokumentet er låst ved utstedelse, så en faktura utstedt før avtalen kom får aldri KID påtrykt i ettertid. Avtalen krysses av i Firmaopplysninger, og bør settes FØR første faktura.
Leveringstidspunkt (§5-1-1 nr. 4, #81)
Section titled “Leveringstidspunkt (§5-1-1 nr. 4, #81)”The forskrift requires when the ytelse was delivered on every
salgsdokument, and it is not the same fact as the invoice date —
anything billed in arrears separates them. InvoiceDraft.delivery_date
is therefore not an Option: every caller has to decide. The choices
in the tree today:
| Path | Leveringsdato |
|---|---|
POST …/invoices |
leveringsdato in the request; omitted = the invoice date (the default is declared at the boundary, and the portal always sends it) |
| Timer → faktura | the last day worked among the billed hours — that is when the ytelse was complete, often weeks before billing |
| Kombinert faktura (varer + timer) | the caller’s date, unless hours were worked later; then the later one wins, so the document cannot claim delivery before the work happened |
| Ordre → faktura | leveringsdato on the request; omitted = the invoice date |
| Repeterende faktura | the period’s own start date (neste_dato) |
| Kreditnota | the original invoice’s delivery date — it credits that delivery; dating it today would assert a delivery that never happened |
| Tilbud / ordrebekreftelse | none: nothing is delivered yet, and these are not salgsdokumenter |
The database column is nullable, deliberately: invoices issued
before #81 have no recorded delivery date, and backfilling them with
the invoice date would invent a legal fact on an immutable document.
That history stays visibly incomplete; the requirement is enforced at
issue time instead. In EHF the field is cac:Delivery/cbc:ActualDeliveryDate
(BT-72) — omitted entirely rather than guessed when absent.
Deres referanse (EN 16931 BT-10, #221)
Section titled “Deres referanse (EN 16931 BT-10, #221)”The buyer’s own reference — an order number, a department, a contact
person — is what public and larger private buyers route an incoming
invoice on. It is stored on the invoice at issue
(invoice.buyer_reference, migration 0084, insert-only like the rest of
the row), printed on the PDF as «Deres ref.» and carried in the EHF as
cbc:BuyerReference.
| Path | Reference |
|---|---|
POST …/invoices |
buyer_reference in the request |
| Repeterende faktura | the template’s own (buyer_reference on create/update; “Gjenta denne” copies the invoice’s) — one per contract |
| Tilbud → ordre → faktura | the tilbud’s own, copied to the ordre and on to the invoice |
| Any of the above without one | the customer’s standing reference (party.buyer_reference, set with PUT …/parties/{pid}/contact) |
| Kreditnota | exactly the original’s — none if the original had none; it never picks up a standing reference the invoice did not carry |
At most 70 characters, refused rather than cut (a cut reference routes nowhere), checked in the code and by the database. The reference is printed on one line of the stored PDF. Setting the standing reference is the same single statement as the rest of the contact update, so a refused reference (on a supplier, or too long) leaves the address, e-mail and account number untouched as well.
PEPPOL-EN16931-R003 requires a buyer reference or an order reference in every EHF. An invoice with neither falls back to our customer number in BT-10: the document stays valid, but a buyer that routes on its own reference (the public sector does) cannot use it. Invoices issued before #221 carry no reference and keep that content.
- Kontaktinfo (migration 0019, editable master data, never hashed):
company address/kontonummer/selskapsform via
GET/PUT /companies/{id}/settings(PUT is admin-only). The company kontonummer is MOD11-checked before it is stored, like a party’s: it is printed on every invoice and reminder as where to pay, and a typo there used to be accepted. It is kept as typed (1234.56.78903); party address/e-mail viaPUT …/parties/{pid}/contact. Portal: Firmaopplysninger under Administrasjon, Kontaktinfo on the party page. - Purringer/inkassovarsler render their stored text deterministically
to PDF on demand (
?format=pdf, docs/purring.md).
E-postutsendelse (#32)
Section titled “E-postutsendelse (#32)”- One rail for all outbound mail: regnmed publishes to the same
JetStream stream regnid’s mail workers consume (
REGNID_MAIL/regnid.mail.send— a wire contract; regnid’sOutboundMailgained serde-defaultedreply_to+ base64attachmentsfor it). SMTP/Brevo stay configured in exactly one place, the worker. - Sending is an explicit human action (portal Send buttons, or
POST …/invoices/{iid}/send/POST …/reminders/{rid}/send, both bokforing+). Recipient defaults to the party’s stored e-mail, overridable per send; reply-to is the company’s own address (settings), never regnmed’s. - Insert-only utsendelseslogg (migration 0020): who sent what to
whom, when. The log id doubles as the queue’s
Nats-Msg-Id, so a retried publish deduplicates in the stream — the log row and the queue message are the same event.GET …/invoices/{iid}/utsendelser. - The attached PDF is the stored salgsdokument (hash-checked on read) — the mail carries byte-exactly what oppbevaringen holds.
- Unconfigured rail (no
NATS_URL) → the endpoints answer with a clear message instead of pretending.
Repeterende faktura (#30)
Section titled “Repeterende faktura (#30)”- A template is a plan, not evidence: customer + lines + intervall (månedlig/kvartalsvis/årlig) + neste/slutt-dato, ordinary editable data. Nothing regnskapsmessig exists until generation.
- Generation adds no posting semantics: it issues a NORMAL invoice
through the existing path — gap-free number, KID, posting, PDF, all
in one transaction — with
{måned}/{år}in line texts interpolated to the generated period (“Husleie august 2026”). Month arithmetic clamps into shorter months (31. jan + 1 mnd = 28. feb). - Idempotent and atomic: the template row is locked, the invoice + run-log row + neste_dato advance commit together, and a partial unique index makes a period impossible to generate twice — even under concurrent runs. Failures roll back, log a failure row (insert-only log), and leave neste_dato untouched for retry. A template several periods behind catches up.
- Driven by the daily CronJob (
regnmed generate-invoices, deploy/base — same pattern as anchoring); the portal’s “Generer nå” is the same code path.merk_utsendelseMARKS the generated invoice for sending in the run log — the send itself stays a human click. - Templates are deactivated, never deleted, once they have runs (FK enforces it).
| Endpoint | Purpose |
|---|---|
GET/POST /companies/{id}/invoice-templates |
list / create (from_invoice_id = “gjenta denne”) |
PUT …/invoice-templates/{tid} |
edit incl. lines and aktiv |
POST …/invoice-templates/{tid}/generate |
generate every due period now |
GET …/invoice-templates/{tid}/runs |
the insert-only generation log |
Tilbud → ordre → faktura (#31)
Section titled “Tilbud → ordre → faktura (#31)”- The commercial chain BEFORE the invoice lives outside the ledger: nothing posts, tilbud are freely editable until akseptert/avslått, an ordre is a frozen confirmation. Both reuse the invoice line model, so conversion is lossless.
- Own gap-free number series per kind (same counter pattern as invoices) — a rejected tilbud is history, not a hole.
- One-way statuses: tilbud utkast → sendt → akseptert | avslått (accepting straight from utkast is allowed); ordre bekreftet → fakturert. At most one ordre per tilbud (unique index); converting an ordre runs the NORMAL atomic invoice path (number, KID, posting, stored PDF) and links the chain tilbud → ordre → invoice — the ordre status flip and the invoice commit together. One ordre → one faktura.
- PDF on demand: TILBUD/ORDREBEKREFTELSE rendered from current state with the same layout (no KID, no betalingsinformasjon — not payable); the stored, hash-verified document arrives with the invoice.
| Endpoint | Purpose |
|---|---|
GET/POST /companies/{id}/quotes, PUT …/{qid} |
tilbud; edit while utkast/sendt |
POST …/quotes/{qid}/status |
sendt | akseptert | avslatt |
POST …/quotes/{qid}/order |
akseptert tilbud → ordre (lines copied) |
GET/POST /companies/{id}/orders |
ordrer (direct creation allowed) |
POST …/orders/{oid}/invoice |
ordre → faktura (ordinary path) |
GET …/quotes/{qid}/pdf, …/orders/{oid}/pdf |
on-demand documents |
Not yet (deliberate)
Section titled “Not yet (deliberate)”- EHF dispatch arrives with the Peppol access point (issue #14).
- Proration and seat-based metering — templates are fixed lines first.
- Delleveranser/delfakturering — one ordre → one faktura in v1.
Purring, forsinkelsesrente og inkassovarsel: shipped — docs/purring.md.
Web API (mutations require bokforing)
Section titled “Web API (mutations require bokforing)”| Endpoint | Purpose |
|---|---|
POST /companies/{id}/invoices |
issue (party_no, dates, lines; defaults: journal GL, receivable 1500, VAT 2700, account 3000, quantity 1). Optional timer_entry_ids: selected unbilled hours appended as hour lines per (prosjekt, sats) and marked fakturert in the SAME transaction — one invoice carries products and hours (docs/timer.md; requires TIMER_FAKTURER, NOK only). Optional expenses: [{expense_id, treatment}]: billable expense claims rebilled as resale (cost + 25 % mva) or disbursement (outside the mva base), locked in the same transaction (docs/utlegg.md «Viderefakturering»; requires UTLEGG_LES_ALLE, NOK only, not on kontantsalg) |
GET /companies/{id}/invoices?status=&q=&limit=&offset= |
list with reskontro remaining and a DERIVED status per invoice (open, overdue, paid, credited, credit_note — computed in SQL from the reskontro and the due date, never stored). status filters (open = open or overdue, credit = kreditnotaer and what they credit), q matches an exact invoice number or KID or part of the customer’s name, limit (≤ 200) pages newest first. The response carries total and per-status counts for the filter. Without limit: every invoice, oldest first, as before. open=true keeps its old meaning (anything with a remainder, kreditnotaer included) |
GET /companies/{id}/invoices/{iid} |
one invoice: header, status, the stored lines (net_ore/vat_ore as issued), the kreditnota link either way, the customer’s e-mail, the voucher it was posted on (voucher_id, voucher) and settlements — every payment and kreditnota matched against the receivable, each with its voucher |
POST /companies/{id}/invoices/{iid}/payments |
record a payment by hand (dato, belop_ore, konto 19xx, default 1920): one voucher money-account / receivable WITH the party, matched against the invoice in the same transaction under the party’s reskontro lock. Requires FAKTURA_SKRIV and BILAG_BOKFOR; refuses more than is open, a date in the future, a non-19xx account, a kreditnota and a currency invoice (settled from Bank, where the agio is posted); the attestation policy governs it like any manual voucher |
GET /companies/{id}/quotes/{qid} |
a tilbud’s or ordre’s lines as stored (product by number), for editing |
POST /companies/{id}/invoices/{iid}/credit-note |
full kreditnota |
GET /companies/{id}/invoices/{iid}/pdf |
the stored salgsdokument (hash-checked) |
GET/PUT /companies/{id}/settings |
firmaopplysninger for the PDF (PUT admin-only) |
PUT /companies/{id}/parties/{pid}/contact |
party address/e-mail |
I portalen
Section titled “I portalen”Faktura-seksjonen er bygget rundt fakturalisten (#/c/{id}/faktura): status
per faktura, søk og filter i adressen, hver rad åpner fakturaen
(#/c/{id}/faktura/{iid}) der alle handlingene bor og det naturlige neste
steget er primærknappen — send en usendt faktura, purre en forfalt.
Ny faktura (#/c/{id}/faktura/ny) tar så mange linjer som trengs og
viser summen mens man skriver. Summen speiler regnmed-cores
avrunding (invoiceMath.js, testet mot de samme tilfellene), men med
dagens satser — serveren regner på nytt med satsen på fakturadatoen når
fakturaen utstedes, og det er dens tall som står på fakturaen. Forfall
følger fakturadato + 14 dager til brukeren endrer det; det finnes ennå
ingen lagret betalingsfrist per selskap eller kunde. Utstedelse viser en
oppsummering først, fordi en utstedt faktura aldri kan endres.
Ingenting i Faktura utsteder en faktura uten at brukeren har sett kunden og beløpet og bekreftet. Det gjelder alle veiene inn: ny faktura, ufakturerte timer (kunden er aldri forhåndsvalgt «første i listen» — bare foreslått når timene selv sier hvem de tilhører), ordre → faktura og «Lag forfalte nå» på repeterende fakturaer. Etter utstedelse lander brukeren på fakturaen, der «Send til kunde» er neste steg. Et avslått tilbud kan ikke tas opp igjen, og spør derfor også.
Registrer innbetaling står på fakturaen for penger som ikke kommer gjennom bankavstemmingen — kontant, Vipps, en enkeltinnbetaling. Den bokfører bilaget og avstemmer det mot fakturaen i én transaksjon (API-raden over), og fakturasiden viser deretter Innbetalinger og kreditering: hver post som har gjort opp fakturaen, med bilaget den er bokført på, og bilaget fakturaen selv er bokført på — sporbarheten fakturaen → betaling → bilag og tilbake er ett klikk hver vei (bokføringsloven §4 nr. 7).
Purringen registreres bare slik den ble forhåndsvist: endres et valg etter forhåndsvisningen, forkastes den, og «Registrer» må vente på en ny. Etter registrering tilbys «Send til kunde» med en gang.
Tilbud har så mange linjer som trengs og kan endres så lenge de er
utkast eller sendt (GET/PUT …/quotes/{qid}).
Where it is tested
Section titled “Where it is tested”regnmed-core/src/invoice.rs— line/VAT computation, rounding, KID validity, voucher balance with party, credit-note sign flip.regnmed-api/tests/grupper/invoice.rs(real Postgres, also CI) — the whole loop over HTTP: issue (12 500 kr, valid KID), failed attempt burns no number, chain verifies, OCR payment resolves the invoice by KID, kreditnota auto-settles, double-credit rejected.a_payment_recorded_by_hand_settles_the_invoice: a part payment in cash leaves the rest open and shows on the invoice with its voucher; overpaying, a non-19xx account, a future date and zero are refused with an actionable message; six simultaneous attempts at the rest settle it exactly once (the guarantee is the party lock — the harness does not reliably make the attempts overlap, so the test pins the outcome); the chain verifies. The invoice page answers with statusoverdueand the stored lines (another company’s id is 404), and the list’s filters are pinned:status=creditholds the kreditnota and the invoice it credits, newest first,qmatches number or name, paging keeps the truetotal, and an unknown status is a 400. Kunderegisteret er festet i samme test: en kundesoverdue_oreer lik den forfalte fakturaen, søk og sortering skjer i SQL,GET …/parties/{pid}og?party_no=på fakturalisten svarer for én kunde, og en ny kunde med ugyldig kontonummer avvises før den finnes (docs/reskontro.md).ui/portal/src/sections/faktura/invoiceMath.test.js— the form’s running sum rounds exactly likeregnmed-core(line amounts, VAT, minutes to hours).regnmed-core/src/pdf.rs+fakturapdf.rs— valid xref structure, WinAnsi encoding incl. CP1252 typografi, escaping, width-based right alignment, determinism, lovpålagt innhold, kreditnota variant, pagination.regnmed-api/tests/grupper/faktura_pdf.rs(real Postgres, also CI) — settings over the API, the PDF exists as a verified attachment the moment the invoice does, served with the kontaktinfo, kreditnota document, purring?format=pdf, settings PUT rejected for non-admins.regnmed-api/tests/grupper/salgsdokument.rs(real Postgres, also CI) — the whole chain over HTTP: tilbud edited while utkast and read back for the editor (another id is 404), PDF without KID/betalingsinfo, one-way trapp, ordre copied losslessly (one per tilbud), fakturering through the ordinary path (chain + stored PDF verify, links carried), avslått path keeps the number series gap-free, direct ordre.regnmed-api/tests/grupper/invoice_template.rs(real Postgres, also CI) — template over the API, catch-up generation with periodetekst through the gap-free path (chain + attachments verify), idempotence, run log append-only and marked til utsendelse, deactivation respected, “gjenta denne” copies customer + lines.regnmed-api/tests/grupper/utsendelse.rs(real Postgres + a spawnednats-server, skips without either) — the send endpoint puts a real JetStream message on the rail in regnid’s wire format (attachment base64-decodes back to the stored PDF, reply-to = company), the log records it, and an unconfigured rail answers clearly. regnid’s own suite pins the wire format’s backward compatibility.
Kontantsalg (#89, bokføringsforskriften §5-3)
Section titled “Kontantsalg (#89, bokføringsforskriften §5-3)”En kontantfaktura dokumenterer en ytelse som er betalt ved levering
— kort, Vipps eller kontanter. Dokumentet er et annet dokument, ikke en
faktura med et flagg: DocumentType::CashInvoice gir tittelen
KONTANTFAKTURA, «Betalt: <betalingsmiddel>» blant dokumentfaktaene, og
ingen KID, ingen forfallsdato og ingen betalingsinformasjon. Å be
noen betale det de allerede har betalt er ikke en skjønnhetsfeil, det er
et krav om betaling nummer to. Testen lister de forbudte strengene og
sjekker samtidig at en vanlig faktura beholder dem alle.
Fordringen oppstår og gjøres opp i SAMME transaksjon. Det ville vært
enklere å postere salget rett mot bank og hoppe over 1500 — og det er
nettopp det som ikke må skje: reskontro-doktrinen sier at en kundes
posteringer bærer en part, og en sidedør forbi den ville gjort
subledger_check (revisors avstemming) stille ufullstendig. Kravet
finnes, bærer parten på BEGGE sider, og den åpne posten lukkes i det
øyeblikket den oppstår.
oppgjorskonto oppgis av kalleren — 1900 kontanter, 1920 bank eller
kortinnløserens oppgjørskonto. Vi gjetter aldri hvordan noen ble betalt.
POST /companies/{id}/invoices med kontant_betalingsmiddel +
oppgjorskonto tar denne veien; uten dem er alt som før.