fix(bookkeeping): harden correction flow and align VAT/cashflow reports (#726)

Bundles a set of bookkeeping-correctness fixes developed together.

Correction / storno flow
- correctEntry resolves (and seeds standard BAS) accounts for the
  corrected lines BEFORE writing the storno. The old order created and
  posted the storno first, then hit AccountsNotInChartError on the
  corrected lines and had to cancel it again — leaving a voided 0 kr
  storno in the chain and permanently burning a voucher number (an
  unexplained BFNAR 2013:2 gap). It now fails fast with nothing written.
- correctEntry re-points the bank transaction and underlag from the
  reversed original to the live corrected entry, so the transaction keeps
  reading as booked (and stays correctable) and the underlag travels with
  it. recordateEntry delegates both relinks to correctEntry.
- reverseEntry (engine) clears transactions.journal_entry_id for rows
  booked by the reversed entry, so a plain storno returns the bank row to
  "Att bokföra" with a re-booking affordance. The agent paths did this
  manually; the dashboard reverse route did not.
- findUnresolvableAccounts replaces findMissingActiveAccounts in the
  categorize routes: a standard BAS account merely absent from the chart
  is seeded on demand by the engine, so pre-validation must not 400 on it
  — only unknown numbers or deactivated accounts block.
- CorrectionChain dims cancelled (0 kr) entries and labels them so they
  no longer render like a live storno.

Report accuracy
- calculateVatLiability() (lib/reports/kpi.ts) is shared by the KPI route,
  the KPI xlsx export and the MCP period-summary tool, and uses the same
  26xx accounts as the momsdeklaration (ruta 49). Reverse-charge and
  import pairs (e.g. 2614 credit + 2645 debit) net to zero instead of
  inflating the receivable (#715). VAT_OUTPUT_ACCOUNTS / VAT_INPUT_ACCOUNTS
  are derived from ACCOUNT_RUTA so the widget can never drift from the
  declaration.
- Kassaflödesanalys records erhållna aktieägartillskott (2093) as a
  financing inflow and counts överkursfond (2086/2097) toward nyemission.
  2093 was previously unmapped, so any contribution broke the 19xx
  reconciliation by exactly the contributed amount (#716). Wired through
  the report type, both PDF templates, the K3 PDF, the dashboard client
  and the årsredovisning summary type.

Agent guidance
- shared-rules: describe the real Accounted correction flow (Rätta rader /
  Rätta datum / Radera verifikat, on-demand BAS backfill) so the assistant
  stops inventing flows that don't exist.
- verifikation-draft: clearer locked-period guidance.

Tests cover all of the above (storno fail-fast + seeding + relink,
reverseEntry unlink, findUnresolvableAccounts, VAT netting and the
cashflow reconciliation cases).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-15 10:17:44 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 7af4b96d10
commit 88f49c0ccc
33 changed files with 774 additions and 136 deletions
@@ -67,7 +67,7 @@ vi.mock('@/lib/bookkeeping/account-validation', async () => {
)
return {
...actual,
findMissingActiveAccounts: (...args: unknown[]) => mockFindMissingActiveAccounts(...args),
findUnresolvableAccounts: (...args: unknown[]) => mockFindMissingActiveAccounts(...args),
}
})
@@ -16,7 +16,7 @@ import {
normalizeOcrReference,
} from '@/lib/invoices/duplicate-payment-guard'
import { AccountsNotInChartError, accountsNotInChartResponse, isBookkeepingError } from '@/lib/bookkeeping/errors'
import { collectMappingResultAccounts, findMissingActiveAccounts } from '@/lib/bookkeeping/account-validation'
import { collectMappingResultAccounts, findUnresolvableAccounts } from '@/lib/bookkeeping/account-validation'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { Logger } from '@/lib/logger'
import type { CategorizationTemplate } from '@/types'
@@ -305,13 +305,17 @@ export const POST = withRouteContext(
// catch below silently marks the transaction as bokförd with no
// verifikation. Catching it here means the row stays in "Att bokföra"
// and the user gets a clear actionable message.
const missingAccounts = await findMissingActiveAccounts(
//
// Only truly unresolvable accounts block: a standard BAS account that is
// merely absent from the chart is seeded on demand by the engine, so the
// user can always book the row without registering accounts first.
const missingAccounts = await findUnresolvableAccounts(
supabase,
companyId,
collectMappingResultAccounts(mappingResult),
)
if (missingAccounts.length > 0) {
txLog.warn('mapping references inactive/missing accounts', { missingAccounts })
txLog.warn('mapping references inactive/unknown accounts', { missingAccounts })
return accountsNotInChartResponse(new AccountsNotInChartError(missingAccounts))
}