2a8bf9b42e
* fix(bookkeeping): allow creating a fiscal year that fills an interior gap Fiscal-period creation only allowed chaining a new räkenskapsår before the earliest or after the latest existing period, so a company with a gap between years (e.g. 2024 + 2026 from an SIE import, missing 2025) could not create the missing year — it failed with "New period must chain before the earliest or after the latest existing period". Generalise forward chaining onto the new period's immediate predecessor, which covers both appending a new latest year and filling an interior gap. The "prior year must be locked" guard now applies only to true appends, not gap fills (a backfill, like backward chaining). previous_period_id is set to the predecessor and the successor is relinked so the BFNAR 2013:2 continuity chain stays intact. The create dialog suggests the missing year (capped so it never overlaps the next period), the settings page seeds the dialog at the earliest gap, and the default suggested name is now "Räkenskapsår <year>". Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(bookkeeping): omföra föregående års resultat (2099 → 2098) at year-end Year-end closing posts the result to 2099 "Årets resultat" and the opening balance carried it forward on 2099 every year, so 2099 accumulated across years and the prior result never moved off "Årets resultat". executeYearEndClosing now posts a separate "Omföring av föregående års resultat" verifikat (Dr 2099 / Cr 2098 for a profit, reversed for a loss) into the new period after the continuity check passes, so 2099 starts each year at zero. Kept as a standalone entry rather than folded into the opening balance so the IB stays a faithful mirror of the prior UB and IB/UB continuity still holds. Aktiebolag only; idempotent; no-op when 2099 is flat. The 2098 → 2091/2898 disposition (bolagsstämma decision) is intentionally left to a separate step. - new source_type 'result_appropriation' (migration + type + Zod enum) - generateResultAppropriation helper (planner + poster) wired as step 11 - ResultStep surfaces the omföring voucher - unit tests + pg-real invariant - scripts/repair-result-appropriation.ts: retroactive catch-up (dry-run default) Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(transactions): shadow-detect date-drift duplicate bank transactions The content-dedup bridge buckets on exact (date, ore), so the same transaction re-imported with a booking date that drifted a day lands in a different bucket and slips past every dedup layer. Add a measure-only ("shadow") detector that flags would-be +/-1-day duplicates and counts them, without changing what is inserted - so the gap can be validated on real data before any enforcement, mirroring the scope-drift shadow. - shiftIsoDate(): pure, deterministic adjacent-date helper - ingest: DEDUP_DATE_DRIFT_MODE flag (default on), pre-loop bucket snapshot, per-row gate with desc-bridge + cross-channel-symmetry signals; logs shadow_date_drift_candidates, never alters inserts - fail-safe date guard so the measurement can never abort an import - regression tests for both signals, account/window/distinct guards, no-double-count, and the malformed-date fail-safe Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * test(bookkeeping): anonymize a customer reference in fiscal-period tests Remove a real customer name ("AXMD AB") from regression-test comments; no logic change. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(workflows): enhance Docker image scanning and caching mechanisms * fix(bookkeeping): enhance year-end result appropriation handling and error reporting --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
222 lines
7.7 KiB
TypeScript
222 lines
7.7 KiB
TypeScript
'use client'
|
||
|
||
import { useState, useMemo } from 'react'
|
||
import {
|
||
Dialog,
|
||
DialogContent,
|
||
DialogHeader,
|
||
DialogTitle,
|
||
DialogDescription,
|
||
DialogFooter,
|
||
} from '@/components/ui/dialog'
|
||
import { Button } from '@/components/ui/button'
|
||
import { Input } from '@/components/ui/input'
|
||
import { Label } from '@/components/ui/label'
|
||
import { useToast } from '@/components/ui/use-toast'
|
||
import { Loader2, Lock } from 'lucide-react'
|
||
import { computeSuggestedPeriod } from '@/lib/bookkeeping/suggest-fiscal-period'
|
||
import type { FiscalPeriod } from '@/types'
|
||
|
||
interface Props {
|
||
open: boolean
|
||
onOpenChange: (open: boolean) => void
|
||
entryDate: string
|
||
periods: FiscalPeriod[]
|
||
onCreated: () => void
|
||
}
|
||
|
||
/** A prior period that must be locked before a new fiscal year can be created. */
|
||
interface BlockingPeriod {
|
||
id: string
|
||
name: string
|
||
period_start: string
|
||
period_end: string
|
||
}
|
||
|
||
/** Read a user-facing message from either a legacy string error or the
|
||
* canonical { code, message } envelope. */
|
||
function errorMessage(err: unknown, fallback = 'Ett oväntat fel uppstod.'): string {
|
||
if (typeof err === 'string') return err
|
||
if (err && typeof err === 'object' && typeof (err as { message?: unknown }).message === 'string') {
|
||
return (err as { message: string }).message
|
||
}
|
||
return fallback
|
||
}
|
||
|
||
export default function CreatePeriodDialog({ open, onOpenChange, entryDate, periods, onCreated }: Props) {
|
||
const { toast } = useToast()
|
||
const suggested = useMemo(() => computeSuggestedPeriod(entryDate, periods), [entryDate, periods])
|
||
|
||
const [name, setName] = useState(suggested.name)
|
||
const [periodStart, setPeriodStart] = useState(suggested.period_start)
|
||
const [periodEnd, setPeriodEnd] = useState(suggested.period_end)
|
||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||
const [isLocking, setIsLocking] = useState(false)
|
||
// Set when creation is blocked because a prior räkenskapsår is still open.
|
||
// The user can lock these inline and retry without leaving the dialog.
|
||
const [blockingPeriods, setBlockingPeriods] = useState<BlockingPeriod[]>([])
|
||
|
||
// Reset form when suggested values change (dialog reopened with new date)
|
||
const [lastSuggested, setLastSuggested] = useState(suggested)
|
||
if (suggested.name !== lastSuggested.name || suggested.period_start !== lastSuggested.period_start) {
|
||
setName(suggested.name)
|
||
setPeriodStart(suggested.period_start)
|
||
setPeriodEnd(suggested.period_end)
|
||
setLastSuggested(suggested)
|
||
setBlockingPeriods([])
|
||
}
|
||
|
||
const handleCreate = async () => {
|
||
setIsSubmitting(true)
|
||
try {
|
||
const res = await fetch('/api/bookkeeping/fiscal-periods', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ name, period_start: periodStart, period_end: periodEnd }),
|
||
})
|
||
|
||
const result = await res.json()
|
||
|
||
if (!res.ok) {
|
||
const err = result?.error
|
||
// Blocked by an open prior year — surface an inline "lås och försök
|
||
// igen" path instead of a dead-end toast.
|
||
if (
|
||
err &&
|
||
typeof err === 'object' &&
|
||
err.code === 'PERIOD_CREATE_BLOCKED_BY_OPEN_PERIODS'
|
||
) {
|
||
const blocking = (err.details?.blockingPeriods ?? []) as BlockingPeriod[]
|
||
setBlockingPeriods(blocking)
|
||
return
|
||
}
|
||
toast({
|
||
title: 'Kunde inte skapa räkenskapsår',
|
||
description: errorMessage(err),
|
||
variant: 'destructive',
|
||
})
|
||
return
|
||
}
|
||
|
||
toast({ title: 'Räkenskapsår skapat', description: `${name} har skapats.` })
|
||
setBlockingPeriods([])
|
||
onOpenChange(false)
|
||
onCreated()
|
||
} catch {
|
||
toast({
|
||
title: 'Kunde inte skapa räkenskapsår',
|
||
description: 'Ett nätverksfel uppstod. Försök igen.',
|
||
variant: 'destructive',
|
||
})
|
||
} finally {
|
||
setIsSubmitting(false)
|
||
}
|
||
}
|
||
|
||
// Lock each blocking prior year (reversible locked_at), then retry creation.
|
||
const handleLockAndRetry = async () => {
|
||
setIsLocking(true)
|
||
try {
|
||
for (const p of blockingPeriods) {
|
||
const res = await fetch(`/api/bookkeeping/fiscal-periods/${p.id}/lock`, {
|
||
method: 'POST',
|
||
})
|
||
if (!res.ok) {
|
||
const body = await res.json().catch(() => ({}))
|
||
// An already-locked period is fine — keep going.
|
||
if (body?.error?.code === 'PERIOD_LOCK_ALREADY_LOCKED') continue
|
||
toast({
|
||
title: `Kunde inte låsa ${p.name}`,
|
||
description: errorMessage(body?.error),
|
||
variant: 'destructive',
|
||
})
|
||
return
|
||
}
|
||
}
|
||
setBlockingPeriods([])
|
||
await handleCreate()
|
||
} catch {
|
||
toast({
|
||
title: 'Kunde inte låsa räkenskapsåret',
|
||
description: 'Ett nätverksfel uppstod. Försök igen.',
|
||
variant: 'destructive',
|
||
})
|
||
} finally {
|
||
setIsLocking(false)
|
||
}
|
||
}
|
||
|
||
const isBlocked = blockingPeriods.length > 0
|
||
const busy = isSubmitting || isLocking
|
||
|
||
return (
|
||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||
<DialogContent>
|
||
<DialogHeader>
|
||
<DialogTitle>Skapa räkenskapsår</DialogTitle>
|
||
<DialogDescription>
|
||
Det finns inget räkenskapsår som täcker datumet {entryDate}. Skapa ett nytt nedan.
|
||
</DialogDescription>
|
||
</DialogHeader>
|
||
|
||
<div className="space-y-3">
|
||
<div>
|
||
<Label>Namn</Label>
|
||
<Input value={name} onChange={(e) => setName(e.target.value)} className="mt-1" />
|
||
</div>
|
||
<div className="grid grid-cols-2 gap-3">
|
||
<div>
|
||
<Label>Startdatum</Label>
|
||
<Input type="date" value={periodStart} onChange={(e) => setPeriodStart(e.target.value)} className="mt-1" />
|
||
</div>
|
||
<div>
|
||
<Label>Slutdatum</Label>
|
||
<Input type="date" value={periodEnd} onChange={(e) => setPeriodEnd(e.target.value)} className="mt-1" />
|
||
</div>
|
||
</div>
|
||
|
||
{isBlocked && (
|
||
<div className="rounded-lg border border-warning/20 bg-warning/5 p-3 text-sm flex gap-2">
|
||
<Lock className="h-4 w-4 text-warning flex-shrink-0 mt-0.5" />
|
||
<div className="space-y-2">
|
||
<div className="space-y-1">
|
||
<p className="font-medium">Föregående räkenskapsår är öppet</p>
|
||
<p className="text-muted-foreground">
|
||
Du måste låsa föregående räkenskapsår innan du kan skapa ett nytt.
|
||
Låsningen är vändbar — du kan låsa upp året igen för att bokföra
|
||
bokslutsposter.
|
||
</p>
|
||
</div>
|
||
<ul className="space-y-0.5 text-muted-foreground">
|
||
{blockingPeriods.map((p) => (
|
||
<li key={p.id} className="tabular-nums">
|
||
{p.name} ({p.period_start} – {p.period_end})
|
||
</li>
|
||
))}
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
)}
|
||
</div>
|
||
|
||
<DialogFooter>
|
||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>
|
||
Avbryt
|
||
</Button>
|
||
{isBlocked ? (
|
||
<Button onClick={handleLockAndRetry} disabled={busy}>
|
||
{busy && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||
{blockingPeriods.length > 1 ? 'Lås åren och skapa' : 'Lås året och skapa'}
|
||
</Button>
|
||
) : (
|
||
<Button onClick={handleCreate} disabled={busy || !name || !periodStart || !periodEnd}>
|
||
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||
Skapa
|
||
</Button>
|
||
)}
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
)
|
||
}
|