79013cf092
* feat(bookkeeping): guarded fiscal-year reset + findable Angra import (#1883) Two deliverables from the community report where a bad SIE test import left no way out short of deleting the company: A) Discoverability: the voucher list shows one attn line linking to /import?history=sie whenever the page contains import-sourced vouchers, and /import?history=sie deep-links straight into the fold-open SIE import history where per-import Angra already lives. B) Reset of an UNLOCKED fiscal year regardless of how the entries arrived: new reset_fiscal_year RPC (same gnubok.allow_delete escape hatch as undo_sie_import; no enforcement trigger touched) behind GET/POST /api/bookkeeping/fiscal-periods/[id]/reset and a typed type-the-year-name confirmation dialog on the fiscal years settings list. Refuses on: locked/closed year, company lock date over any part of the year, executed year-end, arsredovisning state, later year depending on this year's UB, VAT-declared evidence (vat_settlement verifikat, SKV lock/submit audit rows, extension workflow keys, fail closed) and AGI-declared months. Entries referenced by RESTRICT/NO ACTION FKs abort the whole reset (all-or-nothing). Documents are detached, never deleted (BFL 7 kap); every delete is audit-logged plus one behandlingshistorik summary row. Fixes #1883 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(bookkeeping): harden fiscal-year reset after skeptic review (#1883) Blocking skeptic findings on PR #1897, one consolidated pass: - New snapshot blocker cross_year_reference: an entry outside the year whose correction_of_id / reverses_id / reversed_by_id points into the year made the delete crash with an uncaught P0001 (immutability trigger refusing the ON DELETE SET NULL referential UPDATE) after an eligible:true preview, and silently severed draft chains. 12 such chains exist in prod today. - New snapshot blocker rot_rut_state: a begaran om utbetalning that reached Skatteverket (submitted/paid/partially_paid/rejected) was silently unlinked via SET NULL, erasing the bokforing behind a filed and possibly decided myndighetsarende. - Rakenskapsinformation preservation (BFL 7 kap): line-level trigger audit rows carry no company_id and header rows no amounts, so a reset destroyed konton/belopp with no company-readable trace. The RPC now archives the full content of every verifikat in company-scoped RESET_SNAPSHOT audit rows before deleting (action added to audit_log_action_check, NOT VALID), and behandlingshistorik renders them. - Dimension registry lockstep on reset (mirrors undo_sie_import): flipped imports can never be undone again, so their dimensions/values would have been orphaned forever. - EXCEPTION WHEN raise_exception now returns a typed FISCAL_YEAR_RESET_LINKED_ENTRIES envelope instead of a bare 500; gnubok.allow_delete is cleared before leaving the guarded block. - Voucher-list attn line fires only for source_type 'import': opening_balance is also written by year-end closing and the manual IB flows, which mislabelled every year-2+ company as SIE-imported. - /import?history=sie now scrolls the SIE history into view. - Reset dialog copy (sv+en) discloses that linked invoices, payments and bank transactions become unbooked; new blocker strings in both locales. - pg fixture fix: document_attachments seeded without company_id (23502); new pg tests for both blockers, RESET_SNAPSHOT rows and the lockstep. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
241 lines
8.8 KiB
TypeScript
241 lines
8.8 KiB
TypeScript
'use client'
|
|
|
|
import { useTranslations } from 'next-intl'
|
|
import { useState, useEffect, useCallback } from 'react'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Badge } from '@/components/ui/badge'
|
|
import { Skeleton } from '@/components/ui/skeleton'
|
|
import {
|
|
DestructiveConfirmDialog,
|
|
useDestructiveConfirm,
|
|
} from '@/components/ui/destructive-confirm-dialog'
|
|
import { SettingsGroup } from '@/components/settings/SettingsRows'
|
|
import { useToast } from '@/components/ui/use-toast'
|
|
import { useCompany } from '@/contexts/CompanyContext'
|
|
import { Plus, Lock, Unlock, Loader2, Eraser } from 'lucide-react'
|
|
import { formatDate } from '@/lib/utils'
|
|
import type { FiscalPeriod } from '@/types'
|
|
import CreatePeriodDialog from '@/components/bookkeeping/CreatePeriodDialog'
|
|
import { FiscalYearResetDialog } from '@/components/settings/FiscalYearResetDialog'
|
|
import { suggestSeedDate } from '@/lib/bookkeeping/suggest-fiscal-period'
|
|
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
|
|
|
/** Status of a fiscal period, in legal precedence: closed > locked > open. */
|
|
function periodStatus(p: FiscalPeriod): 'closed' | 'locked' | 'open' {
|
|
if (p.is_closed) return 'closed'
|
|
if (p.locked_at) return 'locked'
|
|
return 'open'
|
|
}
|
|
|
|
// Open is the normal state and renders as muted text; only the deviations
|
|
// (locked/closed) get a chip (UI-migration convention 5).
|
|
const STATUS_VARIANT: Record<'closed' | 'locked', 'secondary' | 'warning'> = {
|
|
closed: 'secondary',
|
|
locked: 'warning',
|
|
}
|
|
|
|
export function FiscalYearsManager() {
|
|
const t = useTranslations('settings_bookkeeping')
|
|
const { toast } = useToast()
|
|
const { role } = useCompany()
|
|
const { dialogProps, confirm } = useDestructiveConfirm()
|
|
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
|
|
const [isLoading, setIsLoading] = useState(true)
|
|
const [hasError, setHasError] = useState(false)
|
|
const [dialogOpen, setDialogOpen] = useState(false)
|
|
const [mutatingId, setMutatingId] = useState<string | null>(null)
|
|
const [resetTarget, setResetTarget] = useState<FiscalPeriod | null>(null)
|
|
|
|
// Only owners/admins may change a period's lock state. The API enforces this
|
|
// too (requireWrite); this just hides controls a viewer/member can't use.
|
|
const canManage = role === 'owner' || role === 'admin'
|
|
|
|
const fetchPeriods = useCallback(async () => {
|
|
try {
|
|
const res = await fetch('/api/bookkeeping/fiscal-periods')
|
|
if (!res.ok) throw new Error('fetch failed')
|
|
const { data } = await res.json()
|
|
setPeriods((data as FiscalPeriod[]) || [])
|
|
setHasError(false)
|
|
} catch {
|
|
setHasError(true)
|
|
} finally {
|
|
setIsLoading(false)
|
|
}
|
|
}, [])
|
|
|
|
useEffect(() => { fetchPeriods() }, [fetchPeriods])
|
|
|
|
// Newest first: matches the API's ordering and reads most-recent-at-top.
|
|
const sorted = [...periods].sort((a, b) => b.period_start.localeCompare(a.period_start))
|
|
|
|
async function runLockAction(period: FiscalPeriod, action: 'lock' | 'unlock') {
|
|
setMutatingId(period.id)
|
|
try {
|
|
const res = await fetch(`/api/bookkeeping/fiscal-periods/${period.id}/${action}`, {
|
|
method: 'POST',
|
|
})
|
|
const body = await res.json().catch(() => ({}))
|
|
if (!res.ok) {
|
|
// Surface the backend's message verbatim: e.g. "X affärstransaktion(er)
|
|
// saknar bokföring", which tells the user exactly what to fix first.
|
|
throw new Error(body?.error?.message || t('fy_action_error'))
|
|
}
|
|
toast({ title: action === 'lock' ? t('fy_lock_success') : t('fy_unlock_success') })
|
|
await fetchPeriods()
|
|
} catch (err) {
|
|
toast({
|
|
title: t('fy_action_error'),
|
|
description: err instanceof Error ? getUserErrorMessage(err) : undefined,
|
|
variant: 'destructive',
|
|
})
|
|
} finally {
|
|
setMutatingId(null)
|
|
}
|
|
}
|
|
|
|
async function handleLock(period: FiscalPeriod) {
|
|
const ok = await confirm({
|
|
title: t('fy_lock_confirm_title'),
|
|
description: t('fy_lock_confirm_body', { name: period.name }),
|
|
confirmLabel: t('fy_action_lock'),
|
|
cancelLabel: t('fy_confirm_cancel'),
|
|
variant: 'warning',
|
|
})
|
|
if (ok) await runLockAction(period, 'lock')
|
|
}
|
|
|
|
async function handleUnlock(period: FiscalPeriod) {
|
|
const ok = await confirm({
|
|
title: t('fy_unlock_confirm_title'),
|
|
description: t('fy_unlock_confirm_body', { name: period.name }),
|
|
confirmLabel: t('fy_action_unlock'),
|
|
cancelLabel: t('fy_confirm_cancel'),
|
|
variant: 'warning',
|
|
})
|
|
if (ok) await runLockAction(period, 'unlock')
|
|
}
|
|
|
|
return (
|
|
<SettingsGroup label={t('fy_heading')} help={t('fy_help')}>
|
|
{isLoading ? (
|
|
<div className="space-y-2 px-1 py-3">
|
|
<Skeleton className="h-4 w-48" />
|
|
<Skeleton className="h-4 w-40" />
|
|
</div>
|
|
) : hasError ? (
|
|
<p className="px-1 py-3 text-sm text-muted-foreground">{t('fy_load_error')}</p>
|
|
) : sorted.length === 0 ? (
|
|
<p className="px-1 py-3 text-sm text-muted-foreground">{t('fy_empty')}</p>
|
|
) : (
|
|
// Period rows: flat hairline list, no cards.
|
|
sorted.map((p) => {
|
|
const status = periodStatus(p)
|
|
const isMutating = mutatingId === p.id
|
|
return (
|
|
<div key={p.id} className="flex items-center gap-3 border-b border-border px-1 py-3">
|
|
<div className="min-w-0 flex-1">
|
|
<span className="text-sm font-medium">{p.name}</span>
|
|
<span className="ml-2 text-sm text-muted-foreground tabular-nums">
|
|
{formatDate(p.period_start)} - {formatDate(p.period_end)}
|
|
</span>
|
|
</div>
|
|
<div className="flex shrink-0 items-center gap-3">
|
|
{status === 'open' ? (
|
|
<span className="text-xs text-muted-foreground">{t('fy_status_open')}</span>
|
|
) : (
|
|
<Badge variant={STATUS_VARIANT[status]}>{t(`fy_status_${status}`)}</Badge>
|
|
)}
|
|
{canManage && status === 'open' && (
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="text-muted-foreground hover:text-foreground"
|
|
disabled={isMutating}
|
|
onClick={() => handleLock(p)}
|
|
>
|
|
{isMutating ? (
|
|
<Loader2 className="h-4 w-4 animate-spin" />
|
|
) : (
|
|
<>
|
|
<Lock className="mr-1.5 h-4 w-4" />
|
|
{t('fy_action_lock')}
|
|
</>
|
|
)}
|
|
</Button>
|
|
)}
|
|
{canManage && status === 'open' && (
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="text-destructive hover:text-destructive"
|
|
disabled={isMutating}
|
|
onClick={() => setResetTarget(p)}
|
|
>
|
|
<Eraser className="mr-1.5 h-4 w-4" />
|
|
{t('fy_action_reset')}
|
|
</Button>
|
|
)}
|
|
{canManage && status === 'locked' && (
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="text-muted-foreground hover:text-foreground"
|
|
disabled={isMutating}
|
|
onClick={() => handleUnlock(p)}
|
|
>
|
|
{isMutating ? (
|
|
<Loader2 className="h-4 w-4 animate-spin" />
|
|
) : (
|
|
<>
|
|
<Unlock className="mr-1.5 h-4 w-4" />
|
|
{t('fy_action_unlock')}
|
|
</>
|
|
)}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)
|
|
})
|
|
)}
|
|
|
|
{/* Trailing quiet action: create the next fiscal year. */}
|
|
<div className="px-1 pt-3">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
className="text-muted-foreground hover:text-foreground"
|
|
onClick={() => setDialogOpen(true)}
|
|
disabled={isLoading}
|
|
>
|
|
<Plus className="mr-1.5 h-4 w-4" />
|
|
{t('fy_create')}
|
|
</Button>
|
|
</div>
|
|
|
|
<CreatePeriodDialog
|
|
open={dialogOpen}
|
|
onOpenChange={setDialogOpen}
|
|
entryDate={suggestSeedDate(periods, new Date().toISOString().split('T')[0])}
|
|
periods={periods}
|
|
onCreated={fetchPeriods}
|
|
/>
|
|
|
|
{resetTarget && (
|
|
<FiscalYearResetDialog
|
|
periodId={resetTarget.id}
|
|
periodName={resetTarget.name}
|
|
open={resetTarget !== null}
|
|
onOpenChange={(open) => {
|
|
if (!open) setResetTarget(null)
|
|
}}
|
|
onReset={fetchPeriods}
|
|
/>
|
|
)}
|
|
|
|
<DestructiveConfirmDialog {...dialogProps} />
|
|
</SettingsGroup>
|
|
)
|
|
}
|