Files
accounted/components/settings/sections/BookkeepingSettingsContent.tsx
T
MattssonandClaude Fable 5.1 f1230282a9 feat(bookkeeping): verifikationsserie per bankkonto for bank-transaction bookings (#2160)
* feat(bookkeeping): verifikationsserie per bankkonto for bank-transaction bookings

A company running several bank accounts (main bank on A, company card on M,
both imported via CSV) could not route each account's bookings into its own
series: every bank_transaction booking took the single company-wide default
from default_voucher_series_per_source_type.

- cash_accounts.voucher_series (nullable, single letter): per-account override,
  editable under Inställningar → Bokföring → Verifikationsserier per bankkonto
  (new PATCH /api/cash-accounts/[id]).
- resolveCashAccountVoucherSeries(): step 2 of the resolution order
  (explicit pick → account override → per-type map → A). Wired into the book
  route and createTransactionJournalEntry, which covers categorize, the agent,
  pending operations and the v1 API.
- Booking dialog gets the series picker, seeded from the server via
  /voucher-sequences/next?source_type&cash_account_id so dialog and route can
  never disagree. An unresolved embedded picker omits voucher_series so a
  stray 'A' never overrides the account's series.

Scope: bank_transaction bookings only. Invoice settlements matched from the
bank keep their payment series; bulk-book resolves inside its RPC (see
DECISIONS.md).

Migration applied to staging as 20260902121420.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JWSLbQc3jgpfqnxWe6nteh

* fix(bookkeeping): audit and document the per-bankkonto series, tighten preview and PATCH

Consolidated pass over the PR #2160 findings (skeptics, CodeRabbit, Swedish
compliance review):

- Behandlingshistorik (BFNAR 2013:2 p. 9.16): changing cash_accounts.voucher_series
  is a behandlingsregel that outranks the audited per-type map. New trigger
  audit_cash_accounts_voucher_series (UPDATE only, WHEN the series changes, so
  bank-sync churn never logs), cash_accounts added to AUDITED_TABLES and the
  audit_log filter, "Bankkonto ... Verifikationsserie: (tomt) -> M" events in
  the report, pg-real test. Applied to staging as 20260902124513.
- Systemdokumentation (p. 9.2-9.15): revision/systemdokumentation.json gains a
  verifikationsserier_regler block with the resolution order and the two
  exceptions (invoice settlements, samlingsverifikat); the per-account mapping
  itself is in data/cash_accounts.json.
- Settings picker uses the same closed list as the manual verifikat form
  (presets plus letters already in use) instead of all 26 letters; strings
  moved to messages/sv.json and messages/en.json.
- /voucher-sequences/next applies the account override only for
  source_type=bank_transaction (CodeRabbit), so a manual-entry preview cannot
  show a series the entry will not get.
- Book route resolves the series from the account the row ends up on after a
  stranded-row repoint, not the stale one.
- PATCH /api/cash-accounts/[id] answers 404 for a non-UUID id instead of a
  Postgres cast 500; the series lookup logs a warning when it fails open.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JWSLbQc3jgpfqnxWe6nteh

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-02 15:25:34 +02:00

208 lines
8.8 KiB
TypeScript

