Files
accounted/lib/bookkeeping/account-validation.ts
T
Jakob Wennberg 88f49c0ccc 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>
2026-06-15 10:17:44 +02:00

96 lines
3.6 KiB
TypeScript

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
* given company's chart_of_accounts. Mirrors the engine's resolveAccountIds
* (lib/bookkeeping/engine.ts) so a pre-validation in API routes catches the
* same condition (AccountsNotInChartError) before any DB writes happen.
*
* Empty/duplicate inputs are normalised; preserves first-seen order in output.
* On Supabase error: bubbles up. A chart-of-accounts read failure is real
* infrastructure trouble and should surface as 500 rather than be silently
* masked as "account missing".
*/
export async function findMissingActiveAccounts(
supabase: SupabaseClient,
companyId: string,
accountNumbers: readonly string[],
): Promise<string[]> {
const seen = new Set<string>()
const unique: string[] = []
for (const num of accountNumbers) {
if (!num) continue
if (seen.has(num)) continue
seen.add(num)
unique.push(num)
}
if (unique.length === 0) return []
const { data, error } = await supabase
.from('chart_of_accounts')
.select('account_number')
.eq('company_id', companyId)
.eq('is_active', true)
.in('account_number', unique)
if (error) throw error
const present = new Set<string>((data ?? []).map((r) => r.account_number as string))
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
* (duplicates intact); pass through findMissingActiveAccounts to dedupe.
*/
export function collectMappingResultAccounts(mr: MappingResult): string[] {
const out: string[] = []
if (mr.debit_account) out.push(mr.debit_account)
if (mr.credit_account) out.push(mr.credit_account)
for (const line of mr.vat_lines ?? []) {
if (line.account_number) out.push(line.account_number)
}
return out
}