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
@@ -0,0 +1,96 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
findMissingActiveAccounts,
findUnresolvableAccounts,
} from '../account-validation'
// Sequential thenable builder — each awaited query pops the next result.
let resultIdx: number
let results: Array<{ data?: unknown; error?: unknown }>
function makeBuilder() {
const b: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'in']) {
b[m] = vi.fn().mockReturnValue(b)
}
b.then = (resolve: (v: unknown) => void) => resolve(results[resultIdx++] ?? { data: null, error: null })
return b
}
function makeClient() {
return { from: vi.fn().mockImplementation(() => makeBuilder()) }
}
beforeEach(() => {
resultIdx = 0
results = []
})
describe('findMissingActiveAccounts', () => {
it('returns accounts not present-and-active, first-seen order, deduped', async () => {
results = [{ data: [{ account_number: '1930' }], error: null }]
const missing = await findMissingActiveAccounts(makeClient() as never, 'co-1', [
'5410',
'1930',
'5410',
'3740',
])
expect(missing).toEqual(['5410', '3740'])
})
it('returns empty for empty input without querying', async () => {
const supabase = makeClient()
const missing = await findMissingActiveAccounts(supabase as never, 'co-1', [])
expect(missing).toEqual([])
expect(supabase.from).not.toHaveBeenCalled()
})
})
describe('findUnresolvableAccounts', () => {
it('lets a standard BAS account that is merely absent pass (engine seeds it)', async () => {
results = [
// active-accounts read: only 1930 active, 3740 missing
{ data: [{ account_number: '1930' }], error: null },
// existence read for BAS-seedable: no row at all → engine will seed
{ data: [], error: null },
]
const unresolvable = await findUnresolvableAccounts(makeClient() as never, 'co-1', [
'1930',
'3740',
])
expect(unresolvable).toEqual([])
})
it('blocks a BAS account that exists but is deactivated (backfill never resurrects)', async () => {
results = [
{ data: [{ account_number: '1930' }], error: null },
// 3740 has a row (it surfaced as missing-active, so it must be inactive)
{ data: [{ account_number: '3740' }], error: null },
]
const unresolvable = await findUnresolvableAccounts(makeClient() as never, 'co-1', [
'1930',
'3740',
])
expect(unresolvable).toEqual(['3740'])
})
it('blocks numbers with no BAS reference without an extra existence read', async () => {
results = [
// only the active-accounts read — '9999' has no BAS reference
{ data: [], error: null },
]
const supabase = makeClient()
const unresolvable = await findUnresolvableAccounts(supabase as never, 'co-1', ['9999'])
expect(unresolvable).toEqual(['9999'])
expect(supabase.from).toHaveBeenCalledTimes(1)
})
it('returns empty when everything is already active', async () => {
results = [{ data: [{ account_number: '1930' }, { account_number: '5410' }], error: null }]
const unresolvable = await findUnresolvableAccounts(makeClient() as never, 'co-1', [
'1930',
'5410',
])
expect(unresolvable).toEqual([])
})
})
+90
View File
@@ -483,3 +483,93 @@ describe('createDraftEntry — on-demand BAS account backfill', () => {
expect(mockBackfill).toHaveBeenCalledTimes(1)
})
})
describe('reverseEntry — bank transaction unlink', () => {
// After a reversal the booked bank transaction must return to "Att bokföra"
// (journal_entry_id cleared) so the user can book it again. The agent paths
// in lib/pending-operations/commit.ts did this manually; the engine now owns
// it so the dashboard reverse route behaves the same.
it('clears transactions.journal_entry_id for rows booked by the reversed entry', async () => {
const original = {
id: 'entry-1',
company_id: 'company-1',
status: 'posted',
fiscal_period_id: 'period-1',
voucher_series: 'A',
voucher_number: 7,
entry_date: '2026-02-02',
description: 'ALMI AB - Innovationslån',
source_type: 'manual',
source_id: null,
lines: [
{ account_number: '1930', debit_amount: 1000, credit_amount: 0 },
{ account_number: '2350', debit_amount: 0, credit_amount: 1000 },
],
}
const reversal = { id: 'reversal-1', reverses_id: 'entry-1', source_type: 'storno' }
let jeCall = 0
const jeResults = [
{ data: original, error: null }, // fetch original (.single)
{ data: reversal, error: null }, // insert reversal (.single)
{ data: null, error: null }, // post reversal (await)
{ data: [{ id: 'entry-1' }], error: null }, // CAS original → reversed (await)
{ data: { ...reversal, lines: [] }, error: null }, // fetch complete (.single)
]
function jeBuilder() {
const b: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'in', 'update', 'insert']) {
b[m] = vi.fn().mockReturnValue(b)
}
b.single = vi.fn().mockImplementation(async () => jeResults[jeCall++])
b.then = (resolve: (v: unknown) => void) => resolve(jeResults[jeCall++])
return b
}
const txUpdatePayloads: unknown[] = []
const txFilters: Record<string, unknown> = {}
const supabase = {
rpc: vi.fn().mockResolvedValue({ data: 8, error: null }),
from: vi.fn().mockImplementation((table: string) => {
if (table === 'journal_entries') return jeBuilder()
if (table === 'chart_of_accounts') {
const b: Record<string, unknown> = {}
for (const m of ['select', 'eq', 'in']) b[m] = vi.fn().mockReturnValue(b)
b.then = (resolve: (v: unknown) => void) =>
resolve({
data: [
{ id: 'acc-1930', account_number: '1930' },
{ id: 'acc-2350', account_number: '2350' },
],
error: null,
})
return b
}
if (table === 'journal_entry_lines') {
return { insert: vi.fn().mockResolvedValue({ error: null }) }
}
if (table === 'transactions') {
const b: Record<string, unknown> = {}
b.update = vi.fn().mockImplementation((payload: unknown) => {
txUpdatePayloads.push(payload)
return b
})
b.eq = vi.fn().mockImplementation((col: string, val: unknown) => {
txFilters[col] = val
return b
})
b.then = (resolve: (v: unknown) => void) => resolve({ error: null })
return b
}
return createMockChain()
}),
}
const result = await reverseEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
expect(result.id).toBe('reversal-1')
expect(txUpdatePayloads).toEqual([{ journal_entry_id: null }])
expect(txFilters).toMatchObject({ company_id: 'company-1', journal_entry_id: 'entry-1' })
})
})
+39
View File
@@ -1,5 +1,6 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import type { MappingResult } from '@/types'
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
/**
* Return the subset of `accountNumbers` that are NOT present-and-active in the
@@ -40,6 +41,44 @@ export async function findMissingActiveAccounts(
return unique.filter((n) => !present.has(n))
}
/**
* Return the subset of `accountNumbers` that the engine cannot resolve even
* after its on-demand backfill (lib/bookkeeping/account-backfill.ts):
*
* - numbers with no BAS 2026 reference (typos, non-standard accounts), and
* - accounts that exist in the chart but are deactivated (the backfill never
* resurrects a deliberate deactivation).
*
* An account that is simply absent from the chart but exists in BAS is NOT
* returned — createDraftEntry seeds it automatically, so pre-validation in a
* route must not 400 on it. Read-only on purpose: dry-run/preview paths use
* the same check without side effects. Preserves first-seen order.
*/
export async function findUnresolvableAccounts(
supabase: SupabaseClient,
companyId: string,
accountNumbers: readonly string[],
): Promise<string[]> {
const missing = await findMissingActiveAccounts(supabase, companyId, accountNumbers)
if (missing.length === 0) return []
const basSeedable = missing.filter((num) => Boolean(getBASReference(num)))
if (basSeedable.length === 0) return missing
// A row that exists (but is inactive) blocks the backfill; a BAS number
// with no row at all will be seeded by the engine.
const { data, error } = await supabase
.from('chart_of_accounts')
.select('account_number')
.eq('company_id', companyId)
.in('account_number', basSeedable)
if (error) throw error
const existsInactive = new Set<string>((data ?? []).map((r) => r.account_number as string))
return missing.filter((num) => !getBASReference(num) || existsInactive.has(num))
}
/**
* Extract every chart account number a MappingResult will post to: the headline
* debit/credit plus every account_number in vat_lines. Returns the raw list
+15
View File
@@ -614,6 +614,21 @@ export async function reverseEntry(
throw new EntryAlreadyReversedError()
}
// Unlink any bank transactions booked by the reversed entry so they return
// to "Att bokföra" and can be booked again from the transactions view.
// Without this the row keeps pointing at a status='reversed' entry, reads
// as bokförd forever, and has no re-booking affordance — the agent paths
// (lib/pending-operations/commit.ts) already did this manually after every
// reverseEntry call; the dashboard reverse route did not.
const { error: unlinkError } = await supabase
.from('transactions')
.update({ journal_entry_id: null })
.eq('company_id', companyId)
.eq('journal_entry_id', entryId)
if (unlinkError) {
log.error('failed to unlink transactions from reversed entry', unlinkError, { entryId })
}
// If this was a payment entry, sync the linked invoice/supplier-invoice status.
// Helper is shared with the DELETE journal entry route so both code paths leave
// the invoice in a consistent state (BFL 5 kap 5§ requires GL reversal; this