Files
accounted/components/settings/sections/BookkeepingSettingsContent.tsx
T
Jakob Wennberg 1443235cec feat(invoices): registrera utan att bokföra + explicit Bokför-steg (#1040)
* feat(invoices): registrera utan att bokföra + explicit Bokför-steg

Companies where one person registers supplier invoices / sends customer
invoices while ekonomi does the actual bookkeeping had no way to split
the two: under faktureringsmetoden every registration/send booked the
journal entry inline.

- New company setting defer_invoice_booking (default off, accrual only):
  registering a supplier invoice or sending/marking-sent a customer
  invoice creates NO journal entry.
- New explicit booking routes POST /api/supplier-invoices/[id]/book and
  POST /api/invoices/[id]/book: create the registration/revenue entry
  afterwards, CAS-guarded against concurrent booking (a lost race
  cancels the just-posted voucher with a gap explanation), including
  periodisering schedules.
- Detail pages show "Ej bokförd ännu" + a Bokför button for unbooked
  accrual invoices; the settings toggle lives under Bokföringsmetod.
- mark-paid needs no changes: both payment flows already route on the
  journal-entry link, so an invoice still unbooked when paid gets the
  full cash-style entry.
- The mark-sent fail-closed rollback now keys on the same gate so
  deferred sends are not rolled back as booking failures.

Fixes #967

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(invoices): harden deferred booking after review

CodeRabbit round on #1040:
- CAS link guards also require a still-bookable status (and uncredited,
  customer side) so a concurrent mark-paid/credit cannot end up with a
  double-posting registration/revenue entry.
- Settings reads fail closed instead of defaulting to accrual rules.
- Detail pages surface the ACCRUAL_SCHEDULE_FAILED warning instead of
  showing plain success, and the customer page no longer stringifies
  structured errors into "[object Object]".
- The settings form normalizes defer_invoice_booking to false under
  kontantmetoden so a stale flag cannot re-activate on method switch.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 18:15:20 +02:00

215 lines
9.5 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 { applyDefaultSeriesToMap } from '@/lib/bookkeeping/voucher-series-resolver'
import { PeriodiseringAutoDetectToggle } from '@/components/settings/PeriodiseringAutoDetectToggle'
import { DimensionsToggle } from '@/components/settings/DimensionsToggle'
import { AccountingFrameworkForm } from '@/components/settings/AccountingFrameworkForm'
import { useSettings } from '@/components/settings/useSettings'
import { useCompany } from '@/contexts/CompanyContext'
import { Label } from '@/components/ui/label'
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 { 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 className="space-y-8">
{isAktiebolag && (
<AccountingFrameworkForm
current={framework}
onSaved={(next) => setFramework(next)}
/>
)}
<SettingsFormWrapper onSave={handleSave} className="space-y-8">
{/* Accounting method */}
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{t('method_heading')}
</h2>
<div className="space-y-2">
<Label htmlFor="accounting_method">{t('method_label')}</Label>
<select
id="accounting_method"
name="accounting_method"
defaultValue={settings.accounting_method || 'accrual'}
className="flex h-10 w-full max-w-xs rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<option value="accrual">{t('method_accrual')}</option>
<option value="cash">{t('method_cash')}</option>
</select>
<p className="text-xs text-muted-foreground">
{t('method_help')}
</p>
</div>
{/* #967: register/send without booking; ekonomi books in a separate
explicit step. Only meaningful under faktureringsmetoden. */}
<div className="space-y-2">
<Label htmlFor="defer_invoice_booking">{t('defer_booking_label')}</Label>
<select
id="defer_invoice_booking"
name="defer_invoice_booking"
defaultValue={settings.defer_invoice_booking ? 'true' : 'false'}
className="flex h-10 w-full max-w-xs rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<option value="false">{t('defer_booking_off')}</option>
<option value="true">{t('defer_booking_on')}</option>
</select>
<p className="text-xs text-muted-foreground">
{t('defer_booking_help')}
</p>
</div>
</section>
{/* Default voucher series */}
<div className="border-t border-border pt-8">
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{t('series_heading')}
</h2>
<div className="space-y-2">
<Label htmlFor="default_voucher_series">{t('series_label')}</Label>
<select
id="default_voucher_series"
name="default_voucher_series"
defaultValue={settings.default_voucher_series || 'A'}
className="flex h-10 w-16 rounded-md border border-input bg-background px-3 py-2 text-sm font-mono ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
{SERIES_OPTIONS.map((letter) => (
<option key={letter} value={letter}>{letter}</option>
))}
</select>
<p className="text-xs text-muted-foreground">
{t('series_help')}
</p>
</div>
</section>
</div>
{/* Period locking */}
<div className="border-t border-border pt-8">
<PeriodLockingSettings settings={settings} />
</div>
</SettingsFormWrapper>
{/* Fiscal years */}
<div className="border-t border-border pt-8">
<FiscalYearsManager />
</div>
{/* Voucher series: per-source-type mapping */}
<div className="border-t border-border pt-8">
<VoucherSeriesPerSourceTypeForm
settings={settings}
onSettingsUpdated={updateSettings}
/>
</div>
{/* Voucher series: read-only display */}
<div className="border-t border-border pt-8">
<VoucherSeriesManager defaultSeries={settings.default_voucher_series || 'A'} />
</div>
{/* Periodisering auto-detect toggle */}
<div className="border-t border-border pt-8">
<PeriodiseringAutoDetectToggle />
</div>
{/* Kostnadsställen & projekt (dimensions) toggle */}
<div className="border-t border-border pt-8">
<DimensionsToggle />
</div>
{/* Cross-links */}
<div className="border-t border-border pt-8 space-y-3">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{t('related_heading')}
</h2>
<div className="flex flex-col gap-2">
<Link
href="/bookkeeping?tab=accounts"
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ExternalLink className="h-3.5 w-3.5" />
{t('related_chart_of_accounts')}
</Link>
</div>
</div>
</div>
)
}