'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([]) 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 (

{t('fy_heading')}

{t('fy_help')}

{isLoading ? (
) : hasError ? (

{t('fy_load_error')}

) : sorted.length === 0 ? (

{t('fy_empty')}

) : (
{sorted.map((p) => { const status = periodStatus(p) return (
{p.name} {formatDate(p.period_start)} – {formatDate(p.period_end)}
{t(`fy_status_${status}`)}
) })}
)}
) }