Files
accounted/components/settings/FiscalYearsManager.tsx
T
Mattsson 2a8bf9b42e Bug/year end numbers (#744)
* 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>
2026-06-16 18:22:09 +02:00

110 lines
3.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'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 { Plus } from 'lucide-react'
import { formatDate } from '@/lib/utils'
import type { FiscalPeriod } from '@/types'
import CreatePeriodDialog from '@/components/bookkeeping/CreatePeriodDialog'
import { suggestSeedDate } from '@/lib/bookkeeping/suggest-fiscal-period'
/** 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'
}
const STATUS_VARIANT: Record<'closed' | 'locked' | 'open', 'secondary' | 'warning' | 'success'> = {
closed: 'secondary',
locked: 'warning',
open: 'success',
}
export function FiscalYearsManager() {
const t = useTranslations('settings_bookkeeping')
const [periods, setPeriods] = useState<FiscalPeriod[]>([])
const [isLoading, setIsLoading] = useState(true)
const [hasError, setHasError] = useState(false)
const [dialogOpen, setDialogOpen] = useState(false)
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))
return (
<section className="space-y-4">
<div className="flex items-center justify-between gap-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{t('fy_heading')}
</h2>
<Button
variant="outline"
size="sm"
onClick={() => setDialogOpen(true)}
disabled={isLoading}
>
<Plus className="mr-1.5 h-4 w-4" />
{t('fy_create')}
</Button>
</div>
<p className="text-xs text-muted-foreground">{t('fy_help')}</p>
{isLoading ? (
<div className="space-y-2">
<Skeleton className="h-4 w-48" />
<Skeleton className="h-4 w-40" />
</div>
) : hasError ? (
<p className="text-sm text-muted-foreground">{t('fy_load_error')}</p>
) : sorted.length === 0 ? (
<p className="text-sm text-muted-foreground">{t('fy_empty')}</p>
) : (
<div className="divide-y divide-border">
{sorted.map((p) => {
const status = periodStatus(p)
return (
<div key={p.id} className="flex items-center justify-between gap-4 py-2">
<div className="min-w-0">
<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>
<Badge variant={STATUS_VARIANT[status]}>{t(`fy_status_${status}`)}</Badge>
</div>
)
})}
</div>
)}
<CreatePeriodDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
entryDate={suggestSeedDate(periods, new Date().toISOString().split('T')[0])}
periods={periods}
onCreated={fetchPeriods}
/>
</section>
)
}