'use client'
import Link from 'next/link'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { SettingsFormWrapper } from '@/components/settings/SettingsFormWrapper'
import { SettingsLoadError } from '@/components/settings/SettingsLoadError'
import { SettingsLoadingSkeleton } from '@/components/settings/SettingsLoadingSkeleton'
import { PeriodLockingSettings } from '@/components/settings/PeriodLockingSettings'
import { FiscalYearsManager } from '@/components/settings/FiscalYearsManager'
import { VoucherSeriesManager } from '@/components/settings/VoucherSeriesManager'
import { VoucherSeriesPerSourceTypeForm } from '@/components/settings/VoucherSeriesPerSourceTypeForm'
import { VoucherSeriesPerCashAccountForm } from '@/components/settings/VoucherSeriesPerCashAccountForm'
import { applyDefaultSeriesToMap } from '@/lib/bookkeeping/voucher-series-resolver'
import { DimensionsToggle } from '@/components/settings/DimensionsToggle'
import { MileageToggle } from '@/components/settings/MileageToggle'
import { AccountingFrameworkForm } from '@/components/settings/AccountingFrameworkForm'
import {
SettingsGroup,
SettingsRow,
SettingsSectionHeader,
SettingsSelect,
} from '@/components/settings/SettingsRows'
import { useSettings } from '@/components/settings/useSettings'
import { useCompany } from '@/contexts/CompanyContext'
import { ExternalLink } from 'lucide-react'
import type { AccountingFramework, CompanySettings } from '@/types'
const SERIES_OPTIONS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
export function BookkeepingSettingsContent() {
const t = useTranslations('settings_bookkeeping')
const tNav = useTranslations('settings_nav')
const tIntro = useTranslations('settings_intro')
const { settings, isLoading, updateSettings, refetch } = useSettings()
const { company } = useCompany()
// Local mirror of the company-level accounting_framework so the K2/K3
// selector can reflect its own saves without waiting for the layout to
// re-render through the server. Falls back to k2 (matches the column
// default) until the company row is loaded.
const [framework, setFramework] = useState<AccountingFramework>(
company?.accounting_framework ?? 'k2',
)
if (isLoading) return <SettingsLoadingSkeleton />
if (!settings) return <SettingsLoadError onRetry={refetch} />
function handleSave(formData: FormData) {
const autoLockValue = formData.get('auto_lock_period_days') as string
const lockedThrough = (formData.get('bookkeeping_locked_through') as string) || null
const accountingMethod = (formData.get('accounting_method') as string) || 'accrual'
const defaultVoucherSeries = (formData.get('default_voucher_series') as string) || 'A'
// Deferred booking is an accrual-only concept (#967): normalize to false
// under kontantmetoden so switching back to accrual can never re-activate
// a stale flag the user set in a mode where it had no effect.
const deferInvoiceBooking =
accountingMethod === 'accrual' && formData.get('defer_invoice_booking') === 'true'
const updates: Record<string, unknown> = {
bookkeeping_locked_through: lockedThrough,
auto_lock_period_days: autoLockValue === 'none' ? null : parseInt(autoLockValue),
accounting_method: accountingMethod,
default_voucher_series: defaultVoucherSeries,
defer_invoice_booking: deferInvoiceBooking,
}
// Write-through: the booking engine resolves the series from the
// per-source-type map, NOT from default_voucher_series. So when the user
// changes the global default, propagate it across the map, but only for
// types that were still following the previous default, leaving explicit
// per-type overrides (set via VoucherSeriesPerSourceTypeForm) untouched.
// Without this the "Standardserie" dropdown is a no-op for bookkeeping.
// Only runs when the series actually changed, so saving the form for an
// unrelated reason (e.g. the lock date) never rewrites the map.
const prevDefault = settings?.default_voucher_series || 'A'
const currentMap = settings?.default_voucher_series_per_source_type
if (currentMap && defaultVoucherSeries !== prevDefault) {
updates.default_voucher_series_per_source_type = applyDefaultSeriesToMap(
currentMap,
prevDefault,
defaultVoucherSeries,
)
}
return {
updates,
onSuccess: (data: Record<string, unknown>) => {
updateSettings(data as Partial<CompanySettings>)
},
}
}
// K2/K3 selector is only meaningful for AB. EF stays on EF rules and never
// picks a framework. Use the company row (source of truth) since
// company_settings.entity_type can be stale on legacy data.
const isAktiebolag = company?.entity_type === 'aktiebolag'
return (
<div>
<SettingsSectionHeader title={tNav('bookkeeping')} intro={tIntro('bookkeeping')} />
<SettingsFormWrapper onSave={handleSave}>
{/* Grunder: framework (AB only), method, deferred booking, default
series. The framework row saves through its own PATCH and opts out
of this wrapper's dirty tracking; the rest read via FormData. */}
<SettingsGroup label={t('group_basics')}>
{isAktiebolag && (
<AccountingFrameworkForm
current={framework}
onSaved={(next) => setFramework(next)}
/>
)}
<SettingsRow
label={t('method_label')}
htmlFor="accounting_method"
help={t('method_help')}
>
<SettingsSelect
id="accounting_method"
name="accounting_method"
defaultValue={settings.accounting_method || 'accrual'}
>
<option value="accrual">{t('method_accrual')}</option>
<option value="cash">{t('method_cash')}</option>
</SettingsSelect>
</SettingsRow>
{/* #967: register/send without booking; ekonomi books in a separate
explicit step. Only meaningful under faktureringsmetoden. */}
<SettingsRow
label={t('defer_booking_label')}
htmlFor="defer_invoice_booking"
help={t('defer_booking_help')}
>
<SettingsSelect
id="defer_invoice_booking"
name="defer_invoice_booking"
defaultValue={settings.defer_invoice_booking ? 'true' : 'false'}
>
<option value="false">{t('defer_booking_off')}</option>
<option value="true">{t('defer_booking_on')}</option>
</SettingsSelect>
</SettingsRow>
<SettingsRow
label={t('series_label')}
htmlFor="default_voucher_series"
help={t('series_help')}
>
<SettingsSelect
id="default_voucher_series"
name="default_voucher_series"
defaultValue={settings.default_voucher_series || 'A'}
className="font-mono"
>
{SERIES_OPTIONS.map((letter) => (
<option key={letter} value={letter}>
{letter}
</option>
))}
</SettingsSelect>
</SettingsRow>
</SettingsGroup>
<PeriodLockingSettings settings={settings} />
</SettingsFormWrapper>
<FiscalYearsManager />
<VoucherSeriesPerSourceTypeForm
settings={settings}
onSettingsUpdated={updateSettings}
/>
<VoucherSeriesPerCashAccountForm settings={settings} />
<VoucherSeriesManager defaultSeries={settings.default_voucher_series || 'A'} />
<SettingsGroup label={t('group_automation')}>
{/* Periodisering is a review-gated wizard step, not an automation
that can be switched on or off, so this row is a plain link. The
old toggle here wrote a localStorage preference nothing read. */}
<SettingsRow label={t('periodisering_label')} help={t('periodisering_help')}>
<Link
href="/bookkeeping/year-end/periodisering"
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
>
<ExternalLink className="h-3.5 w-3.5" />
{t('periodisering_open_wizard')}
</Link>
</SettingsRow>
<DimensionsToggle />
<MileageToggle />
</SettingsGroup>
<SettingsGroup>
<SettingsRow label={t('related_heading')} borderless>
<Link
href="/chart-of-accounts"
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
>
<ExternalLink className="h-3.5 w-3.5" />
{t('related_chart_of_accounts')}
</Link>
</SettingsRow>
</SettingsGroup>
</div>
)
}