fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i
server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma
strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
+322
View File
@@ -0,0 +1,322 @@
'use client'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import * as DialogPrimitive from '@radix-ui/react-dialog'
import {
ReceiptText,
ArrowLeftRight,
Users,
Wallet,
BookOpen,
ListTree,
BarChart3,
Upload,
Package,
ClipboardCheck,
HandCoins,
Wand2,
Inbox,
TrendingUp,
Settings,
HelpCircle,
ArrowRight,
Scale,
type LucideIcon,
Truck,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { useCompany } from '@/contexts/CompanyContext'
import { useAgentSheet } from '@/components/agent/AgentSheetProvider'
import { requiredCapabilityForExtension } from '@/lib/entitlements/keys'
type Entry = {
id: string
label: string
hint?: string
icon: LucideIcon
href: string
keywords?: string
}
const ACTION_ENTRIES: Entry[] = [
{ id: 'new-invoice', label: 'Ny faktura', hint: 'Skapa & skicka faktura', icon: ReceiptText, href: '/invoices?new=1', keywords: 'fakturera ny invoice send create' },
{ id: 'book-transaction', label: 'Boka transaktion', hint: 'Gå till transaktionsinkorgen', icon: ArrowLeftRight, href: '/transactions', keywords: 'transaktion bokför kategorisera categorize' },
{ id: 'new-customer', label: 'Lägg till kund', icon: Users, href: '/customers', keywords: 'kund customer ny lägg till' },
{ id: 'new-supplier-invoice', label: 'Skapa leverantörsfaktura', icon: Wallet, href: '/supplier-invoices?new=1', keywords: 'leverantörsfaktura supplier invoice ny' },
{ id: 'reports', label: 'Visa resultaträkning', hint: 'Rapporter', icon: BarChart3, href: '/reports', keywords: 'rapport resultat balans report' },
]
const PAGE_ENTRIES: Entry[] = [
{ id: 'kunder', label: 'Kunder', icon: Users, href: '/customers' },
{ id: 'leverantörer', label: 'Leverantörer', icon: Truck, href: '/suppliers' },
{ id: 'kundfakturor', label: 'Kundfakturor', icon: ReceiptText, href: '/invoices', keywords: 'fakturor fakturering invoices kundfaktura' },
{ id: 'leverantörsfakturor', label: 'Leverantörsfakturor', icon: Wallet, href: '/supplier-invoices' },
{ id: 'bokföring', label: 'Bokföring', icon: BookOpen, href: '/bookkeeping', keywords: 'verifikat journal ledger' },
{ id: 'kontoplan', label: 'Kontoplan', icon: ListTree, href: '/chart-of-accounts', keywords: 'kontoplan konton bas chart of accounts konto' },
{ id: 'anläggningstillgångar', label: 'Anläggningstillgångar', icon: Package, href: '/assets', keywords: 'tillgångar assets' },
{ id: 'rapporter', label: 'Rapporter', icon: BarChart3, href: '/reports' },
{ id: 'rapport-resultatrapport', label: 'Visa rapport: Resultatrapport', icon: BarChart3, href: '/reports/resultatrapport', keywords: 'rapport resultat intäkter kostnader' },
{ id: 'rapport-balansrapport', label: 'Visa rapport: Balansrapport', icon: BarChart3, href: '/reports/balansrapport', keywords: 'rapport balans tillgångar skulder saldo per konto' },
{ id: 'rapport-saldobalans', label: 'Visa rapport: Saldobalans', icon: BarChart3, href: '/reports/trial-balance', keywords: 'rapport saldobalans trial balance saldo per konto' },
{ id: 'rapport-moms', label: 'Visa rapport: Momsdeklaration', icon: BarChart3, href: '/reports/vat-declaration', keywords: 'rapport moms vat deklaration' },
// "verifikat" is the word a bookkeeper reaches for ("verifikat per konto"),
// and matches() requires every typed token, so leaving it out made the exact
// phrase return nothing even though this report is precisely the answer.
// Deliberately NOT carrying "stäm av"/"avstämning" here: the palette
// auto-selects the first hit and huvudbok is listed above Bankavstämning, so
// those words would hijack Enter from the reconciliation page. They live in
// ReportDescriptor.searchTerms instead, where the library shows a list.
{ id: 'rapport-huvudbok', label: 'Visa rapport: Huvudbok', icon: BookOpen, href: '/reports/huvudbok', keywords: 'rapport huvudbok ledger general konto saldo transaktioner per konto verifikat verifikationer verifikationer per konto kontoutdrag kontoanalys kontokort kontohistorik balance account statement transactions vouchers' },
{ id: 'rapport-kundreskontra', label: 'Visa rapport: Kundreskontra', icon: Users, href: '/reports/kundreskontra', keywords: 'rapport kundreskontra ar kundfordringar' },
{ id: 'avstamning', label: 'Avstämning', hint: 'Stäm av bank och skattekonto', icon: Scale, href: '/reconciliation', keywords: 'avstämning stäm av bank skattekonto matcha reconcile reconciliation 1630 1930' },
{ id: 'rapport-bankavstamning', label: 'Bankavstämning', hint: 'Stäm av bank mot bokföring', icon: ArrowLeftRight, href: '/reconciliation', keywords: 'avstämning stäm av bank matcha banktransaktioner reconcile reconciliation 1930' },
{ id: 'importera', label: 'Importera', icon: Upload, href: '/import' },
{ id: 'granskning', label: 'Granskning', icon: ClipboardCheck, href: '/pending', keywords: 'pending review' },
{ id: 'löner', label: 'Löner', icon: HandCoins, href: '/salary' },
{ id: 'anställda', label: 'Anställda', icon: Users, href: '/salary/employees' },
{ id: 'dokumentinkorg', label: 'Dokumentinkorg', icon: Inbox, href: '/e/general/invoice-inbox' },
{ id: 'nyckeltal', label: 'Nyckeltal', icon: TrendingUp, href: '/kpi' },
{ id: 'inställningar', label: 'Inställningar', icon: Settings, href: '/settings' },
{ id: 'hjälp', label: 'Hjälp', icon: HelpCircle, href: '/help' },
]
function matches(entry: Entry, q: string): boolean {
const hay = `${entry.label} ${entry.hint ?? ''} ${entry.keywords ?? ''}`.toLowerCase()
return q.split(/\s+/).filter(Boolean).every(t => hay.includes(t))
}
export default function CommandPalette({ initialOpen = false }: { initialOpen?: boolean } = {}) {
const router = useRouter()
// initialOpen: LazyCommandPalette mounts this component on the first ⌘K,
// so the palette must come up already open rather than waiting for a
// second keypress.
const [open, setOpen] = useState(initialOpen)
const [query, setQuery] = useState('')
const [activeIndex, setActiveIndex] = useState(0)
const inputRef = useRef<HTMLInputElement>(null)
const { capabilities } = useCompany()
const { identity } = useAgentSheet()
// Drop entries that jump to a paywalled extension workspace the active
// company can't reach (e.g. the AI-only Dokumentinkorg). The page itself is
// gated server-side; this keeps ⌘K from offering a dead destination.
const allowedByCapability = useMemo(() => {
return (entry: Entry) => {
const m = entry.href.match(/^\/e\/([^/]+)\/([^/?#]+)/)
if (!m) return true
const required = requiredCapabilityForExtension(m[1], m[2])
return !required || capabilities.includes(required)
}
}, [capabilities])
function handleOpenChange(next: boolean) {
setOpen(next)
if (!next) {
setQuery('')
setActiveIndex(0)
}
}
// Global ⌘K / Ctrl+K
useEffect(() => {
function onKey(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault()
setOpen(prev => !prev)
}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [])
useEffect(() => {
if (!open) return
const raf = requestAnimationFrame(() => inputRef.current?.focus())
return () => cancelAnimationFrame(raf)
}, [open])
const q = query.trim().toLowerCase()
const filteredActions = useMemo(() => {
const visible = ACTION_ENTRIES.filter(allowedByCapability)
return q ? visible.filter(e => matches(e, q)) : visible
}, [q, allowedByCapability])
const filteredPages = useMemo(() => {
const visible = PAGE_ENTRIES.filter(allowedByCapability)
return q ? visible.filter(e => matches(e, q)) : visible.slice(0, 6)
}, [q, allowedByCapability])
// The hand-off-to-assistant entries use the agent name the user chose in
// /onboarding/agent, and hide entirely until that onboarding is done: the
// same gate as the nav entry and the FAB.
const assistantName = identity.displayName?.trim() || 'assistenten'
const assistantFallback: Entry | null = !identity.isVerified || !q
? null
: filteredActions.length === 0 && filteredPages.length === 0
? {
id: 'assistant-fallback',
label: `Fråga ${assistantName}: "${query.trim()}"`,
icon: Wand2,
href: `/chat/new?prompt=${encodeURIComponent(query.trim())}`,
}
: {
id: 'assistant-followup',
label: `Fråga ${assistantName} istället: "${query.trim()}"`,
icon: Wand2,
href: `/chat/new?prompt=${encodeURIComponent(query.trim())}`,
}
const flatEntries: Entry[] = [
...(assistantFallback && filteredActions.length === 0 && filteredPages.length === 0 ? [assistantFallback] : []),
...filteredActions,
...filteredPages,
...(assistantFallback && (filteredActions.length > 0 || filteredPages.length > 0) ? [assistantFallback] : []),
]
function commit(entry: Entry) {
setOpen(false)
router.push(entry.href)
}
function onInputKey(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setActiveIndex(i => Math.min(flatEntries.length - 1, i + 1))
} else if (e.key === 'ArrowUp') {
e.preventDefault()
setActiveIndex(i => Math.max(0, i - 1))
} else if (e.key === 'Enter') {
e.preventDefault()
const target = flatEntries[activeIndex]
if (target) commit(target)
}
}
return (
<DialogPrimitive.Root open={open} onOpenChange={handleOpenChange}>
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay
className="fixed inset-0 z-50 bg-black/40 backdrop-blur-[2px] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
/>
<DialogPrimitive.Content
aria-label="Snabbkommandon"
className="fixed left-[50%] top-[20%] z-50 w-[calc(100vw-2rem)] max-w-xl translate-x-[-50%] rounded-xl border border-border bg-card data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
>
<DialogPrimitive.Title className="sr-only">Snabbkommandon</DialogPrimitive.Title>
<DialogPrimitive.Description className="sr-only">
Sök efter sidor och åtgärder, eller fråga Anna.
</DialogPrimitive.Description>
<div className="px-4 py-3 border-b border-border">
<input
ref={inputRef}
value={query}
onChange={e => { setQuery(e.target.value); setActiveIndex(0) }}
onKeyDown={onInputKey}
placeholder="Sök eller skriv vad du vill göra…"
aria-label="Sök eller skriv vad du vill göra"
className="w-full bg-transparent text-base placeholder:text-muted-foreground outline-none"
/>
</div>
<div className="max-h-[60vh] overflow-y-auto py-1.5" role="listbox">
{filteredActions.length > 0 && (
<Section title="Åtgärder">
{filteredActions.map((entry) => {
const idx = flatEntries.indexOf(entry)
return (
<Row
key={entry.id}
entry={entry}
active={idx === activeIndex}
onSelect={() => commit(entry)}
onHover={() => setActiveIndex(idx)}
/>
)
})}
</Section>
)}
{filteredPages.length > 0 && (
<Section title="Sidor">
{filteredPages.map((entry) => {
const idx = flatEntries.indexOf(entry)
return (
<Row
key={entry.id}
entry={entry}
active={idx === activeIndex}
onSelect={() => commit(entry)}
onHover={() => setActiveIndex(idx)}
/>
)
})}
</Section>
)}
{assistantFallback && (
<Section title={assistantName}>
<Row
entry={assistantFallback}
active={flatEntries.indexOf(assistantFallback) === activeIndex}
onSelect={() => commit(assistantFallback)}
onHover={() => setActiveIndex(flatEntries.indexOf(assistantFallback))}
/>
</Section>
)}
{flatEntries.length === 0 && (
<div className="px-4 py-8 text-center text-sm text-muted-foreground">
Inget hittades. Tryck Enter eller börja om.
</div>
)}
</div>
<div className="px-4 py-2 border-t border-border flex items-center justify-between text-[11px] text-muted-foreground">
<span>↑↓ navigera · Enter välj · Esc stäng</span>
<span className="font-mono">⌘K</span>
</div>
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
</DialogPrimitive.Root>
)
}
function Section({ title, children }: { title: string; children: React.ReactNode }) {
return (
<div className="mb-1.5 last:mb-0">
<p className="px-4 pt-2 pb-1 text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground">{title}</p>
<div>{children}</div>
</div>
)
}
function Row({
entry,
active,
onSelect,
onHover,
}: {
entry: Entry
active: boolean
onSelect: () => void
onHover: () => void
}) {
const Icon = entry.icon
return (
<button
type="button"
role="option"
aria-selected={active}
onMouseEnter={onHover}
onFocus={onHover}
onClick={onSelect}
className={cn(
'w-full text-left flex items-center gap-3 px-4 py-2 text-sm transition-colors',
active ? 'bg-secondary text-foreground' : 'text-foreground hover:bg-secondary/60',
)}
>
<Icon className="h-4 w-4 text-muted-foreground flex-shrink-0" />
<span className="flex-1 truncate">{entry.label}</span>
{entry.hint && <span className="text-xs text-muted-foreground">{entry.hint}</span>}
{active && <ArrowRight className="h-3.5 w-3.5 text-muted-foreground" />}
</button>
)
}
+163
View File
@@ -0,0 +1,163 @@
'use client'
import { useState, useRef, useEffect, useCallback } from 'react'
import { createPortal } from 'react-dom'
import { cn } from '@/lib/utils'
import { Check, ChevronDown } from 'lucide-react'
export interface ContextPickerItem {
id: string
label: string
/** Muted right-side note on the row, e.g. "stängt" for a closed fiscal year. */
annotation?: string
disabled?: boolean
}
interface ContextPickerProps {
items: ContextPickerItem[]
/** Selected item id. */
value: string | null
onChange: (id: string) => void
/** Chip text, e.g. "Räkenskapsår 2026" or "Alla källor · 24 300 kr". */
triggerLabel: string
disabled?: boolean
ariaLabel?: string
className?: string
}
/**
* The page context picker (UI-migration convention 8): a chip-dropdown that
* scopes the page to a fiscal year, account or source. One per page, far
* right in the toolbar. A chip that looks like a picker must be a picker;
* this is that picker.
*/
export function ContextPicker({
items,
value,
onChange,
triggerLabel,
disabled = false,
ariaLabel,
className,
}: ContextPickerProps) {
const [open, setOpen] = useState(false)
const triggerRef = useRef<HTMLButtonElement>(null)
const listRef = useRef<HTMLDivElement>(null)
const [pos, setPos] = useState({ top: 0, left: 0 })
const updatePosition = useCallback(() => {
if (!triggerRef.current || !listRef.current) return
const t = triggerRef.current.getBoundingClientRect()
const l = listRef.current.getBoundingClientRect()
const margin = 8
// Right-aligned under the chip (the picker lives far right in the
// toolbar), clamped to the viewport.
const left = Math.max(margin, Math.min(t.right - l.width, window.innerWidth - l.width - margin))
const top = Math.min(t.bottom + 4, window.innerHeight - l.height - margin)
setPos({ top, left })
}, [])
useEffect(() => {
if (!open) return
const raf = requestAnimationFrame(() => updatePosition())
return () => cancelAnimationFrame(raf)
}, [open, updatePosition])
useEffect(() => {
if (!open) return
function handleClick(e: MouseEvent) {
const target = e.target as HTMLElement
if (!target.isConnected) return
if (
(!triggerRef.current || !triggerRef.current.contains(target)) &&
(!listRef.current || !listRef.current.contains(target))
) {
setOpen(false)
}
}
function handleKey(e: KeyboardEvent) {
if (e.key === 'Escape') setOpen(false)
}
document.addEventListener('mousedown', handleClick)
document.addEventListener('keydown', handleKey)
return () => {
document.removeEventListener('mousedown', handleClick)
document.removeEventListener('keydown', handleKey)
}
}, [open])
return (
<>
<button
ref={triggerRef}
type="button"
onClick={() => setOpen((v) => !v)}
disabled={disabled}
aria-expanded={open}
aria-haspopup="listbox"
aria-label={ariaLabel}
className={cn(
'inline-flex h-8 items-center gap-1.5 whitespace-nowrap rounded-full border border-border px-3 text-[13px]',
'text-foreground transition-colors duration-150',
disabled
? 'opacity-50 cursor-not-allowed'
: 'hover:bg-secondary/60 cursor-pointer',
className,
)}
>
<span className="truncate max-w-[220px]">{triggerLabel}</span>
<ChevronDown className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
</button>
{open &&
createPortal(
<div
ref={listRef}
role="listbox"
// Portaled to document.body, so inside a modal dialog the list is
// DOM-wise outside DialogContent: data-dialog-companion keeps a
// click in it from dismissing the dialog, and pointer-events-auto
// undoes the modal body lock that would swallow item clicks.
data-dialog-companion=""
className="pointer-events-auto fixed z-[60] min-w-[220px] max-w-[320px] rounded-lg border border-border bg-popover py-1 shadow-lg animate-in fade-in slide-in-from-top-1 duration-150"
style={{ top: pos.top, left: pos.left }}
>
<div className="max-h-72 overflow-y-auto px-1">
{items.map((item) => (
<button
key={item.id}
type="button"
role="option"
aria-selected={item.id === value}
disabled={item.disabled}
onClick={() => {
onChange(item.id)
setOpen(false)
}}
className={cn(
'flex w-full items-center gap-2 rounded-sm px-2.5 py-2 text-left text-[13px] leading-snug transition-colors',
item.disabled
? 'text-muted-foreground/40 cursor-not-allowed'
: item.id === value
? 'bg-secondary/60 text-foreground'
: 'text-muted-foreground hover:bg-secondary/60 hover:text-foreground',
)}
>
<span className="min-w-0 flex-1 truncate">{item.label}</span>
{item.annotation && (
<span className="flex-shrink-0 text-[11px] text-muted-foreground/70">
{item.annotation}
</span>
)}
{item.id === value && (
<Check className="h-3.5 w-3.5 flex-shrink-0 text-primary" />
)}
</button>
))}
</div>
</div>,
document.body,
)}
</>
)
}
+86
View File
@@ -0,0 +1,86 @@
import { Skeleton } from '@/components/ui/skeleton'
import { cn } from '@/lib/utils'
interface DetailPageSkeletonProps {
/** Number of summary cards under the title row. */
cards?: 2 | 3
/** Full-width variant for MainContainer's wide routes (max-w-7xl). */
wide?: boolean
className?: string
}
/**
* Silhouette of a register/document detail page: back link, title row with
* action pills, then a card grid. Used both as the route-level loading.tsx of
* the [id] segments and as the client page's own loading state, so the
* handoff from the RSC fallback to the client fetch is a no-op visually
* instead of skeleton -> centred spinner -> content (three unrelated layouts
* on the most-travelled drill-down path).
*/
export function DetailPageSkeleton({ cards = 2, wide = false, className }: DetailPageSkeletonProps) {
return (
<div className={cn('space-y-8', className)} aria-busy="true" aria-live="polite">
{/* Back link */}
<Skeleton className="h-4 w-24" />
{/* Title (24px) + status pill + primary actions (pills) */}
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex items-center gap-3">
<Skeleton className="h-8 w-56" />
<Skeleton className="h-6 w-20 rounded-full" />
</div>
<div className="flex gap-2">
<Skeleton className="h-9 w-28 rounded-full" />
<Skeleton className="h-9 w-24 rounded-full" />
</div>
</div>
{/* Card grid */}
<div
className={cn(
'grid gap-6',
cards === 3 ? 'md:grid-cols-3' : 'md:grid-cols-2',
wide && 'lg:grid-cols-[minmax(0,1fr)_280px]',
)}
>
{Array.from({ length: cards }, (_, i) => (
<div key={i} className="space-y-3 rounded-lg border border-border p-5">
<Skeleton className="h-3 w-28" />
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
<Skeleton className="h-4 w-3/5" />
</div>
))}
</div>
{/* Line/table block */}
<div>
<div className="flex h-10 items-center gap-4 border-b border-border px-4">
<Skeleton className="h-3 w-24" />
<Skeleton className="ml-auto h-3 w-14" />
</div>
{[1, 2, 3].map((i) => (
<div key={i} className="flex items-center justify-between gap-4 border-b border-border px-4 py-3 last:border-b-0">
<Skeleton className="h-4 w-48" />
<Skeleton className="h-4 w-20" />
</div>
))}
</div>
</div>
)
}
/**
* Silhouette of the invoice editor (single-column snabbflöde): heading, the
* customer/details block and the lines block. Matches the fallback the
* "Ny faktura" dialog shows while the editor chunk loads.
*/
export function InvoiceEditorSkeleton({ className }: { className?: string }) {
return (
<div className={cn('space-y-4', className)} aria-busy="true" aria-live="polite">
<Skeleton className="h-8 w-1/3" />
<Skeleton className="h-32 w-full rounded-lg" />
<Skeleton className="h-32 w-full rounded-lg" />
</div>
)
}
+67
View File
@@ -0,0 +1,67 @@
'use client'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import { useDetailPager } from '@/lib/hooks/use-detail-pager'
interface DetailPagerProps {
/** Storage key from listContextKey(), matching what the list page wrote. */
contextKey: string
/** Detail route prefix without trailing slash, e.g. '/invoices'. */
basePath: string
currentId: string
/**
* Set false to suspend arrow-key paging, e.g. while an inline editor with
* unsaved state is open. The chevron buttons stay active.
*/
keyboard?: boolean
className?: string
}
/**
* Quiet prev/next wayfinding for detail pages: two muted chevrons around an
* "n av m" position. Belongs on the back-link row (right-aligned), never
* inside the title cluster, so the heading keeps a stable position while
* stepping. Renders nothing when no list context exists (deep link or new
* tab) or when the list holds a single record, so pages degrade gracefully.
*/
export function DetailPager({
contextKey,
basePath,
currentId,
keyboard = true,
className,
}: DetailPagerProps) {
const t = useTranslations('common')
const pager = useDetailPager(contextKey, basePath, currentId, { keyboard })
if (pager.index === null || pager.total === null || pager.total < 2) return null
return (
<div className={cn('flex items-center', className)}>
<Button
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-foreground"
onClick={pager.goPrev}
disabled={!pager.prevId}
aria-label={t('pager_previous')}
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="min-w-12 whitespace-nowrap px-1 text-center text-xs tabular-nums text-muted-foreground">
{t('pager_position', { index: pager.index, total: pager.total })}
</span>
<Button
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-foreground"
onClick={pager.goNext}
disabled={!pager.nextId}
aria-label={t('pager_next')}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
)
}
+182
View File
@@ -0,0 +1,182 @@
'use client'
import { useEffect, useMemo, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { Label } from '@/components/ui/label'
import { Badge } from '@/components/ui/badge'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Lock } from 'lucide-react'
import { useCompany } from '@/contexts/CompanyContext'
import { STORAGE_KEY_PREFIX, ALL_YEARS_VALUE } from '@/components/common/fiscal-year-storage'
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
import { prepareFiscalPeriods, resolveInitialFiscalScope } from '@/lib/reference-data/fiscal-scope'
import type { FiscalPeriod } from '@/types'
// Re-exported so other surfaces (e.g. JournalEntryList's filter dialog) can
// read and write the same persisted selection without duplicating the magic
// string. The values live in fiscal-year-storage.ts (dependency-free).
export { STORAGE_KEY_PREFIX, ALL_YEARS_VALUE }
interface Props {
/**
* Current selection. `null` means "all years": no filter applied.
*/
value: string | null
/**
* Called with the selected period id (or null for "all years"). The second
* arg is the matching FiscalPeriod object so callers can read period_start
* / period_end without an extra fetch.
*/
onChange: (periodId: string | null, period?: FiscalPeriod | null) => void
/**
* If true, include an "Alla räkenskapsår" option that clears the filter.
* Pages that require a specific period (e.g. Reports) should pass false.
*/
includeAllOption?: boolean
/**
* Optional label above the select. Pass null to render without a label.
*/
label?: string | null
/**
* If true, only show periods whose start date is on or before today.
* Matches the Reports-page filter.
*/
hideFuturePeriods?: boolean
/**
* Called once after the initial period fetch completes. Useful for callers
* that want to suppress a skeleton until the selector is ready.
*/
onReady?: () => void
className?: string
/** Server-loaded periods for the first render, scoped to initialCompanyId. */
initialPeriods?: FiscalPeriod[]
initialCompanyId?: string | null
}
/**
* Shared fiscal-year (räkenskapsår) selector.
*
* Loads periods for the active company, persists the last selection per
* company in localStorage, and renders the same Select used elsewhere in the
* app so the UX is consistent across Bookkeeping, Reports, etc.
*
* The component is controlled: the caller owns the selected period id and
* threads it into whichever queries need scoping.
*/
export function FiscalYearSelector({
value,
onChange,
includeAllOption = true,
label,
hideFuturePeriods = false,
onReady,
className,
initialPeriods,
initialCompanyId,
}: Props) {
const { company } = useCompany()
const t = useTranslations('fiscal_year')
// Session-cached and seeded by the dashboard layout (see FyPicker): the
// restore runs in the first effect tick on a normal visit, no round trip.
const { periods: cachedPeriods, isLoading } = useFiscalPeriods()
const canUseInitialPeriods = initialCompanyId === company?.id && initialPeriods !== undefined
const periods = useMemo(
() => prepareFiscalPeriods(canUseInitialPeriods ? initialPeriods : cachedPeriods, hideFuturePeriods),
[canUseInitialPeriods, initialPeriods, cachedPeriods, hideFuturePeriods],
)
const loaded = canUseInitialPeriods || !isLoading
const restoredForRef = useRef<string | null>(null)
const effectiveLabel = label === null ? null : (label ?? t('label'))
useEffect(() => {
if (!company?.id) {
// Fire onReady so consumers don't stall in a loading state while the
// company context hydrates. The effect re-runs once company.id arrives.
onReady?.()
return
}
if (!loaded || restoredForRef.current === company.id) return
restoredForRef.current = company.id
// Restore last selection (only if caller hasn't already set a value).
if (value === null && typeof window !== 'undefined') {
const stored = window.localStorage.getItem(STORAGE_KEY_PREFIX + company.id)
const pick = resolveInitialFiscalScope(periods, stored, { includeAllOption })
if (pick) onChange(pick.periodId, pick.period)
}
onReady?.()
// onReady/onChange are lifecycle callbacks that fire once per load, not
// again when the parent re-creates them. `value` is read once at restore.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [company?.id, loaded, periods])
const handleChange = (next: string) => {
const nextPeriodId = next === ALL_YEARS_VALUE ? null : next
if (company?.id && typeof window !== 'undefined') {
window.localStorage.setItem(
STORAGE_KEY_PREFIX + company.id,
nextPeriodId ?? ALL_YEARS_VALUE,
)
}
const nextPeriod = nextPeriodId ? periods.find((p) => p.id === nextPeriodId) ?? null : null
onChange(nextPeriodId, nextPeriod)
}
const selectValue = value ?? (includeAllOption ? ALL_YEARS_VALUE : '')
// Surface lock status for the currently-selected period. Browsing locked
// years is read-only and allowed (BFL 7:1 requires access to historical
// data), but the user should see clearly that they're looking at a
// closed/locked year so the absence of write controls feels intentional.
const selectedPeriod = value ? periods.find((p) => p.id === value) : null
const lockState: 'locked' | 'closed' | null = selectedPeriod?.locked_at
? 'locked'
: selectedPeriod?.is_closed
? 'closed'
: null
return (
<div className={className}>
{effectiveLabel && <Label>{effectiveLabel}</Label>}
<div className={`flex items-center gap-2 ${effectiveLabel ? 'mt-1' : ''}`}>
<Select
value={selectValue}
onValueChange={handleChange}
disabled={!loaded || periods.length === 0}
>
<SelectTrigger className="w-full sm:w-[280px]">
<SelectValue placeholder={loaded ? t('placeholder') : t('loading')} />
</SelectTrigger>
<SelectContent>
{includeAllOption && (
<SelectItem value={ALL_YEARS_VALUE}>{t('all_years')}</SelectItem>
)}
{periods.map((p) => (
<SelectItem key={p.id} value={p.id}>
{p.name} ({p.period_start} till {p.period_end})
{p.locked_at ? t('suffix_locked') : p.is_closed ? t('suffix_closed') : ''}
</SelectItem>
))}
</SelectContent>
</Select>
{lockState && (
<Badge
variant="outline"
className="gap-1 text-xs font-normal shrink-0"
title={lockState === 'locked' ? t('tooltip_locked') : t('tooltip_closed')}
>
<Lock className="h-3 w-3" />
{lockState === 'locked' ? t('badge_locked') : t('badge_closed')}
</Badge>
)}
</div>
</div>
)
}
+191
View File
@@ -0,0 +1,191 @@
'use client'
import { useEffect, useMemo, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { useCompany } from '@/contexts/CompanyContext'
import { ContextPicker } from '@/components/common/ContextPicker'
import { STORAGE_KEY_PREFIX, ALL_YEARS_VALUE } from '@/components/common/fiscal-year-storage'
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
import { prepareFiscalPeriods, resolveInitialFiscalScope } from '@/lib/reference-data/fiscal-scope'
import type { FiscalPeriod } from '@/types'
interface FyPickerProps {
/** Current selection. `null` means "all years": no filter applied. */
value: string | null
/**
* Called with the selected period id (or null for "all years") and the
* matching FiscalPeriod so callers avoid an extra fetch.
*/
onChange: (periodId: string | null, period?: FiscalPeriod | null) => void
/** Include an "Alla räkenskapsår" option that clears the filter. */
includeAllOption?: boolean
/** Only show periods that have started (Reports-style filter). */
hideFuturePeriods?: boolean
/**
* Auto-select the most recently ENDED period on load instead of restoring
* the shared per-company scope or falling back to the newest started one.
* For filing surfaces (helårsmoms): only an ended räkenskapsår can be
* declared, so the newest started period is the one default that is always
* wrong there. Manual picks still work and are still persisted.
*/
preferLatestEnded?: boolean
/**
* Never auto-select on load, from ANY source: not the newest-period
* fallback, and not a selection persisted by an earlier session. The picker
* stays empty until the user chooses, every session.
*
* The default behaviour (restore or pick the newest) is right for a filter,
* where a sensible default beats an empty page. It is wrong where the year
* is an ASSERTION the user is making rather than a view they are narrowing:
* the underlag import resolves voucher references inside the chosen year and
* writes irreversible links. A pre-filled newest year would let a 2023 batch
* land in 2026, and a restored LAST-USED year is aimed even worse: in a
* multi-year migration the user is by definition moving to a year other than
* last time. Within one sitting the caller carries the choice in its own
* state (the wizard's reset() keeps it), which covers multi-batch runs
* without any cross-session hazard.
*/
requireExplicitChoice?: boolean
/**
* Skip ONLY the on-load restore of a persisted selection (and its
* newest-period fallback) while keeping manual picks persisted as usual.
* For deep-link visits that arrive with a deliberate transient scope (e.g.
* /bookkeeping?missingUnderlag=true opens as "Alla räkenskapsår" to match
* the all-years dashboard count): without this, the restore fires on
* `value === null` and snaps the scope back to the stored year right after
* load. Unlike requireExplicitChoice this does not change labels or
* persistence semantics.
*/
suppressAutoRestore?: boolean
/** Fires once after the initial period load completes. */
onReady?: () => void
/** Server-loaded periods for the first render, scoped to initialCompanyId. */
initialPeriods?: FiscalPeriod[]
initialCompanyId?: string | null
/**
* localStorage prefix for the persisted selection (companyId is appended).
* Defaults to the report-wide shared scope; pass a page-specific prefix
* when the page's scope must not follow (or steer) the shared one, e.g.
* the transactions inbox, where a narrowed scope hides pending rows.
*/
storageKeyPrefix?: string
className?: string
}
/**
* Fiscal-year context picker (UI-migration plan PR 3): the chip-dropdown
* "Räkenskapsår 2026" with a check on the active choice and closed/locked
* years annotated. Same controlled API and per-company localStorage
* persistence as FiscalYearSelector, which it replaces page by page from
* PR 4 on.
*/
export function FyPicker({
value,
onChange,
includeAllOption = true,
hideFuturePeriods = false,
preferLatestEnded = false,
requireExplicitChoice = false,
suppressAutoRestore = false,
onReady,
initialPeriods,
initialCompanyId,
storageKeyPrefix = STORAGE_KEY_PREFIX,
className,
}: FyPickerProps) {
const { company } = useCompany()
const t = useTranslations('fiscal_year')
// Session-cached and seeded by the dashboard layout, so on a normal visit
// the list is already here on the first render: the restore below runs in
// the first effect tick and onReady fires without a network round trip.
// initialPeriods remains an explicit override for server-rendered pages.
const { periods: cachedPeriods, isLoading } = useFiscalPeriods()
const canUseInitial = initialCompanyId === company?.id && initialPeriods !== undefined
const periods = useMemo(
() => prepareFiscalPeriods(canUseInitial ? initialPeriods : cachedPeriods, hideFuturePeriods),
[canUseInitial, initialPeriods, cachedPeriods, hideFuturePeriods],
)
const loaded = canUseInitial || !isLoading
// Restore once per company load, not on every background revalidation of
// the cached list (which would re-fire onChange/onReady mid-session).
const restoredForRef = useRef<string | null>(null)
useEffect(() => {
if (!company?.id) {
onReady?.()
return
}
if (!loaded || restoredForRef.current === company.id) return
restoredForRef.current = company.id
// Restore last selection (same key as FiscalYearSelector so pages keep
// their scope when the picker swaps in).
//
// requireExplicitChoice gates this WHOLE block, not individual branches:
// every path in here ends in an unprompted onChange (restore, the
// ALL_YEARS-stored fallback, newest-period, preferLatestEnded), and a
// per-branch gate already missed one of them once. Nothing auto-fires;
// the picker stays empty until a human picks.
if (value === null && !requireExplicitChoice && !suppressAutoRestore && typeof window !== 'undefined') {
const stored = window.localStorage.getItem(storageKeyPrefix + company.id)
const pick = resolveInitialFiscalScope(periods, stored, { includeAllOption, preferLatestEnded })
if (pick) onChange(pick.periodId, pick.period)
}
onReady?.()
// onReady/onChange are lifecycle callbacks: fire once per load, not on
// parent re-renders that re-create them. `value` is read once at restore.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [company?.id, loaded, periods])
const handleChange = (id: string) => {
const nextId = id === ALL_YEARS_VALUE ? null : id
// A per-batch assertion is never restored, so persisting it would be a
// write nothing reads. Worse than useless: this write happens BEFORE
// onChange, so a pick the caller rejects (e.g. mid-preview) would still
// be recorded as if it had taken effect.
if (!requireExplicitChoice && company?.id && typeof window !== 'undefined') {
window.localStorage.setItem(storageKeyPrefix + company.id, nextId ?? ALL_YEARS_VALUE)
}
onChange(nextId, nextId ? periods.find((p) => p.id === nextId) ?? null : null)
}
const annotationFor = (p: FiscalPeriod) =>
p.locked_at ? t('badge_locked').toLowerCase() : p.is_closed ? t('badge_closed').toLowerCase() : undefined
const selected = value ? periods.find((p) => p.id === value) : null
// Real period names often already read "Räkenskapsår 2026"; only prefix
// the label when the name is a bare year/name so the chip never doubles up.
const chipLabel = (p: FiscalPeriod) =>
p.name.toLowerCase().includes(t('label').toLowerCase())
? p.name
: `${t('label')} ${p.name}`
const triggerLabel = selected
? chipLabel(selected)
: includeAllOption
? t('all_years')
: loaded
? t('placeholder')
: t('loading')
const items = [
...(includeAllOption ? [{ id: ALL_YEARS_VALUE, label: t('all_years') }] : []),
...periods.map((p) => ({
id: p.id,
label: p.name,
annotation: annotationFor(p),
})),
]
return (
<ContextPicker
items={items}
value={value ?? (includeAllOption ? ALL_YEARS_VALUE : null)}
onChange={handleChange}
triggerLabel={triggerLabel}
disabled={!loaded || periods.length === 0}
ariaLabel={t('label')}
className={className}
/>
)
}
+31
View File
@@ -0,0 +1,31 @@
'use client'
import { useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
const CommandPalette = dynamic(() => import('./CommandPalette'), { ssr: false })
/**
* Defers the command palette bundle (Radix dialog + its icon set) until the
* first ⌘K / Ctrl+K press. The palette is mounted on every dashboard page but
* used only by keyboard, so eagerly parsing it on initial load was pure cost.
* Once mounted, the palette's own global key listener takes over toggling;
* this wrapper's listener only fires the first time.
*/
export default function LazyCommandPalette() {
const [mounted, setMounted] = useState(false)
useEffect(() => {
if (mounted) return
function onKey(e: KeyboardEvent) {
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
e.preventDefault()
setMounted(true)
}
}
document.addEventListener('keydown', onKey)
return () => document.removeEventListener('keydown', onKey)
}, [mounted])
return mounted ? <CommandPalette initialOpen /> : null
}
+256
View File
@@ -0,0 +1,256 @@
'use client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { useCompany } from '@/contexts/CompanyContext'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
export type DateRangeValue = {
/** Inclusive lower bound. ISO YYYY-MM-DD. `undefined` = period start. */
fromDate?: string
/** Inclusive upper bound. ISO YYYY-MM-DD. `undefined` = period end. */
toDate?: string
}
type Preset = 'full_year' | 'ytd' | 'this_month' | 'last_month' | 'this_quarter' | 'custom'
interface Props {
/** Selected fiscal period: bounds the range. */
periodStart: string
periodEnd: string
value: DateRangeValue
onChange: (next: DateRangeValue) => void
/**
* Preset to open on when this company has no stored choice yet. Defaults to
* YTD, which matches Fortnox/Visma for the resultat-/balansrapport family.
* Bank reconciliation passes 'full_year': a reconciliation is carried out
* over a whole räkenskapsår, and a part-year window makes its difference
* describe a period the user did not ask about.
*/
defaultPreset?: Preset
/**
* localStorage prefix for the remembered preset (companyId is appended).
* Defaults to the range shared by the report family. Pass a page-specific
* prefix where inheriting another report's preset would be wrong rather than
* merely surprising: bank reconciliation opened on a "Denna månad" carried
* over from Resultatrapport would show an alarming difference for a window
* nobody chose.
*/
storageKeyPrefix?: string
className?: string
}
const STORAGE_KEY_PREFIX = 'Accounted:report-range-preset:'
const PRESETS: Preset[] = ['full_year', 'ytd', 'this_month', 'last_month', 'this_quarter', 'custom']
function todayIso(): string {
// Local calendar date: using toISOString() returns UTC, which falls a day
// behind for Swedish users between midnight and 01:00/02:00 local time and
// would silently truncate "today" from YTD / this-month / this-quarter.
const d = new Date()
const y = d.getFullYear()
const m = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
return `${y}-${m}-${day}`
}
function clampToPeriod(date: string, periodStart: string, periodEnd: string): string {
if (date < periodStart) return periodStart
if (date > periodEnd) return periodEnd
return date
}
/**
* Resolve a preset to a concrete range inside the fiscal period.
*
* Endpoints are always clamped to the period: e.g. "this month" outside the
* period collapses to a zero-width range at whichever boundary you're nearest.
* `full_year` returns `{}` so the API call omits the params entirely and the
* report falls back to its full-period default (preserves cache parity with
* the pre-feature behaviour).
*/
function resolvePreset(
preset: Preset,
periodStart: string,
periodEnd: string,
reference: string,
): DateRangeValue {
if (preset === 'full_year') return {}
if (preset === 'custom') return {}
if (preset === 'ytd') {
const to = clampToPeriod(reference, periodStart, periodEnd)
return { fromDate: periodStart, toDate: to }
}
const ref = new Date(reference)
// Same UTC pitfall as todayIso(): Date.toISOString() returns UTC, so a
// local Date constructed via `new Date(y, m, d)` round-trips to the wrong
// calendar day in any timezone west of UTC. Use the local components.
const toLocalIso = (d: Date) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
if (preset === 'this_month') {
const y = ref.getFullYear()
const m = ref.getMonth()
const start = `${y}-${String(m + 1).padStart(2, '0')}-01`
const end = toLocalIso(new Date(y, m + 1, 0))
return {
fromDate: clampToPeriod(start, periodStart, periodEnd),
toDate: clampToPeriod(end, periodStart, periodEnd),
}
}
if (preset === 'last_month') {
const y = ref.getFullYear()
const m = ref.getMonth() - 1
const start = toLocalIso(new Date(y, m, 1))
const end = toLocalIso(new Date(y, m + 1, 0))
return {
fromDate: clampToPeriod(start, periodStart, periodEnd),
toDate: clampToPeriod(end, periodStart, periodEnd),
}
}
if (preset === 'this_quarter') {
const y = ref.getFullYear()
const q = Math.floor(ref.getMonth() / 3)
const start = `${y}-${String(q * 3 + 1).padStart(2, '0')}-01`
const end = toLocalIso(new Date(y, q * 3 + 3, 0))
return {
fromDate: clampToPeriod(start, periodStart, periodEnd),
toDate: clampToPeriod(end, periodStart, periodEnd),
}
}
return {}
}
/**
* Date-range picker for the resultat-/balansrapport family.
*
* Default = "Hittills i år" (YTD) which matches Fortnox/Visma. A "Hela året"
* preset clears the range entirely so the API falls back to full-period
* behaviour. Custom range is clamped to the fiscal period: cross-year
* ranges are out of scope.
*/
export function ReportDateRange({
periodStart,
periodEnd,
value,
onChange,
defaultPreset = 'ytd',
storageKeyPrefix = STORAGE_KEY_PREFIX,
className,
}: Props) {
const t = useTranslations('reports')
const { company } = useCompany()
const [preset, setPreset] = useState<Preset>(defaultPreset)
// Restore last-used preset per company, then resolve it against the
// current fiscal period. The period selector lives upstream: when it
// changes, we re-resolve so the dates always sit inside the visible year.
useEffect(() => {
if (!company?.id || typeof window === 'undefined') return
const stored = window.localStorage.getItem(storageKeyPrefix + company.id) as Preset | null
const initial: Preset = stored && PRESETS.includes(stored) ? stored : defaultPreset
setPreset(initial)
if (initial !== 'custom') {
onChange(resolvePreset(initial, periodStart, periodEnd, todayIso()))
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [company?.id, periodStart, periodEnd, storageKeyPrefix, defaultPreset])
const handlePreset = useCallback(
(next: Preset) => {
setPreset(next)
if (company?.id && typeof window !== 'undefined') {
window.localStorage.setItem(storageKeyPrefix + company.id, next)
}
if (next === 'custom') {
// Seed the custom inputs with whatever is currently active so the
// user can nudge them rather than start from scratch.
if (!value.fromDate && !value.toDate) {
onChange({ fromDate: periodStart, toDate: clampToPeriod(todayIso(), periodStart, periodEnd) })
}
return
}
onChange(resolvePreset(next, periodStart, periodEnd, todayIso()))
},
[company?.id, onChange, periodEnd, periodStart, storageKeyPrefix, value.fromDate, value.toDate],
)
const handleFromChange = (raw: string) => {
const next = raw ? clampToPeriod(raw, periodStart, periodEnd) : undefined
onChange({ fromDate: next, toDate: value.toDate })
}
const handleToChange = (raw: string) => {
const next = raw ? clampToPeriod(raw, periodStart, periodEnd) : undefined
onChange({ fromDate: value.fromDate, toDate: next })
}
const presetLabels: Record<Preset, string> = useMemo(
() => ({
full_year: t('date_range_preset_full_year'),
ytd: t('date_range_preset_ytd'),
this_month: t('date_range_preset_this_month'),
last_month: t('date_range_preset_last_month'),
this_quarter: t('date_range_preset_this_quarter'),
custom: t('date_range_preset_custom'),
}),
[t],
)
return (
<div className={cn('flex flex-col gap-2', className)}>
<Label className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
{t('date_range_label')}
</Label>
<div className="flex flex-wrap items-center gap-1.5">
{PRESETS.map((p) => {
const active = preset === p
return (
<button
key={p}
type="button"
onClick={() => handlePreset(p)}
className={cn(
'px-3 py-1.5 text-xs rounded-full border transition-colors duration-150',
active
? 'bg-secondary border-border text-foreground'
: 'bg-transparent border-border text-muted-foreground hover:bg-secondary/60 hover:text-foreground',
)}
>
{presetLabels[p]}
</button>
)
})}
</div>
{preset === 'custom' && (
<div className="flex flex-wrap items-end gap-3 mt-1">
<div className="flex flex-col gap-1">
<Label className="text-xs text-muted-foreground">{t('date_range_from')}</Label>
<Input
type="date"
min={periodStart}
max={periodEnd}
value={value.fromDate ?? ''}
onChange={(e) => handleFromChange(e.target.value)}
className="w-[160px] tabular-nums"
/>
</div>
<div className="flex flex-col gap-1">
<Label className="text-xs text-muted-foreground">{t('date_range_to')}</Label>
<Input
type="date"
min={periodStart}
max={periodEnd}
value={value.toDate ?? ''}
onChange={(e) => handleToChange(e.target.value)}
className="w-[160px] tabular-nums"
/>
</div>
</div>
)}
</div>
)
}
+9
View File
@@ -0,0 +1,9 @@
/**
* Persisted fiscal-year scope: the localStorage key prefix (companyId is
* appended) and the sentinel for an explicit "all years" choice. Lives in
* its own dependency-free module so lib/ code (the reference-data scope
* resolver) can import it without pulling a React component along.
* FiscalYearSelector re-exports both for existing importers.
*/
export const STORAGE_KEY_PREFIX = 'Accounted:fiscal-year:'
export const ALL_YEARS_VALUE = '__all__'