feat(api): Phase 4 PR-1 — AP world (suppliers + supplier-invoices) (#467)

* feat(api): Phase 4 PR-1 — AP world (suppliers + supplier-invoices)

First of two Phase 4 PRs. Ships the public v1 AP-side verticals end-to-end,
mirroring the Phase 2 AR pattern (customers + invoices).

ENDPOINTS (13)

Suppliers:
  GET    /suppliers                       — cursor list + filters
  GET    /suppliers/{id}                  — detail, ?expand=supplier_invoices
  POST   /suppliers                       — idempotent, dry-runnable
  PATCH  /suppliers/{id}                  — idempotent, dry-runnable, can un-archive
  DELETE /suppliers/{id}                  — soft-archive, refused on open SI
  POST   /suppliers/bulk-create           — partial-success, max 50

Supplier invoices:
  GET    /supplier-invoices               — cursor list + filters
  GET    /supplier-invoices/{id}          — detail, ?expand=supplier,items,payments
  POST   /supplier-invoices               — register + post registration JE
  PATCH  /supplier-invoices/{id}          — registered-only
  POST   /supplier-invoices/{id}/approve  — flip to approved
  POST   /supplier-invoices/{id}/mark-paid — book payment JE + flip status
  POST   /supplier-invoices/{id}/credit   — issue kreditfaktura + reversing JE

No DELETE on supplier-invoices — withdrawal is via :credit (mirrors v1 invoices,
keeps both original AND credit note in the audit trail per BFL 5 kap 5 §).

STRICT-MODE V1

Carried forward from Phase 3 lessons:
- Any JE failure ABORTS before SI state mutation (no soft-fall / partial state).
  Applies to register, mark-paid, and credit.
- checkPeriodLock() pre-check before every JE-emitting write — returns
  structured PERIOD_LOCKED / SI_PAID_PERIOD_LOCKED / SI_CREDIT_PERIOD_LOCKED
  instead of letting the DB trigger surface a generic 500.
- CAS-race orphan handling in mark-paid: if the SI status flips between
  pre-flight and our update, the just-posted payment JE is stornoed via
  reverseEntry() rather than left dangling (BFL 5 kap 5 §).
- Math.round monetary throughout. Half-öre epsilon on remaining_amount==0.

SCHEMA MIGRATION

`20260513150000_archived_at_for_customers_and_suppliers.sql`:
  - Adds suppliers.archived_at (new — required for the soft-archive flow).
  - Adds customers.archived_at + customers.vat_number_validated_at —
    retroactively. The Phase 2 v1 customer routes (PR #451 / #452 / #460)
    already reference both columns but no prior migration installed them in
    production. This commit fixes that latent bug while we have the
    migration open.
  - Partial indexes on (company_id, created_at) WHERE archived_at IS NULL
    keep the default-active list path cheap.
  - is_active (legacy boolean) preserved on suppliers; v1 archive sets both
    archived_at = now() AND is_active = false, un-archive flips both back
    so the dashboard's "show only active" filters stay intact.

NEW ERROR CODES

  SUPPLIER_HAS_INVOICES (409) — archive refused while open SI exists
  SI_NOT_DRAFT          (400) — update/delete refused on non-registered SI

GDPR ART.5(1)(c) DEFENSE-IN-DEPTH

SupplierType has no `individual` variant today, so org_number is always
Bolagsverket public-record data. The list endpoint still has the masking
hook (empty INDIVIDUAL_TYPES set) so a future natural-person supplier type
becomes a one-line change. Duplicate-org_number error responses NEVER echo
the submitted value — symmetric with customers.

SCOPES

13 new entries in V1_ENDPOINT_SCOPES under suppliers:read / suppliers:write.

TESTS

36 new integration cases across 2 suites:
  - suppliers: list (incl. filter), get (incl. 404), create (happy + 23505 +
    dry-run + missing-idempotency), patch (happy + empty body), delete
    (archive + open-invoice refusal), bulk-create (partial-success + 501)
  - supplier-invoices: list, get (incl. 404), create (happy accrual + supplier
    404 + period-locked + strict-mode JE rollback + dry-run), patch
    (registered-only), approve (happy + non-registered refusal), mark-paid
    (happy + period-locked + already-paid + strict-mode abort), credit
    (happy + already-credited + period-locked + dry-run)

Full suite green: 3333 passing (237 files). Build + lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(api): PR #467 round-2 — Greptile P1/P2 fixes

Three real findings from Greptile inline review on the Phase 4 PR-1 commit.

P1 — mark-paid: storno orphan JE when SI update fails.
  When the `.update()` after the JE post returned an `updateErr`, the route
  logged + returned SI_PAID_FAILED without reversing the just-posted payment
  JE. The CAS-race branch immediately below already proves journalEntryId is
  in scope and reverseEntry takes it directly — the original comment about
  "requires fetching the entry first" was wrong. Now both error branches
  (the `updateErr` DB-failure path and the `!updated` CAS-race path) storno
  via reverseEntry before returning, keeping the AP ledger consistent
  (BFL 5 kap 5 §). Storno failure itself logs loudly and the error envelope
  surfaces the journal_entry_id so manual reconciliation has a starting
  point.

P1 — credit + register: capture JE link-update result, storno on failure.
  Both supplier-invoices/route.ts (register) and supplier-invoices/[id]/
  credit/route.ts back-fill registration_journal_entry_id on the freshly-
  inserted SI/credit-note row, but were dropping the await result. A
  transient DB error there silently left the row with registration_-
  journal_entry_id=null even though the JE was live on the books — the POST
  response looked correct (it returned the JE id from the local variable)
  but every subsequent GET /supplier-invoices/{id} showed null. Both paths
  now capture the link-update error, storno the orphan JE via reverseEntry,
  then roll back the SI/credit-note row before returning SI_CREATE_FAILED
  / SI_CREDIT_FAILED with step='*_link'. Strict-mode atomicity restored.

P2 — mark-paid: dry-run paid_at format alignment.
  Dry-run preview set `paid_at: paymentDate` (YYYY-MM-DD), but the live
  `.update()` writes `new Date().toISOString()` (full UTC timestamp). A
  caller validating both responses against the same regex would have been
  caught by the mismatch. Dry-run now mirrors the live shape.

P2 — ensureInitialized() finding dismissed as a false positive:
  lib/api/v1/with-api-v1.ts:52 already calls ensureInitialized() at module
  load. Every v1 route imports withApiV1 from that module, so the side
  effect runs on first import and caches. No existing v1 route (customers,
  invoices, transactions) imports ensureInitialized() directly — the
  pattern has been consistent across Phases 1-3 and the AP-world routes
  follow it.

Tests + build green: 3333 passing across 237 files, AP suite 36/36.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(api): PR #467 round-3 — compliance swarm + swedish-compliance fixes

Both bots re-ran and converged on a set of substantive findings. Seven real
issues addressed; several recurring false positives + architectural
deferrals documented inline.

REAL FIXES (7)

1. credit: `remaining_amount` calc was nonsensical.
   `Math.max(0, remaining_amount - total)` was always ≤ 0 (since
   remaining ≤ total), forcing status to 'credited' regardless of paid
   state — but only via the clamp, not the logic. Both swedish-compliance
   and Compliance Swarm (OWASP V2.3 + SOC 2 PI1.3) caught this. A
   kreditfaktura nullifies the AP obligation on the original (BFL 5 kap
   5 §); refunds of already-paid amounts get a separate transaction.
   `remaining_amount: 0` and `status: 'credited'` unconditionally.

2. supplier-invoices register: VAT rate whitelist.
   `computeItemsAndTotals` accepted any float for `vat_rate`, silently
   booking an unrecognised rate into the registration JE → momsdeklaration
   Ruta 48 + INK2R. Now rejects with VALIDATION_ERROR (allowed_rates
   echoed) unless the rate is in `{0, 0.06, 0.12, 0.25}` (ML 2 kap 1 §).

3. mark-paid: `exchange_rate_difference` is required for non-SEK accrual.
   The pitfall docs warned about this but the code didn't enforce it. Without
   it the payment JE doesn't book the FX delta to 3960/7960 and AP carries
   a stranded 2440 balance after the bank line clears. Enforces with field-
   level VALIDATION_ERROR; pass `exchange_rate_difference: 0` if there's
   no rate movement.

4. suppliers PATCH: refuse on archived suppliers (BFL 7 kap 1 §).
   An archived supplier's name/address backs historical verifikationer; a
   post-archive PATCH would silently corrupt 7-year-retained räkenskaps-
   information. The handler now fetches the current row, refuses identifying-
   field updates when `archived_at IS NOT NULL`, and only permits the
   un-archive PATCH (`archived_at: null`).

5. supplier-invoices register: smart vat_treatment / reverse_charge default.
   The previous default of `'standard_25'` regardless of supplier_type left
   EU/non-EU supplier rows with metadata that didn't match the actual booking
   path (which uses `reverse_charge`). Now derives both fields from
   `supplier.supplier_type` when the caller omits them: foreign suppliers
   default to `reverse_charge: true` + `vat_treatment: 'reverse_charge'`.
   Explicit body values still win.

6. reverseEntry: static import (SOC 2 CC8.1).
   Replaced the three dynamic `await import('@/lib/bookkeeping/engine')`
   calls in orphan-storno error branches with a top-level static import.
   The dependency is now visible to SCA / tree-shake / static analysis.

7. Add `userId: ctx.userId` to every storno-failure log context (OWASP
   V16.1). The CAS-race + linkErr branches now consistently include the
   actor identity for security-relevant audit events.

TESTS (+6 new)

  - register: rejects non-Swedish vat_rate (whitelist) → 400
  - register: defaults reverse_charge=true + vat_treatment='reverse_charge'
    for eu_business suppliers
  - mark-paid: requires exchange_rate_difference for non-SEK accrual → 400
  - mark-paid: passes when exchange_rate_difference is explicitly 0
  - suppliers PATCH: refuses identifying-field edit when archived_at IS NOT NULL
  - suppliers PATCH: allows un-archive (archived_at: null) flip

AP suite 42/42 (was 36). Full suite 3339/3339 green (was 3333).

DISMISSED WITH RATIONALE

- swedish-compliance "credit-note amounts should be negative" — false read
  of the engine. `createSupplierCreditNoteEntry` calls `Math.abs()` on
  item amounts (line 421) and posts a reversing JE; the SI row carries
  positive amounts + `is_credit_note=true` as a deliberate data-model
  decision. Negating would break parity with the dashboard and the
  internal AP-ledger reporting.

- OWASP V8.2.1 cross-tenant via path — recurring false positive across
  Phases 2-4. `withApiV1` (line ~340-350) verifies `company_members`
  membership BEFORE setting `ctx.companyId` from the URL.

- OWASP V8.2.1 supplier_invoice_items company_id filter in
  rollbackCreditNote — the table has no `company_id` column;
  cross-tenant protection comes from RLS + the parent
  supplier_invoice_id scoping.

- OWASP V4.5 PATCH allowlist schema-derivation — known architectural
  deferral; centralising the field list against a Zod `.pick()` is a
  separate refactor.

- GDPR Art.5(1)(f) log/event field identifiers — RoPA / log-pseudonymisation
  is an org-wide privacy-eng concern, not a per-route fix.

- ISO 27001 A.8.15/A.8.16 non-blocking inserts — `supplier_invoice_payments`
  insert + event emit failures stay at warn-level for v1 to mirror the
  dashboard internal route. Promoting to error escalations + DLQ is a
  cross-cutting reliability project, not a route patch.

- SOC 2 CC6.3 segregation-of-duties — v1's API-key scope IS the boundary
  by design. Role-based separation between register / approve / pay is a
  v1.x feature, not a v1 surface bug.

- swedish-compliance reverse-charge gating in credit — the engine
  (`createSupplierCreditNoteEntry`) already gates the 2647/2645 reversal
  on `creditNote.reverse_charge` (line 437). Mirrors the registration
  engine.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(api): PR #467 round-4 — BFL 5 kap 5 § + remaining compliance fixes

Compliance bots re-ran on round-3 (Compliance Swarm 13→12 findings,
Swedish-compliance fresh re-read). Five real issues addressed; the rest
are recurring false positives or architectural deferrals carried over
from earlier rounds.

REAL FIXES (5)

1. mark-paid: future payment_date rejected at the schema layer.
   BFL 5 kap 2 § requires bokföring to follow real cash movement;
   payment_date > today is a scheduling artefact, not an affärshändelse.
   Returns 400 VALIDATION_ERROR before the JE engine runs.

2. credit: drop user_id from SI_FULL_COLUMNS (GDPR Art.25).
   The original SI's `user_id` (its historical creator) is never used
   in the credit flow — the new credit-note row uses ctx.userId (the
   actor performing the credit). Don't fetch what you don't need.
   Also drops company_id from the select since it's already filtered.

3. supplier-invoices register: reverse-charge cross-field VAT check.
   For reverse-charge invoices the Swedish supplier doesn't charge VAT,
   the buyer self-assesses (ML 1 kap 2§ p.4b / 16 kap 6 § / 16 kap 13 §).
   If `reverse_charge=true` and ANY item has `vat_rate != 0`, return
   VALIDATION_ERROR — otherwise the engine would book ingående moms in
   Ruta 30 / 48 (BAS 2614 / 2645 / 2641) for an invoice that has no VAT
   to deduct.

4. rollbackSupplierInvoice + rollbackCreditNote: soft-mark, not delete.
   BFL 5 kap 5 § — rättelse av bokföringspost måste vara dokumenterad
   så att både den ursprungliga och den korrigerade noteringen är
   synliga. Hard-deleting the SI row on a mid-write failure destroys
   räkenskapsinformation even when the JE side (if any) is preserved
   via storno. Both rollback paths now UPDATE status='reversed' +
   reversed_at=now() — the SupplierInvoiceStatus enum already has
   'reversed' for exactly this case ("credit note whose journal entry
   was storno-reversed via Ångra kreditering" per the type comment).
   Trade-off: a retry with the same supplier_invoice_number will hit
   the unique-index conflict, so the caller picks a fresh number.

TESTS (+2 new)

  - register: rejects reverse_charge=true with non-zero item vat_rate
  - mark-paid: rejects future payment_date

Pre-existing eu_business reverse_charge test updated: item vat_rate
flipped from 0.25 → 0 to remain valid under the new cross-field check.

AP suite 44/44 (was 42). Full suite 3341/3341 green (was 3339).

DISMISSED (recurring or architectural)

- OWASP V8.2.1 cross-tenant via path — recurring false positive across
  Phase 2-4. withApiV1 verifies company_members membership BEFORE
  setting ctx.companyId from the URL.

- ISO A.8.3 approve-route TOCTOU — already mitigated. The UPDATE has
  `.eq('status', 'registered')` as a race guard; the pre-flight is for
  ergonomic error messages, not security.

- SOC 2 PI1.3 floating-point — project-wide convention is
  Math.round(x * 100) / 100 per CLAUDE.md. Diverging in one route would
  create a parity bug with the bookkeeping engine + dashboard. Settled.

- SOC 2 CC7.3 storno-failure alerting / ISO A.8.15 audit-log on success
  / SOC 2 CC6.1 test-fixture key / OWASP V2.2 status state-machine /
  V1.2.5 dynamic select-clause / V16 audit-log silent-failure / Art.25
  banking-field expand — all architectural deferrals that fit the
  webhook-hardening + scope-redesign work in Phase 6, not the v1 PR.

- swedish-compliance "credit-note original-number reference" — the
  `credited_invoice_id` FK is the structured back-reference; the
  document-rendering layer surfaces the original `supplier_invoice_-
  number` from there. Not a v1 surface bug.

- swedish-compliance "cash-basis credit-note vat_amount" — engine
  behaviour mirrored from the dashboard. Engine-layer audit, separate
  effort.

- swedish-compliance "active-supplier mutability broader than
  archived_at" — solving this requires snapshotting supplier identity
  onto each supplier_invoices row at registration (schema migration).
  Deeper architectural decision; tracking for Phase 4 follow-up
  alongside the journal-entries vertical.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(api): PR #467 round-5 — strict schema + vat_treatment normalisation +
narrow BFL archive lock

Compliance bots re-ran on round-4. Most findings are recurring (V8.2.1
cross-tenant, PI1.3 floating-point, CC6.3 SoD) or the classic oscillation
pattern from the Phase 3 lessons: this round's Art.5(1)(f) flags userId in
storno error logs as PII exposure — but last round's V16.1 demanded I ADD
userId for audit attribution. Staying with audit attribution; the bot can
pick a side.

Three substantive findings addressed.

REAL FIXES (3)

1. V4.5 mass-assignment defense-in-depth on PATCH /supplier-invoices/{id}.
   The shared `UpdateSupplierInvoiceSchema` is consumed by the dashboard
   too, where Zod's default key-stripping is acceptable. The v1 route now
   wraps it in `V1PatchSupplierInvoiceSchema = UpdateSupplierInvoiceSchema
   .strict()` so any unknown key (e.g. `status`, `company_id`, `user_id`)
   returns 400 VALIDATION_ERROR instead of being silently dropped — even
   if the iteration allowlist downstream is later relaxed.

2. vat_treatment normalisation when reverse_charge resolves true.
   Caller could previously pass `vat_treatment: 'standard_25'` explicitly
   on an eu_business supplier, and the supplier-type-driven default would
   set `reverse_charge: true` while the metadata stayed as 'standard_25'.
   The engine books via the boolean (so JE is correct) but a downstream
   momsdeklaration / audit export reading `vat_treatment` would mis-
   classify. Resolution order is now: reverse_charge first, then
   vat_treatment forced to 'reverse_charge' if true; explicit overrides
   only stick when they agree with the resolved boolean.

3. Narrow archived-supplier PATCH lock to identifying fields only.
   The round-4 blanket lock on archived suppliers was too broad: BFL
   7 kap 1 § protects räkenskapsinformation — the fields verifikationer
   reference through the supplier join — but not internal notes or
   payment-config metadata. The check now only refuses PATCHes that touch
   {name, supplier_type, org_number, vat_number, address_*, banking_*}.
   Notes, default_payment_terms, default_expense_account, default_currency,
   email, and phone remain editable on archived rows.

TESTS (+3 new)

  - PATCH /supplier-invoices/{id}: rejects unknown body keys (strict schema)
  - POST /supplier-invoices: explicit vat_treatment='standard_25' is
    overridden when supplier_type drives reverse_charge=true
  - PATCH /suppliers/{id}: allows notes edit on archived supplier (BFL
    narrow scope)

AP suite 47/47 (was 44). Full suite 3344/3344 green (was 3341).

DISMISSED (recurring / settled / oscillating)

- OWASP V8.2.1 cross-tenant via path — recurring false positive 4 rounds
  running. withApiV1 verifies company_members membership BEFORE setting
  ctx.companyId from the URL.

- GDPR Art.5(1)(f) userId in error logs — direct contradiction of
  round-3's OWASP V16.1 finding which demanded userId be ADDED for audit
  attribution. Phase 3 lessons document this oscillation pattern
  ("swedish-compliance / compliance-swarm oscillate between rounds")
  and the correct response is to stay with the more security-positive
  position. Keeping userId on storno-failure logs for ledger-integrity
  attribution.

- SOC 2 CC6.3 segregation-of-duties — same as round-3. v1 design uses
  API-key scope as the boundary; role-based actor separation is Phase 6
  webhook + auth work.

- SOC 2 CC6.1 null-userId guard — redundant. withApiV1 short-circuits
  with 401 UNAUTHORIZED before invoking the handler when API-key
  validation fails (which is the only path that could leave ctx.userId
  unset).

- SOC 2 CC7.2 storno-failure alerting — architectural; webhook-bus +
  dead-letter is Phase 6 territory.

- SOC 2 / OWASP PI1.3 / V2.3 floating-point — project-wide convention
  per CLAUDE.md; the engine, dashboard, and v1 all use Math.round(x*100)/100.

- ISO 27001 A.8.33 test-fixture financial amounts — synthetic UUIDs +
  NODE_ENV=test guard already in place; "TEST-only" sentinel amounts
  would be cosmetic.

- OWASP V16.1 eventBus failure retry / DLQ — Phase 6 webhook hardening.

- swedish-compliance arrival_number gap risk — acknowledged in commit,
  bot itself says "no action required"; supplier_invoice_number retry
  behavior already in the rollback-comment doc.

- swedish-compliance vat_code cross-field — engine derives JE shape from
  `invoice.reverse_charge` (boolean), ignores item vat_code in the RC
  path. No surface-layer leak.

- swedish-compliance credit-note FX at today's rate — bot's reasoning
  inverted. The credit note REVERSES the original AP obligation; to net
  2440 to zero across the original-registration JE + credit-note JE, the
  SEK amounts MUST be copied from the original. FX rate at today's date
  applies at the bank-refund transaction side, not the credit-note
  registration.

- swedish-compliance KREDIT- prefix — dashboard parity. The
  `is_credit_note` + `credited_invoice_id` flags are the structured
  back-references; the prefix is cosmetic on the human-readable number.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

* fix(api): PR #467 round-6 — overpayment guard + two-phase rollback +
SI_FULL_COLUMNS minimisation

Compliance Swarm trended down 12→9 findings, Swedish-compliance 6→5.
Three substantive items addressed; the rest are recurring false positives
or the userId-in-logs oscillation that round-5 already settled.

REAL FIXES (3)

1. mark-paid: reject overpayment up front (Compliance Swarm V2.3).
   Previously `Math.max(0, remaining - payment)` silently truncated an
   overpayment to a zero remaining_amount, while the JE engine booked the
   full payment_amount against 2440 — leaving an unaccounted overpayment
   on the AP ledger. Now refuses with VALIDATION_ERROR when
   `payment_amount > remaining_amount + 0.005` (half-öre tolerance for
   FX-rounding artefacts). Recovery hint points at :credit for
   over-billing and the transactions endpoints for refunds.

2. credit: trim SI_FULL_COLUMNS to fields actually read (Art.25(1)).
   The credit handler never reads notes, paid_at, payment_journal_entry_id,
   transaction_id, document_id, payment_reference, paid_amount,
   delivery_date, received_date, reversed_at, created_at, updated_at,
   exchange_rate_date, due_date — but the projection was fetching them
   all. SEK-conversion fields (subtotal_sek / vat_amount_sek / total_sek)
   ARE read (copied onto the credit-note row so the 2440 reversal nets),
   so they stay. Continues the round-4 user_id / company_id drop.

3. Two-phase soft-rollback (Swedish-compliance, BFL 5 kap 5 §).
   The bot caught a real misapplication: BFL 5:5 only kicks in once a
   verifikation has been COMMITTED. Pre-JE failures (items_insert,
   engine returning null because no fiscal period covers the date) are
   failed insertions, not bokföringsposter. Marking those rows
   `status='reversed'` with a null registration_journal_entry_id creates
   a dangling räkenskapsinformation entry that's harder to audit than a
   clean removal. Both rollback helpers now take a `journalEntryPosted`
   flag: pre-JE failures hard-delete (rows + items), post-JE failures
   keep the round-4 soft-mark + reversed_at behaviour. Call sites tagged
   per failure reason:

     items_insert        → false (hard-delete)
     no_fiscal_period    → false (hard-delete; engine returned null pre-write)
     registration_je     → true  (conservative; engine throw could be post-commit)
     je_link_failed      → true  (JE posted + already stornoed above)
     credit items_insert → false
     credit no_fiscal_period → false
     credit_journal_entry → true
     credit_race          → true

TESTS (+1 new)

  - mark-paid: rejects payment_amount > remaining_amount with VALIDATION_ERROR
    (no JE engine call)

AP suite 48/48 (was 47). Full suite 3345/3345 green (was 3344).

DISMISSED (with rationale)

- OWASP V8.2.1 cross-tenant via path — recurring across 5 rounds.
  withApiV1 verifies company_members membership BEFORE setting
  ctx.companyId from the URL. Fix-once decision in the wrapper, not a
  per-route concern.

- OWASP V4.5 strict schema (re-verification) — round-5 added
  V1PatchSupplierInvoiceSchema = UpdateSupplierInvoiceSchema.strict() +
  a test asserting {"status": "approved"} is rejected. The bot is
  re-flagging because it can't see the upstream schema in the diff;
  manually verified: UpdateSupplierInvoiceSchema only contains
  {supplier_invoice_number, invoice_date, due_date, delivery_date,
  payment_reference, notes}. No status / company_id / user_id field.

- GDPR Art.5(1)(f) userId in logs — same oscillation as round-4. Last
  round V16.1 demanded userId be ADDED for audit attribution; this
  round Art.5(1)(f) wants it REMOVED. Staying with audit attribution
  per the Phase 3 lessons doc's oscillation guidance.

- OWASP V16.1 / ISO A.8.15 / SOC 2 CC7.2 SIEM alerting on storno
  failure — architectural; Phase 6 webhook hardening.

- GDPR Art.25(2) supplier-expand banking fields default-on — same as
  round-4. A scope split (suppliers:read:sensitive) is a v1.x scope
  refactor, not a single-route patch.

- swedish-compliance VAT 0.06 date-aware validation (livsmedel 1 April
  2026) — needs livsmedel BAS classification (which BAS codes signal
  food) and date-aware lookup tables. Engine-layer concern; not
  achievable without engine changes. Documenting the 6% rate's temporary
  nature in the comment was the smaller fix already shipped in round-3.

- swedish-compliance SI_RESPONSE_COLUMNS missing reverse_charge — FALSE
  ALARM. `reverse_charge` IS present in the projection (line 264 of
  supplier-invoices/route.ts); the engine receives it correctly.

- swedish-compliance KREDIT- prefix — dashboard parity, dismissed
  rounds 3-5. The `is_credit_note` + `credited_invoice_id` flags are
  the structured back-references.

- swedish-compliance cash-basis credit-note ingående moms timing
  (ML 13 kap 27 §) — legitimate gap but engine-layer. The
  createSupplierCreditNoteEntry engine function handles accrual only;
  adding a cash-basis-already-paid branch would change engine
  semantics, divering from the dashboard. Tracking as a Phase 4 engine
  follow-up, not a v1 surface bug.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-05-13 20:16:27 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 6c54f80a93
commit abb9f5868c
14 changed files with 5352 additions and 0 deletions
@@ -0,0 +1,142 @@
/**
* POST /api/v1/companies/{companyId}/supplier-invoices/{id}/approve
*
* Transitions a `registered` supplier invoice to `approved`. No journal entry
* is involved in this transition — the registration JE has already been posted
* (under accrual) or is deferred to :mark-paid (under cash). Idempotent
* (mandatory Idempotency-Key). Dry-runnable.
*
* Strict-mode: the optimistic-lock UPDATE filters on status='registered' so
* concurrent calls (or a same-key replay racing the first) yield a clean 409
* rather than a silent no-op.
*/
import { z } from 'zod'
import { ok } from '@/lib/api/v1/response'
import { dryRunPreview } from '@/lib/api/v1/dry-run'
import { registerEndpoint } from '@/lib/api/v1/registry'
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
import { eventBus } from '@/lib/events'
import type { SupplierInvoice } from '@/types'
const SI_RESPONSE_COLUMNS =
'id, supplier_id, arrival_number, supplier_invoice_number, invoice_date, due_date, status, currency, subtotal, vat_amount, total, paid_amount, remaining_amount, is_credit_note, registration_journal_entry_id, payment_journal_entry_id, created_at, updated_at'
const SupplierInvoiceApproved = z.object({
id: z.string().uuid(),
status: z.literal('approved'),
arrival_number: z.number().int(),
supplier_invoice_number: z.string(),
})
registerEndpoint({
operation: 'supplier-invoices.approve',
method: 'POST',
path: '/api/v1/companies/:companyId/supplier-invoices/:id/approve',
summary: 'Approve a registered supplier invoice.',
description:
'Flips a supplier invoice from `registered` to `approved`. No journal entry is posted here — the registration JE was already booked at :create under accrual, or is deferred to :mark-paid under cash. Idempotent. Dry-runnable.',
useWhen:
'A registered SI has been reviewed and you want to mark it ready for payment. Many AP workflows gate :mark-paid behind an explicit approval step.',
doNotUseFor:
'Posting a journal entry (already done at :create under accrual). Paying the SI (use :mark-paid). Re-approving an already-approved SI (returns 400 SI_APPROVE_NOT_REGISTERED).',
pitfalls: [
'Idempotency-Key is mandatory.',
'Returns 400 SI_APPROVE_NOT_REGISTERED when current status !== "registered". Use the detail endpoint to inspect status first if unsure.',
],
example: {
response: {
data: { id: '0e9c…', status: 'approved', arrival_number: 42, supplier_invoice_number: '2026-1234' },
meta: { request_id: 'req_…', api_version: '2026-05-12' },
},
},
scope: 'suppliers:write',
risk: 'low',
idempotent: true,
reversible: false,
dryRunSupported: true,
response: { success: SupplierInvoiceApproved },
})
export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
'supplier-invoices.approve',
async (_request, ctx, params) => {
const { id } = await params.params
const idParse = z.string().uuid().safeParse(id)
if (!idParse.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'id', message: 'Supplier-invoice id must be a UUID.' },
})
}
const invoiceId = idParse.data
const { data: existing, error: fetchErr } = await ctx.supabase
.from('supplier_invoices')
.select(SI_RESPONSE_COLUMNS)
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
.maybeSingle()
if (fetchErr) {
return v1ErrorResponse(fetchErr, ctx.log, { requestId: ctx.requestId })
}
if (!existing) {
return v1ErrorResponseFromCode('SI_NOT_FOUND', ctx.log, { requestId: ctx.requestId })
}
if ((existing as { status: string }).status !== 'registered') {
return v1ErrorResponseFromCode('SI_APPROVE_NOT_REGISTERED', ctx.log, {
requestId: ctx.requestId,
details: { current_status: (existing as { status: string }).status },
})
}
if (ctx.dryRun) {
return dryRunPreview(
{ ...(existing as object), status: 'approved' },
{ requestId: ctx.requestId, log: ctx.log },
)
}
const { data, error } = await ctx.supabase
.from('supplier_invoices')
.update({ status: 'approved' })
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
.eq('status', 'registered')
.select(SI_RESPONSE_COLUMNS)
.maybeSingle()
if (error) {
ctx.log.error('supplier-invoice approve update failed', error, {
invoiceId,
companyId: ctx.companyId,
})
return v1ErrorResponseFromCode('SI_APPROVE_UPDATE_FAILED', ctx.log, { requestId: ctx.requestId })
}
if (!data) {
// Race: status transitioned between pre-flight and update.
return v1ErrorResponseFromCode('SI_APPROVE_NOT_REGISTERED', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'race' },
})
}
try {
await eventBus.emit({
type: 'supplier_invoice.approved',
payload: {
supplierInvoice: data as unknown as SupplierInvoice,
companyId: ctx.companyId!,
userId: ctx.userId,
},
})
} catch (err) {
ctx.log.warn('supplier_invoice.approved emit failed', err as Error)
}
return ok(data, { requestId: ctx.requestId })
},
{ requireIdempotencyKey: true },
)
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,485 @@
/**
* POST /api/v1/companies/{companyId}/supplier-invoices/{id}/mark-paid
*
* Records a payment against a supplier invoice. Books the payment journal
* entry via createSupplierInvoicePaymentEntry (accrual) or
* createSupplierInvoiceCashEntry (cash basis — recognizes the expense here),
* then flips status to `paid` or `partially_paid` with an optimistic-lock
* UPDATE that prevents double-booking under concurrent calls.
*
* Strict-mode v1 (per Phase 3 lessons): if JE creation fails, the route
* ABORTS before any SI state mutation — no payment row is written, status
* is unchanged. The caller can retry cleanly.
*
* Idempotent (mandatory Idempotency-Key). Dry-runnable.
*/
import { z } from 'zod'
import { ok } from '@/lib/api/v1/response'
import { dryRunPreview } from '@/lib/api/v1/dry-run'
import { registerEndpoint } from '@/lib/api/v1/registry'
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
import { checkPeriodLock } from '@/lib/api/v1/check-period-lock'
import { MarkSupplierInvoicePaidSchema } from '@/lib/api/schemas'
import {
createSupplierInvoiceCashEntry,
createSupplierInvoicePaymentEntry,
} from '@/lib/bookkeeping/supplier-invoice-entries'
import { reverseEntry } from '@/lib/bookkeeping/engine'
import { isBookkeepingError } from '@/lib/bookkeeping/errors'
import { eventBus } from '@/lib/events'
import type { SupplierInvoice, SupplierInvoiceItem } from '@/types'
const SI_PAID_RESPONSE_COLUMNS =
'id, supplier_id, arrival_number, supplier_invoice_number, status, currency, total, paid_amount, remaining_amount, paid_at, payment_journal_entry_id'
const PAYABLE_STATUSES = ['registered', 'approved', 'partially_paid', 'overdue'] as const
const SupplierInvoicePaidResponse = z.object({
id: z.string().uuid(),
status: z.enum(['paid', 'partially_paid']),
total: z.number(),
paid_amount: z.number(),
remaining_amount: z.number(),
paid_at: z.string().nullable(),
payment_journal_entry_id: z.string().uuid().nullable(),
})
registerEndpoint({
operation: 'supplier-invoices.mark-paid',
method: 'POST',
path: '/api/v1/companies/:companyId/supplier-invoices/:id/mark-paid',
summary: 'Record a payment against a supplier invoice.',
description:
'Books the payment journal entry (Debit 2440 / Credit 1930 under accrual; or Debit expense + Debit 2641 / Credit 1930 under cash) and flips the SI status to `paid` (full settlement) or `partially_paid`. Strict-mode: a JE failure aborts before any SI mutation. Idempotent. Dry-runnable.',
useWhen:
'You paid a registered or approved leverantörsfaktura through a channel other than the synced bank flow. For bank-matched payments use POST /transactions/{id}/match-supplier-invoice instead — that path also reconciles the bank line.',
doNotUseFor:
'Refunding a payment (the public API does not expose unmark-paid; credit the SI instead). Paying a credited or already-paid SI (returns 409 SI_PAID_ALREADY).',
pitfalls: [
'Idempotency-Key is mandatory.',
'payment_date must fall in an open fiscal period — locked period returns 400 PERIOD_LOCKED.',
'exchange_rate_difference (SEK delta vs the booked rate at registration) is required for foreign-currency SIs to book the FX gain/loss to 3960 / 7960. Omitting it on a non-SEK SI under accrual mis-books FX.',
'Strict-mode: a JE creation failure ABORTS before the status flip. There is no partial-state recovery banner — retry the call.',
'Cash basis (kontantmetoden) recognizes the expense + ingående moms HERE, not at :create.',
],
example: {
request: { payment_date: '2026-05-13' },
response: {
data: {
id: '0e9c…',
status: 'paid',
total: 1250,
paid_amount: 1250,
remaining_amount: 0,
paid_at: '2026-05-13',
payment_journal_entry_id: '7b3a…',
},
meta: { request_id: 'req_…', api_version: '2026-05-12' },
},
},
scope: 'suppliers:write',
risk: 'medium',
idempotent: true,
reversible: false,
dryRunSupported: true,
request: { body: MarkSupplierInvoicePaidSchema },
response: { success: SupplierInvoicePaidResponse },
})
export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
'supplier-invoices.mark-paid',
async (request, ctx, params) => {
const { id } = await params.params
const idParse = z.string().uuid().safeParse(id)
if (!idParse.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'id', message: 'Supplier-invoice id must be a UUID.' },
})
}
const invoiceId = idParse.data
// Body is optional — empty POST = pay the full remaining_amount today.
let rawBody: unknown = null
try {
const text = await request.text()
if (text.trim()) rawBody = JSON.parse(text)
} catch {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'body', message: 'Body is not valid JSON.' },
})
}
let bodyAmount: number | undefined
let bodyPaymentDate: string | undefined
let exchangeRateDifference: number | undefined
let bodyNotes: string | undefined
if (rawBody) {
const parsed = MarkSupplierInvoicePaidSchema.safeParse(rawBody)
if (!parsed.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
issues: parsed.error.issues.map((i) => ({
field: i.path.join('.'),
message: i.message,
})),
},
})
}
bodyAmount = parsed.data.amount
bodyPaymentDate = parsed.data.payment_date
exchangeRateDifference = parsed.data.exchange_rate_difference
bodyNotes = parsed.data.notes
}
const today = new Date().toISOString().split('T')[0]
const paymentDate = bodyPaymentDate || today
// Reject future payment_date at the schema layer. BFL 5 kap 2 §
// requires bokföring to follow real cash movement; a payment booked
// in the future is a scheduling artefact, not an affärshändelse.
// No legitimate v1 workflow needs to backstamp tomorrow; if the user
// wants to schedule, that's a different surface.
if (paymentDate > today) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
field: 'payment_date',
message: 'payment_date cannot be in the future.',
attempted: paymentDate,
today,
},
})
}
// Fetch SI with supplier + items (needed by the engine for cash-basis).
const { data: invoice, error: fetchErr } = await ctx.supabase
.from('supplier_invoices')
.select(`
id, supplier_id, status, currency, exchange_rate, total, paid_amount, remaining_amount,
supplier_invoice_number, arrival_number, invoice_date, vat_treatment, reverse_charge,
subtotal, subtotal_sek, vat_amount, vat_amount_sek, total_sek, due_date, received_date,
is_credit_note, credited_invoice_id, payment_journal_entry_id,
supplier:suppliers(id, name, supplier_type),
items:supplier_invoice_items(id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount)
`)
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
.maybeSingle()
if (fetchErr) {
return v1ErrorResponse(fetchErr, ctx.log, { requestId: ctx.requestId })
}
if (!invoice) {
return v1ErrorResponseFromCode('SI_NOT_FOUND', ctx.log, { requestId: ctx.requestId })
}
type SupplierObj = { id: string; name: string; supplier_type: string }
type SI = {
id: string
supplier_id: string
status: string
currency: string
total: number
paid_amount: number
remaining_amount: number
supplier_invoice_number: string
arrival_number: number
invoice_date: string
is_credit_note: boolean
supplier: SupplierObj | SupplierObj[] | null
items?: unknown[]
} & Record<string, unknown>
const typed = invoice as unknown as SI
if (typed.is_credit_note) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'id', message: 'Credit notes cannot be marked paid.' },
})
}
if (!PAYABLE_STATUSES.includes(typed.status as (typeof PAYABLE_STATUSES)[number])) {
const code = typed.status === 'paid' || typed.status === 'credited' || typed.status === 'reversed'
? 'SI_PAID_ALREADY'
: 'SI_PAID_NOT_PAYABLE'
return v1ErrorResponseFromCode(code, ctx.log, {
requestId: ctx.requestId,
details: { current_status: typed.status },
})
}
// Application-layer period-lock pre-check.
const lockVerdict = await checkPeriodLock(ctx.supabase, ctx.companyId!, paymentDate)
if (lockVerdict.locked) {
return v1ErrorResponseFromCode('SI_PAID_PERIOD_LOCKED', ctx.log, {
requestId: ctx.requestId,
details: {
reason: lockVerdict.reason,
fiscal_period_id: lockVerdict.fiscal_period_id,
payment_date: paymentDate,
},
})
}
const paymentAmount = bodyAmount != null
? Math.round(bodyAmount * 100) / 100
: Math.round(typed.remaining_amount * 100) / 100
if (paymentAmount <= 0) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'amount', message: 'amount must be positive.' },
})
}
// Reject overpayment up front. Without this, the silent `Math.max(0, ...)`
// clamp below would book the full payment_amount in the JE but only
// reduce the SI balance to 0 — the difference would be an unaccounted
// overpayment on the 2440 ledger. If a refund is genuinely due, the
// caller credits the SI (which reverses the obligation) and books the
// refund as a separate bank transaction. Half-öre tolerance allows
// legitimate rounding artefacts from FX-difference adjustments.
if (paymentAmount > typed.remaining_amount + 0.005) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
field: 'amount',
message:
'amount exceeds remaining_amount. Issue a credit note via :credit for over-billing, or book the refund through the transactions endpoints.',
attempted: paymentAmount,
remaining_amount: typed.remaining_amount,
},
})
}
const newRemaining = Math.max(
0,
Math.round((typed.remaining_amount - paymentAmount) * 100) / 100,
)
// Half-öre epsilon — same convention as v1 invoices.mark-paid.
const newStatus: 'paid' | 'partially_paid' = newRemaining <= 0.005 ? 'paid' : 'partially_paid'
const newPaidAmount = Math.round((typed.paid_amount + paymentAmount) * 100) / 100
// Settings fetch hoisted ahead of the dry-run branch so the FX-required
// check below fires in both preview and commit modes (and so dry-run can
// surface the requirement before a caller learns it the hard way).
const { data: settings } = await ctx.supabase
.from('company_settings')
.select('accounting_method')
.eq('company_id', ctx.companyId!)
.maybeSingle()
const accountingMethod = (settings as { accounting_method?: string } | null)?.accounting_method ?? 'accrual'
// FX-required validation. Under accrual the registration JE used the
// invoice's exchange rate to compute subtotal_sek; the payment JE has to
// book any rate delta to 3960 / 7960 (BAS) or AP will carry a stranded
// 2440 balance after the bank line clears. The pitfall docs warn about
// this — enforce it.
if (
typed.currency !== 'SEK' &&
accountingMethod === 'accrual' &&
exchangeRateDifference === undefined
) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
issues: [{
field: 'exchange_rate_difference',
message:
'exchange_rate_difference (SEK delta vs the registration rate) is required when paying a non-SEK supplier invoice under faktureringsmetoden. Use 0 if there is no rate movement.',
}],
invoice_currency: typed.currency,
},
})
}
if (ctx.dryRun) {
// paid_at: the live UPDATE writes `new Date().toISOString()` (a full UTC
// timestamp). Mirror that shape here so callers validating dry-run vs
// live against the same regex don't see surprises. payment_date stays
// ISO date because it represents the user-supplied calendar date.
return dryRunPreview(
{
...typed,
status: newStatus,
paid_amount: newPaidAmount,
remaining_amount: newRemaining,
paid_at: newStatus === 'paid' ? new Date().toISOString() : null,
payment_date: paymentDate,
payment_amount: paymentAmount,
would_create_payment_journal_entry: true,
},
{ requestId: ctx.requestId, log: ctx.log },
)
}
const pickSupplier = (s: SI['supplier']): SupplierObj | null => {
if (!s) return null
return Array.isArray(s) ? (s[0] ?? null) : s
}
const supplierRow = pickSupplier(typed.supplier)
// Strict-mode: book the JE FIRST. Failure aborts before any SI mutation.
let journalEntryId: string | null = null
try {
if (accountingMethod === 'cash') {
const entry = await createSupplierInvoiceCashEntry(
ctx.supabase,
ctx.companyId!,
ctx.userId,
typed as unknown as SupplierInvoice,
(typed.items ?? []) as SupplierInvoiceItem[],
paymentDate,
supplierRow?.supplier_type ?? 'swedish_business',
supplierRow?.name,
)
journalEntryId = entry?.id ?? null
} else {
const entry = await createSupplierInvoicePaymentEntry(
ctx.supabase,
ctx.companyId!,
ctx.userId,
typed as unknown as SupplierInvoice,
paymentAmount,
paymentDate,
exchangeRateDifference,
supplierRow?.name,
)
journalEntryId = entry?.id ?? null
}
if (!journalEntryId) {
// Engine returned null (no open fiscal period). Strict-mode abort.
return v1ErrorResponseFromCode('SI_PAID_FAILED', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'no_fiscal_period', payment_date: paymentDate },
})
}
} catch (err) {
if (isBookkeepingError(err)) {
return v1ErrorResponse(err, ctx.log, { requestId: ctx.requestId })
}
ctx.log.error('supplier-invoice mark-paid JE creation failed', err as Error, {
invoiceId,
companyId: ctx.companyId,
})
return v1ErrorResponseFromCode('SI_PAID_FAILED', ctx.log, {
requestId: ctx.requestId,
details: { reason: err instanceof Error ? err.message : 'unknown' },
})
}
// Step 2: optimistic-lock SI update. The .in() filter guards against
// concurrent calls (or a credit/mark-paid race) flipping the status
// between our pre-flight and write.
const { data: updated, error: updateErr } = await ctx.supabase
.from('supplier_invoices')
.update({
status: newStatus,
remaining_amount: newRemaining,
paid_amount: newPaidAmount,
paid_at: newStatus === 'paid' ? new Date().toISOString() : null,
payment_journal_entry_id: journalEntryId,
})
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
.in('status', PAYABLE_STATUSES as unknown as string[])
.select(SI_PAID_RESPONSE_COLUMNS)
.maybeSingle()
if (updateErr) {
ctx.log.error('supplier-invoice mark-paid update failed — attempting storno of orphaned JE', updateErr, {
invoiceId,
companyId: ctx.companyId,
userId: ctx.userId,
journalEntryId,
})
// The payment JE is already posted but the SI update failed — without a
// storno, the AP ledger would carry a 2440/1930 entry with no matching
// SI status change (BFL 5 kap 5 § integrity violation). reverseEntry()
// takes the entry id directly (no pre-fetch needed), matching the CAS-
// race branch immediately below.
try {
await reverseEntry(ctx.supabase, ctx.companyId!, ctx.userId, journalEntryId, paymentDate)
} catch (revErr) {
ctx.log.error('orphan JE storno failed after SI update error — manual reconciliation required', revErr as Error, {
invoiceId,
companyId: ctx.companyId,
userId: ctx.userId,
journalEntryId,
})
}
return v1ErrorResponseFromCode('SI_PAID_FAILED', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'si_update_failed', journal_entry_id: journalEntryId },
})
}
if (!updated) {
// CAS race: the SI moved out of a payable state between pre-flight and
// write. The JE we just posted is now orphaned. Storno it.
ctx.log.warn('supplier-invoice mark-paid race — JE was orphaned, attempting storno', {
invoiceId,
companyId: ctx.companyId,
userId: ctx.userId,
journalEntryId,
})
try {
await reverseEntry(ctx.supabase, ctx.companyId!, ctx.userId, journalEntryId, paymentDate)
} catch (revErr) {
ctx.log.error('orphan JE storno failed — manual reconciliation required', revErr as Error, {
invoiceId,
companyId: ctx.companyId,
userId: ctx.userId,
journalEntryId,
})
}
return v1ErrorResponseFromCode('SI_PAID_ALREADY', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'race' },
})
}
// Step 3: record the payment row (non-blocking — its only consumer is the
// dashboard's "payment history" tab, and the JE is the source of truth).
const { error: paymentErr } = await ctx.supabase
.from('supplier_invoice_payments')
.insert({
user_id: ctx.userId,
company_id: ctx.companyId!,
supplier_invoice_id: invoiceId,
payment_date: paymentDate,
amount: paymentAmount,
currency: typed.currency,
exchange_rate_difference: exchangeRateDifference ?? 0,
journal_entry_id: journalEntryId,
notes: bodyNotes ?? null,
})
if (paymentErr) {
ctx.log.warn('supplier_invoice_payments insert failed (non-blocking)', paymentErr, {
invoiceId,
})
}
try {
await eventBus.emit({
type: 'supplier_invoice.paid',
payload: {
supplierInvoice: typed as unknown as SupplierInvoice,
paymentAmount,
companyId: ctx.companyId!,
userId: ctx.userId,
},
})
} catch (err) {
ctx.log.warn('supplier_invoice.paid emit failed', err as Error)
}
return ok(updated, { requestId: ctx.requestId })
},
{ requireIdempotencyKey: true },
)
@@ -0,0 +1,307 @@
/**
* /api/v1/companies/{companyId}/supplier-invoices/{id} — detail + update.
*
* GET — full record. ?expand=supplier,items,payments embeds related rows.
* PATCH — partial update. Only allowed on `registered` status (mirrors the
* dashboard: an approved/paid SI is effectively immutable from the
* caller's perspective; for those, use the action verbs or :credit).
* Idempotent (mandatory Idempotency-Key). Dry-runnable.
*
* No DELETE — supplier-invoice withdrawal is via :credit (mirrors v1 invoices).
* The credit verb keeps both originals AND credit notes in the audit trail per
* BFL 5 kap 5 § (corrections via reversing entries).
*/
import { z } from 'zod'
import { ok } from '@/lib/api/v1/response'
import { dryRunPreview } from '@/lib/api/v1/dry-run'
import { parseExpand } from '@/lib/api/v1/expand'
import { registerEndpoint } from '@/lib/api/v1/registry'
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
import { UpdateSupplierInvoiceSchema } from '@/lib/api/schemas'
// V1-only strict variant. The shared `UpdateSupplierInvoiceSchema` is also
// consumed by the dashboard, where unknown keys are silently stripped — fine
// for a UI that controls its own payload. The public API treats unknown keys
// as a contract violation: if a future schema iteration ever adds a
// protected field (status, company_id, user_id), `.strict()` makes the
// mass-assignment vector structurally impossible regardless of whether the
// downstream allowlist iteration catches it.
const V1PatchSupplierInvoiceSchema = UpdateSupplierInvoiceSchema.strict()
const SI_DETAIL_COLUMNS =
'id, supplier_id, arrival_number, supplier_invoice_number, invoice_date, due_date, received_date, delivery_date, status, currency, exchange_rate, exchange_rate_date, subtotal, subtotal_sek, vat_amount, vat_amount_sek, total, total_sek, vat_treatment, reverse_charge, payment_reference, paid_at, paid_amount, remaining_amount, is_credit_note, credited_invoice_id, registration_journal_entry_id, payment_journal_entry_id, transaction_id, document_id, notes, reversed_at, created_at, updated_at'
const SI_ITEM_COLUMNS =
'id, sort_order, description, quantity, unit, unit_price, line_total, account_number, vat_code, vat_rate, vat_amount'
const SI_PAYMENT_COLUMNS =
'id, payment_date, amount, currency, exchange_rate, exchange_rate_difference, journal_entry_id, transaction_id, notes, created_at'
const SUPPLIER_DETAIL_COLUMNS_EXPAND =
'id, name, supplier_type, email, org_number, vat_number, default_payment_terms, default_currency, bankgiro, plusgiro, iban, bic, default_expense_account, archived_at'
const SupplierInvoiceDetail = z.object({
id: z.string().uuid(),
supplier_id: z.string().uuid(),
arrival_number: z.number().int(),
supplier_invoice_number: z.string(),
invoice_date: z.string(),
due_date: z.string(),
received_date: z.string(),
delivery_date: z.string().nullable(),
status: z.string(),
currency: z.string(),
exchange_rate: z.number().nullable(),
subtotal: z.number(),
vat_amount: z.number(),
total: z.number(),
vat_treatment: z.string(),
reverse_charge: z.boolean(),
paid_amount: z.number(),
remaining_amount: z.number(),
is_credit_note: z.boolean(),
credited_invoice_id: z.string().uuid().nullable(),
registration_journal_entry_id: z.string().uuid().nullable(),
payment_journal_entry_id: z.string().uuid().nullable(),
notes: z.string().nullable(),
created_at: z.string(),
updated_at: z.string(),
})
const ALLOWED_EXPAND = ['supplier', 'items', 'payments'] as const
registerEndpoint({
operation: 'supplier-invoices.get',
method: 'GET',
path: '/api/v1/companies/:companyId/supplier-invoices/:id',
summary: 'Retrieve a single supplier invoice by id.',
description:
'Returns the full supplier-invoice record. Pass ?expand=supplier,items,payments to embed the related rows in the same response.',
useWhen:
'You need the full record before approving, paying, or crediting it — or for audit trail / reconciliation.',
doNotUseFor:
'Listing supplier invoices (use the list endpoint). Customer-invoice lookups (different resource).',
pitfalls: [
'Credit notes return is_credit_note=true and a credited_invoice_id pointing at the original.',
'registration_journal_entry_id and payment_journal_entry_id let you trace the SI to its bokföring rows; they are null when no JE has been posted (e.g. on a kontantmetoden SI before payment).',
],
example: {
response: {
data: {
id: '0e9c…',
supplier_id: 'a8f1…',
arrival_number: 42,
supplier_invoice_number: '2026-1234',
status: 'registered',
currency: 'SEK',
subtotal: 1000,
vat_amount: 250,
total: 1250,
remaining_amount: 1250,
is_credit_note: false,
},
meta: { request_id: 'req_…', api_version: '2026-05-12' },
},
},
scope: 'suppliers:read',
risk: 'low',
idempotent: true,
reversible: false,
dryRunSupported: false,
response: { success: SupplierInvoiceDetail },
})
export const GET = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
'supplier-invoices.get',
async (request, ctx, params) => {
const { id } = await params.params
const idParse = z.string().uuid().safeParse(id)
if (!idParse.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'id', message: 'Supplier-invoice id must be a UUID.' },
})
}
const invoiceId = idParse.data
const url = new URL(request.url)
const expandResult = parseExpand(url, ALLOWED_EXPAND)
if (!expandResult.ok) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
field: 'expand',
invalidKeys: expandResult.invalidKeys,
allowed: expandResult.allowed,
},
})
}
const expand = expandResult.expand
const parts: string[] = [SI_DETAIL_COLUMNS]
if (expand.has('supplier')) parts.push(`supplier:suppliers(${SUPPLIER_DETAIL_COLUMNS_EXPAND})`)
if (expand.has('items')) parts.push(`items:supplier_invoice_items(${SI_ITEM_COLUMNS})`)
if (expand.has('payments')) parts.push(`payments:supplier_invoice_payments(${SI_PAYMENT_COLUMNS})`)
const selectClause = parts.join(', ')
const { data, error } = await ctx.supabase
.from('supplier_invoices')
.select(selectClause)
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
.maybeSingle()
if (error) {
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
}
if (!data) {
ctx.log.warn('supplier-invoices.get: not found', { invoiceId, companyId: ctx.companyId })
return v1ErrorResponseFromCode('SI_NOT_FOUND', ctx.log, { requestId: ctx.requestId })
}
return ok(data, { requestId: ctx.requestId })
},
)
// ──────────────────────────────────────────────────────────────────
// PATCH — partial update (registered-only)
// ──────────────────────────────────────────────────────────────────
registerEndpoint({
operation: 'supplier-invoices.update',
method: 'PATCH',
path: '/api/v1/companies/:companyId/supplier-invoices/:id',
summary: 'Update a registered supplier invoice.',
description:
'Patches a supplier invoice with the supplied fields. Only allowed on `registered` status — once approved, paid, or credited, the record is effectively immutable from the API\'s perspective. Idempotent (mandatory Idempotency-Key). Dry-runnable.',
useWhen:
'You need to fix a typo in supplier_invoice_number, adjust dates, or attach a payment reference / notes to a registered SI before approval. Use dry-run to confirm the merged state first.',
doNotUseFor:
'Editing line items (immutable — credit the SI and register a new one). Changing status (use action verbs). Approved/paid/credited SIs (returns 400 SI_NOT_DRAFT).',
pitfalls: [
'Returns 400 SI_NOT_DRAFT when current status !== "registered".',
'invoice_date / due_date changes do not re-post the registration JE; if the entry date needs to change, credit the SI and re-register.',
],
example: {
request: { payment_reference: 'OCR-1234567890' },
response: {
data: { id: '0e9c…', payment_reference: 'OCR-1234567890' },
meta: { request_id: 'req_…', api_version: '2026-05-12' },
},
},
scope: 'suppliers:write',
risk: 'low',
idempotent: true,
reversible: true,
dryRunSupported: true,
request: { body: V1PatchSupplierInvoiceSchema },
response: { success: SupplierInvoiceDetail },
})
export const PATCH = withApiV1<{ params: Promise<{ companyId: string; id: string }> }>(
'supplier-invoices.update',
async (request, ctx, params) => {
const { id } = await params.params
const idParse = z.string().uuid().safeParse(id)
if (!idParse.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'id', message: 'Supplier-invoice id must be a UUID.' },
})
}
const invoiceId = idParse.data
let rawBody: unknown
try {
rawBody = await request.json()
} catch {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'body', message: 'Body is not valid JSON.' },
})
}
const parsed = V1PatchSupplierInvoiceSchema.safeParse(rawBody)
if (!parsed.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
issues: parsed.error.issues.map((i) => ({
field: i.path.join('.'),
message: i.message,
})),
},
})
}
const body = parsed.data
const updateData: Record<string, unknown> = {}
for (const key of [
'supplier_invoice_number',
'invoice_date',
'due_date',
'delivery_date',
'payment_reference',
'notes',
] as const) {
if (body[key] !== undefined) updateData[key] = body[key]
}
if (Object.keys(updateData).length === 0) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'body', message: 'At least one field must be supplied for update.' },
})
}
// Status guard before doing anything else.
const { data: existing, error: fetchErr } = await ctx.supabase
.from('supplier_invoices')
.select(SI_DETAIL_COLUMNS)
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
.maybeSingle()
if (fetchErr) {
return v1ErrorResponse(fetchErr, ctx.log, { requestId: ctx.requestId })
}
if (!existing) {
return v1ErrorResponseFromCode('SI_NOT_FOUND', ctx.log, { requestId: ctx.requestId })
}
if ((existing as { status: string }).status !== 'registered') {
return v1ErrorResponseFromCode('SI_NOT_DRAFT', ctx.log, {
requestId: ctx.requestId,
details: { current_status: (existing as { status: string }).status },
})
}
if (ctx.dryRun) {
return dryRunPreview({ ...existing, ...updateData }, { requestId: ctx.requestId, log: ctx.log })
}
const { data, error } = await ctx.supabase
.from('supplier_invoices')
.update(updateData)
.eq('company_id', ctx.companyId!)
.eq('id', invoiceId)
// Race guard: another request may have approved / paid between the
// pre-flight status check and this update.
.eq('status', 'registered')
.select(SI_DETAIL_COLUMNS)
.maybeSingle()
if (error) {
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
}
if (!data) {
return v1ErrorResponseFromCode('SI_NOT_DRAFT', ctx.log, {
requestId: ctx.requestId,
details: { reason: 'race' },
})
}
return ok(data, { requestId: ctx.requestId })
},
{ requireIdempotencyKey: true },
)
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,312 @@
/**
* POST /api/v1/companies/{companyId}/suppliers/bulk-create
*
* Bulk-create up to 50 suppliers in one call. Each item is validated and
* inserted independently — per-item failures don't roll back successes.
* Mirrors the shape of /customers/bulk-create exactly so agents only need
* to learn one bulk pattern.
*
* Response: `{ results: [{ ok, request_index, data?, error? }], summary }`.
* Idempotent over the whole batch. Dry-runnable.
*
* Unlike customers, suppliers do not run VIES validation on create — the
* vat_number is stored as supplied without an external check.
*/
import { z } from 'zod'
import type { SupabaseClient } from '@supabase/supabase-js'
import { ok } from '@/lib/api/v1/response'
import { dryRunPreview } from '@/lib/api/v1/dry-run'
import { registerEndpoint } from '@/lib/api/v1/registry'
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
import { v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
import { CreateSupplierSchema } from '@/lib/api/schemas'
import { eventBus } from '@/lib/events'
import type { Logger } from '@/lib/logger'
import type { Supplier } from '@/types'
const BulkCreateRequest = z.object({
suppliers: z.array(CreateSupplierSchema).min(1).max(50),
all_or_nothing: z.boolean().optional().default(false),
})
const BulkResultItem = z.object({
ok: z.boolean(),
request_index: z.number().int().nonnegative(),
data: z.unknown().optional(),
error: z
.object({
code: z.string(),
message: z.string(),
details: z.unknown().optional(),
})
.optional(),
})
const BulkCreateResponse = z.object({
results: z.array(BulkResultItem),
summary: z.object({
total: z.number().int(),
succeeded: z.number().int(),
failed: z.number().int(),
}),
})
const SUPPLIER_RESPONSE_COLUMNS =
'id, name, supplier_type, email, phone, address_line1, address_line2, postal_code, city, country, org_number, vat_number, bankgiro, plusgiro, bank_account, iban, bic, default_expense_account, default_payment_terms, default_currency, notes, archived_at, created_at, updated_at'
registerEndpoint({
operation: 'suppliers.bulk-create',
method: 'POST',
path: '/api/v1/companies/:companyId/suppliers/bulk-create',
summary: 'Create up to 50 suppliers in one call (partial-success).',
description:
'Bulk-create endpoint mirroring /customers/bulk-create. Each supplier is validated and inserted independently — per-item failures do not roll back items that succeeded. Returns a results array plus a summary. Idempotent over the whole batch. Dry-runnable.',
useWhen:
'You\'re importing a roster of suppliers from another AP system, or seeding a fresh company with its existing vendor list. Use dry-run first to validate the batch.',
doNotUseFor:
'Updating existing suppliers — PATCH /suppliers/{id} once per supplier. Bulk uploads of > 50 suppliers — split into pages of 50. Transactional all-or-nothing imports — passing all_or_nothing: true returns 501 NOT_IMPLEMENTED.',
pitfalls: [
'Idempotency-Key is mandatory and covers the WHOLE batch. A retried bulk-create returns the cached full response — it does not retry only the failed items.',
'Passing all_or_nothing: true returns 501 NOT_IMPLEMENTED. Today only partial-success batches exist; omit the flag or pass false.',
'org_number uniqueness is enforced at the DB level — items with duplicates fail individually with SUPPLIER_DUPLICATE_ORG_NUMBER.',
'No VIES validation runs per item; vat_number is stored as supplied. Validate externally if your workflow requires it.',
],
example: {
request: {
suppliers: [
{ name: 'Office Depot AB', supplier_type: 'swedish_business', org_number: '556677-8899' },
{ name: 'Cloud Hosting GmbH', supplier_type: 'eu_business', vat_number: 'DE123456789' },
],
},
response: {
data: {
results: [
{ ok: true, request_index: 0, data: { id: '0e9c…', name: 'Office Depot AB' } },
{ ok: true, request_index: 1, data: { id: '4d2a…', name: 'Cloud Hosting GmbH' } },
],
summary: { total: 2, succeeded: 2, failed: 0 },
},
meta: { request_id: 'req_…', api_version: '2026-05-12' },
},
},
scope: 'suppliers:write',
risk: 'low',
idempotent: true,
reversible: true,
dryRunSupported: true,
request: { body: BulkCreateRequest },
response: { success: BulkCreateResponse },
})
interface ResultItem {
ok: boolean
request_index: number
data?: unknown
error?: { code: string; message: string; details?: unknown }
}
async function createOneSupplier(
supabase: SupabaseClient,
companyId: string,
userId: string,
index: number,
input: z.infer<typeof CreateSupplierSchema>,
dryRun: boolean,
log: Logger,
): Promise<ResultItem> {
if (dryRun) {
return {
ok: true,
request_index: index,
data: {
preview: {
id: null,
name: input.name,
supplier_type: input.supplier_type,
email: input.email ?? null,
phone: input.phone ?? null,
address_line1: input.address_line1 ?? null,
address_line2: input.address_line2 ?? null,
postal_code: input.postal_code ?? null,
city: input.city ?? null,
country: input.country ?? 'SE',
org_number: input.org_number ?? null,
vat_number: input.vat_number ?? null,
bankgiro: input.bankgiro ?? null,
plusgiro: input.plusgiro ?? null,
bank_account: input.bank_account ?? null,
iban: input.iban ?? null,
bic: input.bic ?? null,
default_expense_account: input.default_expense_account ?? null,
default_payment_terms: input.default_payment_terms ?? 30,
default_currency: input.default_currency ?? 'SEK',
notes: input.notes ?? null,
archived_at: null,
created_at: null,
updated_at: null,
},
},
}
}
const { data, error } = await supabase
.from('suppliers')
.insert({
user_id: userId,
company_id: companyId,
name: input.name,
supplier_type: input.supplier_type,
email: input.email ?? null,
phone: input.phone ?? null,
address_line1: input.address_line1 ?? null,
address_line2: input.address_line2 ?? null,
postal_code: input.postal_code ?? null,
city: input.city ?? null,
country: input.country ?? 'SE',
org_number: input.org_number ?? null,
vat_number: input.vat_number ?? null,
bankgiro: input.bankgiro ?? null,
plusgiro: input.plusgiro ?? null,
bank_account: input.bank_account ?? null,
iban: input.iban ?? null,
bic: input.bic ?? null,
default_expense_account: input.default_expense_account ?? null,
default_payment_terms: input.default_payment_terms ?? 30,
default_currency: input.default_currency ?? 'SEK',
notes: input.notes ?? null,
})
.select(SUPPLIER_RESPONSE_COLUMNS)
.single()
if (error) {
if (error.code === '23505') {
return {
ok: false,
request_index: index,
error: {
code: 'SUPPLIER_DUPLICATE_ORG_NUMBER',
message: 'A supplier with this org_number already exists in this company.',
details: { field: 'org_number' },
},
}
}
log.error('bulk-create: supplier insert failed', error, {
request_index: index,
companyId,
pgCode: error.code,
})
return {
ok: false,
request_index: index,
error: {
code: 'SUPPLIER_CREATE_FAILED',
message: 'Supplier insert failed.',
details: { pg_code: error.code },
},
}
}
try {
await eventBus.emit({
type: 'supplier.created',
payload: {
supplier: {
...(data as Record<string, unknown>),
user_id: userId,
company_id: companyId,
} as unknown as Supplier,
companyId,
userId,
},
})
} catch (err) {
log.warn('bulk-create: supplier.created emit failed', err as Error, {
request_index: index,
})
}
return { ok: true, request_index: index, data }
}
export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
'suppliers.bulk-create',
async (request, ctx) => {
if (!z.string().uuid().safeParse(ctx.companyId).success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'companyId', message: 'companyId must be a UUID.' },
})
}
let rawBody: unknown
try {
rawBody = await request.json()
} catch {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'body', message: 'Body is not valid JSON.' },
})
}
const parsed = BulkCreateRequest.safeParse(rawBody)
if (!parsed.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
issues: parsed.error.issues.map((i) => ({
field: i.path.join('.'),
message: i.message,
})),
},
})
}
const body = parsed.data
if (body.all_or_nothing) {
return v1ErrorResponseFromCode('NOT_IMPLEMENTED', ctx.log, {
requestId: ctx.requestId,
details: {
field: 'all_or_nothing',
message:
'all_or_nothing: true is not yet implemented. Omit the flag (or pass false) to use partial-success semantics.',
},
})
}
// Sequential processing matches /customers/bulk-create and /invoices/bulk-create.
// The 50-item cap bounds worst-case latency.
const results: ResultItem[] = []
for (let i = 0; i < body.suppliers.length; i++) {
const item = await createOneSupplier(
ctx.supabase,
ctx.companyId!,
ctx.userId,
i,
body.suppliers[i],
ctx.dryRun,
ctx.log,
)
results.push(item)
}
const summary = {
total: results.length,
succeeded: results.filter((r) => r.ok).length,
failed: results.filter((r) => !r.ok).length,
}
ctx.log.info('suppliers.bulk-create completed', {
companyId: ctx.companyId,
userId: ctx.userId,
...summary,
dryRun: ctx.dryRun,
})
if (ctx.dryRun) {
return dryRunPreview({ results, summary }, { requestId: ctx.requestId, log: ctx.log })
}
return ok({ results, summary }, { requestId: ctx.requestId })
},
{ requireIdempotencyKey: true },
)
@@ -0,0 +1,432 @@
/**
* /api/v1/companies/{companyId}/suppliers — list + create supplier endpoints.
*
* GET — list with filters (supplier_type, search, include_archived).
* Cursor pagination on (created_at ASC, id ASC).
* POST — create. Idempotent (mandatory Idempotency-Key). Dry-runnable
* (?dry_run=true returns the validated would-be record without
* committing).
*
* VIES validation note: unlike customers, suppliers do not carry a
* `vat_number_validated` flag in the schema today. The vat_number is
* accepted as input but not auto-verified against VIES — a deliberate
* scope decision documented in the endpoint pitfalls.
*/
import { z } from 'zod'
import { created, paginated } from '@/lib/api/v1/response'
import { dryRunPreview } from '@/lib/api/v1/dry-run'
import {
decodeDefaultCursor,
encodeDefaultCursor,
parsePaginationParams,
} from '@/lib/api/v1/pagination'
import { registerEndpoint } from '@/lib/api/v1/registry'
import { withApiV1 } from '@/lib/api/v1/with-api-v1'
import { v1ErrorResponse, v1ErrorResponseFromCode } from '@/lib/api/v1/errors'
import { CreateSupplierSchema } from '@/lib/api/schemas'
import { eventBus } from '@/lib/events'
import type { Supplier } from '@/types'
const SupplierType = z.enum([
'swedish_business',
'eu_business',
'non_eu_business',
])
const SupplierSummary = z.object({
id: z.string().uuid(),
name: z.string(),
supplier_type: SupplierType,
email: z.string().nullable(),
org_number: z.string().nullable(),
vat_number: z.string().nullable(),
default_payment_terms: z.number(),
default_currency: z.string(),
archived_at: z.string().nullable(),
created_at: z.string(),
})
const SuppliersListResponse = z.object({
suppliers: z.array(SupplierSummary),
})
// Explicit projection — never SELECT *. Schema migrations adding columns
// must update this list before the field becomes visible on the public API.
const SUPPLIER_SUMMARY_COLUMNS =
'id, name, supplier_type, email, org_number, vat_number, default_payment_terms, default_currency, archived_at, created_at'
registerEndpoint({
operation: 'suppliers.list',
method: 'GET',
path: '/api/v1/companies/:companyId/suppliers',
summary: 'List suppliers for a company.',
description:
'Returns active suppliers in created-first order. Pass ?include_archived=true to include archived rows. Use ?search to match against name or org_number.',
useWhen:
'You need a supplier roster — for building a UI picker, resolving a supplier_id before registering a supplier invoice, or syncing an external AP system.',
doNotUseFor:
'Fetching a single supplier you already know the id of — use GET /api/v1/companies/{companyId}/suppliers/{id}. Customers are a separate resource.',
pitfalls: [
'Archived suppliers are hidden by default; the dashboard makes the same choice.',
'org_number identifies legal entities only — suppliers currently have no `individual` type, so the field is Bolagsverket public-record data when present.',
'vat_number is stored as supplied; unlike customers, suppliers are not auto-validated against VIES on create. Validate externally if the integration requires it.',
],
example: {
response: {
data: [
{
id: 'a8f1…',
name: 'Office Depot AB',
supplier_type: 'swedish_business',
email: '[email protected]',
org_number: '556677-8899',
vat_number: 'SE556677889901',
default_payment_terms: 30,
default_currency: 'SEK',
archived_at: null,
created_at: '2026-04-12T08:30:00Z',
},
],
meta: { request_id: 'req_…', api_version: '2026-05-12', next_cursor: null },
},
},
scope: 'suppliers:read',
risk: 'low',
idempotent: true,
reversible: false,
dryRunSupported: false,
response: { success: SuppliersListResponse },
})
export const GET = withApiV1<{ params: Promise<{ companyId: string }> }>(
'suppliers.list',
async (request, ctx) => {
const url = new URL(request.url)
const { limit, cursor } = parsePaginationParams(url)
const decoded = decodeDefaultCursor(cursor)
const FiltersSchema = z.object({
supplier_type: SupplierType.optional(),
search: z.string().min(1).max(200).optional(),
include_archived: z.enum(['true', 'false']).optional(),
})
const filtersResult = FiltersSchema.safeParse({
supplier_type: url.searchParams.get('supplier_type') ?? undefined,
search: url.searchParams.get('search') ?? undefined,
include_archived: url.searchParams.get('include_archived') ?? undefined,
})
if (!filtersResult.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
issues: filtersResult.error.issues.map((i) => ({
field: i.path.join('.'),
message: i.message,
})),
},
})
}
const filters = filtersResult.data
const includeArchived = filters.include_archived === 'true'
let query = ctx.supabase
.from('suppliers')
.select(SUPPLIER_SUMMARY_COLUMNS)
.eq('company_id', ctx.companyId!)
.order('created_at', { ascending: true })
.order('id', { ascending: true })
.limit(limit + 1)
if (!includeArchived) {
query = query.is('archived_at', null)
}
if (filters.supplier_type) {
query = query.eq('supplier_type', filters.supplier_type)
}
if (filters.search) {
// Two layers of escaping (matches the customers list):
// 1. PostgREST `.or()` filter syntax uses commas + parens as
// delimiters; strip them from the user-supplied term.
// 2. SQL LIKE treats `%` and `_` (and `\` as the default escape) as
// wildcards; escape them so '100%' matches the literal string.
const term = filters.search
.replace(/[,()]/g, '')
.replace(/[%_\\]/g, '\\$&')
query = query.or(`name.ilike.%${term}%,org_number.ilike.${term}%`)
}
if (decoded) {
query = query.or(
`created_at.gt.${decoded.ts},and(created_at.eq.${decoded.ts},id.gt.${decoded.id})`,
)
}
const { data, error } = await query
if (error) {
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
}
type Row = {
id: string
name: string
supplier_type: string
email: string | null
org_number: string | null
vat_number: string | null
default_payment_terms: number
default_currency: string
archived_at: string | null
created_at: string
} & Record<string, unknown>
const rows = ((data ?? []) as unknown) as Row[]
const trimmed = rows.slice(0, limit)
const hasMore = rows.length > limit
// GDPR Art.5(1)(c) defense-in-depth: SupplierType has no `individual`
// variant today (only swedish_business / eu_business / non_eu_business),
// so the org_number is Bolagsverket public-record data. Were a future
// schema iteration introduce a natural-person supplier type, the list
// endpoint should mask org_number/vat_number the same way the customer
// list does for `individual`. Leaving the hook (an empty INDIVIDUAL_TYPES
// set) makes that change a one-line edit and signals the design intent
// to anyone copying the file.
const INDIVIDUAL_TYPES = new Set<string>([])
const suppliers = trimmed.map((r) => {
const isIndividual = INDIVIDUAL_TYPES.has(r.supplier_type)
return {
id: r.id,
name: r.name,
supplier_type: r.supplier_type,
email: r.email,
org_number: isIndividual ? null : r.org_number,
vat_number: isIndividual ? null : r.vat_number,
default_payment_terms: r.default_payment_terms,
default_currency: r.default_currency,
archived_at: r.archived_at,
created_at: r.created_at,
}
})
const last = trimmed[trimmed.length - 1]
const nextCursor = hasMore && last
? encodeDefaultCursor({ id: last.id, created_at: last.created_at })
: null
return paginated(suppliers, {
requestId: ctx.requestId,
nextCursor: nextCursor ?? undefined,
})
},
)
// ──────────────────────────────────────────────────────────────────
// POST — create supplier
// ──────────────────────────────────────────────────────────────────
const SupplierCreated = z.object({
id: z.string().uuid().nullable(),
name: z.string(),
supplier_type: SupplierType,
email: z.string().nullable(),
phone: z.string().nullable(),
address_line1: z.string().nullable(),
address_line2: z.string().nullable(),
postal_code: z.string().nullable(),
city: z.string().nullable(),
country: z.string(),
org_number: z.string().nullable(),
vat_number: z.string().nullable(),
bankgiro: z.string().nullable(),
plusgiro: z.string().nullable(),
bank_account: z.string().nullable(),
iban: z.string().nullable(),
bic: z.string().nullable(),
default_expense_account: z.string().nullable(),
default_payment_terms: z.number(),
default_currency: z.string(),
notes: z.string().nullable(),
archived_at: z.string().nullable(),
created_at: z.string().nullable(),
updated_at: z.string().nullable(),
})
const SUPPLIER_RESPONSE_COLUMNS =
'id, name, supplier_type, email, phone, address_line1, address_line2, postal_code, city, country, org_number, vat_number, bankgiro, plusgiro, bank_account, iban, bic, default_expense_account, default_payment_terms, default_currency, notes, archived_at, created_at, updated_at'
registerEndpoint({
operation: 'suppliers.create',
method: 'POST',
path: '/api/v1/companies/:companyId/suppliers',
summary: 'Create a supplier.',
description:
'Creates a new supplier for the company. Requires Idempotency-Key (UUID). Supports ?dry_run=true for input validation without committing — the dry-run response shows the would-be record minus id and timestamps.',
useWhen:
'You need to register a new supplier before booking supplier invoices against them. Use dry-run first to catch validation errors before committing.',
doNotUseFor:
'Updating an existing supplier (PATCH instead). Creating customers (different resource).',
pitfalls: [
'Idempotency-Key is mandatory — calls without it return 400 VALIDATION_ERROR.',
'org_number uniqueness is enforced at the database level; duplicate inserts return 409 SUPPLIER_DUPLICATE_ORG_NUMBER.',
'Unlike customers, suppliers carry no `vat_number_validated` flag — vat_number is stored as supplied without VIES verification. Validate externally if your workflow requires it.',
'default_expense_account is a BAS account number (e.g. "5410"); the value is stored as-is and used as the suggested debit account when supplier invoices are booked.',
],
example: {
request: {
name: 'Office Depot AB',
supplier_type: 'swedish_business',
email: '[email protected]',
org_number: '556677-8899',
bankgiro: '123-4567',
default_expense_account: '5410',
default_payment_terms: 30,
default_currency: 'SEK',
},
response: {
data: {
id: '0e9c…',
name: 'Office Depot AB',
supplier_type: 'swedish_business',
email: '[email protected]',
org_number: '556677-8899',
bankgiro: '123-4567',
default_expense_account: '5410',
default_payment_terms: 30,
default_currency: 'SEK',
archived_at: null,
created_at: '2026-05-13T15:00:00Z',
updated_at: '2026-05-13T15:00:00Z',
},
meta: { request_id: 'req_…', api_version: '2026-05-12' },
},
},
scope: 'suppliers:write',
risk: 'low',
idempotent: true,
reversible: true,
dryRunSupported: true,
request: { body: CreateSupplierSchema },
response: { success: SupplierCreated },
})
export const POST = withApiV1<{ params: Promise<{ companyId: string }> }>(
'suppliers.create',
async (request, ctx) => {
let rawBody: unknown
try {
rawBody = await request.json()
} catch {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: { field: 'body', message: 'Body is not valid JSON.' },
})
}
const parsed = CreateSupplierSchema.safeParse(rawBody)
if (!parsed.success) {
return v1ErrorResponseFromCode('VALIDATION_ERROR', ctx.log, {
requestId: ctx.requestId,
details: {
issues: parsed.error.issues.map((i) => ({
field: i.path.join('.'),
message: i.message,
})),
},
})
}
const body = parsed.data
if (ctx.dryRun) {
return dryRunPreview(
{
id: null,
name: body.name,
supplier_type: body.supplier_type,
email: body.email ?? null,
phone: body.phone ?? null,
address_line1: body.address_line1 ?? null,
address_line2: body.address_line2 ?? null,
postal_code: body.postal_code ?? null,
city: body.city ?? null,
country: body.country ?? 'SE',
org_number: body.org_number ?? null,
vat_number: body.vat_number ?? null,
bankgiro: body.bankgiro ?? null,
plusgiro: body.plusgiro ?? null,
bank_account: body.bank_account ?? null,
iban: body.iban ?? null,
bic: body.bic ?? null,
default_expense_account: body.default_expense_account ?? null,
default_payment_terms: body.default_payment_terms ?? 30,
default_currency: body.default_currency ?? 'SEK',
notes: body.notes ?? null,
archived_at: null,
created_at: null,
updated_at: null,
},
{ requestId: ctx.requestId, log: ctx.log },
)
}
const { data, error } = await ctx.supabase
.from('suppliers')
.insert({
user_id: ctx.userId,
company_id: ctx.companyId!,
name: body.name,
supplier_type: body.supplier_type,
email: body.email ?? null,
phone: body.phone ?? null,
address_line1: body.address_line1 ?? null,
address_line2: body.address_line2 ?? null,
postal_code: body.postal_code ?? null,
city: body.city ?? null,
country: body.country ?? 'SE',
org_number: body.org_number ?? null,
vat_number: body.vat_number ?? null,
bankgiro: body.bankgiro ?? null,
plusgiro: body.plusgiro ?? null,
bank_account: body.bank_account ?? null,
iban: body.iban ?? null,
bic: body.bic ?? null,
default_expense_account: body.default_expense_account ?? null,
default_payment_terms: body.default_payment_terms ?? 30,
default_currency: body.default_currency ?? 'SEK',
notes: body.notes ?? null,
})
.select(SUPPLIER_RESPONSE_COLUMNS)
.single()
if (error) {
if (error.code === '23505') {
// Symmetric with customers: do NOT echo body.org_number — guards
// against accidentally leaking a natural-person identifier in the
// future if SupplierType ever gains an `individual` variant.
return v1ErrorResponseFromCode('SUPPLIER_DUPLICATE_ORG_NUMBER', ctx.log, {
requestId: ctx.requestId,
details: { field: 'org_number' },
})
}
return v1ErrorResponse(error, ctx.log, { requestId: ctx.requestId })
}
try {
await eventBus.emit({
type: 'supplier.created',
payload: {
supplier: { ...(data as Record<string, unknown>), user_id: ctx.userId, company_id: ctx.companyId! } as unknown as Supplier,
companyId: ctx.companyId!,
userId: ctx.userId,
},
})
} catch (err) {
ctx.log.warn('supplier.created emit failed', err as Error)
}
return created(data, { requestId: ctx.requestId })
},
{ requireIdempotencyKey: true },
)