Files
accounted/lib/bokslut/readiness-aggregator.ts
T
2dff83e2f3 feat(bokslut): kontantmetoden year-end cut-off for fordringar and skulder (#1432)
* feat(bokslut): kontantmetoden year-end cut-off for fordringar and skulder

Under kontantmetoden nothing reaches 1510/2440 during the year, but BFL
5 kap 2 § still requires fordringar och skulder to be booked at
rakenskapsarets utgang. That conversion did not exist: the AR/AP tie-outs
were permanently unreconciled by construction for all cash companies, and
the balance sheet omitted every open invoice.

Adds lib/core/bookkeeping/kontantmetod-cutoff.ts:

  Fordringar: Debit 1510 / Credit 30xx / Credit 2618|2628|2638
  Skulder:    Debit 4-6xxx / Debit 2648 / Credit 2440

Moms goes to the VILANDE accounts, never 2611/2641. Under bokslutsmetoden
moms is reported at payment, and the vilande accounts are deliberately
absent from ACCOUNT_RUTA / ACCOUNT_TO_BOX, so parking it there keeps it out
of the momsdeklaration until the invoice is actually paid. Booking it to
2641 would claim the deduction a period early.

Two aggregate verifikat, each reversed on day 1 of the next period, and no
invoices.journal_entry_id link: the payment flows route on that link, so
per-invoice linking would send every new-year payment down the accrual
clearing path against a receivable the vandning already removed. Leaving it
unset means a new-year payment still books the normal kontantmetoden cash
entry at the real payment date.

Outstanding is computed from payment DATES, not remaining_amount: an
invoice settled in January was still a fordran on 31 December, and reading
remaining_amount would shrink the cut-off every day the bokslut is delayed.

Surfaced as a bokslut wizard reminder (warning, not a blocker: promoting it
would newly block every cash company mid-bokslut, which is a separate call).

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

* fix(bokslut): address compliance review on the kontantmetoden cut-off

Three findings from the Swedish compliance review, all real:

1. BFL 5 kap 6-7 § traceability. The aggregate verifikat collected invoice
   references but never wrote them, so an examiner could not trace the
   1510/2440 posting back to the affarshandelser behind it. Invoice numbers
   now go into the entry `notes` via buildCutoffNote(), truncated past 50 so
   the note stays a pointer to the reskontra rather than a copy of it.

2. Non-atomic posting. The cut-off and its vandning were two sequential
   creates with no rollback: if the reversal threw, 1510/2440 stayed
   permanently inflated and every new-year payment would double-book, which
   is exactly what the module docstring warns about.

   postKontantmetodCutoff now asserts the target period exists, is open, and
   contains the reversal date BEFORE posting anything, so the common failures
   refuse without writing. If a reversal still fails after its cut-off
   committed, the cut-off is stornoed through reverseEntry() (BFL 5 kap 5 §:
   never edit or delete a posted entry) and the original error is rethrown.

3. Silent vat_treatment default. Missing vat_treatment fell back to 25 %,
   which would route a 12/6/undantagen invoice to the wrong vilande account
   AND the wrong revenue account. Such rows are now collected into
   CutoffCollection.unknownVatTreatment, excluded from the cut-off, refused
   by the posting step, and surfaced as their own wizard reminder.

Adds 11 cases for postKontantmetodCutoff, which had none: every refusal path
asserts nothing was posted, and the storno-compensation path is covered in
both the happy and the storno-also-failed direction.

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

* fix(bokslut): never split a reverse charge across the cut-off

Second compliance round. Verified the three data-dependent findings against
production before changing anything; two needed no change, one is hardened:

- Credit notes are NOT silently dropped: all 22 credit notes on prod carry
  document_type='invoice', so they are inside the collected set exactly as
  the comment claims. The filter only excludes proforma and delivery_note.
- Vilande account numbers verified against the BAS 2026 chart in
  lib/bookkeeping/bas-data: 2618/2628/2638 utgaende, 2648 ingaende. The
  suggested 2617/2627/2637 do not exist.
- Reverse charge: all 123 RC supplier invoices on prod carry vat_amount = 0,
  so no RC moms could reach 2648 today. That was an implicit data invariant,
  not an enforced one. CutoffPayable now carries reverseCharge and forces the
  cut-off moms to 0 for those rows, so a stray amount can never post a
  one-sided reverse charge into the single vilande bucket. The self-assessed
  output/input pair stays with the payment entry, after the vandning.

Also names the reskontra as the underlag in a truncated aggregate note, so
the verifikat points at its specification rather than implying the listed
subset is the whole of it.

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

* fix(bokslut): surface stray moms on momsfri invoices instead of absorbing it

Third compliance round, one legitimate new finding: moms on a treatment that
cannot carry Swedish output moms (export, omvand betalningsskyldighet,
undantagen) was folded into the revenue line with only a log.warn. That
balances the verifikat while silently swallowing a real invoicing error,
which is the netting the swedish-vat reference prohibits, and it was
inconsistent with how the same module already treats a missing
vat_treatment.

Those rows now travel the same path as a missing treatment: collected into
CutoffCollection.strayVatOnZeroRate, excluded from the cut-off, refused by
the posting step, and surfaced as their own wizard reminder.

buildCutoffLines keeps its balancing fallback for the case where such a row
reaches it directly: it is now a last resort rather than the normal path,
and it must still never invent a moms account nor unbalance the verifikat.

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

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-06 12:12:05 +02:00

324 lines
14 KiB
TypeScript

import type { SupabaseClient } from '@supabase/supabase-js'
import { validateYearEndReadiness } from '@/lib/core/bookkeeping/year-end-service'
import { getReconciliationStatus } from '@/lib/reconciliation/bank-reconciliation'
import { resolveCashAccountScope } from '@/lib/reconciliation/cash-account-scope'
import { generateARReconciliation } from '@/lib/reports/ar-reconciliation'
import { generateReconciliation as generateAPReconciliation } from '@/lib/reports/supplier-reconciliation'
import { collectKontantmetodCutoff } from '@/lib/core/bookkeeping/kontantmetod-cutoff'
import { computeEfDeclarationPreview } from '@/lib/bokslut/enskild-firma/ef-declaration-preview'
import { createLogger } from '@/lib/logger'
import type { YearEndBlocker, YearEndValidation } from '@/types'
const log = createLogger('bokslut-readiness')
export type ReminderSeverity = 'info' | 'warning'
export interface BokslutReminder {
/** Stable id so the UI can suppress duplicates and link to docs. */
code: string
severity: ReminderSeverity
/** Swedish, user-facing. */
message: string
/** Optional deep link to the relevant resolution surface. */
href?: string
}
export interface BokslutReadinessReport {
/** Mirrors validateYearEndReadiness.ready: true ⇔ no blocking errors. */
ready: boolean
/** Blocking errors that prevent year-end execution (from year-end-service). */
blockers: string[]
/** Same blockers with stable machine codes (same order as `blockers`).
* The wizard matches on `code` to attach remediation links; `blockers`
* stays as plain strings for existing consumers. */
blockerItems: YearEndBlocker[]
/** Non-blocking warnings (from year-end-service). */
warnings: string[]
/** Soft reminders (Phase 2+ features not yet shipped, manual steps the user
* should consider). Never blockers: surfaced so users know what's manual. */
reminders: BokslutReminder[]
/** Convenience counts for the UI header. */
draftCount: number
unexplainedGapCount: number
trialBalanceBalanced: boolean
/** Bank reconciliation snapshot for the period. */
reconciliation: {
is_reconciled: boolean
unmatched_transaction_count: number
unmatched_gl_line_count: number
difference: number
} | null
/** Period metadata so the UI can show name/dates without an extra fetch. */
period: {
id: string
name: string
period_start: string
period_end: string
is_closed: boolean
locked_at: string | null
closing_entry_id: string | null
}
/** Entity type drives which dispositions apply (e.g. bolagsskatt only for AB). */
entityType: 'aktiebolag' | 'enskild_firma' | 'handelsbolag' | 'kommanditbolag' | 'ekonomisk_forening'
/** The full raw validation, for callers that want every field. */
rawValidation: YearEndValidation
}
/**
* Single-fetch aggregator that drives the bokslut wizard's preflight step.
*
* Wraps validateYearEndReadiness (which owns the legally-required checks) and
* layers on:
* - bank reconciliation snapshot for the period (informational warning if
* unmatched transactions exist: not a legal blocker)
* - soft reminders for Phase 2+ features that ship later (depreciation,
* accruals, tax provision). These tell the user what's manual today.
*
* Phase 2 will replace each reminder with a concrete proposal once the
* relevant calculator ships.
*/
export async function buildBokslutReadinessReport(
supabase: SupabaseClient,
companyId: string,
userId: string,
fiscalPeriodId: string,
): Promise<BokslutReadinessReport> {
// Fetch period + entity type in parallel with the heavy validation.
const [periodResult, settingsResult, validation] = await Promise.all([
supabase
.from('fiscal_periods')
.select('id, name, period_start, period_end, is_closed, locked_at, closing_entry_id')
.eq('id', fiscalPeriodId)
.eq('company_id', companyId)
.single(),
supabase
.from('company_settings')
.select('entity_type, accounting_method')
.eq('company_id', companyId)
.maybeSingle(),
validateYearEndReadiness(supabase, companyId, userId, fiscalPeriodId),
])
if (periodResult.error || !periodResult.data) {
throw new Error('Fiscal period not found')
}
const period = periodResult.data
const entityType = (settingsResult.data?.entity_type ?? 'aktiebolag') as BokslutReadinessReport['entityType']
const accountingMethod =
((settingsResult.data as { accounting_method?: string | null } | null)?.accounting_method ??
'accrual')
// Bank reconciliation snapshot for the period. Run after period fetch so we
// know the date range. Failure here must not break the report: fall back
// to null so the UI degrades gracefully.
let reconciliation: BokslutReadinessReport['reconciliation'] = null
try {
// Scope to the company's bank account. A 4-arg call leaves cashAccountId
// undefined and the bank side then sums every SEK cash account while the GL
// side stays on 1930 alone: the wizard surfaced that as "Bankavstämningen
// visar en differens" with nothing to match (#1290).
//
// resolveCashAccountScope fails CLOSED on a lookup error, so the catch below
// turns a failed lookup into "no reconciliation snapshot" rather than into
// the unscoped pooling path that produced the phantom difference.
const scope = await resolveCashAccountScope(supabase, companyId)
const status = await getReconciliationStatus(
supabase,
companyId,
period.period_start,
period.period_end,
scope.accountNumber,
scope.currency,
scope.cashAccountId,
scope.includeUnassigned,
)
reconciliation = {
is_reconciled: status.is_reconciled,
unmatched_transaction_count: status.unmatched_transaction_count,
unmatched_gl_line_count: status.unmatched_gl_line_count,
difference: status.difference,
}
} catch {
reconciliation = null
}
const reminders: BokslutReminder[] = []
if (reconciliation && !reconciliation.is_reconciled) {
reminders.push({
code: 'bank_reconciliation_incomplete',
severity: 'warning',
message:
reconciliation.unmatched_transaction_count > 0
? `${reconciliation.unmatched_transaction_count} banktransaktioner är inte matchade. Avstäm banken innan bokslut.`
: `Bankavstämningen visar en differens på ${reconciliation.difference.toFixed(2)} kr.`,
// Bankavstämning's real route: the earlier '/reconciliation/bank' href
// pointed at a page that has never existed, so the wizard's "Öppna"
// link 404ed.
href: '/reports/bank-reconciliation',
})
}
// AR/AP tie-outs: Phase 1 avstämningar per the bokslut process, open
// sub-ledger vs konto 1510 / 2440. Accrual companies only: under
// kontantmetoden open invoices are deliberately not on 1510/2440 until the
// cut-off entry below puts them there, so the tie-out is "unreconciled" by
// construction for the whole year and would only mislead.
// Warnings, never blockers: a difference can be legitimate (e.g. partial
// payments settled at a different FX rate than the invoice-date rate).
if (accountingMethod === 'cash') {
// Kontantmetoden year-end cut-off (BFL 5 kap 2 §): fordringar och skulder
// must be booked at räkenskapsårets utgång even though the year is kept on
// a cash basis. Advisory here, not a blocker: promoting it would newly
// block every cash company mid-bokslut, and the posting step is the
// founder's call to gate on.
try {
const cutoff = await collectKontantmetodCutoff(
supabase,
companyId,
period.period_start,
period.period_end,
)
const openCount = cutoff.receivables.length + cutoff.payables.length
if (openCount > 0) {
reminders.push({
code: 'kontantmetod_cutoff_required',
severity: 'warning',
message:
`${openCount} obetalda fakturor var utestående vid periodens slut. ` +
'Kontantmetoden kräver att fordringar och skulder bokförs vid ' +
'räkenskapsårets utgång (BFL 5 kap 2 §). Momsen bokas som vilande ' +
'och redovisas först vid betalning.',
href: '/reports/kundreskontra',
})
}
// Surfaced separately: these rows block the cut-off entirely, so the
// user needs to see them even when nothing else is outstanding.
if (cutoff.strayVatOnZeroRate.length > 0) {
reminders.push({
code: 'kontantmetod_cutoff_stray_vat',
severity: 'warning',
message:
`${cutoff.strayVatOnZeroRate.length} fakturor har moms trots en momsfri ` +
'momsinställning och kan inte tas med i bokslutsavgränsningen. Rätta dem innan bokslut: ' +
`${cutoff.strayVatOnZeroRate.slice(0, 5).join(', ')}`,
href: '/invoices',
})
}
if (cutoff.unknownVatTreatment.length > 0) {
reminders.push({
code: 'kontantmetod_cutoff_missing_vat_treatment',
severity: 'warning',
message:
`${cutoff.unknownVatTreatment.length} fakturor saknar momsinställning och kan ` +
'inte tas med i bokslutsavgränsningen. Komplettera dem innan bokslut: ' +
`${cutoff.unknownVatTreatment.slice(0, 5).join(', ')}`,
href: '/invoices',
})
}
} catch (err) {
// Advisory: never break the wizard on it, but keep the failure traceable
// so a silently missing reminder is not mistaken for "nothing open".
log.warn('kontantmetoden cut-off check failed; reminder omitted', err as Error)
}
}
if (accountingMethod === 'accrual') {
const [arResult, apResult] = await Promise.allSettled([
generateARReconciliation(supabase, companyId, fiscalPeriodId),
generateAPReconciliation(supabase, companyId, fiscalPeriodId),
])
// A failed tie-out degrades to "no reminder" (these are advisory), but a
// silently swallowed failure is indistinguishable from "reconciled" in
// the report, so the rejection must at least be traceable in logs
// (compliance review on the avstämning controls, BFNAR 2013:2 kap 8).
if (arResult.status === 'rejected') {
log.warn('AR tie-out (kundreskontra vs 1510) failed; reminder omitted', arResult.reason)
}
if (apResult.status === 'rejected') {
log.warn('AP tie-out (leverantörsreskontra vs 2440) failed; reminder omitted', apResult.reason)
}
if (arResult.status === 'fulfilled' && !arResult.value.is_reconciled) {
reminders.push({
code: 'ar_reconciliation_mismatch',
severity: 'warning',
message:
arResult.value.unconverted_fx_count > 0
? `Kundreskontran kan inte stämmas av mot konto 1510: ${arResult.value.unconverted_fx_count} fakturor i utländsk valuta saknar valutakurs.`
: `Kundreskontran stämmer inte mot konto 1510: differens ${arResult.value.difference.toFixed(2)} kr. Kontrollera obetalda kundfakturor innan bokslut.`,
href: '/reports/kundreskontra',
})
}
if (apResult.status === 'fulfilled' && !apResult.value.is_reconciled) {
reminders.push({
code: 'ap_reconciliation_mismatch',
severity: 'warning',
message:
apResult.value.unconverted_fx_count > 0
? `Leverantörsreskontran kan inte stämmas av mot konto 2440: ${apResult.value.unconverted_fx_count} fakturor i utländsk valuta saknar valutakurs.`
: `Leverantörsreskontran stämmer inte mot konto 2440: differens ${apResult.value.difference.toFixed(2)} kr. Kontrollera obetalda leverantörsfakturor innan bokslut.`,
href: '/reports/supplier-ledger',
})
}
}
// Periodiseringar (accruals) are still manual: no wizard step ships in
// Phases 1-3. Depreciation, bolagsskatt and periodiseringsfond now have
// dedicated calculators (DepreciationPanel + DispositionsStep) so they're
// no longer surfaced as manual reminders.
reminders.push({
code: 'accruals_manual',
severity: 'info',
message:
'Periodiseringar (förutbetalda kostnader 17xx, upplupna kostnader 29xx) bokas manuellt. Tänk på att vända dem 1 januari nästa år.',
})
if (entityType === 'enskild_firma') {
// Pre-compute the EF declaration so the wizard's overview reflects what
// the user will see when they reach the dispositions step. Egenavgifter,
// räntefördelning, periodiseringsfond-EF and expansionsfond are NOT
// booked: they go into the NE-bilaga / INK1. This reminder explains
// the BFL distinction.
reminders.push({
code: 'ef_skatt_via_ne',
severity: 'info',
message:
'Egenavgifter, räntefördelning, periodiseringsfond och expansionsfond beräknas i NE-bilagan, inte bokförs. Skatten betalas privat av ägaren.',
})
// Surface a soft warning when kapitalunderlag is missing AND the booked
// surplus is large enough to make positive räntefördelning meaningful
// (> 50 000 kr: the spärrbelopp). This is non-blocking but actionable:
// the user should enter their IB equity on the dispositions step.
try {
const preview = await computeEfDeclarationPreview(supabase, companyId, fiscalPeriodId)
if (preview.bookedSurplus > 50_000) {
reminders.push({
code: 'ef_kapitalunderlag_missing',
severity: 'warning',
message:
'Kapitalunderlag (IB eget kapital) saknas: räntefördelning beräknas inte. Fyll i på dispositionssteget för att utnyttja skattefördelen.',
})
}
} catch {
// EF preview is informational: never block readiness on it.
}
}
return {
ready: validation.ready,
blockers: validation.errors,
blockerItems: validation.blockers,
warnings: validation.warnings,
reminders,
draftCount: validation.draftCount,
unexplainedGapCount: validation.unexplainedGaps.length,
trialBalanceBalanced: validation.trialBalanceBalanced,
reconciliation,
period,
entityType,
rawValidation: validation,
}
}