Files
accounted/lib/errors
Jakob Wennberg a9c98da243 feat(api): Phase 3 — transactions + reconciliation vertical (#464)
* feat(api): Phase 3 — transactions + reconciliation vertical

Closes out Phase 3 of the plan in one PR. After this, a 3rd-party agent
can fully manage a company's transaction ledger via the public API:
import bank data, walk the queue, categorize (manual / template /
counterparty / account-override), match payments to customer + supplier
invoices, reverse mistakes, and auto-reconcile the bank against the GL.

ENDPOINTS (12)

Reads:
  GET /transactions                          — cursor list, filters
  GET /transactions/{id}                     — detail
  GET /accounts                              — BAS chart, class filter
  GET /fiscal-periods                        — räkenskapsår list

Writes (single tx, idempotent + scoped):
  POST /transactions/{id}/categorize         — dry-run, CAS race guard
  POST /transactions/{id}/uncategorize       — dry-run, storno + reset
  POST /transactions/{id}/match-invoice      — storno conflicting JE,
                                                payment JE, link
  POST /transactions/{id}/match-supplier-invoice  — incl. FX diff handling

Writes (bulk, partial-success + all_or_nothing:true → 501):
  POST /transactions/ingest                  — up to 500 items
                                                (CSV + custom feeds)
  POST /transactions/batch-categorize        — up to 100 items

Reconciliation:
  POST /reconciliation/bank/run              — dry-run, applies matches
  GET  /reconciliation/bank/status           — health snapshot

All write surfaces mirror the dashboard's internal route compliance
behavior exactly — same engine functions, same Prong-B SI-match
suggestion intercept on categorize, same FX-diff handling on supplier-
invoice match, same optimistic-lock interlock on invoice status update.
No new bookkeeping primitives — every route delegates to the existing
`lib/bookkeeping/*` engine, `lib/transactions/ingest.ts`, and
`lib/reconciliation/bank-reconciliation.ts`.

SCOPES + ERRORS

Adds 12 entries to lib/auth/scopes.ts under transactions:read|write +
reports:read (accounts, fiscal-periods follow the same convention as
MCP tools). Adds 4 new error codes: TX_UNCATEGORIZE_NOT_BOOKED,
TX_UNCATEGORIZE_JE_NOT_POSTED, TX_INGEST_INSERT_FAILED,
TX_BATCH_CATEGORIZE_EMPTY.

TESTS

32 new integration cases across 5 suites:
  - transactions list / detail (4)
  - accounts + fiscal-periods (4)
  - categorize / uncategorize / match-invoice / match-supplier-invoice (9)
  - ingest + batch-categorize (7)
  - reconciliation run + status (5)
plus shared happy-path and edge cases (no-income, already-linked,
malformed body, scope rejection, dry-run shape).

Full suite green: 3270 passing (234 files). Build + lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(api): address PR #464 review — Phase 3 hardening

Greptile P1 — cursor pagination broken in GET /transactions.
  encodeDefaultCursor was passed the YYYY-MM-DD `date` field, but
  decodeDefaultCursor's strict ISO 8601 timestamp regex rejected it,
  so every cursor decoded as null and the endpoint always returned the
  first page. Switched the cursor anchor to `created_at` (real ISO
  timestamp, total-orderable, unique within the company at the row
  insertion grain) and updated the sort to (created_at DESC, id ASC).
  The `date` column remains in every row + filterable via ?date_from /
  ?date_to. Updated the registry description to reflect the change.

Greptile P1 — JE soft-fall in match-invoice + match-supplier-invoice.
  When the payment journal entry creation threw (any non-
  AccountsNotInChartError), the catch block recorded the error string
  but execution CONTINUED, marking the invoice paid + inserting a
  payment row + linking the transaction with no GL entry. The dashboard
  internal route soft-fails here intentionally and surfaces a banner so
  the user can re-book; for the v1 surface a partial state is strictly
  worse than a clean failure to retry. Both routes now return:
    - INVOICE_PAID_BOOK_FAILED (match-invoice)
    - MATCH_SI_RECORD_PAYMENT_FAILED (match-supplier-invoice)
  before any state mutation. Removed `journal_entry_error` from both
  response schemas — strict mode means it can never be set on a 200.

Greptile P1 — `overdue` supplier invoices fail the optimistic lock.
  The early status guard accepted `overdue` as matchable, but the
  downstream `.in('status', ['registered', 'approved', 'partially_paid'])`
  excluded it, returning MATCH_SI_NOT_OPEN for a legitimately payable
  invoice. Added `overdue` to the optimistic-lock list.

Greptile P1 + Swedish-compliance — CAS-race orphan cancellation.
  Direct `.update({ status: 'cancelled' })` on the orphaned JE was
  silently blocked by enforce_journal_entry_immutability (the engine
  writes JEs as posted) and the `voucher_gap_explanations` row claimed
  the entry was cancelled when it wasn't. BFL 5 kap 5 § requires
  corrections via a reversing entry. Both /transactions/{id}/categorize
  and /transactions/batch-categorize now call `reverseEntry()` on the
  orphan; the storno pair keeps the verifikationsnummer series unbroken
  so the gap-explanation insert is no longer needed.

Greptile P2 + Swedish-compliance — hardcoded category on match-invoice.
  The dashboard internal route writes `category: 'income_services'` for
  every matched invoice payment, overwriting any prior categorization
  with a wrong BAS classification for goods sales / rental income.
  Fixed by preserving the existing transaction.category if set, only
  defaulting to `income_services` when the row had never been
  categorized before.

Compliance Swarm V2.4 — reconciliation date range guard.
  Added a 366-day cap on date_from / date_to via Zod refine. Longer
  reconciliations should be paged.

Greptile P2 — dry-run dedup limitation.
  Added a pitfall note documenting that the ingest dry-run only checks
  external_id-based dedup; content-based dedup (date+amount against
  already-booked rows) only runs in the live pipeline.

Swedish-compliance — BFL chapter typo on fiscal-periods registry.
  "BFL 6 kap" → "BFL 5 kap 2 §" (the löpande bokföring deadline).

Deferred (with rationale documented):
  - OWASP V8.2.1 cross-tenant via path: false positive — wrapper sets
    ctx.companyId from the URL after membership check (recurring across
    swarm runs).
  - OWASP V4.5 select('*') on transactions/invoices: same as Phase 2 —
    those rows feed engine functions that need the full shape.
  - OWASP V2.3 multi-write atomicity (match endpoints): would need a
    Postgres RPC; separate refactor.
  - Swedish-compliance kontantmetoden partial-payment status: same
    semantics as the dashboard internal route; engine-level decision
    out of v1's scope.
  - Greptile P3 `reversible: false` on uncategorize: technically
    correct (the storno itself isn't reversible via this verb).

Tests + build green: 3270 passing, lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(import): distinguish network errors in the SIE upload step

Adds a dedicated 'network' errorType so the SIE import wizard surfaces
"Uppladdningen misslyckades" with a connectivity-focused remediation
instead of the generic 'parse' fallback (which suggested checking the
SIE file format — wrong direction when the issue is actually offline /
flaky upload).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(api): address PR #464 swedish-compliance re-run findings

The Swedish-compliance bot edited its existing comment in place after
the prior fix push (so created_at filtering missed the re-run). The
re-run flagged 6 new substantive findings against the post-fix code.

Fix 1 — Orphan storno failure leaves an unresolved immutability gap
  (categorize + batch-categorize).
  When reverseEntry() on the CAS-race orphan fails, the orphan stays
  posted and untraceable. BFL 5 kap 5 § requires every correction be
  traceable. Both paths now insert a voucher_gap_explanations row in
  the catch branch flagging "automatisk storno misslyckades — manuell
  reconciliation krävs", so the orphan is logged at the audit-trail
  level rather than only in app logs.

Fix 2 — Period-lock pre-check (categorize + batch-categorize).
  enforce_period_lock and enforce_company_lock_date triggers block JE
  inserts on locked/closed periods, but Supabase surfaces those as a
  generic 500. Added a new lib/api/v1/check-period-lock.ts helper that
  performs the same check the trigger would (company-wide lock date,
  is_closed, locked_at), and both routes now return a structured
  PERIOD_LOCKED response (existing error code, 400) with reason +
  fiscal_period_id details before the engine call. Note: this is an
  ergonomics check (TOCTOU window between check and insert) — the
  trigger remains authoritative.

Fix 3 — Ingest dry-run now performs content-based dedup too.
  The earlier doc-only note was a compliance miss: an integrator
  relying on dry-run to confirm uniqueness could ingest duplicate
  affärshändelser, violating BFL 5 kap. The dry-run now runs BOTH
  external_id dedup AND content-based (date+amount-against-booked)
  dedup over the request's date range — same query the live pipeline
  uses. Pitfall doc updated accordingly.

Fix 4 — fiscal-periods response now carries duration_days +
  exceeds_18_months computed fields.
  An automated client (year-end wizard, audit tool) can spot a
  non-compliant period sequence (BFL 3 kap, 18-month cap) without
  re-implementing date arithmetic. 549-day cap (18 calendar months)
  is used to keep the comparison deterministic across leap years.
  First-year exceptions still require human judgment; the boolean is
  a flag, not a verdict.

Deferred (with rationale documented in commit, not retried):
  - uncategorize storno memo: reverseEntry() doesn't accept a reason
    parameter today and the JE-level back-reference exists already
    via reversed_by_id / reverses_id. Engine signature change is
    out of v1's scope.
  - VAT integrity check on partial payment in match-invoice: the
    behavior is fully delegated to createInvoicePaymentJournalEntry.
    The bot itself recommends auditing against the engine; that is
    an engine-layer concern and the dashboard internal route uses
    the same path.
  - 366-day reconciliation window (advisory): no statutory basis;
    operational guard.
  - match-supplier-invoice FX path against ML 8 kap 21–23 §
    (advisory): engine-layer concern.

Tests + build green: 3270 passing, lint clean. Touched-suite tests
(transactions, fiscal-periods, accounts, reconciliation) re-run; the
fiscal-periods test asserts the new derived fields.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(api): PR #464 round-3 review fixes (re-run after period-lock + dedup)

Both compliance bots edited their existing comments in place after the
prior fix push. New findings against the post-fix code:

Fix — VAT account suppression too broad on account_override.
  categorize/route.ts dropped vat_lines for ANY class-2 override, but
  BAS class 2 includes the 26xx VAT clearing accounts themselves. Result:
  a user override TO a VAT account silently lost the auto-VAT line.
  Tightened to `account_class === 2 && !account_override.startsWith('26')`.
  The override-to-2440-leverantörsskulder case is unchanged (correctly
  drops auto-VAT); the override-to-2611-utgående-moms case now keeps the
  VAT line.

Fix — fiscal-periods 18-month cap uses calendar arithmetic.
  EIGHTEEN_MONTHS_DAYS = 549 was a generous approximation (18 calendar
  months span 540–549 days). Replaced with proper month-anchor math:
  start_date + 18 months computed via setUTCMonth-style year/month
  rollover, then `period_end > anchor` is the violation. Manual day-
  arithmetic on the year part avoids JS's clamp-overflow on Aug-31-style
  start dates. duration_days helper preserved for the response field.

Fix — match-invoice no longer hardcodes 'income_services'.
  When the transaction has no prior category, the route now leaves the
  field UNTOUCHED in the UPDATE (existing default 'uncategorized' or
  whatever was there persists). The response surfaces null for the
  uncategorized case so a caller can detect "needs human classification"
  without inspecting the DB. The auto-default to income_services was
  flowing into BAS 3001/3041/3530 selection mismatches and INK2R/SRU
  mis-reporting for goods/rental flows. Existing-category transactions
  still propagate their value.

Doc — accounts.ts BAS 5/6 description tightened.
  Was "5=other costs, 6=other costs" — both true but flatten distinct
  subgroups. Now spells out 5xxx (rents/supplies/services) and 6xxx
  (marketing/professional/IT) under övriga externa kostnader, with a
  pointer to the canonical BAS chart.

Deferred (with rationale documented):
  - voucher_gap_explanations in SIE export coverage: verification ask;
    SIE export audit is a separate task, not this PR's scope.
  - Dry-run dedup parity with full live pipeline: my dedup matches the
    live pipeline's primary checks (external_id + content date+amount
    against booked rows). Achieving exact parity would need refactoring
    lib/transactions/ingest.ts to expose a shared dedup helper.
  - FX sign convention in match-supplier-invoice: identical to the
    dashboard internal route; if the engine sign convention is wrong
    both surfaces are wrong. Engine-layer audit, not v1 surface.
  - OWASP V8.2.1 cross-tenant via path: recurring false positive — the
    wrapper sets ctx.companyId from the URL only AFTER company_members
    membership check.
  - V2.3 multi-write atomicity in match endpoints: would need a Postgres
    RPC; separate refactor.
  - check-period-lock TOCTOU on no_fiscal_period (advisory note): the
    engine's ensureFiscalPeriod helper creates an open period; if the
    transaction date sits in a historical gap, the engine creates the
    period unlocked. The trigger remains the authoritative gate.

Tests + build green: 3270 passing, lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(api): PR #464 round-4 review fixes (compliance bot re-run)

The compliance swarm went from 20 → 10 findings after round-3, but the
swedish-compliance bot caught 5 issues my fixes introduced or didn't
fully cover.

Fix — VAT account suppression narrowed to BAS 2610–2649.
  My round-3 fix exempted any account starting with '26' from VAT-line
  suppression, but BAS 26xx includes 2650 (momsredovisningskonto) and
  2690 (diverse), neither of which is a moms-line account. Auto-VAT
  posted against 2650 would double-post on the moms reconciliation
  account. Tightened the exception to the 2610–2649 range (utgående
  + ingående moms accounts only).

Fix — exceedsEighteenMonths month-end overflow.
  My round-3 manual month math still passed `startD` raw to Date.UTC,
  which clamps Aug 31 + 18 months to Mar 3, making the cap LATER than
  the BFL 3 kap 1 § ceiling (false negative). Now clamps `startD` to
  the last valid day of the target month using `Date.UTC(year, m+1, 0)`.

Fix — ingest dry-run dedup float-key normalization.
  Built the content-dedup set from `${tx.date}|${tx.amount}` where
  amount is a JS number stringified directly — `-349.5` from JSON vs
  `-349.50` from a Postgres numeric round-trip miss-match. Normalized
  both sides to .toFixed(2). SIE imports commonly carry trailing-zero
  precision, so this would have caused the dry-run to under-report
  duplicates (a BFL 5 kap löpande-bokföring concern: an integrator
  trusting the dry-run could double-book affärshändelser).

Fix — CAS-race voucher_series fallback no longer files under 'A'.
  Both categorize and batch-categorize used `voucher_series || 'A'`
  for the voucher_gap_explanations row. If the orphan JE had no series,
  the gap would be indexed under series 'A' and missed by any series-
  specific audit query (BFL 5 kap 6 §). Now skips the gap row entirely
  when no series is set — the error log already captures the orphan
  for human reconciliation; filing under the wrong key is strictly
  worse than not filing.

Fix — match-invoice rejects kontantmetoden partial payments.
  Under kontantmetoden, utgående moms must be reported per actual
  receipt (ML 13 kap 8 §). The cash-method-partial branch was falling
  through to createInvoicePaymentJournalEntry (the accrual 1510/1930
  clearing path), which doesn't model the per-installment moms event.
  Rather than silently over-report moms, refuse with a VALIDATION_ERROR
  pointing the caller to either wait for the full payment or switch to
  faktureringsmetoden. Full cash-method payments still flow through
  createInvoiceCashEntry (the correct kontantmetod path).

Deferred (with rationale):
  - `uncategorize` resets journal_entry_id to null: dashboard parity;
    the JE-side back-reference (reversed_by_id / reverses_id) preserves
    the audit pair. Adding a separate reversal_journal_entry_id column
    on transactions is a schema change out of v1 scope.
  - OWASP V8.2.1 cross-tenant: recurring false positive.
  - OWASP V2.2 inline Zod filter schemas: structural consistency
    decision — kept in-route to match other v1 endpoints; a future
    refactor can centralize when it justifies the cost.
  - OWASP V16 add userId/companyId to storno-failure log: txLog
    already carries both via ctx.log.child; not changing call-site
    syntax for compliance theatre.
  - Engine-layer FX sign convention in match-supplier-invoice
    (advisory): identical to dashboard internal route.

Tests + build green: 3270 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(api): match-supplier-invoice storno conflicting JE before booking

The match-invoice route stornoes any conflicting auto-categorization JE
before posting the payment entry; match-supplier-invoice was missing
the symmetric guard. If a transaction was previously auto-categorized
(e.g. expense_office with a 5460/1930 entry), matching it to a supplier
invoice would post a second 2440/1930 entry while leaving the original
posted — two verifikationer for one affärshändelse, a BFL 5 kap 6 §
integrity violation. Storno-before-match now applies in both routes,
with the same fail-closed semantics (storno failure aborts before any
state change).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 15:22:57 +02:00
..
2026-05-06 11:12:02 +02:00