Files
accounted/components/settings/FiscalYearsManager.tsx
T
Jakob Wennberg 6d9846b1e7 feat(settings): Fönster redesign - flat rows, ? help, dirty save bar (#1193)
* feat(settings): Fönster redesign - flat rows, help behind ?, dirty save bar

Founder-approved concept (2026-07-25) applied to the whole settings
surface, modal and full-page variants alike:

- New primitives in components/settings/SettingsRows.tsx: section header
  (serif title + one-line intro), eyebrow groups, hairline label/control
  rows, flat inputs/selects/textareas, segmented control, animated
  reveal for gated settings, danger zone.
- Every static explanation paragraph moved behind a "?" popover
  (HelpPopover) at row or group level; dynamic status stays visible.
- Modal chrome: company kicker over serif title, fixed 920x680 window.
- SettingsFormWrapper: save is a sticky bar that appears only when the
  form is dirty; collapses to zero height when clean.
- All 11 sections converted (Konto, Abonnemang, Företag, Bokföring,
  Skatt, Löner, Fakturering, Mallar, Bank incl. Enable Banking-panel,
  Assistenten, API) with handlers, validation, role/entitlement/sandbox
  gates and i18n keys preserved; checkboxes became switches, cards
  dissolved into groups.
- Fix: Escape with an open help popover closed the whole settings
  modal; it now closes the popover first.
- New i18n keys: settings_intro.*, group labels, wrapper_unsaved
  (sv+en).

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

* fix(settings): founder feedback round 1 on the Fönster redesign

- Abonnemang paying state: status and manage split into two rows so the
  row no longer wraps awkwardly; the included-features list now shows
  for paying companies too.
- Logos where the counterpart has one: BankID mark on the security row
  and on the Koppla BankID button, Skatteverket mark on the connection
  rows.
- Buttons are unmistakably buttons: 27 text-labeled row actions went
  from ghost to outline pills; icon-only actions stay quiet.
- The agent-knowledge view (Regler & profil: Dina regler, Momsprofil,
  Konventioner) converted to the flat row language; it was the last
  old-style surface inside settings. Descriptions moved behind "?",
  rules render as hairline rows, the per-row "Regel" chip demoted to
  muted text.

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

* fix(settings): address review-bot findings on the Fönster redesign

- SettingsFormWrapper marks the form dirty on switch clicks too: Radix
  Switch is a button and fires no input event, so switch-only changes
  (f-skatt, KU, ROT/RUT, OSS...) never revealed the save bar.
- i18n: the migrated hardcoded strings got keys in both locales
  (fiscal-period start date/range/months, security set-password trio);
  dates in ApiKeysPanel/OAuthClientsPanel/CalendarFeedSettings now pass
  the active locale to formatDateLong.
- A11y: member remove/revoke buttons and the invite role select got
  correct accessible names; BankNameCombobox accepts aria-label wired
  from its row; the pinned-fact icon exposes role img.
- BankIdSettings: explicit Avbryt under the QR block so a cancelled
  BankID flow cannot strand isLinking.
- VoucherSeriesManager: clear the skeleton when no company is resolved.

Verified end to end in sandbox: switch-only dirty bar, PUT /api/settings
200 for text and switch saves, persistence across hard reload.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-25 23:55:08 +02:00

215 lines
7.9 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 } 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'
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)
// 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 === '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}
/>
<DestructiveConfirmDialog {...dialogProps} />
</SettingsGroup>
)
}