Files
accounted/components/settings/sections/BookkeepingSettingsContent.tsx
T
Mattsson 0c854ac54f feat(settings): let a company name each verifikationsserie letter (#2336)
* feat(settings): let a company name each verifikationsserie letter

The series pickers show a fixed preset label next to every letter (A
Redovisning ... M Momsrapport, Fortnox's layout). A byrå that lays its
series out differently sees a wrong or missing name in every dropdown: a
partner running löner on L saw "Kontantfaktura" in the verifikat form and
asked for the series name.

- company_settings.voucher_series_labels JSONB ({"L": "Lön"}), keys A-Z,
  values 1 to 40 chars, CHECK on the JSON shape. Display only; the engine
  never reads it.
- UpdateSettingsSchema validates the map, trims names and strips empty
  values so a cleared field removes the name.
- voucherSeriesLabel(letter, labels) is the one place that decides what a
  letter is called: company name, then preset, then empty.
  buildVoucherSeriesOptions replaces the three near-identical option
  builders in the verifikat form and the two settings pickers.
- The Verifikationsserier list in settings edits the names: rows are the
  union of used, configured and named letters, one save button.
- The SIE import review's two series pickers show the name too.

Migration applied to staging (metjnjrhvujscngnpzdv) as 20260906131300.

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

* fix(settings): keep imported series in the list and unsaved names through a refetch

Skeptic pass on the series-name editor refuted two things:

- The rewritten list filtered voucher_sequences to single letters, dropping
  multi-character series (FT, LB, SKV, ...) that 54 production companies
  carry over from Fortnox and Bokio imports; the old list showed them with
  their highest number. Rows are now every used series plus the configured
  and named letters; only single-letter series get a name input, since
  those are what the pickers offer and the schema accepts.
- The draft re-seeded on the identity of settings.voucher_series_labels,
  and the settings hook revalidates on window focus with a fresh object, so
  unsaved typing was wiped after any earlier save on the page. The re-seed
  is now keyed on the serialized content of the saved names.

Also folds the "new series are created on first use" footnote back into
the group help, which the rewrite had dropped.

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

* fix(settings): name the default-series options and enforce the label shape in the database

Review pass on #2336:

- CodeRabbit: the Standardserie selector under Bokföring still rendered
  bare letters; it now shows the same name the other pickers do, through
  voucherSeriesLabel.
- Compliance swarm (SOC 2 PI1.1, low): the key and length rules for
  voucher_series_labels lived only in UpdateSettingsSchema. Migration
  20260906134700 adds voucher_series_labels_valid(jsonb) and swaps the
  object-only CHECK for one that mirrors the Zod rules (keys A-Z, values
  non-blank strings of at most 40 characters), so a write that bypasses
  /api/settings cannot store a map the pickers cannot handle. Applied to
  staging with its schema_migrations row; verified against good, empty,
  lowercase, blank, over-long, numeric and array inputs.

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

* test(pg): cover the voucher_series_labels CHECK against real Postgres

The coverage gate refuses a migration that adds a function without a
*.pg.test.ts. voucher_series_labels_valid(jsonb) and the constraint that
wraps it now have one: accepts the empty map and single-letter keys with
names of 1 to 40 characters, rejects lowercase and multi-letter keys,
blank, over-long, numeric and null values, arrays and scalars, and leaves
the row untouched after a refused write.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-06 16:20:42 +02:00

214 lines
9.1 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, voucherSeriesLabel } from '@/lib/bookkeeping/voucher-series-resolver'
import { DimensionsToggle } from '@/components/settings/DimensionsToggle'
import { MileageToggle } from '@/components/settings/MileageToggle'
import { SalesOrdersToggle } from '@/components/settings/SalesOrdersToggle'
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) => {
// Same name the pickers show: the company's own, else the preset.
const label = voucherSeriesLabel(letter, settings.voucher_series_labels)
return (
<option key={letter} value={letter}>
{label ? `${letter} ${label}` : letter}
</option>
)
})}
</SettingsSelect>
</SettingsRow>
</SettingsGroup>
<PeriodLockingSettings settings={settings} />
</SettingsFormWrapper>
<FiscalYearsManager />
<VoucherSeriesPerSourceTypeForm
settings={settings}
onSettingsUpdated={updateSettings}
/>
<VoucherSeriesPerCashAccountForm settings={settings} />
<VoucherSeriesManager settings={settings} onSettingsUpdated={updateSettings} />
<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 />
<SalesOrdersToggle />
</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>
)
}