Aller au contenu principal

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 requires vat_exemption_reason at issuance (CII category E), other rates are category S.
  • 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_cents on 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): kind company | individual | public_body, name, SIREN/SIRET (SIREN derived from the SIRET), VAT number, address, up to 5 e-mails, phone, payment terms, optional user_id (customers), auxiliary account code (C… / F…). For individuals the name, address, e-mails and phone are sealed with cryptox.Keyring (subject = party ID) in the document and in events; search uses a keyed blind index (HMAC tokens and 3+ prefixes, FINANCE_SEARCH_KEY). ARN atl:finance:*:customer/<id>.
  • Quotes: numbered at creation D-<SITE>-<YYYY>-<NNNN>, draft → sent → accepted | rejected | expired (sent/rejected/expired → draft to rework), editable only as drafts, valid_until; a lease job expires sent quotes past their validity. POST …/convert creates 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 in fees_cents).
  • Purchases: requested → approved | rejected → ordered → [partially_received →] received → invoiced → paid (cancelled before reception); lines may reference an inventory item_id. POST …/receive takes an optional {lines: [{line_id, quantity_milli}]} (no body: everything remaining); each receipt is numbered (receipts[].seq), lines track received_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 give revenue_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:

  1. re-reads the draft (version check), and for a credit note settles the credited invoice (409 credit_exceeds_invoice when the total of credit notes would exceed the invoice);
  2. increments the counter invoice-<F|A>-<site>-<year> ($inc on counters, the year of the issue date in FINANCE_TIMEZONE) and formats F-<SITE>-<YYYY>-<NNNN> (credit notes A-…);
  3. 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);
  4. enqueues finance.invoice.issued and 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), so GET …/pdf of 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.7 followed by the binary marker comment (xref offsets shifted), then an incremental update adds the factur-x.xml embedded 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 CC0 sRGB-v2-magic ICC 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 (AAB no early payment discount, PMD late penalties, PMT recovery 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_PMT on 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/ in services/finance. It issues the samples through the service (MongoDB testcontainer), then runs verapdf/cli:v1.30.3 and the Mustang jar on eclipse-temurin:21-jre in throw-away containers without network. The jar is downloaded once into the user cache (SHA-256 checked) unless MUSTANG_JAR points at it; FACTURX_OUT=<dir> keeps the generated PDF and XML files, FACTURX_STRICT=1 fails on unexpected warnings, VERAPDF_IMAGE / JAVA_IMAGE override the images. The plain go 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>, purpose invoice, site and project parents), then handed to the PA adapter (no-op: platform_state = not_configured). Failures leave pdf.state = pending; the finance-archive lease job retries with backoff, POST …/archive retries immediately.

Accounting​

Simplified French associative chart, mapping configurable in the settings (accounts, journals):

FlowJournalEntry
Issued invoiceVED 411000 (customer aux) TTC / C 706000 HT per rate / C 445710 VAT per rate
Issued credit noteVEreverse of the above
Supplier invoice of a purchaseACD 606000 (or the purchase account) HT / D 445660 VAT / C 401000 (supplier aux) TTC
Approved expense claimODD expense category account (606400, 606300, 625100, 625700, 625600, 628000) HT / D 445660 VAT / C 467000 (member aux M<8 hex>)
PaymentBQincoming: 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).

ActionRule
Customers / suppliersfinance.customer.* / finance.supplier.* on atl:finance:*:<role>/*
Read quotes / invoicesfinance.quote.read / finance.invoice.read on the document (project scoped); otherwise 404; lists use the Lookup scope
Create, edit, delete drafts, convertfinance.quote.create/update/delete, finance.invoice.create/update/delete (+ finance.invoice.create to convert)
Issue, archivefinance.invoice.issue (sensitive)
Paymentsread 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 transactionslist, read, confirm, ignore finance.payment.confirm (sensitive) on atl:finance:<site>:payment/*
Purchasesrequest 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 claimscreate and submit finance.expense.submit (requester only edits); read requester or finance.expense.approve; approve / refuse finance.expense.approve (sensitive), never the requester
Budgetsfinance.budget.manage (sensitive); project budgets readable with finance.purchase.read on the project
Journal, FECfinance.export.run (sensitive) on atl:finance:<site>:journal/*
Settingsread: 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.

MethodPathNotes
GET, PUT/v1/finance/settingsVAT number, penalties, terms, IBAN, fiscal year, account mapping
GET, POST/v1/finance/customers, /v1/finance/suppliersq, kind, user_id
GET, PUT, DELETE/v1/finance/customers/{id}, /v1/finance/suppliers/{id}
GET, POST/v1/finance/quotessite, 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/invoicessite, 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/paymentssite 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/purchasessite, 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&topdashboard 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&yearFEC file
POST/internal/v1/attachments/authorizefiles 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​

KindNameNotes
outfinance.invoice.v1created, updated, deleted, issued, credited, payment_applied, archived (IDs, numbers, amounts)
outfinance.quote.v1created, updated, status_changed, converted, deleted
outfinance.payment.v1recorded
outfinance.purchase.v1requested, updated, approved, refused, ordered, received, invoiced, paid, cancelled
outfinance.expense.v1created, updated, deleted, submitted, approved, refused, reimbursed
outfinance.budget.v1created, updated, deleted
outfinance.customer.v1, finance.supplier.v1created, updated, deleted (identity of individuals sealed)
outaudit.records.v1every write, issuance, archiving and FEC export (IDs only)
inbank.transaction.v1bank.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)​

CollectionContent
customers, suppliersparties (search_terms, user_id)
quotes, invoices, purchases, expenses, budgetsversioned 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_transactionspayments (unique bank_transaction_id), imported transactions
journal_entriesjournal (site_id, fiscal_year, number)
countersgap-free sequences (invoices, credit notes, quotes, journal)
settingsfinance settings
data_keysper-party encryption keys (cryptox)
outbox, leasespending Kafka messages, lease jobs

Jobs​

  • finance-archive (every FINANCE_JOB_INTERVAL): archives issued invoices whose PDF is pending.
  • finance-quotes (every FINANCE_JOB_INTERVAL): expires sent quotes past their validity.

Configuration​

VariableDefaultDescription
HTTP_ADDR:8091Listen address
METRICS_ADDR:9191Prometheus listener
MONGO_URI, MONGO_DATABASEmongodb://localhost:27017/?directConnection=true, financeMongoDB
KAFKA_BROKERSlocalhost:19092Outbox relay and consumer
PRINCIPAL_PUBLIC_KEYrequiredVerifies X-Atl-Principal
PRINCIPAL_SIGNING_KEYrequiredService identity (files uploads)
AUTHZ_URLhttp://localhost:8081authz checks and authenticated organisation settings
FILES_URLhttp://localhost:8084invoice PDF archiving
CRYPTO_KEK_SOURCE, CRYPTO_KEKenv, requiredKEK of the per-party keys
FINANCE_SEARCH_KEYderived from CRYPTO_KEK32 bytes base64, blind index key (required with Barbican)
FINANCE_BANK_TOPICbank.transaction.v1bank-sync transactions
FINANCE_JOB_INTERVAL5marchive and quote expiry jobs
FINANCE_TIMEZONEEurope/Parislegal dates (issue date, numbering year)

Plus the common APP_ENV, LOG_LEVEL, OTEL_EXPORTER_OTLP_ENDPOINT (see environment variables).