finance
Status: implemented (services/finance, contract: docs/dev/phase4-contracts.md, Finance service; specs:
features.md "Money"). Runs in the apps profile of docker-compose.yml on port 8091 and is reached through the
gateway route /v1/finance. No web screens yet.
Role: replaces Abby. Customers and suppliers, quotes, invoices and credit notes compliant with French invoicing rules, payments (manual, bank transaction matches, SumUp payouts), purchase requests linked to inventory and projects, expense claims, budgets and the double-entry journal with its FEC export. The association is subject to VAT.
Limits: bank accounts and transactions are owned by bank-sync (finance only consumes
bank.transaction.v1). No payment initiation. The e-invoicing platform (PA) adapter is a no-op. Payments are
immutable (no cancellation endpoint yet: record a reversing document). Factur-X output is validated offline only
(PDF/A-3B and EN 16931, see PDF and Factur-X); B2C invoices keep one French Schematron warning
and the PDF is untagged (PDF/A-3B, not 3A/3U).
Money and VAT
- Amounts: integer cents (EUR). Quantities: milli-units (
2500= 2.5). VAT rates and discounts: basis points (2000= 20 %; accepted 2000, 1000, 550, 210, 0). A 0 % line requiresvat_exemption_reasonat issuance (CII categoryE), other rates are categoryS. - Line net = quantity × unit price × (1 − discount), rounded to the cent, half away from zero (
math/big, no overflow). VAT is computed per rate on the sum of the line nets of that rate and rounded once (totals.breakdown); the document VAT is the sum of the per-rate VAT, the TTC total = HT + VAT.vat_centson a line is informative and may differ from the breakdown by a cent (three lines of 0.33 € at 20 %: 0.07 × 3 per line, 0.20 in the breakdown). Totals are always computed by the server (internal/money, table-driven tests).
Documents
- Customers / suppliers (
customers,suppliers): kindcompany | individual | public_body, name, SIREN/SIRET (SIREN derived from the SIRET), VAT number, address, up to 5 e-mails, phone, payment terms, optionaluser_id(customers), auxiliary account code (C…/F…). For individuals the name, address, e-mails and phone are sealed withcryptox.Keyring(subject = party ID) in the document and in events; search uses a keyed blind index (HMAC tokens and 3+ prefixes,FINANCE_SEARCH_KEY). ARNatl:finance:*:customer/<id>. - Quotes: numbered at creation
D-<SITE>-<YYYY>-<NNNN>,draft → sent → accepted | rejected | expired(sent/rejected/expired → draftto rework), editable only as drafts,valid_until; a lease job expires sent quotes past their validity.POST …/convertcreates a draft invoice (once) in the same transaction. PDF rendered on demand (watermarked while draft). - Invoices and credit notes (
kind: invoice | credit_note):draft → issued → partially_paid → paid(paid= settled by payments and credit notes). Drafts are editable and deletable; once issued nothing changes except settlement and archiving fields, and nothing is ever deleted (10-year archive). - Payments:
{site, date, method, incoming, amount_cents, fees_cents, allocations[]}; allocations settle invoices (incoming), credit notes (refunds), purchases and expense claims (outgoing). Incoming allocations sum to amount + fees (SumUp grouped payouts: gross sales settled, net received, commission infees_cents). - Purchases:
requested → approved | rejected → ordered → [partially_received →] received → invoiced → paid(cancelledbefore reception); lines may reference an inventoryitem_id.POST …/receivetakes an optional{lines: [{line_id, quantity_milli}]}(no body: everything remaining); each receipt is numbered (receipts[].seq), lines trackreceived_milli, and the supplier invoice needs a fully received purchase. - Expense claims:
draft → submitted → approved | rejected → reimbursed; editing a submitted claim sends it back to draft; receipts are files owned by the claim. - Budgets: per site (and optionally project) and fiscal year; consumption is computed on read (amounts
excluding VAT): committed purchases (approved and beyond) and approved expense claims linked by
budget_id, or for project budgets linked to the project without explicit budget; issued project invoices giverevenue_cents.
Issuance and numbering
POST /v1/finance/invoices/{id}/issue (finance.invoice.issue, sensitive) checks the draft (customer, lines,
positive total, exemption reason), builds the seller identity (legal name, SIRET, address and contact from the authz
authenticated organisation settings (service identity); VAT number, IBAN/BIC from the finance settings — 409 seller_incomplete when one is
missing) and the buyer snapshot (sealed for individuals), then runs one MongoDB transaction:
- re-reads the draft (version check), and for a credit note settles the credited invoice (409
credit_exceeds_invoicewhen the total of credit notes would exceed the invoice); - increments the counter
invoice-<F|A>-<site>-<year>($inconcounters, the year of the issue date inFINANCE_TIMEZONE) and formatsF-<SITE>-<YYYY>-<NNNN>(credit notesA-…); - stores the issued invoice (dates, due date = issue date + payment terms of the invoice, customer or settings,
frozen identities, mandatory mentions) and posts the sales journal entry (entry number from the
journal-<site>-<fiscal year>counter); - enqueues
finance.invoice.issuedand the audit record.
The counter document is created beforehand outside the transaction ($setOnInsert); concurrent issuances conflict
on it and the driver retries the whole transaction, so an aborted issuance never consumes a number: the sequence is
gap-free and unique (unique index on number). TestConcurrentIssuanceIsGapFree issues 24 invoices
concurrently and checks numbers 1…24 and journal entries 1…24.
Mandatory mentions stored with the invoice (and exported as CII notes with their UNTDID 4451 code): payment
terms and due date with "pas d'escompte" (AAB), late penalty rate (PMD, from the settings), the 40 € fixed
recovery fee for professional customers (PMT), the nature of the operation (goods, services, mixed, ABL), the
VAT-on-debits option when enabled. Seller identity, SIRET, VAT numbers, dates, buyer identity, line details, VAT
breakdown and totals are printed from the snapshots; credit notes reference the corrected invoice number and date.
PDF and Factur-X
- PDF rendered in pure Go with
github.com/go-pdf/fpdf(MIT) and embedded DejaVu Sans fonts (Bitstream Vera licence,internal/pdf/fonts/LICENSE): A4, seller and buyer blocks, lines table with page breaks, VAT breakdown, totals, mentions, page footer. Rendering is deterministic (dates come from the document), soGET …/pdfof an issued invoice returns the same bytes as the archived file (X-Content-SHA256) as long as the renderer is unchanged (invoices archived before a renderer change re-render differently; the archive is the reference). - Factur-X: CII XML, EN 16931 profile (
urn:cen.eu:en16931:2017), embedded in the fpdf output. The fpdf header is rewritten as%PDF-1.7followed by the binary marker comment (xref offsets shifted), then an incremental update adds thefactur-x.xmlembedded file (/AFRelationship /Data,/Subtype /text#2Fxml, size, date and MD5 checksum), the catalog/AF, XMP metadata declaring PDF/A-3B and the Factur-X extension schema (synchronised with the rewritten Info dictionary), an sRGB output intent (the CC0sRGB-v2-magicICC profile from Compact-ICC-Profiles,internal/facturx/icc/LICENSE) and a trailer/ID. Fonts are embedded (subsets) by fpdf. - CII details: the delivery date (BT-72) is the service date, or the issue date when none is given; party electronic
addresses (BT-34/BT-49) are the SIREN (EAS
0225) for French organisations, otherwise the first e-mail (EM). Invoices and credit notes carry the payment mentions as notes (AABno early payment discount,PMDlate penalties,PMTrecovery fee for professionals). - Validation status (veraPDF 1.30.3, Mustang CLI 2.26.0: PDF/A, CII XSD, EN 16931 and French "Flux 2"
Schematron): standard invoice, credit note, multi-rate VAT (20/10/5.5/2.1/0 % with a discount), B2C individual and
EU B2B (German buyer) all pass with no error. Only warning left:
BR-FR-05_BT-22_PMTon the B2C sample (the 40 € recovery fee does not apply to consumers). Nothing is validated at runtime. - Rerun (Docker required, no compose stack):
make validate-facturx, i.e.go test -tags validation -run TestFacturXValidation -v ./internal/invoice/inservices/finance. It issues the samples through the service (MongoDB testcontainer), then runsverapdf/cli:v1.30.3and the Mustang jar oneclipse-temurin:21-jrein throw-away containers without network. The jar is downloaded once into the user cache (SHA-256 checked) unlessMUSTANG_JARpoints at it;FACTURX_OUT=<dir>keeps the generated PDF and XML files,FACTURX_STRICT=1fails on unexpected warnings,VERAPDF_IMAGE/JAVA_IMAGEoverride the images. The plaingo test ./...never needs these tools. - Archiving: after issuance the PDF is uploaded to files with the finance service identity (owner
atl:finance:<site>:invoice/<id>, purposeinvoice, site and project parents), then handed to the PA adapter (no-op:platform_state = not_configured). Failures leavepdf.state = pending; thefinance-archivelease job retries with backoff,POST …/archiveretries immediately.
Accounting
Simplified French associative chart, mapping configurable in the settings (accounts, journals):
| Flow | Journal | Entry |
|---|---|---|
| Issued invoice | VE | D 411000 (customer aux) TTC / C 706000 HT per rate / C 445710 VAT per rate |
| Issued credit note | VE | reverse of the above |
| Supplier invoice of a purchase | AC | D 606000 (or the purchase account) HT / D 445660 VAT / C 401000 (supplier aux) TTC |
| Approved expense claim | OD | D expense category account (606400, 606300, 625100, 625700, 625600, 628000) HT / D 445660 VAT / C 467000 (member aux M<8 hex>) |
| Payment | BQ | incoming: D 512000 net, D 627000 fees, C 411000 per invoice; outgoing: C 512000, D 401000 / 467000 / 411000 |
Entries are posted in the transaction of the operation, balanced (checked), numbered gap-free per site and fiscal
year (fiscal_year_start_month, fiscal year = starting calendar year) and never modified. Individuals appear as
Client particulier <code> (no clear name in the journal). FEC (GET /v1/finance/exports/fec?site&year,
finance.export.run, audited finance.export.run): the 18 columns of article A47 A-1 LPF, tab separated, CRLF,
ISO-8859-15, amounts with a decimal comma, EcritureNum = <SITE>-<FY>-<NNNNNN>, file name
<SIREN>FEC<closing date>.txt.
Bank matching
Consumer group finance-bank on bank.transaction.v1 (bank.transaction.imported): each transaction is stored
once (_id = bank-sync transaction ID) with suggestions — incoming: issued invoices of the site whose amount due
equals the amount (score 50) and/or whose number appears in the remittance text (spaces ignored, score +50);
outgoing: invoiced purchases and approved expense claims of the same amount. A treasurer confirms
(POST /v1/finance/bank-transactions/{id}/confirm, best suggestion by default or explicit allocations; the
difference between allocations and an incoming amount is recorded as fees) or ignores it. The payment, the
settlements, the bank entry and the reconciliation are written in one transaction.
Authorization
authz maps finance.<res>.<action> to the Permify entity finance_<res>: checks target the document ARN with its
site and project parents (project roles act on their project documents) or the collection pattern
atl:finance:<site>:<type>/* (site level, global permissions).
| Action | Rule |
|---|---|
| Customers / suppliers | finance.customer.* / finance.supplier.* on atl:finance:*:<role>/* |
| Read quotes / invoices | finance.quote.read / finance.invoice.read on the document (project scoped); otherwise 404; lists use the Lookup scope |
| Create, edit, delete drafts, convert | finance.quote.create/update/delete, finance.invoice.create/update/delete (+ finance.invoice.create to convert) |
| Issue, archive | finance.invoice.issue (sensitive) |
| Payments | read finance.payment.read on the payment (project scoped: a payment whose settled documents all belong to one project carries its project_id; lists use the Lookup scope); record finance.payment.record (sensitive) on atl:finance:<site>:payment/* |
| Bank transactions | list, read, confirm, ignore finance.payment.confirm (sensitive) on atl:finance:<site>:payment/* |
| Purchases | request finance.purchase.request; read requester or finance.purchase.read; approve, refuse, supplier invoice finance.purchase.approve (sensitive); edit, order, receive, cancel requester or approver |
| Expense claims | create and submit finance.expense.submit (requester only edits); read requester or finance.expense.approve; approve / refuse finance.expense.approve (sensitive), never the requester |
| Budgets | finance.budget.manage (sensitive); project budgets readable with finance.purchase.read on the project |
| Journal, FEC | finance.export.run (sensitive) on atl:finance:<site>:journal/* |
| Settings | read: finance.invoice.read at site or organisation level (not project scoped) or settings.organization.update; write: settings.organization.update (unchanged: the organisation settings writers own the seller identity) |
Capabilities. Quote, invoice, purchase, expense and budget responses (documents and list items) carry
capabilities, the actions the caller may perform now: quote edit, delete, change_status, convert; invoice
edit, delete, issue, archive, credit, record_payment; purchase edit, approve, refuse, order,
receive, cancel, attach_invoice, record_payment; expense edit, delete, submit, approve, refuse,
record_payment; budget edit, delete. They combine the document state with the rules above, decided with one
CheckMany per response (deduplicated, cached for the request together with the guards' checks); authz failures
count as denied. The web gates action buttons on them and keeps permission-based gating for creation and lists.
Files delegate (FILES_DELEGATES entry finance=http://finance:8091): expense receipts
(atl:finance:<site>:expense/<id>: read requester or approver, write requester while draft or submitted, otherwise
an approver) and purchase documents (atl:finance:<site>:purchase/<id>: read requester or finance.purchase.read,
write requester until paid or cancelled, otherwise an approver). Invoice PDFs use the derived
finance.invoice.read permission of the files service.
HTTP API
OpenAPI: API reference (services/finance/openapi.yaml). Lists are cursor paginated.
| Method | Path | Notes |
|---|---|---|
| GET, PUT | /v1/finance/settings | VAT number, penalties, terms, IBAN, fiscal year, account mapping |
| GET, POST | /v1/finance/customers, /v1/finance/suppliers | q, kind, user_id |
| GET, PUT, DELETE | /v1/finance/customers/{id}, /v1/finance/suppliers/{id} | |
| GET, POST | /v1/finance/quotes | site, project, customer, status (comma list), q |
| GET, PATCH, DELETE | /v1/finance/quotes/{id} | drafts only for PATCH / DELETE |
| POST | /v1/finance/quotes/{id}/status, /convert | |
| GET | /v1/finance/quotes/{id}/pdf | |
| GET, POST | /v1/finance/invoices | site, project, customer, status (comma list), kind, overdue, due_before, due_after, q |
| GET, PATCH, DELETE | /v1/finance/invoices/{id} | drafts only for PATCH / DELETE |
| POST | /v1/finance/invoices/{id}/issue, /archive, /credit-notes | |
| GET | /v1/finance/invoices/{id}/pdf, /facturx.xml | |
| GET, POST | /v1/finance/payments | site required, document |
| GET | /v1/finance/payments/{id} | |
| GET | /v1/finance/bank-transactions, /{id} | site required, status |
| POST | /v1/finance/bank-transactions/{id}/confirm, /ignore | |
| GET, POST | /v1/finance/purchases | site, project, status (comma list), budget, mine, q |
| GET, PATCH | /v1/finance/purchases/{id} | |
| POST | /v1/finance/purchases/{id}/approve, /refuse, /order, /receive, /cancel, /invoice | |
| GET, POST | /v1/finance/expenses | |
| GET, PATCH, DELETE | /v1/finance/expenses/{id} | |
| POST | /v1/finance/expenses/{id}/submit, /approve, /refuse | |
| GET, POST | /v1/finance/budgets; GET, PATCH, DELETE /{id} | consumption computed on read |
| GET | /v1/finance/summary?site&top | dashboard figures in one call (unpaid and overdue invoices, pending approvals excluding own claims, most consumed budgets), each section filtered by scope and omitted without one |
| GET | /v1/finance/journal?site&year&journal | |
| GET | /v1/finance/exports/fec?site&year | FEC file |
| POST | /internal/v1/attachments/authorize | files delegate, not routed by the gateway |
List filters. status accepts several comma-separated values (OR). overdue=true keeps unpaid invoices
(issued, partially_paid) whose due_date is before today in Europe/Paris; due_before / due_after bound
the due date (inclusive). q searches quotes and invoices by number, subject (and credited number) or customer name,
and purchases by title, supplier invoice reference or supplier name: documents store blind index search_terms
(same keyed HMAC as parties, see internal/search), the party name is matched through the customers / suppliers
index (at most 500 parties). Terms are computed on every write; documents stored before are backfilled at startup.
Kafka
| Kind | Name | Notes |
|---|---|---|
| out | finance.invoice.v1 | created, updated, deleted, issued, credited, payment_applied, archived (IDs, numbers, amounts) |
| out | finance.quote.v1 | created, updated, status_changed, converted, deleted |
| out | finance.payment.v1 | recorded |
| out | finance.purchase.v1 | requested, updated, approved, refused, ordered, received, invoiced, paid, cancelled |
| out | finance.expense.v1 | created, updated, deleted, submitted, approved, refused, reimbursed |
| out | finance.budget.v1 | created, updated, deleted |
| out | finance.customer.v1, finance.supplier.v1 | created, updated, deleted (identity of individuals sealed) |
| out | audit.records.v1 | every write, issuance, archiving and FEC export (IDs only) |
| in | bank.transaction.v1 | bank.transaction.imported (group finance-bank) |
finance.purchase.received data: {purchase_id, site_id, project_id?, receipt_seq, lines: [{line_id, item_id, quantity, quantity_milli, unit_cost_cents}]} — one event per receipt, carrying only the quantities of that receipt
and only lines with an inventory item; quantity in item units, unit_cost_cents = line net / ordered quantity
(discount included). inventory adds the stock once per line and receipt and updates the unit cost.
Data (MongoDB finance)
| Collection | Content |
|---|---|
customers, suppliers | parties (search_terms, user_id) |
quotes, invoices, purchases, expenses, budgets | versioned documents (site_id, project_id, status with _id; unique invoices.number; search_terms; invoices status+due_date, site_id+status+due_date, due_date) |
payments, bank_transactions | payments (unique bank_transaction_id), imported transactions |
journal_entries | journal (site_id, fiscal_year, number) |
counters | gap-free sequences (invoices, credit notes, quotes, journal) |
settings | finance settings |
data_keys | per-party encryption keys (cryptox) |
outbox, leases | pending Kafka messages, lease jobs |
Jobs
finance-archive(everyFINANCE_JOB_INTERVAL): archives issued invoices whose PDF is pending.finance-quotes(everyFINANCE_JOB_INTERVAL): expires sent quotes past their validity.
Configuration
| Variable | Default | Description |
|---|---|---|
HTTP_ADDR | :8091 | Listen address |
METRICS_ADDR | :9191 | Prometheus listener |
MONGO_URI, MONGO_DATABASE | mongodb://localhost:27017/?directConnection=true, finance | MongoDB |
KAFKA_BROKERS | localhost:19092 | Outbox relay and consumer |
PRINCIPAL_PUBLIC_KEY | required | Verifies X-Atl-Principal |
PRINCIPAL_SIGNING_KEY | required | Service identity (files uploads) |
AUTHZ_URL | http://localhost:8081 | authz checks and authenticated organisation settings |
FILES_URL | http://localhost:8084 | invoice PDF archiving |
CRYPTO_KEK_SOURCE, CRYPTO_KEK | env, required | KEK of the per-party keys |
FINANCE_SEARCH_KEY | derived from CRYPTO_KEK | 32 bytes base64, blind index key (required with Barbican) |
FINANCE_BANK_TOPIC | bank.transaction.v1 | bank-sync transactions |
FINANCE_JOB_INTERVAL | 5m | archive and quote expiry jobs |
FINANCE_TIMEZONE | Europe/Paris | legal dates (issue date, numbering year) |
Plus the common APP_ENV, LOG_LEVEL, OTEL_EXPORTER_OTLP_ENDPOINT (see
environment variables).