PR #1295 (144cc514) fixed computeVatCloseCheck on main while this branch was
fixing it a second, different way. This rebuilds the branch on top of that
merge instead of re-landing the duplicate: main's local
getScopedReconciliationStatus stays as the MCP entry point, its lookup body
moves into lib/reconciliation/cash-account-scope.ts, and the pieces main does
not have are added on top.
Why the lookup has to live in lib/: the bokslut readiness aggregator has the
same defect and is core code, which must never import from @/extensions/. It
called getReconciliationStatus with 4 positional args, so cashAccountId stayed
undefined and scopeTransactionsToAccount fell through to its currency-only
filter: the bank side summed every SEK cash account while the GL side stayed on
1930, and the wizard reported "Bankavstamningen visar en differens" with zero
unmatched transactions and zero unmatched GL lines to point at. Same shape as
the MCP blocker in #1290, different surface.
Decisions taken deliberately, not by taking 'ours':
1. Lookup errors fail CLOSED, everywhere. resolveCashAccountScope throws
"Kunde inte hamta kassakonto <n>" instead of returning the unscoped
fallback. The earlier version on this branch logged and fell back, which
turned a transient DB error or an RLS denial straight back into the #1290
pooling path. Main's contract wins; its merged test asserting exactly that
still passes untouched.
2. The default resolution no longer hard-codes 1930. With no account_number
argument the resolver tries 1930 and, only if the company has no such row,
falls back to its primary cash account. Measured read-only on prod
2026-07-30: 2 companies have no 1930 cash_accounts row while running two SEK
cash accounts each and zero journal_entry_lines on 1930, so the check
compared their entire SEK bank volume against an empty GL side, i.e. a
high-severity bank_unreconciled blocker with count 0 that no user action
could clear. Roughly 20x the difference the issue reported. A caller that
NAMES an account gets no fallback, so gnubok_get_reconciliation_status still
rejects "Okant kassakonto 9999" rather than silently answering about a
different account. 1367 companies have a 1930 row and are unaffected,
including the 5 whose 1930 row is not the primary one.
3. The blocker message names the resolved account instead of a literal 1930:
pointing a user at 1930 when the reconciliation ran on 1935 sends them to an
account with no lines on it.
4. warnIfUnscopedAcrossCashAccounts logs a warning when a run left
cashAccountId undefined AND the rows it fetched really do span more than one
cash account. Kept on the write path too: an unscoped runReconciliation can
persist a wrong journal_entry_id, which does not clear itself later.
Duplicate regression suite collapsed: the branch's
vat-close-check-bank-scope.test.ts overlapped main's
vat-close-check-reconciliation-scope.test.ts case for case, so only the cases
main lacked were merged into main's file (the primary-account fallback, the
message naming the resolved account, the blocker still firing on a genuine
scoped difference, and the tool handler's own scope resolution).
Residuals are now tracked issues, not code comments:
- #1298: the post-sync runReconciliation sweeps in
app/api/extensions/enable-banking/sync/cron/route.ts and
extensions/general/enable-banking/index.ts still run unscoped. They are write
paths.
- #1299: booked transactions with a NULL cash_account_id whose verifikat has no
line on the primary account still inflate the bank total. Measured all-time
on prod: 294 booked NULL rows, 22 of them on verifikat with no 1930 line,
4 companies, net -4170.31 kr with monthly swings from -18055.82 kr to
+38086.00 kr. Fixing it means finishing the cash_account_id backfill.
Also: the file-global logger mock in bank-reconciliation.test.ts now wraps the
real module and swaps only warn, instead of substituting a four-method stub
whose child() returned undefined for the entire module graph of that suite.
Verified: npx vitest run over lib/reconciliation, lib/bokslut,
extensions/general/mcp-server, app/api/reconciliation, app/api/extensions,
app/api/v1, app/api/bookkeeping, app/api/transactions, lib/pending-operations,
lib/bookkeeping, lib/invoices, lib/transactions, lib/reports: all green.
eslint on the 8 changed files: 0 errors (18 pre-existing unused-import
warnings in server.ts). tsc --noEmit: 405 errors, byte-identical to the
origin/main baseline. check:guards passes. No migration, so no pg-real test.
Fixes #1290
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
207 lines
8.1 KiB
TypeScript
207 lines
8.1 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 { computeEfDeclarationPreview } from '@/lib/bokslut/enskild-firma/ef-declaration-preview'
|
|
import type { YearEndValidation } from '@/types'
|
|
|
|
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[]
|
|
/** 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')
|
|
.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']
|
|
|
|
// 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',
|
|
})
|
|
}
|
|
|
|
// 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,
|
|
warnings: validation.warnings,
|
|
reminders,
|
|
draftCount: validation.draftCount,
|
|
unexplainedGapCount: validation.unexplainedGaps.length,
|
|
trialBalanceBalanced: validation.trialBalanceBalanced,
|
|
reconciliation,
|
|
period,
|
|
entityType,
|
|
rawValidation: validation,
|
|
}
|
|
}
|