docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
-96
View File
@@ -1,96 +0,0 @@
'use client'
import { useEffect } from 'react'
import posthog from 'posthog-js'
import { isAnalyticsEnabled } from '@/lib/analytics/enabled'
import {
buildPersonProperties,
buildGroupProperties,
type AnalyticsCompanyInput,
type AnalyticsUserInput,
} from '@/lib/analytics/properties'
/**
* Attaches the logged-in user and their active company to PostHog.
*
* Mounted from app/(dashboard)/layout.tsx, which is the only place that has
* both the auth user and the resolved company in one render, and gated there
* on `!isSandbox` so demo companies never pollute funnels or get surveyed.
*
* identify() runs on every dashboard load rather than only at login, per
* PostHog's guidance: with `persistence: 'memory'` (see
* instrumentation-client.ts) nothing survives a hard reload, so re-identifying
* on each load is what keeps person-level analytics correct without storing
* anything on the device.
*
* A useEffect is correct here despite the general rule against it: this
* synchronises with an external, non-React system (the PostHog SDK).
*/
export default function AnalyticsIdentify({
user,
company,
identityHash,
}: {
user: AnalyticsUserInput
company: AnalyticsCompanyInput
/** Server-computed HMAC of userId (lib/analytics/identity-hash.ts). Null
* when POSTHOG_SECRET_API_KEY is unset, which is normal off hosted. */
identityHash?: string | null
}) {
const { userId, email, fullName, role } = user
const {
id: companyId,
name: companyName,
entityType,
accountingFramework,
paysSalaries,
trialEndsAt,
capabilities,
} = company
// The dashboard layout rebuilds the props objects (and the capabilities
// array) on every render, so depending on them directly would re-fire
// identify on every navigation. Depend on primitives, and collapse the
// array to a stable string key.
const capabilityKey = capabilities ? [...capabilities].sort().join(',') : ''
useEffect(() => {
if (!isAnalyticsEnabled()) return
// Verified identity first: it tells PostHog Support this browser really
// is `userId`, so a support ticket follows the person across devices
// instead of being scoped to one browser session. Without the secret key
// this is skipped and tickets fall back to email recovery.
if (identityHash) posthog.setIdentity(userId, identityHash)
posthog.identify(userId, buildPersonProperties({ userId, email, fullName, role }))
posthog.group(
'company',
companyId,
buildGroupProperties({
id: companyId,
name: companyName,
entityType,
accountingFramework,
paysSalaries,
trialEndsAt,
capabilities: capabilityKey ? capabilityKey.split(',') : undefined,
})
)
}, [
userId,
email,
fullName,
role,
companyId,
companyName,
entityType,
accountingFramework,
paysSalaries,
trialEndsAt,
capabilityKey,
identityHash,
])
return null
}
-42
View File
@@ -1,42 +0,0 @@
'use client'
import { useEffect } from 'react'
// How long after the last scroll event the scrollbar stays visible.
const IDLE_MS = 700
/**
* Reveals scrollbars only while their container is actually scrolling.
* One capture-phase listener on the document catches scroll events from
* every scroll container (panel, sidebar, dialogs, dropdown lists) and
* stamps .is-scrolling on the scrolled element; globals.css makes the
* thumb visible for that class and transparent otherwise. Renders nothing.
*/
export function ScrollbarReveal() {
useEffect(() => {
const timers = new WeakMap<Element, number>()
const onScroll = (e: Event) => {
const target = e.target
const el =
target === document ? document.documentElement : (target as Element)
if (!(el instanceof Element)) return
el.classList.add('is-scrolling')
const prev = timers.get(el)
if (prev) window.clearTimeout(prev)
timers.set(
el,
window.setTimeout(() => el.classList.remove('is-scrolling'), IDLE_MS),
)
}
document.addEventListener('scroll', onScroll, {
capture: true,
passive: true,
})
return () =>
document.removeEventListener('scroll', onScroll, { capture: true })
}, [])
return null
}
@@ -1,123 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import Link from 'next/link'
import { Pin, ArrowUpRight } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { SettingsGroup, SettingsRow } from '@/components/settings/SettingsRows'
import type { AgentCompetence, AtomTier, FactKind, FactSource } from '@/lib/agent-context/agent-competence'
/**
* Read-only views of the agent's competence (domain-knowledge atoms) and top
* learned facts, for the "Vad din agent vet" overview. Each renders as a flat
* settings group (Fönster language) with its description behind the group
* "?" help. Full editable management lives in /settings/assistant; each
* links there.
*/
const TIER_ORDER: AtomTier[] = ['horizontal', 'vertical', 'modifier']
export function CompetenceCard({ competence }: { competence: AgentCompetence }) {
const t = useTranslations('agentKnowledge')
const { atoms } = competence
const activeAtoms = atoms.filter((a) => a.active).length
const tierLabel = (tier: AtomTier) =>
tier === 'horizontal' ? t('tier_horizontal') : tier === 'vertical' ? t('tier_vertical') : t('tier_modifier')
return (
<SettingsGroup label={t('comp_title')} help={t('comp_desc')}>
{atoms.length === 0 ? (
<p className="px-1 py-3 text-sm text-muted-foreground">{t('comp_empty')}</p>
) : (
<>
{/* One row per tier: micro-label left, atom chips right. Dormant
atoms are the exception the outline chip variant marks. */}
{TIER_ORDER.map((tier) => {
const items = atoms.filter((a) => a.tier === tier)
if (items.length === 0) return null
return (
<SettingsRow key={tier} label={tierLabel(tier)} align="baseline">
<div className="flex flex-wrap gap-2">
{items.map((a) => (
<Badge
key={a.id}
variant={a.active ? 'secondary' : 'outline'}
className={a.active ? '' : 'text-muted-foreground'}
title={a.description}
>
{a.title}
{!a.active && tier !== 'horizontal' && (
<span className="ml-1.5 opacity-70">· {t('badge_dormant')}</span>
)}
</Badge>
))}
</div>
</SettingsRow>
)
})}
<div className="flex items-center justify-between gap-4 px-1 pt-3 text-xs text-muted-foreground">
<span className="tabular-nums">{t('comp_count', { total: atoms.length, active: activeAtoms })}</span>
<ManageLink href="/settings/assistant?view=skills" label={t('comp_manage')} />
</div>
</>
)}
</SettingsGroup>
)
}
export function FactsCard({ competence }: { competence: AgentCompetence }) {
const t = useTranslations('agentKnowledge')
const { facts, factsActiveTotal } = competence
const kindLabel = (k: FactKind) =>
k === 'fact' ? t('kind_fact') : k === 'preference' ? t('kind_preference') : k === 'pattern' ? t('kind_pattern') : t('kind_correction')
const sourceLabel = (s: FactSource) =>
s === 'composer' ? t('source_composer') : s === 'user_taught' ? t('source_user_taught') : s === 'agent_learned' ? t('source_agent_learned') : t('source_derived')
return (
<SettingsGroup label={t('facts_title')} help={t('facts_desc')}>
{facts.length === 0 ? (
<p className="px-1 py-3 text-sm text-muted-foreground">{t('facts_empty')}</p>
) : (
<>
{/* Flat hairline rows: fact content with its kind/source flowing
inline as muted text; the pin marks the exception. */}
<ul>
{facts.map((f) => (
<li key={f.id} className="flex items-start gap-2 border-b border-border px-1 py-3">
{f.is_pinned ? (
<Pin role="img" className="mt-1 h-3.5 w-3.5 shrink-0 fill-current text-muted-foreground" aria-label={t('facts_pinned')} />
) : (
<span className="mt-1 h-3.5 w-3.5 shrink-0" aria-hidden />
)}
<div className="flex min-w-0 flex-1 flex-wrap items-baseline gap-x-2 gap-y-1">
<span className="text-sm text-foreground">{f.content}</span>
<span className="text-[11px] text-muted-foreground">
{kindLabel(f.kind)} · {sourceLabel(f.source)}
</span>
</div>
</li>
))}
</ul>
<div className="flex items-center justify-between gap-4 px-1 pt-3 text-xs text-muted-foreground">
<span className="tabular-nums">
{factsActiveTotal > facts.length ? t('facts_more', { n: factsActiveTotal - facts.length }) : ''}
</span>
<ManageLink href="/settings/assistant?view=memory" label={t('facts_manage')} />
</div>
</>
)}
</SettingsGroup>
)
}
function ManageLink({ href, label }: { href: string; label: string }) {
return (
<Button asChild variant="outline" size="sm">
<Link href={href}>
{label}
<ArrowUpRight className="ml-1 h-3 w-3" />
</Link>
</Button>
)
}
@@ -1,86 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Skeleton } from '@/components/ui/skeleton'
import { EmptyState } from '@/components/ui/empty-state'
import { Brain } from 'lucide-react'
import type { LedgerContext } from '@/lib/agent-context/ledger-context'
import type { DeepLedgerContext } from '@/lib/agent-context/ledger-deep'
import type { AgentCompetence } from '@/lib/agent-context/agent-competence'
import { AgentKnowledgeView } from './AgentKnowledgeView'
interface KnowledgePayload {
context: LedgerContext
deep: DeepLedgerContext
competence: AgentCompetence
companyName: string
}
/**
* Client wrapper for the "Vad din agent vet" view inside the assistant
* settings hub. Fetches the ledger context from /api/agent/knowledge on mount
* (lazy: this panel only renders when the Kunskap tab is opened, since Radix
* unmounts inactive tabs). Fetching client-side rather than via a server prop
* is deliberate: the settings sections mount as propless components in BOTH
* the full-page rail and the routed settings modal, so a server fetch wouldn't
* reach the modal.
*/
export function AgentKnowledgePanel() {
const t = useTranslations('agentKnowledge')
const [payload, setPayload] = useState<KnowledgePayload | null>(null)
const [error, setError] = useState(false)
useEffect(() => {
let cancelled = false
fetch('/api/agent/knowledge')
.then((res) => {
if (!res.ok) throw new Error(`knowledge fetch failed: ${res.status}`)
return res.json()
})
.then((json) => {
if (!cancelled) setPayload(json.data as KnowledgePayload)
})
.catch(() => {
if (!cancelled) setError(true)
})
return () => {
cancelled = true
}
}, [])
if (error) {
return (
<EmptyState
icon={Brain}
title={t('load_error_title')}
description={t('load_error_description')}
/>
)
}
if (!payload) {
// Mirrors the loaded layout: graph hero, section header, two profile cards.
return (
<div className="space-y-8">
<Skeleton className="h-96 w-full rounded-lg" />
<div className="space-y-4">
<Skeleton className="h-4 w-40" />
<div className="grid gap-4 md:grid-cols-2">
<Skeleton className="h-48 w-full rounded-lg" />
<Skeleton className="h-48 w-full rounded-lg" />
</div>
</div>
</div>
)
}
return (
<AgentKnowledgeView
context={payload.context}
deep={payload.deep}
competence={payload.competence}
companyName={payload.companyName}
/>
)
}
@@ -1,182 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import { Brain } from 'lucide-react'
import {
SettingsGroup,
SettingsRow,
SettingsSectionHeader,
} from '@/components/settings/SettingsRows'
import { AccountNumber } from '@/components/ui/account-number'
import { EmptyState } from '@/components/ui/empty-state'
import { formatDateLong } from '@/lib/utils'
import type { LedgerContext } from '@/lib/agent-context/ledger-context'
import type { DeepLedgerContext } from '@/lib/agent-context/ledger-deep'
import type { AgentCompetence } from '@/lib/agent-context/agent-competence'
import { LedgerGraph } from './LedgerGraph'
import { CompetenceCard, FactsCard } from './AgentCompetenceSections'
// Swedish VAT (moms) treatment codes stay Swedish in both locales, like BAS
// account names and momsdeklaration labels (.claude/rules/i18n.md).
const VAT_LABELS: Record<string, string> = {
standard_25: 'Moms 25%',
standard_12: 'Moms 12%',
standard_6: 'Moms 6%',
reduced_12: 'Moms 12%',
reduced_6: 'Moms 6%',
reverse_charge: 'Omvänd moms',
reverse_charge_eu: 'Omvänd moms (EU)',
reverse_charge_services: 'Omvänd moms (tjänster)',
eu_reverse_charge_services: 'Omvänd moms (EU-tjänster)',
eu_goods: 'EU-varor',
export: 'Export',
exempt: 'Momsfri',
no_vat: 'Ingen moms',
}
function vatLabel(code: string | null): string | null {
if (!code) return null
return VAT_LABELS[code] ?? code
}
export function AgentKnowledgeView({
context,
deep,
competence,
companyName,
}: {
context: LedgerContext
deep: DeepLedgerContext
competence: AgentCompetence
companyName: string
}) {
const t = useTranslations('agentKnowledge')
const { meta, explicit_rules, vat_profile, conventions } = context
const entities = [...deep.counterparty_entities, ...deep.supplier_entities]
const isEmpty = meta.coverage.posted_entries_window === 0 && entities.length === 0 && explicit_rules.length === 0
if (isEmpty) {
// No bookings yet, but the agent still ships with competence and may
// already remember facts: show those rather than a dead end.
return (
<div className="space-y-8">
<EmptyState
icon={Brain}
title={t('empty_title')}
description={t('empty_description')}
actionLabel={t('empty_action')}
actionHref="/transactions"
/>
<div>
<CompetenceCard competence={competence} />
<FactsCard competence={competence} />
</div>
</div>
)
}
const methodLabel =
conventions.accounting_method === 'accrual'
? t('method_accrual')
: conventions.accounting_method === 'cash'
? t('method_cash')
: t('method_unknown')
const periodLabel =
vat_profile.moms_period === 'monthly'
? t('period_monthly')
: vat_profile.moms_period === 'quarterly'
? t('period_quarterly')
: vat_profile.moms_period === 'yearly'
? t('period_yearly')
: (vat_profile.moms_period ?? t('unknown'))
return (
<div className="space-y-8">
{/* The cinematic hero: a self-contained dark panel with its own header */}
<LedgerGraph deep={deep} companyName={companyName} />
{/* "Regler & profil": user-authored rules + observed VAT + conventions,
in the flat settings language (groups under eyebrow labels, static
descriptions behind the group "?"). Minne and Kompetens have their
own top-level views, so no second tab row here. */}
<section>
<SettingsSectionHeader title={t('tab_config')} />
{explicit_rules.length > 0 && (
<SettingsGroup label={t('rules_title')} help={t('rules_description')}>
{explicit_rules.map((r, i) => {
const vat = vatLabel(r.vat_treatment)
return (
<div
key={r.rule_name + r.match + i}
className="flex flex-wrap items-baseline gap-x-3 gap-y-1 border-b border-border px-1 py-3"
>
<span className="text-sm">{r.rule_name}</span>
<span className="min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground">
{r.match}
</span>
<span className="flex shrink-0 flex-wrap items-baseline gap-x-2 text-xs text-muted-foreground">
{r.account_number ? (
<AccountNumber number={r.account_number} showName size="sm" />
) : (
<span>-</span>
)}
{vat && <span>· {vat}</span>}
<span>· {t('src_rule')}</span>
</span>
</div>
)
})}
</SettingsGroup>
)}
<SettingsGroup label={t('vat_title')} help={t('vat_description')}>
<SettingsRow label={t('vat_registered_label')}>
<span>{vat_profile.registered ? t('yes') : t('no')}</span>
</SettingsRow>
<SettingsRow label={t('vat_period_label')}>
<span>{periodLabel}</span>
</SettingsRow>
<SettingsRow label={t('vat_treatments_label')}>
{vat_profile.treatments_used_12m.length === 0 ? (
<span className="text-muted-foreground">{t('vat_no_treatments')}</span>
) : (
<span>{vat_profile.treatments_used_12m.map((code) => vatLabel(code)).join(' · ')}</span>
)}
</SettingsRow>
</SettingsGroup>
<SettingsGroup label={t('conv_title')} help={t('conv_description')}>
<SettingsRow label={t('conv_method_label')}>
<span>{methodLabel}</span>
</SettingsRow>
<SettingsRow label={t('conv_series_label')}>
{conventions.voucher_series_in_use.length === 0 ? (
<span className="text-muted-foreground">-</span>
) : (
<span className="font-mono text-xs">{conventions.voucher_series_in_use.join(', ')}</span>
)}
</SettingsRow>
<SettingsRow label={t('conv_salary_label')}>
<span>{conventions.salary_run_active ? t('yes') : t('no')}</span>
</SettingsRow>
{conventions.typical_booking_lag_days !== null && (
<SettingsRow label={t('conv_lag_label')}>
<span className="tabular-nums">
{t('meta_lag_value', { days: conventions.typical_booking_lag_days })}
</span>
</SettingsRow>
)}
</SettingsGroup>
</section>
<p className="text-right text-xs text-muted-foreground">
{t('footer_basis', { entries: meta.coverage.posted_entries_window, date: formatDateLong(meta.computed_at) })}
</p>
</div>
)
}
-842
View File
@@ -1,842 +0,0 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { motion, AnimatePresence, useReducedMotion, animate } from 'framer-motion'
import { RotateCw } from 'lucide-react'
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
import { useBasReference } from '@/lib/bookkeeping/use-bas-reference'
import { useTranslations } from 'next-intl'
import { formatAmount, formatCurrency } from '@/lib/utils'
import type { DeepEntity, DeepLedgerContext } from '@/lib/agent-context/ledger-deep'
import { entityMagnitude, selectAccountRing, type RingBasis } from './ledger-graph-magnitude'
/**
* "Reconciliation Aurora" - the cinematic hero of the "Vad din agent vet" page.
*
* A self-contained dark SVG panel. The company is a luminous hub; the BAS
* accounts it books to form an inner ring of wedges (each wedge sized by the
* money that flows through it); the counterparties/suppliers live in the outer
* band, each constrained to its dominant account's angular slice so threads can
* never cross between accounts (the anti-hairball guarantee).
*
* Four orthogonal channels, so no two compete:
* - node AREA = magnitude (radius = k·√x), see ledger-graph-magnitude.ts
* - node COLOUR = booking cadence (weekly / monthly / irregular) - the one
* semantic axis; everything else stays achromatic
* - node SHAPE = kind (supplier = filled, counterparty = open ring)
* - node FOCUS = the agent's confidence in the account mapping, rendered as
* optical depth of field (sure = crisp/forward, unsure = soft)
*
* On mount it performs the signature act: for the most-merged payees, the raw
* bank descriptors ("CLAUDE.AI", "Anthropic PBC", "claude.ai*sub") fly in as
* ghost chips and magnetically collapse into one named node with a "×N" badge -
* the agent resolving chaos into knowledge, live, in front of the customer.
*
* Deterministic (seeded jitter, fixed input order) so the demo looks identical
* on every load. Motion is CSS-driven (single-clock idle, GPU dash pulses) with
* framer only orchestrating the entrance, the merge and the hover card. Fully
* keyboard-navigable; a visually-hidden table carries the payload for readers;
* honours prefers-reduced-motion (jumps straight to the settled state).
*/
const W = 1000
const H = 1000
const CX = W / 2
const CY = H / 2
const R_HUB = 34
const R_ACCOUNT = 178
const R_PAYEE_MIN = 258
const R_PAYEE_MAX = 432
const WEDGE_GAP = 0.07 // radians of padding between account wedges
// This panel is its own dark world regardless of the app theme, so the depth of
// field, the glow and the cadence hues all read. Achromatic chrome; colour only
// ever means cadence.
const INK = '#0a0a0c'
const PAPER = '#ecebe6'
const HAIR = 'rgba(236,235,230,0.13)'
const HAIR_STRONG = 'rgba(236,235,230,0.30)'
const MUTED = 'rgba(236,235,230,0.52)'
const CAD: Record<Cadence, string> = {
weekly: '#e0895f', // terracotta - fast, recurring
monthly: '#d7a648', // ochre - monthly
irregular: '#83a98d', // sage - one-off / irregular
}
// Depth-of-field buckets: stdDeviation in viewBox units (~0.64× on screen).
const DOF = [0, 1.7, 3.4, 5.2]
type Cadence = 'weekly' | 'monthly' | 'irregular'
interface Payee {
id: string
entity: DeepEntity
accountNumber: string
x: number
y: number
r: number
cadence: Cadence
bucket: number // depth-of-field bucket index into DOF
thread: string // svg path from hub to node, bowed through the account anchor
labelRight: boolean
revealDelay: number
merge: boolean // show the ghost-descriptor collapse on mount
chips: string[]
}
interface Account {
number: string
name: string | null
x: number
y: number
midAngle: number
arc: string
revealDelay: number
}
interface Model {
accounts: Account[]
payees: Payee[]
truncated: boolean
/** What the wedge widths and node areas actually measure. See the legend. */
basis: RingBasis
totals: { tx: number; payees: number; accounts: number }
}
function polar(cx: number, cy: number, r: number, a: number) {
return { x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) }
}
function arcPath(cx: number, cy: number, r: number, a0: number, a1: number) {
const s = polar(cx, cy, r, a0)
const e = polar(cx, cy, r, a1)
const large = a1 - a0 > Math.PI ? 1 : 0
return `M ${s.x.toFixed(2)} ${s.y.toFixed(2)} A ${r} ${r} 0 ${large} 1 ${e.x.toFixed(2)} ${e.y.toFixed(2)}`
}
function lerp(a: number, b: number, t: number) {
return a + (b - a) * t
}
// Deterministic [0,1) hash of a string (xmur3 → mulberry32), so seeded jitter is
// byte-identical on every render: the live demo never reshuffles.
function rand01(seed: string): number {
let h = 1779033703 ^ seed.length
for (let i = 0; i < seed.length; i++) {
h = Math.imul(h ^ seed.charCodeAt(i), 3432918353)
h = (h << 13) | (h >>> 19)
}
h = Math.imul(h ^ (h >>> 16), 2246822507)
h = Math.imul(h ^ (h >>> 13), 3266489909)
h ^= h >>> 16
return (h >>> 0) / 4294967296
}
function cadenceOf(e: DeepEntity): Cadence {
const cd = e.cadence_days
if (cd === null || e.occurrences < 3) return 'irregular'
if (cd >= 4 && cd <= 10) return 'weekly'
if (cd > 10 && cd <= 45) return 'monthly'
return 'irregular'
}
function bucketOf(share: number | null): number {
if (share === null) return 3
if (share >= 0.85) return 0
if (share >= 0.7) return 1
if (share >= 0.5) return 2
return 3
}
// Center-out slot order: biggest spender sits at the wedge's angular centre.
function centerOut(n: number): number[] {
const mid = (n - 1) / 2
return Array.from({ length: n }, (_, i) => i).sort(
(a, b) => Math.abs(a - mid) - Math.abs(b - mid),
)
}
function buildModel(deep: DeepLedgerContext): Model {
const all: DeepEntity[] = [
...(deep?.counterparty_entities ?? []),
...(deep?.supplier_entities ?? []),
].filter((e) => e.dominant_account_number)
const totalTx = all.reduce((s, e) => s + e.occurrences, 0)
// Grouping, weighting, ranking and truncation of the account ring live in
// ledger-graph-magnitude.ts so they can be unit tested. The one rule that
// matters here: every wedge weight below is expressed in the SAME unit
// (`ring.basis`), so the shared denominator never adds kronor to booking
// counts and no account is squeezed to an invisible sliver, or truncated
// away entirely, just for being measured differently.
const ring = selectAccountRing(all)
const { basis, groups, truncated } = ring
// The most name-merged payees earn the on-mount "descriptors collapse" moment.
const mergeIds = new Set(
all
.filter((e) => e.variant_count >= 3)
.sort((a, b) => b.variant_count - a.variant_count)
.slice(0, 5)
.map((e) => `${e.dominant_account_number}:${e.key}`),
)
const accounts: Account[] = []
const payees: Payee[] = []
const spans = 2 * Math.PI - WEDGE_GAP * groups.length
let angle = -Math.PI / 2 + WEDGE_GAP / 2
groups.forEach((g, gi) => {
const width = spans * (g.weight / ring.totalWeight)
const mid = angle + width / 2
const anchor = polar(CX, CY, R_ACCOUNT, mid)
accounts.push({
number: g.number,
name: getAccountDescription(g.number)?.name ?? null,
x: anchor.x,
y: anchor.y,
midAngle: mid,
arc: arcPath(CX, CY, R_ACCOUNT, angle + width * 0.04, angle + width * 0.96),
revealDelay: 0.2 + gi * 0.06,
})
const n = g.items.length
const inner = width * 0.16
const order = centerOut(n) // order[rank] = slot for that rank (rank 0 = biggest → centre)
g.items.forEach((e, rank) => {
const slot = order[rank]
const t = n === 1 ? 0.5 : slot / (n - 1)
const pa = angle + inner + t * (width - 2 * inner)
// Same unit as the wedge it sits in, so a node is never sized against a
// maximum measured in something else.
const sizeFrac = Math.sqrt(entityMagnitude(e, basis) / ring.maxMagnitude)
const radius = lerp(R_PAYEE_MIN, R_PAYEE_MAX, rand01(e.key)) + sizeFrac * 14
const pos = polar(CX, CY, Math.min(radius, R_PAYEE_MAX + 10), pa)
const id = `${g.number}:${e.key}`
payees.push({
id,
entity: e,
accountNumber: g.number,
x: pos.x,
y: pos.y,
r: 7 + 19 * sizeFrac,
cadence: cadenceOf(e),
bucket: bucketOf(e.dominant_account_share),
thread: `M ${CX} ${CY} Q ${anchor.x.toFixed(2)} ${anchor.y.toFixed(2)} ${pos.x.toFixed(2)} ${pos.y.toFixed(2)}`,
labelRight: Math.cos(pa) >= 0,
revealDelay: 0.55 + gi * 0.05 + rank * 0.045,
merge: mergeIds.has(id),
chips: e.variants.slice(0, 6),
})
angle += 0
})
angle += width + WEDGE_GAP
})
return {
accounts,
payees,
truncated,
basis,
totals: { tx: totalTx, payees: payees.length, accounts: accounts.length },
}
}
// Weekly beats faster than monthly; irregular drifts slow. Seconds per pulse.
const PULSE_DUR: Record<Cadence, number> = { weekly: 1.15, monthly: 2.7, irregular: 4.3 }
export function LedgerGraph({ deep, companyName }: { deep: DeepLedgerContext; companyName: string }) {
const t = useTranslations('agentKnowledge')
// Loads the BAS chart chunk after mount and re-renders once names and
// descriptions for non-hardcoded accounts are available.
useBasReference()
const reduce = useReducedMotion() ?? false
const model = useMemo(() => buildModel(deep), [deep])
const [hover, setHover] = useState<string | null>(null)
const [runKey, setRunKey] = useState(0)
// Track which run has finished its intro rather than a bare boolean, so a
// replay (runKey++) resets to "unresolved" by derivation, without a
// setState-in-effect. Chips fly in, then collapse into their node.
const [resolvedRun, setResolvedRun] = useState(-1)
useEffect(() => {
const id = setTimeout(() => setResolvedRun(runKey), reduce ? 0 : 1300)
return () => clearTimeout(id)
}, [runKey, reduce])
const resolved = reduce || resolvedRun === runKey
const payeeById = useMemo(() => new Map(model.payees.map((p) => [p.id, p])), [model])
function payeeCaption(p: Payee): string {
const e = p.entity
const nm = getAccountDescription(e.dominant_account_number ?? '')?.name
return [
e.name,
t('cap_bookings', { n: e.occurrences }),
e.variant_count > 1 ? t('cap_variants', { n: e.variant_count }) : null,
t(`cadence_${p.cadence}`),
formatCurrency(e.total_amount),
`${e.dominant_account_number}${nm ? ` ${nm}` : ''}${
e.dominant_account_share !== null ? ` · ${Math.round(e.dominant_account_share * 100)}%` : ''
}`,
]
.filter(Boolean)
.join(' · ')
}
if (model.payees.length === 0) {
return (
<div
className="rounded-lg border border-border p-16 text-center text-sm"
style={{ background: INK, borderColor: HAIR, color: MUTED }}
>
{t('none_cp')}
</div>
)
}
// Which ids are "lit" given the current hover (a payee lights its account and
// the reverse); everything else recedes into the depth of field.
const active = new Set<string>()
if (hover) {
active.add(hover)
if (hover.startsWith('acc:')) {
const num = hover.slice(4)
model.payees.forEach((p) => p.accountNumber === num && active.add(p.id))
} else {
const p = payeeById.get(hover)
if (p) active.add(`acc:${p.accountNumber}`)
}
}
const lit = (id: string) => !hover || active.has(id)
const hoveredPayee = hover && !hover.startsWith('acc:') ? payeeById.get(hover) ?? null : null
return (
<div
className="relative overflow-hidden rounded-lg border border-border"
style={{
borderColor: HAIR_STRONG,
background: `radial-gradient(120% 120% at 50% 42%, #17171b 0%, ${INK} 62%)`,
}}
>
<style>{keyframes}</style>
{/* header */}
<div className="flex items-start justify-between gap-4 px-5 pt-5 md:px-7 md:pt-6">
<div>
<h2
className="font-display text-lg tracking-tight md:text-xl"
style={{ color: PAPER }}
>
{t('graph_title')}
</h2>
<p className="mt-1 max-w-md text-sm leading-relaxed" style={{ color: MUTED }}>
{t('graph_description')}
</p>
</div>
{!reduce && (
<button
type="button"
onClick={() => setRunKey((k) => k + 1)}
className="inline-flex shrink-0 items-center gap-2 rounded-full border px-3 py-1.5 text-xs transition-colors"
style={{ borderColor: HAIR_STRONG, color: MUTED }}
>
<RotateCw className="h-3.5 w-3.5" />
{t('graph_replay')}
</button>
)}
</div>
{/* stage */}
<div className="relative mx-auto aspect-square w-full max-w-[680px]">
<svg
viewBox={`0 0 ${W} ${H}`}
className="block h-full w-full"
role="img"
aria-label={t('graph_aria', { payees: model.payees.length, accounts: model.accounts.length })}
>
<defs>
{DOF.map((sd, i) => (
<filter key={i} id={`dof-${i}`} x="-50%" y="-50%" width="200%" height="200%">
<feGaussianBlur stdDeviation={sd} />
</filter>
))}
<radialGradient id="aurora-hub" cx="50%" cy="50%" r="50%">
<stop offset="0%" stopColor={PAPER} stopOpacity="0.22" />
<stop offset="100%" stopColor={PAPER} stopOpacity="0" />
</radialGradient>
</defs>
<g key={runKey}>
{/* account wedge arcs (the spine) */}
{model.accounts.map((a) => (
<g key={`acc:${a.number}`} opacity={lit(`acc:${a.number}`) ? 1 : 0.14}>
<motion.path
d={a.arc}
fill="none"
stroke={HAIR_STRONG}
strokeWidth={1.4}
strokeLinecap="round"
initial={reduce ? false : { pathLength: 0, opacity: 0 }}
animate={{ pathLength: 1, opacity: 1 }}
transition={{ duration: 0.7, delay: a.revealDelay, ease: 'easeInOut' }}
/>
<AccountHit account={a} caption={accountCaption(a)} onHover={setHover} lit={lit(`acc:${a.number}`)} />
</g>
))}
{/* threads: base vein + travelling cadence pulse */}
{model.payees.map((p) => (
<g key={`thread:${p.id}`} opacity={lit(p.id) ? 1 : 0.08}>
<motion.path
d={p.thread}
fill="none"
stroke={PAPER}
strokeOpacity={0.16}
strokeWidth={0.9 + 1.1 * (p.entity.dominant_account_share ?? 0.6)}
initial={reduce ? false : { pathLength: 0 }}
animate={{ pathLength: 1 }}
transition={{ duration: 0.6, delay: p.revealDelay, ease: 'easeOut' }}
/>
<path
d={p.thread}
fill="none"
stroke={CAD[p.cadence]}
strokeWidth={2.4}
strokeLinecap="round"
pathLength={1}
className={reduce ? undefined : 'aurora-pulse'}
style={{
strokeDasharray: '0.035 1',
opacity: resolved && lit(p.id) ? 0.9 : 0,
transition: 'opacity .6s ease',
animationDuration: `${PULSE_DUR[p.cadence]}s`,
animationDelay: `${rand01(p.id + 'd') * -PULSE_DUR[p.cadence]}s`,
}}
/>
</g>
))}
{/* payee nodes, blurry buckets first so the confident ones sit on top */}
{[...model.payees]
.sort((a, b) => b.bucket - a.bucket)
.map((p) => (
<PayeeGlyph
key={p.id}
p={p}
reduce={reduce}
resolved={resolved}
lit={lit(p.id)}
focused={hover === p.id}
caption={payeeCaption(p)}
onHover={setHover}
/>
))}
{/* company hub */}
<g>
<circle cx={CX} cy={CY} r={R_HUB * 2.6} fill="url(#aurora-hub)" />
<circle
cx={CX}
cy={CY}
r={R_HUB}
fill={PAPER}
className={reduce ? undefined : 'aurora-breathe'}
style={{ transformOrigin: `${CX}px ${CY}px` }}
/>
<text
x={CX}
y={CY}
fill={INK}
fontSize={20}
fontWeight={600}
textAnchor="middle"
dominantBaseline="central"
>
{initialsOf(companyName)}
</text>
</g>
</g>
</svg>
{/* tally: the "understood" count-up */}
<div
className="pointer-events-none absolute bottom-3 left-4 text-xs tabular-nums md:bottom-4 md:left-6"
style={{ color: MUTED }}
>
<span style={{ color: PAPER }}>
<CountUp target={model.totals.tx} run={runKey} reduce={reduce} />
</span>{' '}
{t('graph_tally', {
payees: model.totals.payees,
accounts: model.totals.accounts,
})}
</div>
{/* hover detail card, anchored to the node */}
<AnimatePresence>
{hoveredPayee && (
<DetailCard key={hoveredPayee.id} p={hoveredPayee} t={t} />
)}
</AnimatePresence>
</div>
{/* legend */}
<div
className="flex flex-wrap items-center gap-x-5 gap-y-2 border-t px-5 py-3 text-xs md:px-7"
style={{ borderColor: HAIR, color: MUTED }}
>
<span className="inline-flex items-center gap-2">
<Dot fill={CAD.weekly} /> {t('cadence_weekly')}
</span>
<span className="inline-flex items-center gap-2">
<Dot fill={CAD.monthly} /> {t('cadence_monthly')}
</span>
<span className="inline-flex items-center gap-2">
<Dot fill={CAD.irregular} /> {t('cadence_irregular')}
</span>
{/* Says what the sizes actually measure. The ring drops to booking
volume whenever any account lacks a usable amount, and claiming
"Storlek = belopp" there would describe a unit nothing is drawn in. */}
<span className="opacity-70">
{model.basis === 'amount' ? t('legend_size') : t('legend_size_volume')}
</span>
<span className="opacity-70">{t('legend_focus')}</span>
{model.truncated && <span className="italic opacity-70">{t('graph_truncated')}</span>}
</div>
{/* screen-reader alternative: the full payload as a plain list */}
<ul className="sr-only">
{model.payees.map((p) => (
<li key={`sr:${p.id}`}>{payeeCaption(p)}</li>
))}
</ul>
</div>
)
}
function accountCaption(a: Account): string {
return `${a.number}${a.name ? ` · ${a.name}` : ''}`
}
// Enlarged invisible hit target + keyboard focus for an account arc.
function AccountHit({
account,
caption,
onHover,
lit,
}: {
account: Account
caption: string
onHover: (id: string | null) => void
lit: boolean
}) {
const id = `acc:${account.number}`
const inside = polar(CX, CY, R_ACCOUNT - 20, account.midAngle)
return (
<g
tabIndex={0}
role="button"
aria-label={caption}
onMouseEnter={() => onHover(id)}
onMouseLeave={() => onHover(null)}
onFocus={() => onHover(id)}
onBlur={() => onHover(null)}
className="cursor-pointer outline-none [&:focus-visible>circle]:opacity-100"
>
<title>{caption}</title>
<circle cx={account.x} cy={account.y} r={22} fill="transparent" />
<circle cx={account.x} cy={account.y} r={26} fill="none" stroke={PAPER} strokeWidth={1.25} opacity={0} />
<text
x={inside.x}
y={inside.y}
fill={lit ? PAPER : MUTED}
fontSize={13}
fontWeight={500}
textAnchor="middle"
dominantBaseline="central"
style={{ fontFamily: 'var(--font-geist-mono, ui-monospace, monospace)' }}
>
{account.number}
</text>
</g>
)
}
function PayeeGlyph({
p,
reduce,
resolved,
lit,
focused,
caption,
onHover,
}: {
p: Payee
reduce: boolean
resolved: boolean
lit: boolean
focused: boolean
caption: string
onHover: (id: string | null) => void
}) {
const colour = CAD[p.cadence]
const showChips = !reduce && p.merge && !resolved
// The depth-of-field blur only attaches once the entrance spring settles, so
// feGaussianBlur never re-rasterizes per frame while the node is moving (and
// the blur "racking in" as the node comes to rest is the intended focus pull).
const [settled, setSettled] = useState(reduce)
// Only the biggest spenders keep a resting label; the rest reveal on focus.
const bigLabel = p.r >= 14
const label = p.entity.name.length > 16 ? p.entity.name.slice(0, 15) + '…' : p.entity.name
const lx = p.labelRight ? p.r + 8 : -(p.r + 8)
return (
// Positioning lives on a plain <g> (SVG transform attribute) so it can never
// be clobbered by framer's CSS transform on the scaling child below. Hover
// "racks focus" onto a node by dropping it to the crisp filter bucket.
<g
transform={`translate(${p.x} ${p.y})`}
filter={`url(#dof-${focused || !settled ? 0 : p.bucket})`}
tabIndex={0}
role="button"
aria-label={caption}
onMouseEnter={() => onHover(p.id)}
onMouseLeave={() => onHover(null)}
onFocus={() => onHover(p.id)}
onBlur={() => onHover(null)}
className="cursor-pointer outline-none"
>
<title>{caption}</title>
{/* always-full-size transparent hit target */}
<circle cx={0} cy={0} r={Math.max(p.r + 8, 16)} fill="transparent" />
{/* opacity layer: entrance fade + hover dimming. Animates opacity only, so
framer never sets a CSS transform that would fight the attribute. */}
<motion.g
initial={reduce ? false : { opacity: 0 }}
animate={{ opacity: lit ? 1 : 0.12 }}
transition={{ duration: reduce ? 0.2 : 0.4, delay: reduce ? 0 : p.merge ? 0.1 : p.revealDelay }}
>
{/* the money shot: raw bank descriptors that collapse inward. Kept OUT
of the scaling group so they show at full size during the scatter. */}
<AnimatePresence>
{showChips &&
p.chips.map((chip, i) => {
const ang = rand01(p.id + chip) * Math.PI * 2
const rad = 34 + rand01(chip + String(i)) * 52
const ox = Math.cos(ang) * rad
const oy = Math.sin(ang) * rad
return (
<motion.text
key={chip + i}
fontSize={12}
fill={MUTED}
textAnchor="middle"
dominantBaseline="central"
initial={{ opacity: 0, x: ox * 1.55, y: oy * 1.55 }}
animate={{ opacity: 0.7, x: ox, y: oy }}
exit={{ opacity: 0, x: 0, y: 0, scale: 0.4 }}
transition={{ duration: 0.5, delay: 0.1 + i * 0.05, ease: 'easeOut' }}
>
{chip.length > 18 ? chip.slice(0, 17) + '…' : chip}
</motion.text>
)
})}
</AnimatePresence>
{/* scale layer: the node grows in around its centre (fill-box) */}
<motion.g
initial={reduce ? false : { scale: 0 }}
animate={{ scale: 1 }}
onAnimationComplete={() => setSettled(true)}
transition={
reduce
? { duration: 0 }
: { type: 'spring', stiffness: 150, damping: 17, delay: p.merge ? 1.32 : p.revealDelay }
}
style={{ transformBox: 'fill-box', transformOrigin: 'center' }}
>
{/* variant echo ring: faint concentric hint that this node is a merge */}
{p.entity.variant_count > 2 && (
<circle cx={0} cy={0} r={p.r + 5} fill="none" stroke={colour} strokeWidth={0.75} strokeOpacity={0.35} />
)}
{focused && <circle cx={0} cy={0} r={p.r + 6} fill="none" stroke={PAPER} strokeWidth={1.5} />}
{/* the glyph: supplier = filled, counterparty = open */}
<circle
cx={0}
cy={0}
r={p.r}
fill={p.entity.kind === 'supplier' ? colour : INK}
fillOpacity={p.entity.kind === 'supplier' ? 0.85 : 1}
stroke={colour}
strokeWidth={2}
/>
{/* "×N" merge badge */}
{p.entity.variant_count > 1 && (resolved || reduce) && (
<g transform={`translate(${p.r * 0.72} ${-p.r * 0.72})`}>
<circle r={8.5} fill={INK} stroke={colour} strokeWidth={1} />
<text fill={PAPER} fontSize={9} fontWeight={600} textAnchor="middle" dominantBaseline="central">
{p.merge ? (
<CountUp target={p.entity.variant_count} run={resolved ? 1 : 0} reduce={reduce} prefix="×" duration={0.5} />
) : (
`×${p.entity.variant_count}`
)}
</text>
</g>
)}
</motion.g>
{bigLabel && (
<text
x={lx}
y={0}
fill={lit ? PAPER : MUTED}
fontSize={12}
dominantBaseline="central"
textAnchor={p.labelRight ? 'start' : 'end'}
>
{label}
</text>
)}
</motion.g>
</g>
)
}
function DetailCard({ p, t }: { p: Payee; t: ReturnType<typeof useTranslations> }) {
const e = p.entity
const nm = getAccountDescription(e.dominant_account_number ?? '')?.name
const share = e.dominant_account_share !== null ? Math.round(e.dominant_account_share * 100) : null
// Anchor to the node: viewBox coords → % of the square stage. Flip sides so it
// never spills off the edge.
const left = (p.x / W) * 100
const top = (p.y / H) * 100
const right = p.x < CX
return (
<motion.div
className="pointer-events-none absolute z-10 w-60 rounded-lg border p-3 backdrop-blur-sm"
style={{
left: `${left}%`,
top: `${top}%`,
transform: `translate(${right ? '14px' : 'calc(-100% - 14px)'}, -50%)`,
background: 'rgba(14,14,17,0.92)',
borderColor: HAIR_STRONG,
color: PAPER,
}}
initial={{ opacity: 0, scale: 0.94 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.96 }}
transition={{ type: 'spring', stiffness: 320, damping: 26 }}
>
<div className="flex items-center gap-2">
<span className="inline-block h-2.5 w-2.5 shrink-0 rounded-full" style={{ background: CAD[p.cadence] }} />
<span className="truncate font-medium">{e.name}</span>
</div>
<div className="mt-2 space-y-1.5 text-xs" style={{ color: MUTED }}>
<div className="flex justify-between gap-3">
<span>{t('cap_bookings', { n: e.occurrences })}</span>
<span style={{ color: PAPER }}>{t(`cadence_${p.cadence}`)}</span>
</div>
{e.variant_count > 1 && (
<div className="flex justify-between gap-3">
<span>{t('card_variants')}</span>
<span style={{ color: PAPER }}>×{e.variant_count}</span>
</div>
)}
{/* Its own label: `legend_size` now describes whichever unit the ring
settled on, which is not always the amount. Rendered as a plain
number with NO currency suffix: total_amount is the RAW FOREIGN
amount when no SEK equivalent exists (ledger-graph-magnitude.ts),
so labelling it "kr" would show a 500 EUR supplier as "500 kr".
Proper per-currency display is deferred to the RPC fix documented
in that module. */}
<div className="flex justify-between gap-3">
<span>{t('card_amount')}</span>
<span className="tabular-nums" style={{ color: PAPER }}>
{formatAmount(e.total_amount)}
</span>
</div>
<div className="mt-2 border-t pt-2" style={{ borderColor: HAIR }}>
<div className="flex items-center justify-between gap-3">
<span className="font-mono" style={{ color: PAPER }}>
{e.dominant_account_number}
{nm ? ` ${nm}` : ''}
</span>
{share !== null && <span className="tabular-nums">{t('card_confidence', { share })}</span>}
</div>
{share !== null && (
<div className="mt-1.5 h-1 overflow-hidden rounded-full" style={{ background: HAIR }}>
<div className="h-full rounded-full" style={{ width: `${share}%`, background: CAD[p.cadence] }} />
</div>
)}
{e.dominant_account_count != null && e.dominant_account_total != null && (
<div className="mt-1 tabular-nums opacity-80">
{t('card_evidence', { k: e.dominant_account_count, n: e.dominant_account_total })}
</div>
)}
</div>
{e.variants.length > 1 && (
<div className="pt-1 leading-relaxed opacity-80">
{e.variants.slice(0, 4).join(' · ')}
{e.variant_count > 4 ? ' …' : ''}
</div>
)}
</div>
</motion.div>
)
}
function CountUp({
target,
run,
reduce,
prefix = '',
duration = 1,
}: {
target: number
run: number
reduce: boolean
prefix?: string
duration?: number
}) {
const [v, setV] = useState(0)
// Re-run whenever `run` bumps (mount / replay / resolve). No ref-guard: it
// would early-return on React StrictMode's second effect setup in dev and
// freeze the number at 0 (the cleanup already stops any prior animation).
useEffect(() => {
if (reduce) return
const controls = animate(0, target, {
duration,
ease: 'easeOut',
onUpdate: (x) => setV(Math.round(x)),
})
return () => controls.stop()
}, [target, run, reduce, duration])
const shown = reduce ? target : v
return <>{prefix}{shown.toLocaleString('sv-SE')}</>
}
function Dot({ fill }: { fill: string }) {
return <span className="inline-block h-2.5 w-2.5 rounded-full" style={{ background: fill }} />
}
function initialsOf(name: string): string {
return (
name
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((w) => w[0]?.toUpperCase() ?? '')
.join('') || '•'
)
}
// One clock for all continuous life: GPU-friendly CSS keyframes, frozen for
// prefers-reduced-motion users.
const keyframes = `
@keyframes aurora-pulse { to { stroke-dashoffset: -1; } }
@keyframes aurora-breathe { 0%,100% { transform: scale(1); } 50% { transform: scale(1.03); } }
.aurora-pulse { animation-name: aurora-pulse; animation-timing-function: linear; animation-iteration-count: infinite; }
.aurora-breathe { animation: aurora-breathe 5.5s ease-in-out infinite; }
@media (prefers-reduced-motion: reduce) {
.aurora-pulse, .aurora-breathe { animation: none !important; }
}
`
@@ -1,163 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
entityMagnitude,
selectAccountRing,
MAX_ACCOUNTS,
} from '@/components/agent-knowledge/ledger-graph-magnitude'
import type { DeepEntity } from '@/lib/agent-context/ledger-deep'
function entity(overrides: Partial<DeepEntity> & { key: string }): DeepEntity {
return {
name: overrides.key,
variants: [overrides.key],
variant_count: 1,
occurrences: 1,
total_amount: 0,
first_seen: '2026-01-01',
last_seen: '2026-06-01',
cadence_days: null,
dominant_account_number: '5420',
dominant_account_share: 0.8,
dominant_account_count: 4,
dominant_account_total: 5,
kind: 'counterparty',
...overrides,
}
}
/** Share of the ring an account gets, ignoring the fixed inter-wedge padding. */
function share(weight: number, totalWeight: number): number {
return weight / totalWeight
}
describe('selectAccountRing', () => {
it('weighs a SEK-only company by amount, exactly as before', () => {
const ring = selectAccountRing([
entity({ key: 'a', dominant_account_number: '5420', total_amount: 24000, occurrences: 12 }),
entity({ key: 'b', dominant_account_number: '5420', total_amount: 6000, occurrences: 3 }),
entity({ key: 'c', dominant_account_number: '6540', total_amount: 10000, occurrences: 2 }),
])
expect(ring.basis).toBe('amount')
expect(ring.groups.map((g) => g.number)).toEqual(['5420', '6540'])
expect(ring.groups.map((g) => g.weight)).toEqual([30000, 10000])
expect(ring.totalWeight).toBe(40000)
expect(ring.maxMagnitude).toBe(24000)
expect(ring.truncated).toBe(false)
// Biggest spender first inside the wedge: it lands at the angular centre.
expect(ring.groups[0].items.map((e) => e.key)).toEqual(['a', 'b'])
})
it('never puts kronor and booking counts in the same denominator', () => {
// 6570 is booked 4 times but carries no usable amount: on the counterparty
// side that is a spend of 0, and it used to fall back to its booking count
// while 5420 stayed in kronor.
const entities = [
entity({ key: 'big', dominant_account_number: '5420', total_amount: 250000, occurrences: 6 }),
entity({ key: 'nil', dominant_account_number: '6570', total_amount: 0, occurrences: 4 }),
]
const ring = selectAccountRing(entities)
expect(ring.basis).toBe('volume')
expect(ring.groups.map((g) => [g.number, g.weight])).toEqual([
['5420', 6],
['6570', 4],
])
expect(ring.totalWeight).toBe(10)
// No weight is a kronor figure, so nothing can be summed across units.
expect(ring.groups.every((g) => g.weight < 1000)).toBe(true)
// The pre-fix mix: 250 000 kr against 4 bookings in one denominator gave
// 6570 a wedge of 0.0016% of the circle, an invisible sliver. Now it is a
// legible tenth of the ring.
const mixedShare = share(4, 250000 + 4)
expect(mixedShare).toBeLessThan(0.0001)
expect(share(ring.groups[1].weight, ring.totalWeight)).toBeCloseTo(0.4, 10)
})
it('keeps an account with no usable amount inside the truncation cap', () => {
// Ten accounts, cap is nine. The amount-less one is the most-booked account
// the company has, so dropping it is the worst possible choice.
const entities: DeepEntity[] = [
entity({ key: 'unpriced', dominant_account_number: '4000', total_amount: 0, occurrences: 40 }),
]
for (let i = 0; i < 9; i++) {
entities.push(
entity({
key: `priced-${i}`,
dominant_account_number: `55${10 + i}`,
total_amount: 100000 + i,
occurrences: 2,
}),
)
}
const ring = selectAccountRing(entities)
expect(ring.groups).toHaveLength(MAX_ACCOUNTS)
expect(ring.truncated).toBe(true)
expect(ring.groups.map((g) => g.number)).toContain('4000')
// It is the largest wedge, not a survivor by luck.
const unpriced = ring.groups.find((g) => g.number === '4000')
expect(unpriced?.weight).toBe(40)
expect(Math.max(...ring.groups.map((g) => g.weight))).toBe(40)
})
it('sizes nodes against a maximum measured in the same unit', () => {
const ring = selectAccountRing([
entity({ key: 'a', dominant_account_number: '5420', total_amount: 0, occurrences: 9 }),
entity({ key: 'b', dominant_account_number: '6540', total_amount: 500, occurrences: 3 }),
])
expect(ring.basis).toBe('volume')
expect(ring.maxMagnitude).toBe(9)
// The 500 is not compared against 9: under a volume ring it is not read.
expect(entityMagnitude(ring.groups[1].items[0], ring.basis)).toBe(3)
})
it('truncates payees per wedge without changing what the wedge weighs', () => {
const items = Array.from({ length: 8 }, (_, i) =>
entity({ key: `e${i}`, dominant_account_number: '5420', total_amount: 1000, occurrences: 1 }),
)
const ring = selectAccountRing(items, { maxPerAccount: 6 })
expect(ring.truncated).toBe(true)
expect(ring.groups[0].items).toHaveLength(6)
expect(ring.groups[0].weight).toBe(8000)
})
it('drops entities with no dominant account and survives an empty ledger', () => {
const ring = selectAccountRing([
entity({ key: 'orphan', dominant_account_number: null, total_amount: 900, occurrences: 2 }),
])
expect(ring.groups).toEqual([])
expect(ring.basis).toBe('volume')
// Safe divisors: the layout divides by both.
expect(ring.totalWeight).toBe(1)
expect(ring.maxMagnitude).toBe(1)
})
it('is deterministic when weights tie', () => {
const build = (order: string[]) =>
selectAccountRing(
order.map((number) =>
entity({ key: number, dominant_account_number: number, total_amount: 5000, occurrences: 1 }),
),
{ maxAccounts: 2 },
)
expect(build(['6000', '5000', '7000']).groups.map((g) => g.number)).toEqual(['5000', '6000'])
expect(build(['7000', '6000', '5000']).groups.map((g) => g.number)).toEqual(['5000', '6000'])
})
})
describe('entityMagnitude', () => {
it('clamps a negative amount rather than subtracting it from a sibling', () => {
const e = entity({ key: 'credit', total_amount: -4000, occurrences: 2 })
expect(entityMagnitude(e, 'amount')).toBe(0)
expect(entityMagnitude(e, 'volume')).toBe(2)
})
})
@@ -1,176 +0,0 @@
/**
* Pure account-ring selection and weighting for `LedgerGraph`.
*
* Lives outside the component (which is `'use client'` and pure JSX) so the
* rule below can be unit tested: this repo runs Vitest in the `node`
* environment and never renders components, so logic embedded in a component
* is unverifiable by construction. Same arrangement as
* `components/transactions/invoice-candidate-ranking.ts`.
*
* # Why this exists
*
* The ring weighted each account wedge with:
*
* const spend = items.reduce((s, i) => s + Math.max(i.total_amount, 0), 0)
* return spend > 0 ? spend : items.reduce((s, i) => s + i.occurrences, 0)
*
* The fallback is per group, but the weights are then summed into one
* denominator (`shownWeight`) and ranked against each other. So an account
* whose entities carry no usable amount contributed a booking COUNT (say 4)
* into a denominator otherwise made of kronor (say 250 000), and:
*
* - its wedge came out ~0.002% of the circle, i.e. an invisible sliver whose
* payee nodes all collapse onto one angle, and
* - it sorted below every money-weighted account, so it was the first thing
* dropped by the top-`maxAccounts` truncation.
*
* An account the agent genuinely books to therefore vanished from the map for
* no reason other than its magnitude being expressed in a different unit.
* Silent exclusion, which is exactly what this surface must not do.
*
* The rule here: the whole ring is measured in ONE unit. Amount if every
* account has a usable amount, booking volume otherwise. Never a mix. The unit
* is decided over every account, not just the nine that end up shown, because
* the unit is what ranks them: deciding it from the survivors would be circular
* and would reintroduce the truncation bug it exists to prevent. The chosen
* unit is returned as `basis` so the legend can say which one the sizes
* actually mean instead of always claiming "Storlek = belopp".
*
* # What this does NOT fix
*
* `DeepEntity.total_amount` arrives from `get_ledger_deep_context` already
* summed to a single scalar per entity, built as
* `abs(coalesce(t.amount_sek, t.amount))` on the counterparty side and
* `coalesce(si.total_sek, si.total, 0)` on the supplier side. That is SEK when
* a SEK equivalent was recorded and the RAW FOREIGN AMOUNT otherwise, and the
* RPC projects neither `currency` nor a per-row breakdown. A 500 EUR supplier
* invoice with no stored exchange rate therefore reaches this file as the
* number 500, indistinguishable from 500 kr.
*
* Nothing here can undo that: by the time the payload exists the currencies
* have already been added together upstream, and no field survives that would
* let us split them, convert them or even count them. Forming a per-currency
* total on this side would mean inventing one. The fix belongs in the RPC
* (project `total_amount_sek` + per-currency totals + a count of rows with no
* SEK equivalent, and drop the raw-foreign fallback); this file is written so
* that the moment those fields exist, `entityMagnitude` is the single place
* that has to learn about them.
*/
import type { DeepEntity } from '@/lib/agent-context/ledger-deep'
/** How many account wedges the ring shows before it truncates. */
export const MAX_ACCOUNTS = 9
/** How many payee nodes one wedge shows before it truncates. */
export const MAX_PER_ACCOUNT = 6
/**
* The unit the whole ring is measured in.
*
* - `amount`: `total_amount` as delivered by the RPC (kronor, with the caveat
* in the file header). Only chosen when every account has one.
* - `volume`: number of bookings. Currency-free, so it is always available and
* is what the ring falls back to rather than mixing units.
*/
export type RingBasis = 'amount' | 'volume'
export interface RingGroup {
/** BAS account number. Strings, never numbers (CLAUDE.md). */
number: string
/** Entities booked to this account, biggest magnitude first. */
items: DeepEntity[]
/**
* Wedge weight, in `basis` units. Computed over ALL the account's entities,
* including the ones `items` truncated away, so the wedge keeps the size the
* account actually earned.
*/
weight: number
}
export interface RingSelection {
basis: RingBasis
/** Shown accounts, ordered by account number so wedges never swap places. */
groups: RingGroup[]
/** True when accounts or payees were dropped by the display caps. */
truncated: boolean
/** Sum of the shown weights, floored at 1 so it is always a safe divisor. */
totalWeight: number
/** Largest single-entity magnitude among the shown groups, floored at 1. */
maxMagnitude: number
}
/**
* One entity's magnitude in the ring's unit.
*
* `total_amount` is whole kronor (`round(...)::bigint` in the RPC), so summing
* these is exact integer arithmetic and needs no öre rounding. Negative totals
* are clamped to 0 rather than subtracted from a sibling: this drives geometry,
* and a negative radius is not a thing.
*/
export function entityMagnitude(entity: DeepEntity, basis: RingBasis): number {
if (basis === 'volume') return Math.max(entity.occurrences, 0)
return Math.max(entity.total_amount, 0)
}
function sumMagnitude(items: DeepEntity[], basis: RingBasis): number {
return items.reduce((sum, item) => sum + entityMagnitude(item, basis), 0)
}
/**
* Groups entities by their dominant account and picks what the ring shows.
*
* Deterministic end to end: ties break on account number rather than on input
* order, so the demo lays out identically on every load.
*/
export function selectAccountRing(
entities: DeepEntity[],
options: { maxAccounts?: number; maxPerAccount?: number } = {},
): RingSelection {
const maxAccounts = options.maxAccounts ?? MAX_ACCOUNTS
const maxPerAccount = options.maxPerAccount ?? MAX_PER_ACCOUNT
const byAccount = new Map<string, DeepEntity[]>()
for (const entity of entities) {
const account = entity.dominant_account_number
if (!account) continue
const bucket = byAccount.get(account)
if (bucket) bucket.push(entity)
else byAccount.set(account, [entity])
}
const buckets = [...byAccount.entries()]
// The unit decision, made once for the whole ring. An account with no usable
// amount would otherwise be weighted in bookings while its siblings are
// weighted in kronor, and the two get summed into one denominator below.
const basis: RingBasis =
buckets.length > 0 && buckets.every(([, items]) => sumMagnitude(items, 'amount') > 0)
? 'amount'
: 'volume'
let groups: RingGroup[] = buckets.map(([number, items]) => ({
number,
items: [...items].sort((a, b) => entityMagnitude(b, basis) - entityMagnitude(a, basis)),
weight: sumMagnitude(items, basis),
}))
// Rank to decide what to show, then lay out in account-number order.
groups.sort((a, b) => b.weight - a.weight || a.number.localeCompare(b.number))
const accountCount = groups.length
groups = groups.slice(0, maxAccounts)
let truncated = accountCount > groups.length
for (const group of groups) {
if (group.items.length > maxPerAccount) {
truncated = true
group.items = group.items.slice(0, maxPerAccount)
}
}
groups.sort((a, b) => a.number.localeCompare(b.number))
const totalWeight = groups.reduce((sum, group) => sum + group.weight, 0) || 1
const maxMagnitude = Math.max(
...groups.flatMap((group) => group.items.map((item) => entityMagnitude(item, basis))),
1,
)
return { basis, groups, truncated, totalWeight, maxMagnitude }
}
-60
View File
@@ -1,60 +0,0 @@
'use client'
import { MessageCircle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { getAvatarUrl } from './avatars'
interface Props {
avatarId: string | null | undefined
size?: 'xs' | 'sm' | 'md' | 'lg'
className?: string
alt?: string
}
// Renders the agent's avatar: either the chosen SVG from the AVATAR_OPTIONS
// registry, or a fallback MessageCircle glyph on a dark circle when no avatar
// is set yet (free tier / older profiles).
//
// `next/image` is intentionally NOT used: these are tiny static SVGs served
// from our own /public, and the optimizer does not process SVG anyway, so it
// would add a round trip through /_next/image for nothing.
export default function AgentAvatar({ avatarId, size = 'sm', className, alt }: Props) {
const url = getAvatarUrl(avatarId)
const dim = SIZES[size]
const altText = alt ?? 'Avatar'
if (!url) {
return (
<span
className={cn(
'inline-flex items-center justify-center rounded-full bg-foreground text-background shrink-0',
dim.box,
className,
)}
aria-label={altText}
>
<MessageCircle className={dim.icon} />
</span>
)
}
// eslint-disable-next-line @next/next/no-img-element
return (
<img
src={url}
alt={altText}
className={cn(
'rounded-full shrink-0 bg-secondary object-cover',
dim.box,
className,
)}
/>
)
}
const SIZES = {
xs: { box: 'h-5 w-5', icon: 'h-2.5 w-2.5' },
sm: { box: 'h-8 w-8', icon: 'h-3.5 w-3.5' },
md: { box: 'h-10 w-10', icon: 'h-4 w-4' },
lg: { box: 'h-14 w-14', icon: 'h-5 w-5' },
}
File diff suppressed because it is too large Load Diff
-216
View File
@@ -1,216 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import { Search, X, Loader2, MessageSquare, Pencil, Pin, PinOff, Archive } from 'lucide-react'
import { cn } from '@/lib/utils'
import {
type ConversationRow,
BUCKET_LABELS,
relativeTime,
intentLabel,
} from './conversation-display'
import { useConversationList } from './use-conversation-list'
interface Props {
// Highlight the row for the conversation currently open in the sheet.
activeConversationId?: string | null
// Fired when the user picks a conversation to resume. The sheet fetches its
// messages and swaps back to the chat view: the list itself stays dumb.
onSelect: (id: string) => void
}
// In-sheet conversation picker. Renders the same grouped/searchable list as the
// /chat sidebar (shared helpers in conversation-display.ts), but instead of
// navigating to /chat/[id] it hands the id back so the conversation opens
// inline in the sheet and the user keeps chatting without leaving the page.
// Rows are renameable inline (PATCH /api/agent/conversations/[id]).
export default function AgentSessionList({ activeConversationId, onSelect }: Props) {
// Same hook the /chat sidebar uses, so pin/archive/rename behave identically
// on both surfaces (optimistic, rolled back on failure, with a message).
// Pin and archive are new here: the sheet could only rename before.
const {
conversations,
setConversations,
query,
setQuery,
grouped,
togglePin,
archive,
editingId,
editValue,
setEditValue,
startEdit,
cancelEdit,
commitEdit,
} = useConversationList([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
let cancelled = false
void (async () => {
setLoading(true)
setError(null)
try {
const res = await fetch('/api/agent/conversations?limit=100')
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const json = (await res.json()) as { data?: ConversationRow[] }
if (!cancelled) setConversations(json.data ?? [])
} catch {
if (!cancelled) setError('Kunde inte hämta konversationer.')
} finally {
if (!cancelled) setLoading(false)
}
})()
return () => {
cancelled = true
}
// setConversations is the hook's stable useState setter; listing it would
// not change when this runs, and this must fire exactly once on mount.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return (
<div className="flex flex-1 flex-col min-h-0">
<div className="border-b border-border px-5 py-3">
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Sök konversationer…"
className="w-full rounded-lg border border-border bg-background pl-8 pr-7 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
{query.length > 0 && (
<button
type="button"
onClick={() => setQuery('')}
aria-label="Rensa sökning"
className="absolute right-1 top-1/2 -translate-y-1/2 inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground"
>
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto">
{loading ? (
<div className="flex items-center justify-center gap-2 p-6 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Hämtar…
</div>
) : error ? (
<div className="p-6 text-sm text-destructive">{error}</div>
) : grouped.length === 0 ? (
<div className="flex flex-col items-center gap-2 p-10 text-center text-sm text-muted-foreground">
<MessageSquare className="h-6 w-6 opacity-40" />
{conversations.length === 0 ? 'Inga konversationer ännu.' : 'Inga träffar.'}
</div>
) : (
grouped.map(({ bucket, rows }) => (
<section key={bucket} className="py-2">
<p className="px-4 pb-1 text-[10px] uppercase tracking-wider text-muted-foreground">
{BUCKET_LABELS[bucket]}
</p>
<ul className="space-y-1">
{rows.map((c) => (
<li key={c.id}>
{editingId === c.id ? (
<div className="px-4 py-2">
<input
autoFocus
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onBlur={() => void commitEdit(c.id)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
;(e.target as HTMLInputElement).blur()
} else if (e.key === 'Escape') {
e.preventDefault()
cancelEdit()
}
}}
placeholder="Namnge konversationen…"
maxLength={200}
aria-label="Nytt namn på konversationen"
className="w-full rounded-lg border border-border bg-background px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
) : (
<div
className={cn(
'group flex items-stretch border-l-2 transition-colors',
activeConversationId === c.id
? 'bg-secondary/50 border-foreground'
: 'border-transparent hover:bg-secondary/60',
)}
>
<button
type="button"
onClick={() => onSelect(c.id)}
className="flex flex-1 min-w-0 items-start gap-2 px-4 py-2 text-left"
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<p className="text-sm font-medium truncate flex-1 min-w-0">
{c.title ?? intentLabel(c.intent_id)}
</p>
<p className="text-[11px] text-muted-foreground tabular-nums shrink-0">
{relativeTime(c.last_message_at ?? c.created_at)}
</p>
</div>
<p className="text-xs text-muted-foreground line-clamp-1 mt-0.5">
{c.last_message_preview ?? intentLabel(c.intent_id)}
</p>
</div>
</button>
<div className="shrink-0 flex items-center pr-1">
<button
type="button"
onClick={() => void togglePin(c.id, c.pinned)}
title={c.pinned ? 'Lossa' : 'Fäst överst'}
aria-label={
c.pinned ? 'Lossa konversationen' : 'Fäst konversationen överst'
}
aria-pressed={c.pinned}
className="flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors"
>
{c.pinned ? (
<PinOff className="h-3.5 w-3.5" />
) : (
<Pin className="h-3.5 w-3.5" />
)}
</button>
<button
type="button"
onClick={() => startEdit(c)}
title="Byt namn"
aria-label="Byt namn på konversation"
className="flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors"
>
<Pencil className="h-3.5 w-3.5" />
</button>
<button
type="button"
onClick={() => void archive(c.id)}
title="Arkivera"
aria-label="Arkivera konversationen"
className="flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-foreground transition-colors"
>
<Archive className="h-3.5 w-3.5" />
</button>
</div>
</div>
)}
</li>
))}
</ul>
</section>
))
)}
</div>
</div>
)
}
-846
View File
@@ -1,846 +0,0 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import {
X,
Expand,
Shrink,
PanelRight,
PanelRightClose,
PictureInPicture2,
Eraser,
History,
ChevronLeft,
Loader2,
} from 'lucide-react'
import AgentChat, {
attachStagedOperations,
normalizeStoredMessages,
type ChatMessage,
} from './AgentChat'
import AskConsole, { type AskConsoleMessage } from './AskConsole'
import { CHAT_INTENT_ID } from '@/lib/agent/ask/persist'
import type { AgentPanelFloatRect, StoredStagedOperation } from '@/types'
import {
DOCK_GUTTER,
DOCK_WIDTH_MAX,
DOCK_WIDTH_MIN,
clampDockWidth,
clampFloatRect,
containFloatRect,
defaultFloatRect,
expandedDockWidth,
resizeFloatRect,
type ResizeEdges,
} from '@/lib/agent-panel/geometry'
import type { AgentStatusEvent } from './agent-status'
import ContextChip from './ContextChip'
import { intentLabel } from './conversation-display'
import AgentAvatar from './AgentAvatar'
import AgentSessionList from './AgentSessionList'
import SandboxAgentPreview from './SandboxAgentPreview'
import { useAgentSheet } from './AgentSheetProvider'
import { useCompanyOptional } from '@/contexts/CompanyContext'
import {
clearAgentSheetSession,
writeAgentSheetSession,
} from '@/lib/agent-panel/session-restore'
import { cn } from '@/lib/utils'
// Undimmed non-modal side sheet: sits above the page on a hairline border +
// shadow, but the page underneath stays fully interactive. Plan §3b.
//
// The sheet is a thin wrapper around AgentChat: it owns the title bar, close
// button, and "expand to /chat/[id]" affordance. All message rendering and
// streaming live in AgentChat so the full-page chat view can reuse them.
interface Props {
intentId: string
intentArgs?: Record<string, unknown>
contextRef?: string
seedUserMessage?: string
// Open this existing thread on mount (a reload restore, see the provider)
// instead of starting a fresh one on the intent.
resumeConversationId?: string
// Hidden (display:none) but still mounted so the conversation survives. The
// provider keeps rendering this component; we just visually remove it.
collapsed: boolean
// Publishes what the agent is doing to the one status channel, so the
// floating trigger can say "arbetar" / "är klar" while the panel is hidden.
onStatus?: (event: AgentStatusEvent) => void
// How much width the panel is claiming from the page, or null while it
// overlays. Docking is what makes the panel a second column instead of a
// curtain over the thing being discussed.
onDockWidthChange?: (px: number | null) => void
onCollapse: () => void
onRestart: () => void
onClose: () => void
}
// Geometry (docked width, expanded width, floating rect) lives in
// lib/agent-panel/geometry and is persisted per user via the provider
// (ui_state.agent_panel). The drag paths below write styles imperatively and
// commit ONE preference update on release, so a long conversation never
// re-renders at pointer-move frequency while the user drags.
function useViewportSize() {
const [size, setSize] = useState(() =>
typeof window === 'undefined'
? { w: 1440, h: 900 }
: { w: window.innerWidth, h: window.innerHeight },
)
useEffect(() => {
let frame = 0
const onResize = () => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(() =>
setSize({ w: window.innerWidth, h: window.innerHeight }),
)
}
window.addEventListener('resize', onResize)
return () => {
cancelAnimationFrame(frame)
window.removeEventListener('resize', onResize)
}
}, [])
return size
}
/** Matches Tailwind's md breakpoint: floating mode exists on desktop only. */
function useMinWidthMd() {
const [md, setMd] = useState(
() => typeof window !== 'undefined' && window.matchMedia('(min-width: 768px)').matches,
)
useEffect(() => {
const mq = window.matchMedia('(min-width: 768px)')
const onChange = () => setMd(mq.matches)
mq.addEventListener('change', onChange)
return () => mq.removeEventListener('change', onChange)
}, [])
return md
}
/** Current sidebar column width (--nav-w, set inline on #dash-shell). */
function readNavWidth(): number {
if (typeof document === 'undefined') return 248
const shell = document.getElementById('dash-shell')
const px = shell ? parseInt(getComputedStyle(shell).getPropertyValue('--nav-w'), 10) : NaN
return Number.isFinite(px) ? px : 248
}
/**
* Reactive sidebar width: the nav toggle rewrites #dash-shell's inline
* --nav-w, which fires no resize event, so observe the style attribute
* instead of forcing a computed-style read on every render.
*/
function useNavWidth(): number {
const [w, setW] = useState(readNavWidth)
useEffect(() => {
const shell = document.getElementById('dash-shell')
if (!shell) return
const update = () => setW(readNavWidth())
update()
const mo = new MutationObserver(update)
mo.observe(shell, { attributes: true, attributeFilter: ['style'] })
return () => mo.disconnect()
}, [])
return w
}
/**
* Minimal pointer drag: capture on the handle, report cursor deltas, call
* onEnd exactly once on release or cancel. Deliberately not a library:
* three call sites, no gesture semantics beyond delta tracking.
*/
function startPointerDrag(
e: React.PointerEvent,
onMove: (dx: number, dy: number) => void,
onEnd: () => void,
) {
if (e.button !== 0) return
e.preventDefault()
const target = e.currentTarget as HTMLElement
const startX = e.clientX
const startY = e.clientY
try {
target.setPointerCapture(e.pointerId)
} catch {
// Capture is best-effort: without it the drag still works while the
// cursor stays over the handle.
}
// Listeners live on window, NOT on the handle: if capture fails (or the
// handle unmounts mid-drag), a pointerup outside the 8px strip would never
// reach the handle and onEnd would never run, leaving the drag's global
// side effects (transition suppression, data-agent-resizing) stuck for the
// rest of the session. lostpointercapture covers the mid-drag-unmount case.
// Window listeners see every active pointer, so a second touch or a pen
// must not move this drag or end it early: only the initiating pointer id
// counts. lostpointercapture carries no useful pointerId in all engines,
// so it stays unfiltered; it can only fire for the captured pointer anyway.
const pointerId = e.pointerId
const move = (ev: PointerEvent) => {
if (ev.pointerId !== pointerId) return
onMove(ev.clientX - startX, ev.clientY - startY)
}
const end = () => {
window.removeEventListener('pointermove', move)
window.removeEventListener('pointerup', up)
window.removeEventListener('pointercancel', up)
target.removeEventListener('lostpointercapture', end)
onEnd()
}
const up = (ev: PointerEvent) => {
if (ev.pointerId !== pointerId) return
end()
}
window.addEventListener('pointermove', move)
window.addEventListener('pointerup', up)
window.addEventListener('pointercancel', up)
target.addEventListener('lostpointercapture', end)
}
interface LoadedConversation {
id: string
intentId: string
contextRef: string | null
title: string | null
messages: ChatMessage[]
}
export default function AgentSheet({
intentId,
intentArgs,
contextRef,
seedUserMessage,
resumeConversationId,
collapsed,
onStatus,
onDockWidthChange,
onCollapse,
onRestart,
onClose,
}: Props) {
// Live conversation id from the active AgentChat (fresh sessions report it via
// onConversationIdChange; resumed ones we set directly on select).
// Drops the enter class once the slide has played, so re-expanding a
// collapsed session is instant rather than sliding in again.
const [entering, setEntering] = useState(true)
useEffect(() => {
const t = setTimeout(() => setEntering(false), 320)
return () => clearTimeout(t)
}, [])
const [conversationId, setConversationId] = useState<string | null>(null)
// 'chat' shows the conversation; 'list' shows the session picker.
const [view, setView] = useState<'chat' | 'list'>('chat')
// A past conversation the user picked from the list, hydrated for resume. When
// set, it replaces the intent-driven fresh chat.
const [loaded, setLoaded] = useState<LoadedConversation | null>(null)
// Starts true on a restore so the first frame is the spinner, not a fresh
// chat on the intent: a fresh tool-loop chat fires its first turn on mount
// and would create a stray conversation before the restore replaced it.
const [loadingConversation, setLoadingConversation] = useState(!!resumeConversationId)
const [loadError, setLoadError] = useState<string | null>(null)
// Enlarge the panel IN PLACE (no navigation): the user stays on the current
// page (e.g. /bookkeeping) with a wider reading/verifying surface. Transient
// focus mode, deliberately not persisted (unlike the dock width below).
const [expanded, setExpanded] = useState(false)
const { identity, panelPrefs, updatePanelPrefs } = useAgentSheet()
const viewport = useViewportSize()
const isDesktop = useMinWidthMd()
const navW = useNavWidth()
// Resolved geometry for this render. Floating exists on desktop only: below
// md the sheet stays the full-screen mobile surface whatever the persisted
// mode says. Everything re-clamps against the live viewport, so preferences
// saved on another screen can never strand the panel off-screen.
const floating = panelPrefs.mode === 'floating' && isDesktop
const dockW = clampDockWidth(panelPrefs.dockWidth, viewport.w, navW)
const expandedW = expandedDockWidth(viewport.w, navW)
const floatRect = floating
? clampFloatRect(
panelPrefs.float ?? defaultFloatRect(viewport.w, viewport.h),
viewport.w,
viewport.h,
)
: null
// Open/resize-time validation of the persisted float rect: a rect saved at
// the viewport edge (or on a larger monitor) passes clampFloatRect but
// renders as a 48px sliver, so snap it fully on screen and persist the
// corrected position. panelPrefs.float is read through a ref, NOT the deps:
// putting it in the deps would re-run this on every drag commit and snap
// the window back mid-session, killing the deliberate hang-off-the-edge
// allowance of the live drag path. The effect fires on sheet mount (every
// fresh open remounts, keyed by the provider) and on viewport resize only.
const floatPrefRef = useRef(panelPrefs.float)
useEffect(() => {
floatPrefRef.current = panelPrefs.float
}, [panelPrefs.float])
useEffect(() => {
if (!floating) return
const rect = floatPrefRef.current
if (!rect) return
const contained = containFloatRect(rect, viewport.w, viewport.h)
if (
contained.x !== rect.x ||
contained.y !== rect.y ||
contained.w !== rect.w ||
contained.h !== rect.h
) {
updatePanelPrefs({ float: contained })
}
}, [floating, viewport.w, viewport.h, updatePanelPrefs])
// Reserve page margin while docked, compact AND expanded: both reflow the
// page beside the panel instead of covering it (the original complaint).
// Floating and collapsed claim nothing; below md the margin variable is
// inert (the frame layout gates it on md:).
const reservedWidth = collapsed || floating ? null : (expanded ? expandedW : dockW) + DOCK_GUTTER
useEffect(() => {
onDockWidthChange?.(reservedWidth)
}, [reservedWidth, onDockWidthChange])
useEffect(() => () => onDockWidthChange?.(null), [onDockWidthChange])
const companyCtx = useCompanyOptional()
const isSandbox = companyCtx?.isSandbox ?? false
const agentName = identity.displayName?.trim() || null
const sheetTitle = intentLabel(intentId, agentName)
const displayTitle = loaded ? (loaded.title ?? intentLabel(loaded.intentId, agentName)) : sheetTitle
const activeConversationId = loaded?.id ?? conversationId
// A resumed thread's stored ref wins: it says what THAT conversation was
// about, which is the whole reason to show this. Falls back to the ref the
// panel was opened with for a thread that has not been persisted yet.
const activeContextRef = loaded ? loaded.contextRef : (contextRef ?? null)
const sheetRef = useRef<HTMLDivElement | null>(null)
// Monotonic counter so a slow conversation fetch can't clobber a newer pick.
const selectSeqRef = useRef(0)
// Esc: back out of the session list first, otherwise close. Never while
// collapsed (the sheet is hidden off-screen, so Esc belongs elsewhere).
//
// The sheet is deliberately non-modal, so this listener sits on window while
// the rest of the page stays interactive: it must therefore only claim the
// key when nothing nearer the user wants it. Closing the sheet discards the
// whole in-memory conversation, so an Esc meant for a dropdown inside an
// approval card, the command palette, or any dialog used to destroy the
// session outright. Three guards, cheapest first:
// - defaultPrevented: a Radix popover/dialog that handled Esc marks it.
// - an open overlay anywhere on the page (Radix marks these on the body
// and on the overlay elements themselves) means the key isn't ours.
// - focus sitting outside the sheet means the user is working elsewhere.
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (collapsed || e.key !== 'Escape') return
if (e.defaultPrevented) return
if (typeof document !== 'undefined') {
// Match on data-state="open", not on the popper wrapper itself: a
// force-mounted popper stays in the DOM while closed, and keying off
// the wrapper alone would then block Escape for the rest of the session.
const overlayOpen = document.querySelector(
'[data-radix-popper-content-wrapper] [data-state="open"], [role="dialog"][data-state="open"], [role="alertdialog"][data-state="open"], [role="listbox"][data-state="open"], [data-radix-menu-content][data-state="open"], [data-radix-select-content][data-state="open"]',
)
if (overlayOpen) return
const active = document.activeElement
if (active && sheetRef.current && !sheetRef.current.contains(active)) return
}
if (view === 'list') setView('chat')
else onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [onClose, collapsed, view])
// Move focus off the sheet before hiding it, so it never sits on a
// display:none node (accessibility).
const handleCollapse = () => {
if (typeof document !== 'undefined') {
;(document.activeElement as HTMLElement | null)?.blur()
}
onCollapse()
}
// ── Docked width drag ─────────────────────────────────────────────────
// Live frames write the sheet's max-width and the page-margin variable
// directly; data-agent-resizing suppresses the 300ms margin transition
// (globals.css) so the page reflow tracks the cursor 1:1. One preference
// commit on release.
const pendingDockW = useRef<number | null>(null)
function onDockResizeStart(e: React.PointerEvent) {
const el = sheetRef.current
if (!el) return
const base = expanded ? expandedW : dockW
document.documentElement.setAttribute('data-agent-resizing', '')
el.style.transition = 'none'
startPointerDrag(
e,
(dx) => {
// The handle sits on the panel's left edge: dragging left widens.
// navW from the closure: the sidebar cannot change mid-drag, and this
// avoids a computed-style read on every pointer frame.
const w = clampDockWidth(base - dx, window.innerWidth, navW)
pendingDockW.current = w
el.style.maxWidth = `${w}px`
document.documentElement.style.setProperty('--agent-dock-w', `${w + DOCK_GUTTER}px`)
},
() => {
document.documentElement.removeAttribute('data-agent-resizing')
el.style.transition = ''
if (pendingDockW.current !== null) {
// Keep the final width as the inline override too: if the committed
// value equals the previous preference, React sees identical style
// props and writes nothing, so the DOM must already be correct.
el.style.maxWidth = `${pendingDockW.current}px`
// Dragging from focus mode lands on a custom width: that IS leaving
// focus mode, so fold the result back into the normal dock.
setExpanded(false)
updatePanelPrefs({ dockWidth: pendingDockW.current })
pendingDockW.current = null
}
},
)
}
function onDockResizeKey(e: React.KeyboardEvent) {
const step = 24
// Step from the width the user actually sees: in focus mode that is
// expandedW, and the first keypress folds it into a custom dock width.
const base = expanded ? expandedW : dockW
let next: number | null = null
if (e.key === 'ArrowLeft') next = base + step
if (e.key === 'ArrowRight') next = base - step
if (next === null) return
e.preventDefault()
setExpanded(false)
updatePanelPrefs({ dockWidth: clampDockWidth(next, viewport.w, navW) })
}
// ── Floating move / resize ────────────────────────────────────────────
const pendingFloat = useRef<AgentPanelFloatRect | null>(null)
const commitFloatRect = () => {
if (pendingFloat.current !== null) {
updatePanelPrefs({ float: pendingFloat.current })
pendingFloat.current = null
}
}
function onFloatMoveStart(e: React.PointerEvent) {
const el = sheetRef.current
if (!el || !floatRect) return
// Header buttons keep their clicks; only bare header surface drags.
if ((e.target as Element).closest('button, a, input, textarea, select, [role="button"]')) {
return
}
const base = floatRect
startPointerDrag(
e,
(dx, dy) => {
const r = clampFloatRect(
{ ...base, x: base.x + dx, y: base.y + dy },
window.innerWidth,
window.innerHeight,
)
pendingFloat.current = r
el.style.left = `${r.x}px`
el.style.top = `${r.y}px`
},
commitFloatRect,
)
}
function onFloatResizeStart(e: React.PointerEvent, edges: ResizeEdges) {
const el = sheetRef.current
if (!el || !floatRect) return
const base = floatRect
startPointerDrag(
e,
(dx, dy) => {
const r = resizeFloatRect(base, dx, dy, edges, window.innerWidth, window.innerHeight)
pendingFloat.current = r
el.style.left = `${r.x}px`
el.style.top = `${r.y}px`
el.style.width = `${r.w}px`
el.style.height = `${r.h}px`
},
commitFloatRect,
)
}
function toggleFloating() {
if (floating) {
updatePanelPrefs({ mode: 'docked' })
} else {
updatePanelPrefs({
mode: 'floating',
float: panelPrefs.float ?? defaultFloatRect(viewport.w, viewport.h),
})
}
}
// Open a past conversation inline: fetch its messages and hydrate. Shared by
// the session list and the reload restore below.
const loadConversation = useCallback(async (id: string) => {
setLoaded(null)
setLoadingConversation(true)
setLoadError(null)
// Sequence token: picking A (slow) then B (fast) used to end with A's
// response overwriting B, leaving the user typing into a conversation they
// did not choose. Only the newest selection may write state.
const seq = ++selectSeqRef.current
try {
const res = await fetch(`/api/agent/conversations/${id}`)
if (!res.ok) throw new Error(`HTTP ${res.status}`)
const json = (await res.json()) as {
data?: {
conversation: {
id: string
intent_id: string
context_ref: string | null
title: string | null
}
messages: { role: string; content: unknown; hidden?: boolean | null }[]
staged_operations?: StoredStagedOperation[]
}
}
const data = json.data
if (!data) throw new Error('missing data')
if (seq !== selectSeqRef.current) return
setLoaded({
id: data.conversation.id,
intentId: data.conversation.intent_id,
contextRef: data.conversation.context_ref,
title: data.conversation.title,
messages: attachStagedOperations(
normalizeStoredMessages(data.messages),
data.staged_operations ?? [],
),
})
setConversationId(data.conversation.id)
} catch {
if (seq === selectSeqRef.current) {
setLoadError('Kunde inte öppna konversationen.')
// A thread that no longer opens must not be retried on every reload.
clearAgentSheetSession()
}
} finally {
if (seq === selectSeqRef.current) setLoadingConversation(false)
}
}, [])
// Reload restore: the provider remounts the sheet on the thread this tab
// had open, and it is loaded here the same way a picked one is.
useEffect(() => {
if (resumeConversationId) void loadConversation(resumeConversationId)
}, [resumeConversationId, loadConversation])
// Remember the open thread for this tab so a reload brings it back (see
// lib/agent-panel/session-restore). Nothing to remember until the thread
// has an id: a fresh chat that never sent anything simply does not return.
const activeIntentId = loaded?.intentId ?? intentId
useEffect(() => {
if (!activeConversationId) return
writeAgentSheetSession({
conversationId: activeConversationId,
intentId: activeIntentId,
contextRef: activeContextRef,
collapsed,
})
}, [activeConversationId, activeIntentId, activeContextRef, collapsed])
// Resume a past conversation from the list and swap the sheet back to the
// chat view. Picking the one already open just closes the list (keeps its
// live in-memory state instead of re-hydrating it).
function handleSelectConversation(id: string) {
setView('chat')
if (id === activeConversationId) return
void loadConversation(id)
}
return (
<div
ref={sheetRef}
role="dialog"
aria-label={displayTitle}
// Interactions here must never dismiss an open (non-modal) dialog:
// DialogContent treats data-agent-ui as inside the dialog.
data-agent-ui=""
// z-[60] sits above the mobile bottom nav (z-50) so on phones the sheet
// covers the full screen including where the nav would otherwise show.
// `hidden` (display:none) when collapsed keeps the component mounted (the
// conversation state in AgentChat survives) while removing it from view
// and layout entirely (no stray horizontal scroll from an off-screen box).
className={cn(
'fixed z-[60] flex flex-col bg-background',
floating
? // Undocked window: free rect from inline styles; overlay chrome
// (rounded, hairline border, shadow) like every other overlay.
'overflow-hidden rounded-lg border border-border shadow-lg'
: 'inset-y-0 right-0 w-full border-l border-border shadow-lg transition-[max-width] duration-300 ease-[cubic-bezier(0.32,0.72,0,1)]',
// Arrive along the same edge, on the same curve and duration, as the
// page panel that animates its margin to make room (layout.tsx). Gated
// on first mount only: the panel stays mounted while collapsed, and
// display:none -> visible would otherwise replay the slide every time
// the user re-expands the same session. A floating window has no edge
// to arrive from, so it just fades in.
entering && (floating ? 'animate-in fade-in-0' : 'animate-in slide-in-from-right-full fade-in-0'),
collapsed && 'hidden',
)}
style={
floating && floatRect
? { left: floatRect.x, top: floatRect.y, width: floatRect.w, height: floatRect.h }
: {
// Width is the persisted dock preference; expanded (focus mode)
// grows as far as the viewport allows while the page keeps a
// readable column beside it.
maxWidth: expanded ? expandedW : dockW,
// iOS notch / Android cutout: the sheet top edge needs to clear
// the status bar. Bottom is handled inside the form below.
paddingTop: 'env(safe-area-inset-top, 0px)',
}
}
>
{/* Docked: left-edge width handle (desktop only; mobile is full-width). */}
{!floating && (
<div
role="separator"
aria-orientation="vertical"
aria-label="Ändra panelens bredd"
aria-valuenow={expanded ? expandedW : dockW}
aria-valuemin={DOCK_WIDTH_MIN}
aria-valuemax={clampDockWidth(DOCK_WIDTH_MAX, viewport.w, navW)}
tabIndex={0}
onPointerDown={onDockResizeStart}
onKeyDown={onDockResizeKey}
className="group absolute inset-y-0 left-0 z-10 hidden w-2 cursor-col-resize touch-none focus-visible:outline-none md:block"
>
<div className="mx-auto h-full w-px bg-transparent transition-colors duration-150 group-hover:bg-border group-active:bg-border group-focus-visible:bg-ring" />
</div>
)}
{/* Undocked: edge + corner resize handles. Pointer-only affordances
(aria-hidden): the keyboard path is dock -> arrow keys on the
separator above. */}
{floating && (
<>
<div
onPointerDown={(e) => onFloatResizeStart(e, { left: true })}
className="absolute inset-y-0 left-0 z-10 w-2 cursor-ew-resize touch-none"
aria-hidden="true"
/>
<div
onPointerDown={(e) => onFloatResizeStart(e, { right: true })}
className="absolute inset-y-0 right-0 z-10 w-2 cursor-ew-resize touch-none"
aria-hidden="true"
/>
<div
onPointerDown={(e) => onFloatResizeStart(e, { bottom: true })}
className="absolute inset-x-0 bottom-0 z-10 h-2 cursor-ns-resize touch-none"
aria-hidden="true"
/>
<div
onPointerDown={(e) => onFloatResizeStart(e, { left: true, bottom: true })}
className="absolute bottom-0 left-0 z-10 h-4 w-4 cursor-nesw-resize touch-none"
aria-hidden="true"
/>
<div
onPointerDown={(e) => onFloatResizeStart(e, { right: true, bottom: true })}
className="absolute bottom-0 right-0 z-10 h-4 w-4 cursor-nwse-resize touch-none"
aria-hidden="true"
/>
</>
)}
{view === 'list' ? (
<header
onPointerDown={floating ? onFloatMoveStart : undefined}
className={cn(
'flex items-center gap-3 border-b border-border px-5 py-4',
floating && 'cursor-move touch-none select-none',
)}
>
<button
onClick={() => setView('chat')}
className="h-9 w-9 -ml-1 inline-flex items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label="Tillbaka"
title="Tillbaka"
>
<ChevronLeft className="h-4 w-4" />
</button>
<h2 className="font-display text-lg tracking-tight truncate">Konversationer</h2>
<button
onClick={onClose}
className="ml-auto h-9 w-9 inline-flex items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label="Stäng"
title="Avsluta sessionen"
>
<X className="h-4 w-4" />
</button>
</header>
) : (
<header
// In floating mode the header doubles as the window's drag surface
// (buttons excluded inside onFloatMoveStart).
onPointerDown={floating ? onFloatMoveStart : undefined}
className={cn(
'flex items-center gap-2 border-b border-border px-4 py-4',
floating && 'cursor-move touch-none select-none',
)}
>
{!isSandbox && (
<button
onClick={() => setView('list')}
className="h-9 w-9 inline-flex items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label="Tidigare konversationer"
title="Tidigare konversationer"
>
<History className="h-4 w-4" />
</button>
)}
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName ?? 'Assistent'} />
<div className="min-w-0 flex-1">
<h2 className="font-display text-lg leading-tight tracking-tight truncate">
{displayTitle}
</h2>
{/* What this conversation is anchored to. context_ref has been
stored since the first intents shipped and read by nothing, so a
thread resumed days later gave no clue which invoice it was
about. Matters more now the panel sits BESIDE the page. */}
<ContextChip contextRef={activeContextRef} className="mt-0.5" />
</div>
<div className="ml-auto flex items-center gap-1">
{/* Undock into a floating window the user can move and resize
freely / dock it back to the right edge. Hidden on mobile
where the sheet is always the full-screen surface. */}
{!isSandbox && (
<button
onClick={toggleFloating}
className="hidden md:inline-flex h-9 w-9 items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label={floating ? 'Docka mot högerkanten' : 'Frigör panelen'}
title={
floating
? 'Docka mot högerkanten'
: 'Frigör panelen: flytta och ändra storlek fritt'
}
>
{floating ? (
<PanelRight className="h-4 w-4" />
) : (
<PictureInPicture2 className="h-4 w-4" />
)}
</button>
)}
{/* Grow/shrink the panel in place: NEVER navigates away, so the
user stays on the current page. Hidden on mobile where the sheet
is already full-width (the toggle would be a no-op), and while
floating (the window resizes by its edges instead). */}
{!isSandbox && !floating && (
<button
onClick={() => setExpanded((v) => !v)}
className="hidden md:inline-flex h-9 w-9 items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label={expanded ? 'Förminska' : 'Förstora'}
title={expanded ? 'Förminska' : 'Förstora'}
>
{expanded ? <Shrink className="h-4 w-4" /> : <Expand className="h-4 w-4" />}
</button>
)}
{/* Labeled (not icon-only) so it isn't mistaken for close/minimize,
and gated on an existing conversation so there's nothing to
mis-click on a fresh, empty chat. */}
{activeConversationId && !isSandbox && (
<button
onClick={onRestart}
className="h-9 inline-flex items-center gap-2 rounded-sm px-2 text-xs font-medium text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label="Rensa: börja en ny konversation"
title="Rensa: börja en ny konversation"
>
<Eraser className="h-4 w-4" />
Rensa
</button>
)}
<button
onClick={handleCollapse}
className="h-9 w-9 inline-flex items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label="Minimera"
title="Minimera: behåll sessionen"
>
<PanelRightClose className="h-4 w-4" />
</button>
<button
onClick={onClose}
className="h-9 w-9 inline-flex items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors"
aria-label="Stäng"
title="Avsluta sessionen"
>
<X className="h-4 w-4" />
</button>
</div>
</header>
)}
{isSandbox ? (
<SandboxAgentPreview agentName={agentName} />
) : view === 'list' ? (
<AgentSessionList
activeConversationId={activeConversationId}
onSelect={handleSelectConversation}
/>
) : loadingConversation ? (
<div className="flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" /> Öppnar konversation…
</div>
) : loadError ? (
<div className="flex flex-1 flex-col items-center justify-center gap-3 p-6 text-center text-sm">
<p className="text-destructive">{loadError}</p>
<button
onClick={() => setView('list')}
className="text-xs font-medium text-foreground hover:underline"
>
Tillbaka till konversationer
</button>
</div>
) : loaded ? (
loaded.intentId === CHAT_INTENT_ID ? (
// Resumed free-form thread: the single-call console (runs on a local
// model). Its turns are text-only, so drop any empty/tool rows.
<AskConsole
key={loaded.id}
initialConversationId={loaded.id}
initialMessages={loaded.messages
.filter((m) => m.text.trim().length > 0)
.map((m): AskConsoleMessage => ({ role: m.role, text: m.text }))}
contextRef={loaded.contextRef}
/>
) : (
<AgentChat
key={loaded.id}
intentId={loaded.intentId}
contextRef={loaded.contextRef ?? undefined}
initialConversationId={loaded.id}
initialMessages={loaded.messages}
onConversationIdChange={(id) => setConversationId(id)}
onStatus={onStatus}
/>
)
) : intentId === CHAT_INTENT_ID ? (
// Fresh free-form ask (the FAB's "Fråga min assistent" catch-all).
<AskConsole
seedUserMessage={seedUserMessage}
initialConversationId={null}
contextRef={contextRef ?? null}
onConversationCreated={(id) => setConversationId(id)}
/>
) : (
<AgentChat
intentId={intentId}
intentArgs={intentArgs}
contextRef={contextRef}
seedUserMessage={seedUserMessage}
onConversationIdChange={(id) => setConversationId(id)}
onStatus={onStatus}
/>
)}
</div>
)
}
-413
View File
@@ -1,413 +0,0 @@
'use client'
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from 'react'
import dynamic from 'next/dynamic'
import type { AgentPanelState } from '@/types'
import {
resolveAgentPanelPrefs,
serializeAgentPanelPrefs,
type ResolvedAgentPanelPrefs,
} from '@/lib/agent-panel/geometry'
import { persistUiState } from '@/lib/ui-state/client'
import {
clearAgentSheetSession,
readAgentSheetSession,
} from '@/lib/agent-panel/session-restore'
import {
INITIAL_AGENT_STATUS,
reduceAgentStatus,
type AgentStatus,
type AgentStatusEvent,
} from './agent-status'
import { Skeleton } from '@/components/ui/skeleton'
// The sheet is a lazy chunk, and it used to have no loading state at all: a
// click on the launcher produced NOTHING until the chunk arrived, then the
// whole panel appeared at once. Two fixes: a skeleton in the same geometry so
// the surface is there on the first frame, and a prefetch once the page is
// idle so the chunk is usually already loaded before anyone clicks.
const AgentSheet = dynamic(() => import('./AgentSheet'), {
loading: () => <AgentSheetSkeleton />,
})
function AgentSheetSkeleton() {
return (
<div
aria-hidden="true"
className="fixed inset-y-0 right-0 z-[60] flex w-full flex-col border-l border-border bg-background shadow-lg"
style={{
// Tracks the user's persisted dock width (set by the provider below)
// so the skeleton has the same geometry as the sheet it stands in for.
maxWidth: 'var(--agent-panel-w, 480px)',
paddingTop: 'env(safe-area-inset-top, 0px)',
}}
>
<div className="flex items-center gap-2 border-b border-border px-4 py-4">
<Skeleton className="h-8 w-8 shrink-0 rounded-full" />
<Skeleton className="h-4 w-32" />
</div>
</div>
)
}
/**
* Serialize intent args into the sheet's remount key.
*
* The key used to be intent + contextRef + seed only, but some callers pass a
* CONSTANT contextRef with varying args: bulk-book always uses 'inbox:bulk' and
* carries the selected item ids. Selecting A+B, collapsing, then selecting C+D
* produced the same key, so the sheet did not remount and the earlier
* conversation reopened while the user believed C+D were being booked.
*
* Key order so the same selection reached by different routes stays one session.
*/
// Fallback identity for args that cannot be serialized (cycles, non-JSON
// values). A timestamp would be wrong twice over: two different objects created
// in the same millisecond would collide, and the same object would get a new
// key on every render tick, remounting the sheet under the user mid-session.
// A WeakMap gives each object one stable id for as long as it exists.
const argsFallbackIds = new WeakMap<object, string>()
let argsFallbackSeq = 0
function stableArgsKey(args?: Record<string, unknown>): string {
if (!args) return ''
try {
const keys = Object.keys(args).sort()
return JSON.stringify(keys.map((k) => [k, args[k]]))
} catch {
let id = argsFallbackIds.get(args)
if (!id) {
id = `unserializable:${++argsFallbackSeq}`
argsFallbackIds.set(args, id)
}
return id
}
}
/** Warm the sheet chunk when the browser is idle, never on the critical path. */
function useSheetPrefetch() {
useEffect(() => {
const warm = () => {
// Swallow a failed prefetch: the real import on click will surface any
// genuine problem, and warming must never produce an unhandled rejection.
void import('./AgentSheet').catch(() => {})
}
const w = window as Window & {
requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number
cancelIdleCallback?: (id: number) => void
}
if (typeof w.requestIdleCallback === 'function') {
// A busy page can stay non-idle indefinitely, so cap the wait: the point
// is to have the chunk ready before the first click, not to hold out for
// a quiet moment that may never arrive.
const id = w.requestIdleCallback(warm, { timeout: 2000 })
return () => w.cancelIdleCallback?.(id)
}
const t = setTimeout(warm, 2000)
return () => clearTimeout(t)
}, [])
}
export interface AgentIdentity {
displayName: string | null
avatarId: string | null
// True only after the user has completed Phase B verification in
// /onboarding/agent. Consumers (AgentTrigger, page-level Sparkle
// buttons) should hide themselves when this is false so the FAB
// doesn't pop up before the agent build flow has run.
isVerified: boolean
}
// Provider exposes a single imperative function: openAgentSheet({...}). Any
// client component (top-nav button, transaction row "Fråga om" button, etc.)
// calls it to bring the sheet up with a specific intent + capture args.
//
// The sheet itself manages its own message list, streaming state, and
// dismissal. The provider just owns "what is open" and re-opens or replaces
// the panel when called again.
export interface OpenAgentSheetArgs {
intentId: string
// Intent-specific args passed to the server's intent.capture(), e.g.
// { transaction_id: '...' } for transaction.categorization.
intentArgs?: Record<string, unknown>
// Optional ref persisted on agent_conversations.context_ref so the UI can
// surface a back-pointer ("om transaktion 12 mar / 1 240 kr") later.
contextRef?: string
// Pre-populated first user message. When set, the chat skips the intent's
// promptTemplate and sends this verbatim instead. Used by /chat empty-state
// suggestion chips to give the user a one-click starting prompt.
seedUserMessage?: string
// Reopen an existing thread instead of starting one. Set by the provider
// itself when it restores the panel after a page reload (see
// lib/agent-panel/session-restore); the sheet loads the thread on mount
// exactly as if it had been picked from "Tidigare konversationer".
resumeConversationId?: string
}
interface AgentSheetContextValue {
openAgentSheet: (args: OpenAgentSheetArgs) => void
closeAgentSheet: () => void
// Collapse hides the sheet WITHOUT unmounting it, so the in-memory
// conversation (messages, streaming, pending approval cards) survives: the
// floating trigger re-expands the same session. Distinct from close, which
// ends the session entirely.
collapseAgentSheet: () => void
expandAgentSheet: () => void
// Discard the current thread and start a fresh conversation on the same
// intent (the header "Ny konversation" control). Implemented by remounting
// the sheet via a nonce in its key.
restartAgentSheet: () => void
// True while a session exists (open or collapsed).
isOpen: boolean
// True while a session exists but is minimized off-screen.
collapsed: boolean
// What the assistant is doing, for surfaces outside the panel (today the
// floating trigger). See agent-status.ts: one channel, so a durable
// background run can publish to it later without a second one.
status: AgentStatus
publishAgentStatus: (event: AgentStatusEvent) => void
// Width in px the docked panel is claiming from the page, or null when it is
// overlaying instead. Set by the panel, read by the frame layout.
setDockWidth: (px: number | null) => void
// Panel geometry preferences (docked width, floating rect, active mode).
// Owned here rather than in the sheet so they survive sheet remounts
// (intent changes bump the sheet's key) and persist across sessions via
// user_preferences.ui_state.agent_panel.
panelPrefs: ResolvedAgentPanelPrefs
updatePanelPrefs: (patch: Partial<ResolvedAgentPanelPrefs>) => void
// Agent name + avatar: set once from the server-loaded agent_profile
// and exposed through context so the trigger / chat headers can render
// them without their own fetches. Null when the user hasn't verified a
// profile yet (free tier or pre-onboarding).
identity: AgentIdentity
}
const AgentSheetContext = createContext<AgentSheetContextValue | null>(null)
interface AgentSheetProviderProps {
children: React.ReactNode
identity?: AgentIdentity
// Server-seeded ui_state.agent_panel, so the panel opens at the user's
// persisted size/mode without a first-paint jump.
initialPanelPrefs?: AgentPanelState
}
export function AgentSheetProvider({
children,
identity,
initialPanelPrefs,
}: AgentSheetProviderProps) {
useSheetPrefetch()
const [activeArgs, setActiveArgs] = useState<OpenAgentSheetArgs | null>(null)
// Collapsed = session alive but hidden. Kept separate from activeArgs so
// collapsing never unmounts AgentChat (which would wipe the conversation).
const [collapsed, setCollapsed] = useState(false)
// Bumped by restartAgentSheet to force a fresh AgentChat mount (a new thread)
// on the same intent, without closing the sheet.
const [restartNonce, setRestartNonce] = useState(0)
const [status, publishAgentStatus] = useReducer(reduceAgentStatus, INITIAL_AGENT_STATUS)
const [dockWidth, setDockWidth] = useState<number | null>(null)
// Geometry preferences. The ref mirrors the state so updatePanelPrefs can
// merge and persist from event handlers without a stale closure (drag
// commits fire from listeners installed at drag start).
const [panelPrefs, setPanelPrefs] = useState<ResolvedAgentPanelPrefs>(() =>
resolveAgentPanelPrefs(initialPanelPrefs),
)
const panelPrefsRef = useRef(panelPrefs)
// Trailing debounce on the POST only: local state stays immediate, but key
// auto-repeat on the resize handle (one updatePanelPrefs per repeat) must
// not become one read-merge-write against user_preferences per repeat.
const persistTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const updatePanelPrefs = useCallback((patch: Partial<ResolvedAgentPanelPrefs>) => {
const next = { ...panelPrefsRef.current, ...patch }
panelPrefsRef.current = next
setPanelPrefs(next)
// Fire-and-forget: cosmetic preference, a lost write self-corrects on the
// next change.
if (persistTimerRef.current) clearTimeout(persistTimerRef.current)
persistTimerRef.current = setTimeout(() => {
// Null before writing: a fired timer is no longer pending, and the
// unmount flush below must not replay this (possibly stale) value.
persistTimerRef.current = null
persistUiState({ agent_panel: serializeAgentPanelPrefs(panelPrefsRef.current) })
}, 300)
}, [])
useEffect(
() => () => {
// Flush on unmount so a pending debounced write is not lost.
if (persistTimerRef.current) {
clearTimeout(persistTimerRef.current)
persistUiState({ agent_panel: serializeAgentPanelPrefs(panelPrefsRef.current) })
}
},
[],
)
// The lazy sheet's loading skeleton renders before the sheet can report any
// geometry, so the persisted dock width is published as a CSS variable for
// it (and only it) to read.
useEffect(() => {
document.documentElement.style.setProperty('--agent-panel-w', `${panelPrefs.dockWidth}px`)
}, [panelPrefs.dockWidth])
// Visibility drives whether a finished turn is news or not, so it is derived
// from the session state rather than reported by the panel: closing counts as
// hidden just like collapsing, and a panel that never opened is neither.
const panelVisible = activeArgs !== null && !collapsed
useEffect(() => {
publishAgentStatus({ type: 'visibility', visible: panelVisible })
}, [panelVisible])
// Dock the panel into the frame instead of over it: the page panel gives up
// its right margin so the content the user is asking about stays readable
// beside the answer. Written as a CSS variable rather than a class on <main>
// because the frame layout is a server component; globals.css seeds the
// default so the first paint is not a jump.
// --agent-sheet-w is the docked-only sibling: unlike --agent-dock-w it has
// NO stylesheet default (globals.css seeds dock-w at the 10px frame gutter),
// so consumers that must be a no-op when the sheet is closed (dialog
// centering and width caps in ui/dialog.tsx and the wide booking/review
// dialogs) read this one and get their 0px fallback.
useEffect(() => {
const root = document.documentElement
if (dockWidth === null) {
root.style.removeProperty('--agent-dock-w')
root.style.removeProperty('--agent-sheet-w')
return
}
root.style.setProperty('--agent-dock-w', `${dockWidth}px`)
root.style.setProperty('--agent-sheet-w', `${dockWidth}px`)
return () => {
root.style.removeProperty('--agent-dock-w')
root.style.removeProperty('--agent-sheet-w')
}
}, [dockWidth])
// Bring back the thread this tab had open before a full page reload. The
// panel's state is React-only, so the deploy prompt's "Ladda om" (or any
// refresh) used to close it and drop the thread from view; the user then
// had to find it again under "Tidigare konversationer". The sheet records
// the open thread per tab (sessionStorage), and this reopens it on mount.
// Only on mount: client-side navigation keeps the provider, and a session
// the user closed has already been cleared from storage.
useEffect(() => {
const stored = readAgentSheetSession()
if (!stored) return
// sessionStorage is client-only: reading it in the state initializer would
// render the panel on the client but not on the server (hydration
// mismatch), so it has to be an effect that sets state once.
// eslint-disable-next-line react-hooks/set-state-in-effect
setActiveArgs({
intentId: stored.intentId,
contextRef: stored.contextRef ?? undefined,
resumeConversationId: stored.conversationId,
})
setCollapsed(stored.collapsed)
}, [])
const openAgentSheet = useCallback((args: OpenAgentSheetArgs) => {
setActiveArgs(args)
setCollapsed(false)
}, [])
const closeAgentSheet = useCallback(() => {
setActiveArgs(null)
setCollapsed(false)
setDockWidth(null)
// Close ends the session: a reload after this must not bring it back.
clearAgentSheetSession()
publishAgentStatus({ type: 'reset' })
}, [])
const collapseAgentSheet = useCallback(() => setCollapsed(true), [])
const expandAgentSheet = useCallback(() => setCollapsed(false), [])
const restartAgentSheet = useCallback(() => {
// Discarding the thread: forget it for reload purposes too, so the old
// one does not reappear while the new one has no id yet, and drop any
// restore id from the args, or the remount would reopen that thread
// instead of starting a fresh one.
clearAgentSheetSession()
setActiveArgs((args) =>
args?.resumeConversationId ? { ...args, resumeConversationId: undefined } : args,
)
setRestartNonce((n) => n + 1)
setCollapsed(false)
}, [])
const resolvedIdentity = useMemo<AgentIdentity>(
() => identity ?? { displayName: null, avatarId: null, isVerified: false },
[identity],
)
const value = useMemo<AgentSheetContextValue>(
() => ({
openAgentSheet,
closeAgentSheet,
collapseAgentSheet,
expandAgentSheet,
restartAgentSheet,
isOpen: activeArgs !== null,
collapsed,
status,
publishAgentStatus,
setDockWidth,
panelPrefs,
updatePanelPrefs,
identity: resolvedIdentity,
}),
[
openAgentSheet,
closeAgentSheet,
collapseAgentSheet,
expandAgentSheet,
restartAgentSheet,
activeArgs,
collapsed,
status,
panelPrefs,
updatePanelPrefs,
resolvedIdentity,
],
)
return (
<AgentSheetContext.Provider value={value}>
{children}
{activeArgs && (
<AgentSheet
key={`${activeArgs.intentId}:${activeArgs.contextRef ?? ''}:${stableArgsKey(activeArgs.intentArgs)}:${activeArgs.seedUserMessage ?? ''}:${activeArgs.resumeConversationId ?? ''}:${restartNonce}`}
intentId={activeArgs.intentId}
intentArgs={activeArgs.intentArgs}
contextRef={activeArgs.contextRef}
seedUserMessage={activeArgs.seedUserMessage}
resumeConversationId={activeArgs.resumeConversationId}
collapsed={collapsed}
onStatus={publishAgentStatus}
onDockWidthChange={setDockWidth}
onCollapse={collapseAgentSheet}
onRestart={restartAgentSheet}
onClose={closeAgentSheet}
/>
)}
</AgentSheetContext.Provider>
)
}
export function useAgentSheet(): AgentSheetContextValue {
const ctx = useContext(AgentSheetContext)
if (!ctx) {
throw new Error('useAgentSheet must be used inside <AgentSheetProvider>')
}
return ctx
}
-276
View File
@@ -1,276 +0,0 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import { useAgentSheet } from './AgentSheetProvider'
import { usePathname, useRouter } from 'next/navigation'
import { Loader2, X } from 'lucide-react'
import AgentAvatar from './AgentAvatar'
import { collapsedStatusLabel } from './agent-status'
import { routeToIntent } from '@/lib/agent/intents/route-mapping'
import { useAssistantAvailable, useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
// Floating trigger sits above the page bottom-right, opens the AgentSheet when
// clicked. Hidden when the sheet is already open so the icon doesn't double up.
//
// Desktop-only for a FRESH open (founder call 2026-08-06). On mobile the pill
// landed on top of the bottom nav and covered page content, and the bottom nav
// already carries an "Assistent" tab to /chat behind the very same
// identity.isVerified gate used here, so the pill was pure redundancy. A
// COLLAPSED session keeps its handle on every viewport and on every page except
// /chat: see the page-suppression block and the visibility class below.
//
// Route-aware: routeToIntent(pathname) picks the right intent + intentArgs so
// clicking the FAB on /invoices/abc-123 opens invoice.draft with that invoice
// id (rather than the page-agnostic general.help with just the URL). The
// label suffix renders "Fråga Anna om denna faktura" so the user can tell at
// a glance that the agent is going to know which entity they're on.
//
// Reads the agent's display_name + avatar_id from the AgentSheet context so
// the button reads "Fråga Anna" (with Anna's face) rather than the generic
// "Fråga min assistent".
//
// Page-specific triggers (e.g. "Granska med assistent" on a supplier invoice)
// still call useAgentSheet() directly from their own buttons because they
// know exactly which entity to pass. (Per-transaction help has its own
// row-level "Fråga [namn]" button in TransactionInboxCard, and the matching
// "Fråga assistenten" in Dokumentinkorgen: both passing a transaction_id the
// pathname-only FAB can't know.)
// Session-scoped dismissal flag for the non-payer upsell pill. sessionStorage
// on purpose: "close" means gone for THIS browser session, and the pill comes
// back full-size next session. Anything permanent (localStorage or
// user_preferences) would let a non-payer silence the conversion surface
// forever with one click (founder call 2026-08-09).
const UPSELL_DISMISSED_KEY = 'agent-upsell-dismissed'
export default function AgentTrigger({ hidden = false }: { hidden?: boolean }) {
const { openAgentSheet, expandAgentSheet, isOpen, collapsed, status, identity } = useAgentSheet()
const pathname = usePathname()
const router = useRouter()
const hasAi = useCapability(CAPABILITY.ai)
const assistantAvailable = useAssistantAvailable()
// Read the dismissal AFTER hydration (effect, not state initializer): the
// server always renders the pill, so an initializer that reads
// sessionStorage would mismatch the SSR HTML. Costs one frame of pill
// before it hides, which is invisible in practice.
const [upsellDismissed, setUpsellDismissed] = useState(false)
useEffect(() => {
try {
if (window.sessionStorage.getItem(UPSELL_DISMISSED_KEY) === '1') setUpsellDismissed(true)
} catch {
// Storage unavailable (private mode, blocked cookies): the pill simply
// stays dismissible per page load instead of per session.
}
}, [])
const dismissUpsellForSession = () => {
setUpsellDismissed(true)
try {
window.sessionStorage.setItem(UPSELL_DISMISSED_KEY, '1')
} catch {
// Same as above: in-memory state still hides it for this page.
}
}
// For a non-payer the sheet is a paywall surface, so closing it means "not
// now": treat it exactly like dismissing the pill. Otherwise the user closes
// the big panel and the wide "Uppgradera för att använda ..." pill pops
// right back, which is the residual-overlay complaint this fixes. Collapse
// (Minimera) is not a close and never lands here: isOpen stays true.
const prevOpenRef = useRef(isOpen)
useEffect(() => {
const wasOpen = prevOpenRef.current
prevOpenRef.current = isOpen
if (wasOpen && !isOpen && !hasAi) {
setUpsellDismissed(true)
try {
window.sessionStorage.setItem(UPSELL_DISMISSED_KEY, '1')
} catch {
// In-memory dismissal still applies.
}
}
}, [isOpen, hasAi])
// User opt-out (Inställningar → Assistenten): the sidebar entry stays, the
// floating button goes. A collapsed session keeps its reopen handle even
// when hidden: it's the only way back to a minimized conversation, and its
// existence implies the user is actively using the assistant right now.
if (hidden && !collapsed) return null
// Dismissed upsell (non-payer clicked the pill's X, or closed the paywalled
// sheet): render nothing at all for the rest of the browser session. A
// collapsed session still shows its handle even then: it is the only way
// back to the minimized conversation, and its label is a resume action
// ("Fortsätt med ..."), not the upsell.
if (!hasAi && upsellDismissed && !collapsed) return null
// Sheet open AND visible → hide the FAB so the icon doesn't double up. When
// the session is merely collapsed we KEEP the FAB: it's the handle that
// brings the minimized conversation back.
if (isOpen && !collapsed) return null
// Page suppression, split by WHY the page suppresses. The split is the point:
// one rule is about redundancy (the page already IS the conversation), the
// other is about crowding (the page is dense and the pill would sit on top of
// it). Only the redundancy rule survives into the collapsed state, because
// only it leaves the user another route back to the conversation.
//
// /chat*: suppressed in BOTH states. Fresh open: the surface IS the chat, so
// a floating "Fråga …" pill is redundant and overlaps the input. Collapsed:
// the /chat layout lists every conversation in its sidebar and renders the
// selected one in the main pane, so navigating here IS the way back; a handle
// that re-expands the panel on top of it would put two chats on one screen.
// Safe because the session lives in AgentSheetProvider in the dashboard
// layout, one level above the page: it stays mounted (messages, streaming,
// pending approval cards intact) the whole time the user is on /chat, and the
// handle reappears the moment they navigate anywhere else, bottom nav
// included. Nothing is discarded, the handle is just hidden while the user is
// standing inside the surface it would lead to.
if (pathname?.startsWith('/chat')) return null
// /bookkeeping/[id]: FRESH open only. The verifikation editor is a dense
// regulatory surface (debits/credits, BAS codes, period locks) and a floating
// "Fråga … om denna verifikation" pill on top of it adds noise without
// earning its place. A COLLAPSED session keeps its handle here, and on every
// other page in the app: this page offers no other route back to a minimized
// conversation, and stranding a half-finished booking is a worse outcome than
// a pill over the editor. (/bookkeeping list, /bookkeeping/new and
// /bookkeeping/year-end are not the editor and keep the fresh-open FAB.)
if (!collapsed) {
const segs = pathname?.split('/').filter(Boolean) ?? []
if (segs[0] === 'bookkeeping' && segs[1] && segs[1] !== 'year-end' && segs[1] !== 'new') {
return null
}
}
// Pre-onboarding: no agent_profile.verified_at yet. The FAB would lead
// into a generic chat with no specialization. Better to hide it until
// the user has finished /onboarding/agent. (A collapsed session implies the
// agent is already in use, so this only gates fresh opens in practice.)
if (!identity.isVerified) return null
const name = identity.displayName?.trim() || 'min assistent'
// Without the tool-loop runtime (OpenAI-compatible or unconfigured AI, #2204)
// every route dispatches to general.help: the single-call console runs on
// any provider, so the pill stays but never opens a chat that would 503.
const dispatch = routeToIntent(pathname, { assistantAvailable })
// AI assistant runs on a paid cloud service. Without the capability, opening
// the sheet would land the user in a chat whose send is dead. Keep the FAB
// visible (it's the conversion surface) but route it to billing instead.
// A minimized session used to be silent: the agent could be three tool calls
// into a booking, or finished ten minutes ago, and the pill said "Fortsätt
// med Anna" either way. While hidden, the status channel does the talking.
const statusText = collapsed ? collapsedStatusLabel(status, name) : null
const working = status.activity === 'working' || status.activity === 'detached'
const finished = collapsed && status.activity === 'done'
const labelText =
statusText ??
(collapsed
? `Fortsätt med ${name}`
: !hasAi
? `Uppgradera för att använda ${name}`
: dispatch.labelSuffix
? `Fråga ${name} ${dispatch.labelSuffix}`
: `Fråga ${name}`)
const handleClick = () => {
// Collapsed → bring the existing session back, don't start a new one.
if (collapsed) {
expandAgentSheet()
return
}
if (!hasAi) {
router.push('/settings/billing')
return
}
openAgentSheet({
intentId: dispatch.intentId,
intentArgs: dispatch.intentArgs,
contextRef: dispatch.contextRef,
})
}
// Mobile visibility, decided per state rather than per viewport alone:
//
// fresh open -> 'hidden md:flex'. `display: none` (not opacity/visibility)
// so the button is genuinely non-interactive on mobile: not
// clickable, not tabbable, out of the accessibility tree.
// Losing it costs nothing, the bottom nav's "Assistent" tab
// reaches the same agent.
// collapsed -> 'flex' on every viewport. Off /chat this is the ONLY route
// back to a minimized conversation: the bottom-nav tab opens
// the /chat surface instead of restoring the in-progress
// sheet, so hiding the handle on mobile would strand a
// session mid-booking with no way to reopen it. On /chat the
// handle is suppressed outright (see above), which is exactly
// the case where the nav tab does lead somewhere useful.
//
// A pure CSS switch on purpose: no useMediaQuery, so no hydration mismatch,
// no resize listener, no layout shift on first paint.
const visibilityClass = collapsed ? 'flex' : 'hidden md:flex'
// The upsell pill (fresh state, no capability) carries its own dismiss so a
// non-payer is never stuck with an undismissable ad in the corner. Payer and
// collapsed states are unchanged: no X there, the pill is functional UI.
const dismissible = !hasAi && !collapsed
return (
// Wrapper div carries the pill shell; the two segments inside are separate
// buttons because a dismiss nested in the main <button> would be invalid
// HTML. Segment hover is a background/10 overlay, visually equivalent to
// the old whole-pill foreground/90 shift.
<div
// Mobile: sit above the bottom nav (h-16 = 64px) AND the iOS home
// indicator (env(safe-area-inset-bottom)). Still needed after the FAB
// went desktop-only: the collapsed handle above renders on mobile too.
// Desktop: standard 20px lift, no mobile nav to worry about, except when
// the page declares a bottom action bar (body[data-page-bottom-bar],
// set by e.g. the standalone invoice editor): lift above it so the FAB
// never covers the bar's primary button.
// z-[45]: above the DialogVeil (z-40) so the assistant can be OPENED
// while a non-modal dialog (booking, invoice) holds the page inert, but
// below dialog content (z-50). Under a true modal dialog Radix sets
// pointer-events: none on <body>, which keeps the trigger dead there
// regardless of z.
// data-agent-ui: opening the assistant must not dismiss an open
// non-modal dialog (DialogContent treats this as inside).
data-agent-ui=""
className={`fixed right-4 z-[45] ${visibilityClass} h-12 max-w-[calc(100vw-2rem)] items-stretch rounded-full bg-foreground text-background shadow-lg bottom-[calc(env(safe-area-inset-bottom,0px)+5rem)] md:bottom-4 md:[body[data-page-bottom-bar]_&]:bottom-20`}
>
<button
onClick={handleClick}
className={`flex min-w-0 items-center gap-2 pl-2 ${dismissible ? 'rounded-l-full pr-2' : 'rounded-full pr-4'} hover:bg-background/10 transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2`}
aria-label={labelText}
// The label changes on its own while the panel is hidden, so it has to be
// announced rather than only redrawn. Polite: it never interrupts.
aria-live="polite"
>
<span className="relative shrink-0">
<AgentAvatar
avatarId={identity.avatarId}
size="sm"
className="ring-2 ring-background/20"
alt={name}
/>
{/* An answer waiting behind a hidden panel is the one thing worth a
dot: it is unread, not in progress. */}
{finished && (
<span className="absolute -right-1 -top-1 h-2 w-2 rounded-full bg-success ring-2 ring-foreground" />
)}
</span>
{working && collapsed && (
<Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin motion-reduce:animate-none" />
)}
<span className="text-sm font-medium truncate">{labelText}</span>
</button>
{dismissible && (
<button
onClick={dismissUpsellForSession}
aria-label="Dölj tills nästa besök"
className="flex items-center rounded-r-full pl-1 pr-3 text-background/70 hover:text-background hover:bg-background/10 transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
>
<X className="h-4 w-4" />
</button>
)}
</div>
)
}
-544
View File
@@ -1,544 +0,0 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { Check, X, Loader2, AlertTriangle, Lock, ShieldCheck, ArrowRight } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import type { PendingOperationRejectionCategory } from '@/types'
import { cn } from '@/lib/utils'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { OperationPreview, AccountNamesContext } from '@/components/pending-operations/OperationPreview'
import { useAccountNamesSource } from '@/components/pending-operations/use-account-names'
import { REJECTION_CATEGORY_LABELS } from '@/components/pending-operations/vocabulary'
import { operationTypeFromToolName } from '@/lib/pending-operations/tool-name'
// Inline approval card for an agent-staged pending_operation.
//
// Risk tiers (plan §9, §12):
// low: single-click "Godkänn". Trust UI for auto-approve lives
// post-V0 (data model supports it via agent_profiles.trust_per_tool).
// medium: single-click "Godkänn".
// high: requires the user to type "godkänn" verbatim. Never auto-
// approvable, by design (legal compliance).
//
// Reject is always one-click.
//
// The card posts to the existing /api/pending-operations/<id>/{commit,reject}
// endpoints: same surface the Accounted "Förslag" page uses, so there is
// exactly one approval source of record.
//
// Structured preview: when the staged envelope carries a preview object, we
// render the shared OperationPreview (components/pending-operations), the
// same renderers /pending uses, dispatched on operation_type. Live streamed
// cards carry the MCP tool name; hydrated cards carry the stored
// operation_type directly. Unknown types fall through to the generic
// key/value renderer so a new tool can ship without an ApprovalCard change.
interface PeriodStatus {
period_id?: string | null
status: 'open' | 'locked' | 'closed'
lock_date?: string | null
}
interface Props {
operationId: string
riskLevel: 'low' | 'medium' | 'high'
message: string
toolName?: string
// The stored pending_operations.operation_type. Preferred over deriving it
// from toolName: hydrated cards pass it straight from the DB row, so every
// operation type keeps its specialized preview on resume.
operationType?: string
// pending_operations.params (the staging tool's input). Some previews read
// it: attach_document's DocumentViewButton needs params.document_id.
params?: Record<string, unknown>
preview?: unknown
periodStatus?: PeriodStatus
// Fired after a reject that carries a reason: the chat feeds this synthetic
// correction back as a hidden user turn so the agent re-proposes inline.
onRequestCorrection?: (correctionMessage: string) => void
}
type State = 'pending' | 'committing' | 'committed' | 'rejecting' | 'rejected' | 'error'
// Subset of fields the commit response may return that the success state
// uses to deep-link to the freshly-created artifact. Different
// operation_types return different shapes: only the ones we actually
// surface as links are declared.
interface CommitResultData {
journal_entry_id?: string | null
invoice_id?: string | null
customer_id?: string | null
supplier_invoice_id?: string | null
// bulk_book_inbox_items creates N verifikationer, not one artifact: the
// executor returns per-item counts instead of a single id. Surfaced as a
// "N bokförda" summary + a link to the ledger (or the sole verifikat).
booked_count?: number
skipped_count?: number
booked?: Array<{ journal_entry_id?: string | null }>
}
export default function ApprovalCard({
operationId,
riskLevel,
message,
toolName,
operationType,
params,
preview,
periodStatus,
onRequestCorrection,
}: Props) {
// Gating the AI re-propose path only: approving/rejecting the staged
// operation is manual ledger work and stays enabled without the AI add-on.
// What's paid is feeding a rejection back so the agent generates a *new*
// proposal (an LLM call): that's suppressed when the company lacks `ai`.
const hasAi = useCapability(CAPABILITY.ai)
// Chart names for the preview lines (same source as /pending).
const accountNames = useAccountNamesSource()
const [state, setState] = useState<State>('pending')
const [errorMessage, setErrorMessage] = useState<string | null>(null)
const [confirmText, setConfirmText] = useState('')
// Reject-with-reason form (mirrors the granskning dialog). Clicking "Avslå"
// opens it; both fields are optional. When a reason is given, the rejection
// is fed back so the agent re-proposes.
const [showRejectForm, setShowRejectForm] = useState(false)
const [rejectCategory, setRejectCategory] = useState<PendingOperationRejectionCategory | ''>('')
const [rejectReason, setRejectReason] = useState('')
// Surfaced in the "Godkänt" success state so the user can jump directly
// to the newly-created artifact (verifikation / faktura / kund) instead
// of hunting through /bookkeeping.
const [commitResult, setCommitResult] = useState<CommitResultData | null>(null)
// Set when commit fails because the booking posts to BAS accounts not yet
// active in the chart. Drives the inline "activate and approve" affordance
// (the op stays pending server-side, so retrying after activation works).
const [accountsToActivate, setAccountsToActivate] = useState<string[] | null>(null)
const requiresTextConfirm = riskLevel === 'high'
const canCommit =
!requiresTextConfirm || confirmText.trim().toLowerCase() === 'godkänn'
// Render key for the shared preview. Hydrated cards pass operation_type
// straight from the pending_operations row; live streamed cards carry the
// MCP tool name, which maps to the bare operation_type by stripping the
// wire prefix. The old dispatch keyed on 4 hardcoded tool names, so every
// other hydrated type silently lost its specialized preview.
const previewOperationType =
operationType ?? (toolName ? operationTypeFromToolName(toolName) : '')
async function handleCommit() {
setState('committing')
setErrorMessage(null)
setAccountsToActivate(null)
try {
const res = await fetch(`/api/pending-operations/${operationId}/commit`, {
method: 'POST',
})
const body = (await res.json().catch(() => ({}))) as {
data?: CommitResultData
error?: string | { code?: string; message?: string; account_numbers?: string[] }
}
if (!res.ok) {
// Recoverable: the booking posts to BAS accounts not active in the
// chart. Offer to activate them and retry: the op stays pending.
const structured = typeof body.error === 'object' && body.error !== null ? body.error : null
if (structured?.code === 'ACCOUNTS_NOT_IN_CHART' && structured.account_numbers?.length) {
setAccountsToActivate(structured.account_numbers)
setState('pending')
return
}
// Map the parsed body plus the status, never `new Error(body.error)`:
// the route answers thrown errors with the canonical envelope
// `{ error: { code, message } }`, and the Error constructor would
// stringify that object to "[object Object]", discarding the route's
// own Swedish reason.
setState('error')
setErrorMessage(getUserErrorMessage(body, { statusCode: res.status }))
return
}
// Best-effort deep-link to the created artifact in the success state.
if (body?.data) setCommitResult(body.data)
setState('committed')
} catch (err) {
setState('error')
setErrorMessage(err instanceof Error ? getUserErrorMessage(err) : 'Kunde inte godkänna.')
}
}
// Activate the missing BAS accounts (one POST) then retry the commit. The
// pending_operation was left 'pending' server-side precisely so this retry
// commits the same booking without re-staging it.
async function handleActivateAndCommit() {
if (!accountsToActivate || accountsToActivate.length === 0) return
setState('committing')
setErrorMessage(null)
try {
const res = await fetch('/api/bookkeeping/accounts/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_numbers: accountsToActivate }),
})
if (!res.ok) {
const body = await res.json().catch(() => null)
setState('error')
setErrorMessage(getUserErrorMessage(body, { statusCode: res.status }))
return
}
setAccountsToActivate(null)
await handleCommit()
} catch (err) {
setState('error')
setErrorMessage(err instanceof Error ? getUserErrorMessage(err) : 'Kunde inte aktivera kontona.')
}
}
async function handleReject() {
setState('rejecting')
setErrorMessage(null)
const categoryLabel = rejectCategory ? REJECTION_CATEGORY_LABELS[rejectCategory] : null
const reason = rejectReason.trim()
// Both fields optional: a bare "Avvisa" still rejects (parity with the
// granskning dialog and older bodyless clients).
const body =
rejectCategory || reason
? {
...(rejectCategory ? { rejection_category: rejectCategory } : {}),
...(reason ? { rejection_reason: reason } : {}),
}
: undefined
try {
const res = await fetch(`/api/pending-operations/${operationId}/reject`, {
method: 'POST',
...(body
? { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }
: {}),
})
if (!res.ok) {
const body = await res.json().catch(() => null)
setState('error')
setErrorMessage(getUserErrorMessage(body, { statusCode: res.status }))
return
}
setShowRejectForm(false)
setState('rejected')
// Feed the correction back so the agent re-proposes: only when the user
// actually said what was wrong. A bare reject just stops here.
const parts = [categoryLabel, reason].filter(Boolean) as string[]
if (hasAi && parts.length > 0) {
onRequestCorrection?.(
`Jag avvisade förslaget. Det som var fel: ${parts.join(', ')}. Föreslå en korrigerad bokning.`,
)
}
} catch (err) {
setState('error')
setErrorMessage(err instanceof Error ? getUserErrorMessage(err) : 'Kunde inte avslå.')
}
}
if (state === 'committed') {
// Build a deep-link to the newly-created artifact when the commit
// response told us what it was. Falls back to nothing if no relevant
// id was returned (e.g. period close / unlock / mark-as-sent).
let deepLink: { href: string; label: string } | null = null
if (commitResult?.journal_entry_id) {
deepLink = {
href: `/bookkeeping/${commitResult.journal_entry_id}`,
label: 'Öppna verifikation',
}
} else if (commitResult?.invoice_id) {
deepLink = {
href: `/invoices/${commitResult.invoice_id}`,
label: 'Öppna faktura',
}
} else if (commitResult?.supplier_invoice_id) {
deepLink = {
href: `/supplier-invoices/${commitResult.supplier_invoice_id}`,
label: 'Öppna leverantörsfaktura',
}
} else if (commitResult?.customer_id) {
deepLink = {
href: `/customers/${commitResult.customer_id}`,
label: 'Öppna kund',
}
}
// Bulk operations (bulk_book_inbox_items) book N underlag at once and return
// counts instead of a single id. Show the outcome ("N bokförda · M
// överhoppade") (a bulk commit silently skips non-bookable items, so
// without this the user can't tell whether anything was booked) and link to
// the ledger list, or straight to the sole verifikat when exactly one landed.
const bulkSummary =
typeof commitResult?.booked_count === 'number'
? { booked: commitResult.booked_count, skipped: commitResult.skipped_count ?? 0 }
: null
if (bulkSummary && !deepLink) {
const soleEntryId =
bulkSummary.booked === 1 ? commitResult?.booked?.[0]?.journal_entry_id : null
deepLink = soleEntryId
? { href: `/bookkeeping/${soleEntryId}`, label: 'Öppna verifikation' }
: { href: '/bookkeeping', label: 'Öppna bokföringen' }
}
// The server's `message` field (e.g. "Operation staged for review …
// Open the Accounted web app to approve or reject it.") was written for
// MCP clients without an inline approval surface. Inside the in-app
// chat it's redundant noise: the agent already narrated the why
// above the card. We keep it accessible via aria-description for
// screen readers but don't render it.
return (
<div
className="rounded-lg border border-success/40 bg-success/10 px-4 py-3 text-sm"
aria-description={message}
>
<p className="flex items-center gap-2 font-medium">
<Check className="h-4 w-4" /> Godkänt
</p>
{bulkSummary && (
<p className="mt-1 text-xs text-muted-foreground tabular-nums">
{bulkSummary.booked} {bulkSummary.booked === 1 ? 'underlag bokfört' : 'underlag bokförda'}
{bulkSummary.skipped > 0 ? ` · ${bulkSummary.skipped} överhoppade` : ''}
</p>
)}
{deepLink && (
<Link
href={deepLink.href}
className="mt-2 inline-flex items-center gap-1 text-xs font-medium text-foreground hover:underline"
>
{deepLink.label}
<ArrowRight className="h-3 w-3" />
</Link>
)}
</div>
)
}
if (state === 'rejected') {
return (
<div
className="rounded-lg border border-border bg-card px-4 py-3 text-sm text-muted-foreground"
aria-description={message}
>
<p className="flex items-center gap-2">
<X className="h-4 w-4" /> Avslaget
{rejectCategory && (
<span className="text-xs text-muted-foreground/80">· {REJECTION_CATEGORY_LABELS[rejectCategory]}</span>
)}
</p>
</div>
)
}
const isBusy = state === 'committing' || state === 'rejecting'
return (
<div
className={cn(
// Subtle accent border-top tells the eye what to do BEFORE reading
// the risk label. high = destructive red, medium = warning yellow,
// low = neutral foreground. animate-scale-in gives the card a soft
// entrance when it first lands inline in the conversation.
'rounded-lg border bg-card px-4 py-3 space-y-3 border-t-2 animate-scale-in',
riskLevel === 'high'
? 'border-destructive/50 border-t-destructive'
: riskLevel === 'medium'
? 'border-border border-t-warning'
: 'border-border border-t-foreground/30',
)}
>
<div className="flex items-center justify-between gap-2 flex-wrap">
<p className="text-xs uppercase tracking-wide text-muted-foreground">
Förslag · risk {translateRisk(riskLevel)}
</p>
{periodStatus && <PeriodBadge status={periodStatus} />}
</div>
{preview != null && typeof preview === 'object' && (
<div className="rounded-lg border border-border bg-muted/30 px-3 py-2">
<AccountNamesContext.Provider value={accountNames}>
<OperationPreview
op={{
operation_type: previewOperationType,
preview_data: preview as Record<string, unknown>,
params,
}}
/>
</AccountNamesContext.Provider>
</div>
)}
{requiresTextConfirm && (
<div className="space-y-1">
<p className="flex items-center gap-2 text-xs text-destructive">
<AlertTriangle className="h-3.5 w-3.5" />
Hög risk: skriv <strong className="font-semibold">godkänn</strong> för att bekräfta.
</p>
<input
type="text"
value={confirmText}
onChange={(e) => setConfirmText(e.target.value)}
disabled={isBusy}
className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
autoComplete="off"
aria-label="Bekräfta med ordet godkänn"
/>
</div>
)}
{errorMessage && <p className="text-xs text-destructive">{errorMessage}</p>}
{showRejectForm ? (
<div className="space-y-2 rounded-lg border border-border bg-muted/30 px-3 py-2">
<p className="text-xs font-medium">Vad är fel?</p>
<Select
value={rejectCategory}
onValueChange={(v) => setRejectCategory(v as PendingOperationRejectionCategory)}
>
<SelectTrigger className="h-8 text-xs" aria-label="Anledning">
<SelectValue placeholder="Anledning (valfritt)" />
</SelectTrigger>
{/* The agent sheet panel is z-[60]; SelectContent defaults to z-50
and portals to <body>, so without this it opens BEHIND the
sheet. z-[70] sits above the sheet, below toasts (z-[100]). */}
<SelectContent className="z-[70]">
{(Object.keys(REJECTION_CATEGORY_LABELS) as PendingOperationRejectionCategory[]).map((cat) => (
<SelectItem key={cat} value={cat}>{REJECTION_CATEGORY_LABELS[cat]}</SelectItem>
))}
</SelectContent>
</Select>
<Textarea
value={rejectReason}
onChange={(e) => setRejectReason(e.target.value)}
placeholder="T.ex. ska vara IT-tjänster, inte telefoni…"
rows={2}
maxLength={2000}
disabled={isBusy}
className="text-xs"
aria-label="Notering"
/>
{hasAi ? (
<p className="text-[11px] text-muted-foreground">
Med en anledning eller notering föreslår assistenten en korrigerad bokning direkt.
</p>
) : (
<p className="text-[11px] text-muted-foreground">
Din anledning sparas på förslaget. Vill du att assistenten automatiskt
föreslår en korrigerad bokning?{' '}
<Link href="/settings/billing" className="font-medium text-foreground hover:underline">
Uppgradera
</Link>
.
</p>
)}
<div className="flex gap-2">
<Button
variant="destructive"
size="sm"
onClick={handleReject}
disabled={isBusy}
className="flex-1"
>
{state === 'rejecting' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Avvisa'}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setShowRejectForm(false)}
disabled={isBusy}
className="flex-1"
>
Avbryt
</Button>
</div>
</div>
) : accountsToActivate ? (
<div className="space-y-2 rounded-lg border border-border bg-muted/30 px-3 py-2">
<p className="text-xs leading-5">
Bokningen använder konton som inte är aktiva i din kontoplan:{' '}
<strong className="tabular-nums">{accountsToActivate.join(', ')}</strong>. Aktivera dem för att godkänna bokningen.
</p>
<div className="flex gap-2">
<Button
size="sm"
onClick={handleActivateAndCommit}
disabled={isBusy}
className="flex-1"
>
{state === 'committing' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Aktivera och godkänn'}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setAccountsToActivate(null)}
disabled={isBusy}
className="flex-1"
>
Avbryt
</Button>
</div>
</div>
) : (
<>
<div className="flex gap-2">
<Button
size="sm"
onClick={handleCommit}
disabled={isBusy || !canCommit}
className="flex-1"
>
{state === 'committing' ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
'Godkänn'
)}
</Button>
<Button
variant="outline"
size="sm"
onClick={() => setShowRejectForm(true)}
disabled={isBusy}
className="flex-1"
>
Avslå
</Button>
</div>
{/* Keep in sync with EXPIRY_DAYS in
app/api/pending-operations/expire/cron/route.ts. */}
<p className="text-[11px] text-muted-foreground">
Om du inte gör något utgår förslaget automatiskt efter 30 dagar, inget bokförs.
</p>
</>
)}
</div>
)
}
function PeriodBadge({ status }: { status: PeriodStatus }) {
if (status.status === 'open') {
return (
<span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-success">
<ShieldCheck className="h-3 w-3" /> Period öppen
</span>
)
}
if (status.status === 'locked') {
return (
<span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-warning">
<Lock className="h-3 w-3" /> Period låst
{status.lock_date ? <span className="tabular-nums">· {status.lock_date}</span> : null}
</span>
)
}
return (
<span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-destructive">
<Lock className="h-3 w-3" /> Period stängd
</span>
)
}
function translateRisk(risk: 'low' | 'medium' | 'high'): string {
if (risk === 'low') return 'låg'
if (risk === 'medium') return 'medel'
return 'hög'
}
-377
View File
@@ -1,377 +0,0 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import dynamic from 'next/dynamic'
import { AlertTriangle, MessageSquare, Send } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { UpgradeNote } from '@/components/billing/UpgradeNote'
import { useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { cn } from '@/lib/utils'
/**
* The single-call chat console for general.help (audit Option A / rip).
*
* Replaces the streaming AgentChat runtime for free-form questions: one POST
* to /api/agent/ask, one answer, no tool loop and no NDJSON stream. That is
* exactly what lets it run on a local model (the endpoint is gated on
* `configured`, any provider, not `assistantAvailable`). The tool-loop intents
* (categorization, invoice draft, supplier review) still use AgentChat +
* run-turn.ts because they stage operations; this console is only wired where
* the intent is general.help.
*
* The surrounding view (ChatConversationView / ChatNewStarter) renders the
* header, the agent avatar and the context chip, so this component is just the
* thread + composer, the same division of labour AgentChat had.
*
* Threads persist: every turn is written server-side to
* agent_conversations/agent_messages (persist:true), so the /chat sidebar and
* "resume a conversation" keep working across old streaming threads and new
* single-call ones.
*/
// Same lazy markdown chunk AgentChat uses, so a resumed thread renders links,
// lists and tables. Loaded on demand; a plain-text fallback covers the frame
// before the chunk resolves.
const MarkdownMessage = dynamic(() => import('./MarkdownMessage'), {
ssr: false,
loading: () => null,
})
let markdownReady = false
let markdownPromise: Promise<unknown> | null = null
function prefetchMarkdown(): Promise<unknown> {
if (!markdownPromise) {
markdownPromise = import('./MarkdownMessage')
.then((mod) => {
markdownReady = true
return mod
})
.catch(() => {
// Keep the plain-text fallback; a failed chunk load must not blank the answer.
})
}
return markdownPromise
}
function useMarkdownReady(): boolean {
const [ready, setReady] = useState(markdownReady)
useEffect(() => {
if (ready) return
let alive = true
void prefetchMarkdown().then(() => {
if (alive) setReady(true)
})
return () => {
alive = false
}
}, [ready])
return ready
}
const ANSWER_PROSE =
'prose prose-sm max-w-none text-foreground [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 prose-headings:font-display prose-headings:font-normal prose-headings:tracking-tight prose-h2:text-base prose-h2:mt-3 prose-h2:mb-2 prose-h3:text-sm prose-h3:mt-3 prose-h3:mb-1 prose-p:my-2 prose-p:leading-6 prose-strong:font-semibold prose-strong:text-foreground prose-ul:my-2 prose-li:my-0.5 prose-blockquote:border-l-2 prose-blockquote:border-foreground/30 prose-blockquote:not-italic prose-blockquote:text-muted-foreground prose-blockquote:pl-3 prose-blockquote:my-2 prose-code:bg-secondary prose-code:rounded-sm prose-code:px-1 prose-code:py-0.5 prose-code:text-xs prose-code:before:content-none prose-code:after:content-none prose-a:text-foreground prose-a:underline prose-a:underline-offset-2 prose-pre:bg-secondary prose-pre:text-foreground prose-pre:border prose-pre:border-border prose-pre:rounded-lg prose-pre:my-2 prose-pre:p-3 prose-pre:text-xs prose-pre:leading-relaxed prose-pre:overflow-x-auto [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_pre_code]:text-foreground [&_pre_code]:text-xs prose-table:my-2 prose-table:text-xs prose-table:border-collapse [&_table]:w-full [&_th]:border-b [&_th]:border-border [&_th]:py-1.5 [&_th]:px-2 [&_th]:text-left [&_th]:font-medium [&_th]:text-muted-foreground [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-[10px] [&_td]:border-b [&_td]:border-border [&_td]:py-1.5 [&_td]:px-2 [&_td]:align-top [&_tbody_tr:last-child_td]:border-b-0'
// Mirrors ChatEmptyState's three so the in-console empty state and the /chat
// index offer the same way in.
const SUGGESTIONS: { label: string; prompt: string }[] = [
{
label: 'Vad är min största utgiftspost den här månaden?',
prompt: 'Vad är min största utgiftspost den här månaden? Visa de fem största kategorierna.',
},
{
label: 'Hur ser min momsrapport ut för senaste perioden?',
prompt:
'Hur ser min momsrapport ut för den senaste perioden? Vad blir moms att betala eller få tillbaka, och ser något ovanligt ut?',
},
{
label: 'När är min nästa skatte- eller momsdeadline?',
prompt: 'När är min nästa skatte- eller momsdeadline, och vad behöver jag göra inför den?',
},
]
export interface AskConsoleMessage {
role: 'user' | 'assistant'
text: string
}
interface AskConsoleProps {
/** Existing general.help thread to resume; null/undefined starts a fresh one on first send. */
initialConversationId?: string | null
/** Already-persisted turns to hydrate (from normalizeStoredMessages, text only). */
initialMessages?: AskConsoleMessage[]
/** Bound page ref ("report:vat:2026-07"); stored on a fresh thread. The header renders the chip. */
contextRef?: string | null
/** Fire this question once on mount (suggestion chips / ⌘K deep link). */
seedUserMessage?: string
/** Called with the id once a fresh thread is created, so the starter can swap the URL to /chat/[id]. */
onConversationCreated?: (id: string) => void
/** Vertical padding override for the scroller (the full-page chat uses px-6 py-8). */
scrollerClassName?: string
}
export default function AskConsole({
initialConversationId,
initialMessages,
contextRef,
seedUserMessage,
onConversationCreated,
scrollerClassName,
}: AskConsoleProps) {
const hasAi = useCapability(CAPABILITY.ai)
const [messages, setMessages] = useState<AskConsoleMessage[]>(initialMessages ?? [])
const [input, setInput] = useState('')
const [pending, setPending] = useState(false)
const [error, setError] = useState<string | null>(null)
// Set when the endpoint 503s because no AI backend is configured (self-host
// without AI_BASE_URL). Distinct from the paywall (hasAi handles that).
const [unconfigured, setUnconfigured] = useState(false)
const conversationIdRef = useRef<string | null>(initialConversationId ?? null)
const scrollerRef = useRef<HTMLDivElement>(null)
const seedFiredRef = useRef(false)
// Keep the newest turn in view. A resumed thread lands at the bottom too,
// which is where the composer is.
useEffect(() => {
const el = scrollerRef.current
if (el) el.scrollTop = el.scrollHeight
}, [messages, pending])
const send = useCallback(
async (raw: string) => {
const question = raw.trim()
if (!question || pending) return
setInput('')
setError(null)
setUnconfigured(false)
setMessages((prev) => [...prev, { role: 'user', text: question }])
setPending(true)
try {
const res = await fetch('/api/agent/ask', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question,
persist: true,
conversation_id: conversationIdRef.current,
// context_ref only binds a FRESH thread; a resumed one already has it.
context_ref: conversationIdRef.current ? undefined : (contextRef ?? undefined),
}),
})
if (res.status === 503) {
setUnconfigured(true)
return
}
if (!res.ok) {
let message = 'Något gick fel. Försök igen.'
try {
const b = (await res.json()) as { error?: unknown }
if (typeof b?.error === 'string') message = b.error
} catch {
// keep the default
}
setError(message)
return
}
const body = (await res.json()) as {
data?: { answer?: string; conversation_id?: string }
}
const answer = body?.data?.answer ?? ''
const convId = body?.data?.conversation_id
if (convId && !conversationIdRef.current) {
conversationIdRef.current = convId
onConversationCreated?.(convId)
}
if (answer.trim().length === 0) {
// Belt and braces with the server's 502 guard: a 200 whose answer is
// empty must not append an invisible bubble ("Tänker" collapses and
// nothing appears). Same message the server sends on 502; the thread
// id (if one was created) is kept above so a retry lands in it.
setError('Assistenten gav inget svar. Försök igen.')
return
}
setMessages((prev) => [...prev, { role: 'assistant', text: answer }])
} catch {
setError('Kunde inte nå assistenten. Kontrollera anslutningen och försök igen.')
} finally {
setPending(false)
}
},
[pending, contextRef, onConversationCreated],
)
// Auto-fire a seeded question exactly once (a suggestion chip the user
// actually clicked, not an unprompted greeting: RIP-1 removed that).
useEffect(() => {
if (seedFiredRef.current) return
const seed = seedUserMessage?.trim()
if (!seed) return
seedFiredRef.current = true
void send(seed)
}, [seedUserMessage, send])
const showEmpty = messages.length === 0 && !pending && !unconfigured
return (
<div className="flex flex-1 min-h-0 flex-col">
<div
ref={scrollerRef}
className={cn('flex-1 overflow-y-auto px-5 py-6 space-y-6', scrollerClassName)}
>
{showEmpty ? (
<EmptyState onPick={(p) => void send(p)} canSend={hasAi} />
) : (
<>
{messages.map((m, i) => (
<MessageRow key={i} message={m} />
))}
{pending && <ThinkingRow />}
</>
)}
{unconfigured && <UnconfiguredNotice />}
{error && (
<div className="rounded-lg border border-destructive/50 bg-destructive/10 px-4 py-3 text-sm text-destructive">
{error}
</div>
)}
</div>
{/* Paywall parity with AgentChat: the ask endpoint 403s without CAPABILITY.ai,
so replace the composer with an upsell rather than offer an input that can't send. */}
{!hasAi ? (
<div className="border-t border-border px-5 pt-4 pb-[calc(env(safe-area-inset-bottom,0px)+1rem)]">
<UpgradeNote>AI-assistenten kräver ett abonnemang.</UpgradeNote>
</div>
) : (
<form
className="border-t border-border px-5 pt-4 pb-[calc(env(safe-area-inset-bottom,0px)+1rem)]"
onSubmit={(e) => {
e.preventDefault()
void send(input)
}}
>
<div className="flex items-end gap-2">
<textarea
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Skriv din fråga…"
rows={1}
disabled={pending}
className="flex-1 resize-none rounded-lg border border-border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring max-h-32 overflow-y-auto disabled:opacity-60"
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
void send(input)
}
}}
/>
<Button
type="submit"
size="icon"
disabled={pending || input.trim().length === 0}
aria-label="Skicka"
>
<Send className="h-4 w-4" />
</Button>
</div>
<p className="mt-2 text-[11px] text-muted-foreground">
Enter att skicka · Shift+Enter för ny rad
</p>
</form>
)}
</div>
)
}
function MessageRow({ message }: { message: AskConsoleMessage }) {
const isUser = message.role === 'user'
const markdownLoaded = useMarkdownReady()
if (isUser) {
return (
<div className="flex justify-end">
<div className="max-w-[85%] rounded-lg bg-secondary px-4 py-3 text-sm leading-6 text-foreground whitespace-pre-wrap">
{message.text}
</div>
</div>
)
}
// Assistant answer: bare prose, no card (the sign-off design).
return (
<div className="flex">
<div className={cn('max-w-[88%]', ANSWER_PROSE)}>
{markdownLoaded ? (
<MarkdownMessage text={message.text} />
) : (
<p className="whitespace-pre-wrap">{message.text}</p>
)}
</div>
</div>
)
}
function ThinkingRow() {
return (
<div className="flex" aria-live="polite">
<div className="inline-flex items-center gap-2 text-sm text-muted-foreground">
<span className="inline-flex gap-1">
<span className="h-1.5 w-1.5 rounded-full bg-muted-foreground/70 animate-bounce [animation-delay:-0.3s]" />
<span className="h-1.5 w-1.5 rounded-full bg-muted-foreground/70 animate-bounce [animation-delay:-0.15s]" />
<span className="h-1.5 w-1.5 rounded-full bg-muted-foreground/70 animate-bounce" />
</span>
Tänker
</div>
</div>
)
}
function EmptyState({ onPick, canSend }: { onPick: (prompt: string) => void; canSend: boolean }) {
return (
<div className="flex flex-1 flex-col items-center justify-center py-10 text-center">
<div className="mb-3.5 grid h-9 w-9 place-items-center rounded-lg bg-secondary text-foreground">
<MessageSquare className="h-[18px] w-[18px]" />
</div>
<h3 className="mb-1.5 text-[15px] font-medium text-foreground">Fråga om det du ser</h3>
<p className="mx-auto max-w-[34ch] text-sm text-muted-foreground">
Assistenten svarar utifrån den här sidan och din bokföring.
</p>
{canSend && (
<div className="mt-5 flex flex-col gap-2 w-full max-w-md">
{SUGGESTIONS.map((s) => (
<button
key={s.label}
type="button"
onClick={() => onPick(s.prompt)}
className="rounded-lg border border-border bg-card px-4 py-3 text-left text-sm text-muted-foreground transition-colors hover:border-foreground/30 hover:bg-secondary/30 hover:text-foreground"
>
{s.label}
</button>
))}
</div>
)}
</div>
)
}
function UnconfiguredNotice() {
return (
<div className="flex items-start gap-3 rounded-lg border border-border bg-secondary/40 px-4 py-3 text-sm">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warning" />
<div>
<strong className="font-medium">Assistenten är inte konfigurerad</strong>
<p className="mt-1 text-muted-foreground">
Den här installationen har ingen AI-modell inställd. Sätt{' '}
<code className="rounded-sm bg-secondary px-1 py-0.5 text-xs">AI_BASE_URL</code> och{' '}
<code className="rounded-sm bg-secondary px-1 py-0.5 text-xs">AI_MODEL</code> (t.ex. en
lokal modell) så svarar assistenten. Bokföringen och underlagstolkningen påverkas inte.
</p>
</div>
</div>
)
}
-106
View File
@@ -1,106 +0,0 @@
'use client'
import { useMemo } from 'react'
import Link from 'next/link'
import { ArrowLeft } from 'lucide-react'
import AgentChat, { attachStagedOperations, normalizeStoredMessages } from './AgentChat'
import AskConsole, { type AskConsoleMessage } from './AskConsole'
import { CHAT_INTENT_ID } from '@/lib/agent/ask/persist'
import type { StoredStagedOperation } from '@/types'
import AgentAvatar from './AgentAvatar'
import ContextChip from './ContextChip'
import SandboxAgentPreview from './SandboxAgentPreview'
import { useAgentSheet } from './AgentSheetProvider'
import { useCompanyOptional } from '@/contexts/CompanyContext'
interface Props {
conversationId: string
intentId: string
contextRef: string | null
title: string
rawMessages: { role: string; content: unknown; hidden?: boolean }[]
// Proposals this conversation staged that are still awaiting an answer, so
// the approval card reappears on resume instead of the proposal silently
// waiting out its expiry in Granskning.
stagedOperations?: StoredStagedOperation[]
}
// Full-page conversation view. Wraps AgentChat with a header that shows the
// title (or intent label). AgentChat handles the streaming + input + render.
export default function ChatConversationView({
conversationId,
intentId,
contextRef,
title,
rawMessages,
stagedOperations,
}: Props) {
const initialMessages = useMemo(
() => attachStagedOperations(normalizeStoredMessages(rawMessages), stagedOperations ?? []),
[rawMessages, stagedOperations],
)
// general.help runs on the single-call console; it never stages operations,
// so the thread is text-only. Empty turns (a historical pure-tool_use row
// from the old runtime) are dropped rather than rendered as blank rows.
const isSingleCall = intentId === CHAT_INTENT_ID
const consoleMessages = useMemo<AskConsoleMessage[]>(
() =>
normalizeStoredMessages(rawMessages)
.filter((m) => m.text.trim().length > 0)
.map((m) => ({ role: m.role, text: m.text })),
[rawMessages],
)
const { identity } = useAgentSheet()
const companyCtx = useCompanyOptional()
const isSandbox = companyCtx?.isSandbox ?? false
const agentName = identity.displayName?.trim() || null
return (
<>
<header className="flex items-center gap-3 border-b border-border px-5 py-4 shrink-0">
{/* Mobile-only back-to-list arrow. On desktop the sidebar is always
visible so a back button would be redundant. */}
<Link
href="/chat"
className="md:hidden inline-flex h-9 w-9 items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground transition-colors -ml-1"
aria-label="Tillbaka till konversationer"
>
<ArrowLeft className="h-4 w-4" />
</Link>
<AgentAvatar
avatarId={identity.avatarId}
size="sm"
alt={identity.displayName ?? 'Assistent'}
/>
<div className="min-w-0">
<h1 className="font-display text-lg leading-tight tracking-tight truncate">{title}</h1>
{/* Was printing context_ref raw, so the subtitle read
"invoice:5f3a-9c21-...": a database identifier, shown to an
accountant, under the title of their own conversation. */}
<ContextChip contextRef={contextRef} className="mt-0.5" />
</div>
</header>
<div className="flex-1 min-h-0 flex flex-col">
{isSandbox ? (
<SandboxAgentPreview agentName={agentName} />
) : isSingleCall ? (
<AskConsole
initialConversationId={conversationId}
initialMessages={consoleMessages}
contextRef={contextRef}
scrollerClassName="px-6 py-8"
/>
) : (
<AgentChat
intentId={intentId}
contextRef={contextRef ?? undefined}
initialConversationId={conversationId}
initialMessages={initialMessages}
scrollerClassName="px-6 py-8"
/>
)}
</div>
</>
)
}
-132
View File
@@ -1,132 +0,0 @@
'use client'
import { ArrowUpRight, Sparkles } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { useAgentSheet } from './AgentSheetProvider'
import AgentAvatar from './AgentAvatar'
import { useCompanyOptional, useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { createClient } from '@/lib/supabase/client'
// Tiny client component for /chat empty state. Reads the agent identity from
// the provider so it can show the user's chosen avatar + name above the
// "starta en konversation" CTA.
//
// The three suggestion chips below the headline give users a one-click way
// in. They navigate to /chat/new?intent=…&prompt=… which mounts AgentChat
// inline and swaps to /chat/[id] once the conversation is created: so the
// flow stays full-screen instead of opening a slide-in sheet.
const SUGGESTIONS: { label: string; prompt: string }[] = [
{
label: 'Vad är min största utgiftspost den här månaden?',
prompt: 'Vad är min största utgiftspost den här månaden? Visa de fem största kategorierna.',
},
{
label: 'Hur ser min momsrapport ut för senaste perioden?',
prompt: 'Hur ser min momsrapport ut för den senaste perioden? Vad blir moms att betala eller få tillbaka, och ser något ovanligt ut?',
},
{
label: 'När är min nästa skatte- eller momsdeadline?',
prompt: 'När är min nästa skatte- eller momsdeadline, och vad behöver jag göra inför den?',
},
]
export default function ChatEmptyState() {
const { identity } = useAgentSheet()
const companyCtx = useCompanyOptional()
const router = useRouter()
const isSandbox = companyCtx?.isSandbox ?? false
const hasAi = useCapability(CAPABILITY.ai)
const name = identity.displayName?.trim() || 'din assistent'
if (isSandbox) {
const handleCreateAccount = async () => {
const supabase = createClient()
// Sign-out is best-effort: navigate even if Supabase is unreachable
// so the button never looks dead.
try {
await supabase.auth.signOut()
} catch {
// Intentionally swallowed.
}
router.push('/register')
}
return (
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
<div className="rounded-lg border border-border bg-secondary/40 px-5 py-4 max-w-md mb-6 text-left">
<div className="flex items-center gap-2 text-sm font-medium">
<Sparkles className="h-4 w-4" />
Avstängd i sandlådan
</div>
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
AI-assistenten använder en betald molntjänst och är därför
inaktiverad här. I den fullständiga produkten kan {name} kategorisera
transaktioner, granska leverantörsfakturor och svara på frågor om
din bokföring.
</p>
</div>
<Button size="lg" onClick={handleCreateAccount}>
Skapa konto för att använda {name}
</Button>
</div>
)
}
if (!hasAi) {
return (
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
<div className="rounded-lg border border-border bg-secondary/40 px-5 py-4 max-w-md mb-6 text-left">
<div className="flex items-center gap-2 text-sm font-medium">
<Sparkles className="h-4 w-4" />
Ingår i abonnemanget
</div>
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
AI-assistenten använder en betald molntjänst. Uppgradera för att låta
{' '}{name} kategorisera transaktioner, granska leverantörsfakturor
och svara på frågor om din bokföring.
</p>
</div>
<Button size="lg" asChild>
<Link href="/settings/billing">Uppgradera för att använda {name}</Link>
</Button>
</div>
)
}
// Hidden on mobile: the sidebar IS the page when no conversation is open.
// On desktop, fills the right pane with a centered prompt.
return (
<div className="hidden md:flex flex-1 flex-col items-center justify-center px-6 py-12 text-center">
<AgentAvatar avatarId={identity.avatarId} size="lg" alt={name} className="mb-5" />
<h1 className="font-display text-2xl tracking-tight mb-2">Fråga {name}</h1>
<p className="text-muted-foreground max-w-md mb-6">
Välj en konversation till vänster, eller starta en ny om något har dykt upp.
</p>
<div className="flex flex-col gap-2 w-full max-w-md mb-6">
{SUGGESTIONS.map((s) => (
<Link
key={s.label}
href={`/chat/new?intent=general.help&prompt=${encodeURIComponent(s.prompt)}`}
className="group flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3 text-left text-sm transition-colors hover:border-foreground/30 hover:bg-secondary/30"
>
<span className="flex-1 text-muted-foreground group-hover:text-foreground transition-colors">
{s.label}
</span>
<ArrowUpRight className="h-3.5 w-3.5 shrink-0 text-muted-foreground/60 group-hover:text-foreground transition-colors" />
</Link>
))}
</div>
<Button size="lg" variant="outline" asChild>
<Link href="/chat/new?intent=general.help">Eller skriv din egen fråga</Link>
</Button>
</div>
)
}
-67
View File
@@ -1,67 +0,0 @@
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
import AgentChat from './AgentChat'
import AgentAvatar from './AgentAvatar'
import SandboxAgentPreview from './SandboxAgentPreview'
import { useAgentSheet } from './AgentSheetProvider'
import { useCompanyOptional } from '@/contexts/CompanyContext'
// Phase C entry surface. Lands here from ReviewCard's "kör" after Phase B
// verify succeeds. Renders AgentChat in fresh-start mode: no
// initialConversationId, no initialMessages: so the auto-fire effect
// kicks the first invoke. As soon as /api/agent/invoke emits the
// conversation event, the URL swaps to /chat/[id] so reload / share /
// browser-back all work like any other conversation.
//
// Plan refs: §7 Phase C.
export default function ChatIntakeStarter() {
const router = useRouter()
const { identity } = useAgentSheet()
const companyCtx = useCompanyOptional()
const isSandbox = companyCtx?.isSandbox ?? false
const agentName = identity.displayName?.trim() || 'Din assistent'
// Lock the swap to the first id we see: defensive guard against the
// AgentChat callback firing twice during React 19 Strict Mode reruns.
const [swapped, setSwapped] = useState(false)
return (
<>
<header className="flex items-center gap-3 border-b border-border px-6 py-4 shrink-0">
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName} />
<div className="min-w-0">
<h1 className="font-display text-lg tracking-tight truncate">{agentName} är redo</h1>
<p className="text-xs text-muted-foreground">
{isSandbox
? 'Förhandsvisning: den verkliga konversationen kräver ett konto.'
: 'Några frågor för att lära känna din verksamhet: svara i din egen takt, du kan avsluta när du vill.'}
</p>
</div>
</header>
<div className="flex-1 min-h-0 flex flex-col">
{isSandbox ? (
<SandboxAgentPreview agentName={agentName} />
) : (
<AgentChat
intentId="onboarding.intake"
initialMessages={[]}
initialConversationId={null}
onFirstTurnComplete={(id) => {
// Wait for the greeting to finish streaming AND persist before
// swapping the URL. Swapping on the early `conversation` event
// unmounts AgentChat mid-stream, so the greeting is never saved
// and /chat/[id] hydrates empty: the bug where the chat lands
// blank and only shows the intro on a later visit.
if (swapped) return
setSwapped(true)
router.replace(`/chat/${id}`)
}}
scrollerClassName="px-6 py-8"
/>
)}
</div>
</>
)
}
-81
View File
@@ -1,81 +0,0 @@
'use client'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
import AgentChat from './AgentChat'
import AskConsole from './AskConsole'
import { CHAT_INTENT_ID } from '@/lib/agent/ask/persist'
import AgentAvatar from './AgentAvatar'
import SandboxAgentPreview from './SandboxAgentPreview'
import { useAgentSheet } from './AgentSheetProvider'
import { useCompanyOptional } from '@/contexts/CompanyContext'
// Inline starter used by suggestion chips and ⌘K. Mirrors ChatIntakeStarter
// but accepts any intent + seed so we don't fork the intake-specific
// onboarding path. When AgentChat emits the new conversation_id, the URL
// is swapped to /chat/[id] so reload / share / browser-back all work.
export default function ChatNewStarter({
intentId,
seedUserMessage,
}: {
intentId: string
seedUserMessage?: string
}) {
const router = useRouter()
const { identity } = useAgentSheet()
const companyCtx = useCompanyOptional()
const isSandbox = companyCtx?.isSandbox ?? false
const agentName = identity.displayName?.trim() || 'Din assistent'
const [swapped, setSwapped] = useState(false)
const isSingleCall = intentId === CHAT_INTENT_ID
const swapToConversation = (id: string) => {
// Swap once, after the turn is created. For the single-call console both
// the question and the answer are already persisted by the time we get the
// id back, so /chat/[id] hydrates the full thread.
if (swapped) return
setSwapped(true)
router.replace(`/chat/${id}`)
}
return (
<>
<header className="flex items-center gap-3 border-b border-border px-6 py-4 shrink-0">
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName} />
<div className="min-w-0">
<h1 className="font-display text-lg tracking-tight truncate">{agentName}</h1>
<p className="text-xs text-muted-foreground truncate">
{isSandbox ? 'Förhandsvisning: avstängd i sandlådan' : 'Ny konversation'}
</p>
</div>
</header>
<div className="flex-1 min-h-0 flex flex-col">
{isSandbox ? (
<SandboxAgentPreview agentName={agentName} />
) : isSingleCall ? (
<AskConsole
seedUserMessage={seedUserMessage}
initialConversationId={null}
onConversationCreated={swapToConversation}
scrollerClassName="px-6 py-8"
/>
) : (
<AgentChat
intentId={intentId}
seedUserMessage={seedUserMessage}
initialMessages={[]}
initialConversationId={null}
onFirstTurnComplete={(id) => {
// Wait for the first turn to finish before swapping the URL:
// otherwise the unmount aborts the in-flight stream and
// /chat/[id] hydrates with only the user message.
swapToConversation(id)
}}
scrollerClassName="px-6 py-8"
/>
)}
</div>
</>
)
}
-283
View File
@@ -1,283 +0,0 @@
'use client'
import { useEffect, useState, useTransition } from 'react'
import Link from 'next/link'
import { usePathname, useRouter } from 'next/navigation'
import { Pin, PinOff, Archive, Pencil, Search, X, PanelLeftOpen, PanelLeftClose } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useAgentSheet } from './AgentSheetProvider'
import AgentAvatar from './AgentAvatar'
import {
type ConversationRow,
BUCKET_LABELS,
relativeTime,
intentLabel,
} from './conversation-display'
import { useConversationList } from './use-conversation-list'
interface Props {
initialConversations: ConversationRow[]
}
export default function ChatSidebar({ initialConversations }: Props) {
const router = useRouter()
const pathname = usePathname()
const { openAgentSheet, identity } = useAgentSheet()
const agentName = identity.displayName?.trim() || null
// State + all three mutations live in the shared hook so this surface and the
// in-sheet list cannot drift apart again. Pin/archive/rename here used to be
// fire-and-forget with no rollback.
const {
conversations,
query,
setQuery,
grouped,
togglePin,
archive: archiveConversation,
editingId,
editValue,
setEditValue,
startEdit,
cancelEdit,
commitEdit,
} = useConversationList(initialConversations)
const [, startTransition] = useTransition()
// Collapsed by default; persisted across reloads so power users keep
// their preference. Hidden behind a thin rail when collapsed so the
// conversation pane runs nearly edge-to-edge.
const [collapsed, setCollapsed] = useState(true)
useEffect(() => {
const stored = localStorage.getItem('Accounted:chat-sidebar-collapsed')
if (stored === 'false') setCollapsed(false)
}, [])
const toggleCollapsed = () => {
setCollapsed(c => {
const next = !c
try { localStorage.setItem('Accounted:chat-sidebar-collapsed', next ? 'true' : 'false') } catch {}
return next
})
}
const activeId = pathname?.startsWith('/chat/') ? pathname.split('/')[2] : null
const isConversationOpen = !!activeId
async function archive(id: string) {
const removed = await archiveConversation(id)
if (removed && activeId === id) startTransition(() => router.push('/chat'))
}
// Collapsed rail (desktop only). Mobile keeps the existing behavior where
// the sidebar IS the page when no conversation is open, so the rail is
// hidden below md. On desktop the rail keeps a thin column with toggle
// + new-chat buttons so the conversation pane runs near-edge-to-edge.
const railAside = collapsed ? (
<aside
className="hidden md:flex md:w-12 flex-col items-center border-r border-border bg-card/40 shrink-0 py-3 gap-2"
aria-label="Konversationer (hopfälld)"
>
<button
type="button"
onClick={toggleCollapsed}
aria-label="Visa konversationer"
title="Visa konversationer"
className="inline-flex h-9 w-9 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
>
<PanelLeftOpen className="h-4 w-4" />
</button>
<div className="h-px w-6 bg-border" />
<button
type="button"
onClick={() => openAgentSheet({ intentId: 'general.help' })}
aria-label="Ny konversation"
title="Ny konversation"
className="inline-flex h-9 w-9 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors text-lg"
>
+
</button>
</aside>
) : null
return (
<>
{railAside}
<aside
className={cn(
'flex-col border-r border-border bg-card/40 shrink-0',
// Mobile: sidebar IS the page when no conversation; hidden otherwise.
isConversationOpen ? 'hidden' : 'flex w-full',
// Desktop: hidden if collapsed (rail takes its place); else 320px.
collapsed ? 'md:hidden' : 'md:flex md:w-80',
)}
>
<div className="border-b border-border px-5 py-4 space-y-3">
<div className="flex items-center gap-2">
<AgentAvatar avatarId={identity.avatarId} size="sm" alt={agentName ?? 'Assistent'} />
<div className="flex-1 min-w-0">
<h2 className="font-display text-base tracking-tight truncate">
{agentName ?? 'Din assistent'}
</h2>
<p className="text-[11px] text-muted-foreground">Konversationer</p>
</div>
<button
onClick={toggleCollapsed}
aria-label="Dölj konversationer"
title="Dölj konversationer"
className="hidden md:inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground hover:text-foreground hover:bg-secondary/60 transition-colors"
>
<PanelLeftClose className="h-4 w-4" />
</button>
<button
onClick={() => openAgentSheet({ intentId: 'general.help' })}
className="text-xs uppercase tracking-wider text-muted-foreground hover:text-foreground transition-colors"
>
+ Ny
</button>
</div>
<div className="relative">
<Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Sök…"
className="w-full rounded-lg border border-border bg-background pl-8 pr-7 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
{query.length > 0 && (
<button
type="button"
onClick={() => setQuery('')}
aria-label="Rensa sökning"
className="absolute right-1 top-1/2 -translate-y-1/2 inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground hover:bg-secondary hover:text-foreground"
>
<X className="h-3 w-3" />
</button>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto">
{grouped.length === 0 ? (
<div className="p-6 text-sm text-muted-foreground">
{conversations.length === 0
? 'Inga konversationer ännu. Klicka på + Ny för att börja.'
: 'Inga träffar.'}
</div>
) : (
grouped.map(({ bucket, rows }) => (
<section key={bucket} className="py-2">
<p className="px-4 pb-1 text-[10px] uppercase tracking-wider text-muted-foreground">
{BUCKET_LABELS[bucket]}
</p>
<ul className="space-y-1">
{rows.map((c) => (
<li key={c.id}>
{editingId === c.id ? (
<div className="px-4 py-2">
<input
autoFocus
value={editValue}
onChange={(e) => setEditValue(e.target.value)}
onBlur={() => void commitEdit(c.id)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
;(e.target as HTMLInputElement).blur()
} else if (e.key === 'Escape') {
e.preventDefault()
cancelEdit()
}
}}
placeholder="Namnge konversationen…"
maxLength={200}
aria-label="Nytt namn på konversationen"
className="w-full rounded-lg border border-border bg-background px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
) : (
<Link
href={`/chat/${c.id}`}
className={cn(
'group flex items-start gap-2 px-4 py-2 hover:bg-secondary/60 transition-colors border-l-2',
activeId === c.id
? 'bg-secondary/50 border-foreground'
: 'border-transparent',
)}
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<p className="text-sm font-medium truncate flex-1 min-w-0">
{c.title ?? intentLabel(c.intent_id)}
</p>
<p className="text-[11px] text-muted-foreground tabular-nums shrink-0">
{relativeTime(c.last_message_at ?? c.created_at)}
</p>
</div>
<p className="text-xs text-muted-foreground line-clamp-1 mt-0.5">
{c.last_message_preview ?? intentLabel(c.intent_id)}
</p>
</div>
{/* Always-visible action icons. Touch-friendly, no
hover-only invisibility on mobile. Laid out
horizontally so three icons don't stack and inflate
the row height. */}
<div className="flex items-center gap-1 shrink-0 -mr-1">
<button
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
startEdit(c)
}}
title="Byt namn"
aria-label="Byt namn på konversation"
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground/50 hover:text-foreground hover:bg-secondary transition-colors"
>
<Pencil className="h-3 w-3" />
</button>
<button
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
void togglePin(c.id, c.pinned)
}}
title={c.pinned ? 'Avfäst' : 'Fäst'}
aria-label={c.pinned ? 'Avfäst konversation' : 'Fäst konversation'}
className={cn(
'inline-flex h-8 w-8 items-center justify-center rounded-sm transition-colors',
c.pinned
? 'text-foreground'
: 'text-muted-foreground/50 hover:text-foreground hover:bg-secondary',
)}
>
{c.pinned ? (
<Pin className="h-3 w-3" fill="currentColor" />
) : (
<PinOff className="h-3 w-3" />
)}
</button>
<button
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
void archive(c.id)
}}
title="Arkivera"
aria-label="Arkivera konversation"
className="inline-flex h-8 w-8 items-center justify-center rounded-sm text-muted-foreground/50 hover:text-foreground hover:bg-secondary transition-colors"
>
<Archive className="h-3 w-3" />
</button>
</div>
</Link>
)}
</li>
))}
</ul>
</section>
))
)}
</div>
</aside>
</>
)
}
-59
View File
@@ -1,59 +0,0 @@
'use client'
import Link from 'next/link'
import { ArrowUpRight } from 'lucide-react'
import { contextRefToTarget } from '@/lib/agent/intents/route-mapping'
import { cn } from '@/lib/utils'
/**
* What a conversation is anchored to, as a chip.
*
* `agent_conversations.context_ref` has been written since the first intents
* shipped. The panel ignored it entirely, and /chat printed it raw, so a
* resumed thread's subtitle read "invoice:5f3a-9c21-...": a database
* identifier shown to an accountant. Both surfaces now render the same chip,
* which names the thing and links to it.
*
* Kind-agnostic on purpose (plan seam 8.4): the mapping lives in
* route-mapping.ts, so teaching every surface about a new ref kind is one
* entry in that map and no component change. A kind the map does not know
* yet, a flow run for instance, renders nothing rather than a broken link.
*/
export default function ContextChip({
contextRef,
className,
}: {
contextRef: string | null | undefined
className?: string
}) {
const target = contextRefToTarget(contextRef)
if (!target) return null
const shape =
'inline-flex max-w-full items-center gap-1 rounded-full border border-border px-2 py-0.5 text-xs text-muted-foreground'
// Not every context has a page to go to: the document inbox is an extension
// route, and core cannot hardcode a path that exists only when the extension
// is enabled. Naming it without linking beats a link that 404s.
if (!target.href) {
return (
<span className={cn(shape, className)}>
<span className="truncate">{target.label}</span>
</span>
)
}
return (
<Link
href={target.href}
className={cn(
shape,
'hover:bg-secondary hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
className,
)}
>
<span className="truncate">{target.label}</span>
<ArrowUpRight className="h-3 w-3 shrink-0" />
</Link>
)
}
-68
View File
@@ -1,68 +0,0 @@
'use client'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import Link from 'next/link'
import { isInternalHref } from './markdown-links'
/**
* Isolated so AgentChat can load the markdown parser (react-markdown +
* remark-gfm and their unified/remark dependency tree) via next/dynamic:
* the chunk is fetched when the first assistant message renders instead of
* being parsed eagerly whenever the chat surface mounts.
*/
export default function MarkdownMessage({ text }: { text: string }) {
return (
<ReactMarkdown remarkPlugins={[remarkGfm]} components={{ a: MarkdownLink }}>
{text}
</ReactMarkdown>
)
}
/**
* Links inside an answer.
*
* These were plain anchors, so following one the agent had written did a full
* document load: the whole app rebooted and the conversation went with it, in
* the panel and in /chat alike. Internal links now route client-side, which
* keeps the thread alive beside the page the user just opened, which is the
* point of docking the panel in the first place.
*
* External links open in a new tab for the same reason, and carry
* rel="noopener noreferrer": the href came out of a model that reads customer
* documents, and target="_blank" without it hands the opened page a
* window.opener handle back into an authenticated session.
*/
function MarkdownLink({
href,
title,
children,
}: {
href?: string
// Markdown carries an optional title: [text](url "title"). Dropping it here
// would silently discard something the answer's author wrote.
title?: string
children?: React.ReactNode
}) {
if (!href) return <>{children}</>
if (isInternalHref(href)) {
return (
<Link href={href} title={title} className="underline underline-offset-2">
{children}
</Link>
)
}
return (
<a
href={href}
title={title}
target="_blank"
rel="noopener noreferrer"
className="underline underline-offset-2"
>
{children}
</a>
)
}
-111
View File
@@ -1,111 +0,0 @@
'use client'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Sparkles, ArrowRight } from 'lucide-react'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
/**
* Stand-in for AgentChat in the sandbox. The real chat surface POSTs to
* /api/agent/invoke which is server-gated by guardSandbox(), so the input
* would just produce a 403. Instead of showing that as a raw error, we
* render a brief description of what the assistant does in prod and a
* single "Skapa konto" CTA. Same chrome (header) as the real chat: only
* the body swaps out.
*
* Mirrors the look of the empty-state but with an explanation block so the
* sandbox user understands what they're seeing without typing into a
* dead-end input.
*/
export default function SandboxAgentPreview({
agentName,
}: {
agentName: string | null
}) {
const router = useRouter()
const name = agentName?.trim() || 'din assistent'
async function handleCreateAccount() {
const supabase = createClient()
// Sign-out is best-effort: a transient Supabase failure shouldn't
// strand the user on a dead button; navigate to /register either way
// and let the registration flow re-init auth state.
try {
await supabase.auth.signOut()
} catch {
// Intentionally swallowed: see comment above.
}
router.push('/register')
}
return (
<div className="flex-1 flex flex-col">
<div className="flex-1 overflow-y-auto px-5 py-8">
<div className="mx-auto max-w-md space-y-6">
<div className="rounded-lg border border-border bg-secondary/40 p-5">
<div className="flex items-center gap-2 text-sm font-medium">
<Sparkles className="h-4 w-4" />
Förhandsvisning i sandlådan
</div>
<p className="text-sm text-muted-foreground mt-2 leading-relaxed">
{name} är en specialiserad bokföringsassistent som kan
kategorisera transaktioner, granska leverantörsfakturor och
svara på frågor om din bokföring: kalibrerad mot dina
kontoplaner, verksamhet och svensk skattelagstiftning.
</p>
<p className="text-sm text-muted-foreground mt-3 leading-relaxed">
I sandlådan är AI-funktionerna avstängda eftersom de använder
externa AI-tjänster som kostar pengar att köra. Skapa ett
konto för att aktivera assistenten på riktigt.
</p>
</div>
<ul className="space-y-2 text-sm text-muted-foreground">
<li className="flex items-start gap-2">
<span className="text-foreground mt-0.5">·</span>
<span>
<span className="text-foreground">Föreslår bokföring</span>{' '}
för oklassificerade transaktioner: du godkänner i ett klick.
</span>
</li>
<li className="flex items-start gap-2">
<span className="text-foreground mt-0.5">·</span>
<span>
<span className="text-foreground">Förklarar momsrutor</span>,
årets resultat och vad som driver KPI:erna.
</span>
</li>
<li className="flex items-start gap-2">
<span className="text-foreground mt-0.5">·</span>
<span>
<span className="text-foreground">Granskar verifikat</span>{' '}
och föreslår rättningar enligt BFL och K2.
</span>
</li>
</ul>
</div>
</div>
<div className="border-t border-border px-5 pt-4 pb-[calc(env(safe-area-inset-bottom,0px)+1rem)]">
<div className="flex items-center gap-2">
<Button
type="button"
className="flex-1"
onClick={handleCreateAccount}
>
Skapa konto för att använda {name}
<ArrowRight className="ml-1.5 h-4 w-4" />
</Button>
</div>
<p className="mt-2 text-[11px] text-muted-foreground">
Sandlådedata raderas efter 24 timmar.{' '}
<Link href="/register" className="underline underline-offset-2 hover:text-foreground">
Skapa konto
</Link>
.
</p>
</div>
</div>
)
}
@@ -1,120 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
INITIAL_AGENT_STATUS,
collapsedStatusLabel,
reduceAgentStatus,
type AgentStatus,
type AgentStatusEvent,
} from '../agent-status'
/**
* What this protects: a user who minimizes the panel mid-answer used to lose
* every signal about it. The reducer is what decides whether the trigger says
* "arbetar", "är klar", or nothing at all, so these are the real transitions,
* not a description of them.
*/
function run(events: AgentStatusEvent[], from: AgentStatus = INITIAL_AGENT_STATUS): AgentStatus {
return events.reduce(reduceAgentStatus, from)
}
describe('reduceAgentStatus', () => {
it('reports a finished turn only when it finished out of sight', () => {
const onScreen = run([{ type: 'turn_start' }, { type: 'turn_end' }])
expect(onScreen.activity).toBe('idle')
const hidden = run([
{ type: 'turn_start' },
{ type: 'visibility', visible: false },
{ type: 'turn_end' },
])
expect(hidden.activity).toBe('done')
})
it('clears the finished-turn signal once the panel is back on screen', () => {
const seen = run([
{ type: 'turn_start' },
{ type: 'visibility', visible: false },
{ type: 'turn_end' },
{ type: 'visibility', visible: true },
])
expect(seen.activity).toBe('idle')
expect(seen.step).toBeNull()
})
it('does not cancel work that is still running when the panel reopens', () => {
// Reopening mid-answer must not read as "nothing is happening": the pill
// would go quiet while the turn was still streaming.
const stillWorking = run([
{ type: 'turn_start' },
{ type: 'step', label: 'Bokar avskrivningar…' },
{ type: 'visibility', visible: false },
{ type: 'visibility', visible: true },
])
expect(stillWorking.activity).toBe('working')
expect(stillWorking.step).toBe('Bokar avskrivningar…')
})
it('keeps the latest step and drops it when the turn ends', () => {
const mid = run([
{ type: 'turn_start' },
{ type: 'step', label: 'Hämtar underlag…' },
{ type: 'step', label: 'Bokar avskrivningar…' },
])
expect(mid.step).toBe('Bokar avskrivningar…')
expect(reduceAgentStatus(mid, { type: 'turn_end' }).step).toBeNull()
})
it('treats a step for work it never saw start as working', () => {
// A stream resumed after a remount can deliver a tool event with no
// turn_start behind it; dropping it would leave the pill idle mid-turn.
expect(reduceAgentStatus(INITIAL_AGENT_STATUS, { type: 'step', label: 'Bokar…' }).activity).toBe(
'working',
)
})
it('remembers visibility across a reset so the next turn reports correctly', () => {
const afterReset = run([
{ type: 'visibility', visible: false },
{ type: 'turn_start' },
{ type: 'reset' },
{ type: 'turn_start' },
{ type: 'turn_end' },
])
expect(afterReset.activity).toBe('done')
})
it('carries the detached state built for durable runs', () => {
// Nothing dispatches this in v1. It exists so a background run publishes to
// this channel instead of the pill needing a second one.
const detached = reduceAgentStatus(INITIAL_AGENT_STATUS, {
type: 'detached',
label: 'Kör momsavstämning',
})
expect(detached.activity).toBe('detached')
expect(collapsedStatusLabel(detached, 'Anna')).toBe('Kör momsavstämning')
})
})
describe('collapsedStatusLabel', () => {
it('says nothing when there is nothing to say', () => {
expect(collapsedStatusLabel(INITIAL_AGENT_STATUS, 'Anna')).toBeNull()
})
it('drops the narration ellipsis so the pill does not read as two spinners', () => {
const working = run([{ type: 'turn_start' }, { type: 'step', label: 'Bokar avskrivningar…' }])
expect(collapsedStatusLabel(working, 'Anna')).toBe('Bokar avskrivningar')
})
it('falls back to the agent name while working without a named step', () => {
expect(collapsedStatusLabel(run([{ type: 'turn_start' }]), 'Anna')).toBe('Anna arbetar')
})
it('announces a finished turn by name', () => {
const done = run([
{ type: 'visibility', visible: false },
{ type: 'turn_start' },
{ type: 'turn_end' },
])
expect(collapsedStatusLabel(done, 'Anna')).toBe('Anna är klar')
})
})
@@ -1,143 +0,0 @@
import { describe, it, expect } from 'vitest'
import { attachStagedOperations } from '../AgentChat'
import type { StoredStagedOperation } from '@/types'
/**
* Approval cards ride on streamed `staged_operation` events, which are never
* persisted. Without re-attaching them, reopening a conversation showed the
* tool trace and the answer but no card, so an unapproved proposal waited out
* its full 30-day expiry in Granskning with nothing in the thread pointing at
* it. This is the reattachment.
*/
const op = (overrides: Partial<StoredStagedOperation> = {}): StoredStagedOperation => ({
id: 'op-1',
// As actually stored: pending_operations.operation_type is the bare action
// name, verified against prod (categorize_transaction / create_voucher /
// approve_supplier_invoice are the values in the wild).
operation_type: 'categorize_transaction',
title: 'Kontering: Circle K, 689 kr',
risk_level: 'low',
preview_data: { lines: [] },
...overrides,
})
describe('attachStagedOperations', () => {
it('returns the thread untouched when nothing is pending', () => {
const messages = [
{ role: 'user' as const, text: 'boka om' },
{ role: 'assistant' as const, text: 'klart' },
]
expect(attachStagedOperations(messages, [])).toBe(messages)
})
it('attaches a pending proposal to the last assistant turn', () => {
const messages = [
{ role: 'user' as const, text: 'boka om Circle K' },
{ role: 'assistant' as const, text: 'Klart att godkänna.' },
]
const [, assistant] = attachStagedOperations(messages, [op()])
expect(assistant!.staged).toHaveLength(1)
expect(assistant!.staged![0]).toMatchObject({
operation_id: 'op-1',
risk_level: 'low',
operation_type: 'categorize_transaction',
message: 'Kontering: Circle K, 689 kr',
})
})
it('passes the stored operation_type through untranslated, for EVERY type', () => {
// The predecessor mapped operation_type onto an MCP tool name here and
// ApprovalCard's old preview dispatch only recognized 4 of them, so a
// hydrated attach_document_to_transaction card (among others) silently
// fell back to the raw generic preview. The stored bare name now drives
// the dispatch directly; nothing may rewrite it on the way.
for (const t of [
'categorize_transaction',
'create_invoice',
'create_voucher',
'correct_entry',
'attach_document_to_transaction',
'match_transaction_invoice',
'create_customer',
'create_transaction',
]) {
const out = attachStagedOperations(
[{ role: 'assistant', text: 'svar' }],
[op({ operation_type: t })],
)
expect(out[0]!.staged![0]!.operation_type).toBe(t)
}
})
it('keeps risk level for medium and high, and floors anything unknown to low', () => {
const messages = [{ role: 'assistant' as const, text: 'svar' }]
const risks = (level: string | null) =>
attachStagedOperations(messages, [op({ risk_level: level })])[0]!.staged![0]!.risk_level
expect(risks('high')).toBe('high')
expect(risks('medium')).toBe('medium')
// An unrecognized value must not silently render as a one-click low-risk
// approval... but it also must not crash: low is the safe render, and the
// server re-checks risk on commit regardless.
expect(risks('nonsense')).toBe('low')
expect(risks(null)).toBe('low')
})
it('preserves staged cards already on the message', () => {
const messages = [
{
role: 'assistant' as const,
text: 'svar',
staged: [
{
tool_use_id: 'tu_live',
operation_id: 'op-live',
risk_level: 'low' as const,
message: 'redan här',
},
],
},
]
const out = attachStagedOperations(messages, [op({ id: 'op-2' })])
expect(out[0]!.staged!.map((s) => s.operation_id)).toEqual(['op-live', 'op-2'])
})
it('appends a carrier turn when the thread has no assistant message', () => {
// Defensive: a conversation whose assistant turn was never persisted still
// has to show its proposal rather than swallow it.
const out = attachStagedOperations([{ role: 'user', text: 'boka' }], [op()])
expect(out).toHaveLength(2)
expect(out[1]!.role).toBe('assistant')
expect(out[1]!.staged).toHaveLength(1)
})
it('attaches to the LAST assistant turn, not the first', () => {
const messages = [
{ role: 'assistant' as const, text: 'första' },
{ role: 'user' as const, text: 'och sen?' },
{ role: 'assistant' as const, text: 'andra' },
]
const out = attachStagedOperations(messages, [op()])
expect(out[0]!.staged).toBeUndefined()
expect(out[2]!.staged).toHaveLength(1)
})
it('gives every hydrated card a distinct tool_use_id key', () => {
const out = attachStagedOperations(
[{ role: 'assistant', text: 'svar' }],
[op({ id: 'op-a' }), op({ id: 'op-b' })],
)
const keys = out[0]!.staged!.map((s) => s.tool_use_id)
expect(new Set(keys).size).toBe(2)
})
})
@@ -1,85 +0,0 @@
import { describe, it, expect } from 'vitest'
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { AVATAR_OPTIONS, getAvatarUrl } from '../avatars'
/**
* These avatars used to be fetched from api.dicebear.com on every render, so
* every authenticated page view of an accounting product told a third party
* who was looking at it, and a firewalled or self-hosted install showed no
* faces at all. The point of these tests is that the registry cannot quietly
* drift back to a remote URL, and that every entry actually has a file.
*/
const PUBLIC_DIR = join(process.cwd(), 'public')
describe('AVATAR_OPTIONS', () => {
it('serves every avatar from our own origin', () => {
for (const option of AVATAR_OPTIONS) {
expect(option.url.startsWith('/'), `${option.id} must be a local path`).toBe(true)
expect(option.url).not.toMatch(/^https?:/)
expect(option.url).not.toContain('dicebear.com')
}
})
it('has a real file behind every entry', () => {
// A registry entry with no file renders a broken image, which looks like a
// bug in the agent rather than a missing asset.
for (const option of AVATAR_OPTIONS) {
expect(existsSync(join(PUBLIC_DIR, option.url)), `missing file for ${option.id}`).toBe(true)
}
})
it('ships avatars that make no network requests of their own', () => {
// Self-hosting the file is pointless if the file then phones home. This
// asserts the PROPERTY (nothing points off-origin) rather than a list of
// elements: an allowlist of <image> and xlink:href would still let a
// future asset through via <use href>, <feImage href>, or a
// scheme-relative //host, which is how this sort of guard rots.
for (const option of AVATAR_OPTIONS) {
const svg = readFileSync(join(PUBLIC_DIR, option.url), 'utf8')
// Namespace declarations and the licence metadata legitimately contain
// URLs and are never fetched, so they are removed before the check
// rather than special-cased inside it.
const referencing = svg
.replace(/<metadata[\s\S]*?<\/metadata>/gi, '')
.replace(/xmlns(:[a-z0-9-]+)?\s*=\s*"[^"]*"/gi, '')
.replace(/xsi:type\s*=\s*"[^"]*"/gi, '')
expect(referencing, `${option.id} references an absolute URL`).not.toMatch(/https?:\/\//i)
// Scheme-relative: "//host/x" inherits the page's scheme and still
// leaves the origin.
expect(referencing, `${option.id} references a scheme-relative URL`).not.toMatch(
/(href|src)\s*=\s*"\/\//i,
)
expect(referencing).not.toMatch(/url\(\s*['"]?\/\//i)
expect(referencing, `${option.id} contains a script`).not.toMatch(/<script/i)
expect(referencing, `${option.id} contains a foreignObject`).not.toMatch(/<foreignObject/i)
}
})
it('keeps ids and files one-to-one', () => {
const ids = AVATAR_OPTIONS.map((a) => a.id)
const urls = AVATAR_OPTIONS.map((a) => a.url)
expect(new Set(ids).size).toBe(ids.length)
expect(new Set(urls).size).toBe(urls.length)
})
})
describe('getAvatarUrl', () => {
it('resolves a known id and returns null otherwise', () => {
expect(getAvatarUrl('notionists-1')).toBe('/agent-avatars/notionists-1.svg')
// Null is what makes AgentAvatar fall back to its glyph, so an id from an
// older profile degrades to a placeholder rather than a broken image.
expect(getAvatarUrl('notionists-99')).toBeNull()
expect(getAvatarUrl(null)).toBeNull()
expect(getAvatarUrl(undefined)).toBeNull()
expect(getAvatarUrl('')).toBeNull()
})
it('does not resolve inherited Object keys', () => {
expect(getAvatarUrl('toString')).toBeNull()
expect(getAvatarUrl('constructor')).toBeNull()
})
})
@@ -1,246 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import type { ConversationRow } from '../conversation-display'
import {
createRevisionGuard,
patchConversation,
removeRow,
restoreRow,
runOptimisticPatch,
setPinned,
setTitle,
} from '../conversation-mutations'
/**
* These exercise the REAL transforms and the real write coordinator, not copies
* of them: deleting the rollback or the response check makes this suite fail.
*
* What is being protected: the /chat sidebar used to fire pin, archive and
* rename blind, so a failed archive removed a row that still existed on the
* server and a failed rename showed a title the server never saved, both until
* the next reload.
*/
const row = (over: Partial<ConversationRow> = {}): ConversationRow => ({
id: 'c1',
intent_id: 'general.help',
context_ref: null,
title: 'Juli mot juni',
pinned: false,
archived: false,
last_message_at: '2026-07-26T10:00:00Z',
last_message_preview: 'Juli gick 12 procent bättre',
created_at: '2026-07-26T09:00:00Z',
...over,
})
/** Minimal stand-in for React's setState updater contract. */
function fakeState(initial: ConversationRow[]) {
let current = initial
return {
set: (updater: (prev: ConversationRow[]) => ConversationRow[]) => {
current = updater(current)
},
get list() {
return current
},
}
}
beforeEach(() => {
vi.clearAllMocks()
})
afterEach(() => {
vi.restoreAllMocks()
// restoreAllMocks does not undo vi.stubGlobal, so the stubbed fetch would
// otherwise outlive this file.
vi.unstubAllGlobals()
})
describe('restoreRow', () => {
it('puts an archived row back into the CURRENT list, keeping later changes', () => {
const a = row({ id: 'a', last_message_at: '2026-07-26T12:00:00Z' })
const b = row({ id: 'b', last_message_at: '2026-07-26T11:00:00Z' })
// While the archive of `a` was in flight, the user renamed `b`.
const currentAfterOtherEdit = [{ ...b, title: 'Nytt namn' }]
const restored = restoreRow(currentAfterOtherEdit, a)
expect(restored.map((c) => c.id)).toEqual(['a', 'b'])
// The concurrent rename must survive: restoring a stale snapshot of the
// whole list would have thrown it away.
expect(restored.find((c) => c.id === 'b')!.title).toBe('Nytt namn')
})
it('re-inserts by the server ordering: pinned first, then most recent', () => {
const pinned = row({ id: 'p', pinned: true })
const newer = row({ id: 'n', last_message_at: '2026-07-26T12:00:00Z' })
const older = row({ id: 'o', last_message_at: '2026-07-20T12:00:00Z' })
expect(restoreRow([newer, older], pinned).map((c) => c.id)).toEqual(['p', 'n', 'o'])
expect(
restoreRow([pinned, older], row({ id: 'mid', last_message_at: '2026-07-25T12:00:00Z' })).map(
(c) => c.id,
),
).toEqual(['p', 'mid', 'o'])
})
it('is a no-op when the row is already present', () => {
const list = [row({ id: 'a' })]
expect(restoreRow(list, row({ id: 'a' }))).toBe(list)
})
})
describe('runOptimisticPatch', () => {
it('applies immediately and keeps the change when the server accepts it', async () => {
const state = fakeState([row({ id: 'c1' })])
const ok = await runOptimisticPatch({
id: 'c1',
body: { pinned: true },
apply: (l) => setPinned(l, 'c1', true),
revert: (l) => setPinned(l, 'c1', false),
setList: state.set,
guard: createRevisionGuard(),
onError: () => {},
patch: async () => true,
})
expect(ok).toBe(true)
expect(state.list[0]!.pinned).toBe(true)
})
it('reverts and reports when the server refuses', async () => {
const state = fakeState([row({ id: 'c1', title: 'Original' })])
const onError = vi.fn()
const ok = await runOptimisticPatch({
id: 'c1',
body: { title: 'Nytt' },
apply: (l) => setTitle(l, 'c1', 'Nytt'),
revert: (l) => setTitle(l, 'c1', 'Original'),
setList: state.set,
guard: createRevisionGuard(),
onError,
patch: async () => false,
})
expect(ok).toBe(false)
expect(state.list[0]!.title).toBe('Original')
expect(onError).toHaveBeenCalledOnce()
})
it('does not roll back over a newer write to the same row', async () => {
// Double-click on pin: the first request fails AFTER the second has already
// set the newer value. Reverting here would clobber it.
const state = fakeState([row({ id: 'c1', pinned: false })])
const guard = createRevisionGuard()
const onError = vi.fn()
let releaseFirst: (v: boolean) => void = () => {}
const first = runOptimisticPatch({
id: 'c1',
body: { pinned: true },
apply: (l) => setPinned(l, 'c1', true),
revert: (l) => setPinned(l, 'c1', false),
setList: state.set,
guard,
onError,
patch: () => new Promise<boolean>((resolve) => (releaseFirst = resolve)),
})
// Second write lands and succeeds while the first is still in flight.
await runOptimisticPatch({
id: 'c1',
body: { pinned: false },
apply: (l) => setPinned(l, 'c1', false),
revert: (l) => setPinned(l, 'c1', true),
setList: state.set,
guard,
onError,
patch: async () => true,
})
releaseFirst(false)
await first
// The newer write owns the row: its value stands and no error is shown for
// a change the user already superseded.
expect(state.list[0]!.pinned).toBe(false)
expect(onError).not.toHaveBeenCalled()
})
it('still rolls back a stale write to a DIFFERENT row', async () => {
const state = fakeState([row({ id: 'a', pinned: false }), row({ id: 'b', pinned: false })])
const guard = createRevisionGuard()
const onError = vi.fn()
await runOptimisticPatch({
id: 'b',
body: { pinned: true },
apply: (l) => setPinned(l, 'b', true),
revert: (l) => setPinned(l, 'b', false),
setList: state.set,
guard,
onError,
patch: async () => true,
})
await runOptimisticPatch({
id: 'a',
body: { pinned: true },
apply: (l) => setPinned(l, 'a', true),
revert: (l) => setPinned(l, 'a', false),
setList: state.set,
guard,
onError,
patch: async () => false,
})
expect(state.list.find((c) => c.id === 'a')!.pinned).toBe(false)
expect(state.list.find((c) => c.id === 'b')!.pinned).toBe(true)
expect(onError).toHaveBeenCalledOnce()
})
it('restores an archived row into the list as it stands when the request fails', async () => {
const archived = row({ id: 'a', last_message_at: '2026-07-26T12:00:00Z' })
const other = row({ id: 'b', last_message_at: '2026-07-26T11:00:00Z' })
const state = fakeState([archived, other])
await runOptimisticPatch({
id: 'a',
body: { archived: true },
apply: (l) => removeRow(l, 'a'),
revert: (l) => restoreRow(l, archived),
setList: state.set,
guard: createRevisionGuard(),
onError: () => {},
patch: async () => false,
})
expect(state.list.map((c) => c.id)).toEqual(['a', 'b'])
})
})
describe('patchConversation', () => {
it('reports failure for a non-2xx instead of assuming success', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 403 }))
expect(await patchConversation('c1', { pinned: true })).toBe(false)
})
it('reports failure when the request throws (offline)', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new TypeError('Failed to fetch')))
// Must not reject: an unhandled rejection was the old behaviour.
expect(await patchConversation('c1', { pinned: true })).toBe(false)
})
it('sends the PATCH to the conversation endpoint', async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
vi.stubGlobal('fetch', fetchMock)
await patchConversation('c1', { archived: true })
expect(fetchMock).toHaveBeenCalledWith(
'/api/agent/conversations/c1',
expect.objectContaining({ method: 'PATCH', body: JSON.stringify({ archived: true }) }),
)
})
})
@@ -1,71 +0,0 @@
import { describe, it, expect, vi } from 'vitest'
import { sendFeedback } from '../feedback-client'
/**
* The thumbs shipped wired to nothing: they lit up and the vote died in
* component state. These pin the contract the button now depends on, in
* particular that a failed send reports false, because the pressed state is
* set from this return value and must never claim a report that never arrived.
*/
describe('sendFeedback', () => {
it('posts the vote to the feedback endpoint', async () => {
const fetchImpl = vi.fn().mockResolvedValue({ ok: true })
const ok = await sendFeedback({
conversationId: 'c1',
sentiment: 'negative',
messageIndex: 3,
fetchImpl: fetchImpl as unknown as typeof fetch,
})
expect(ok).toBe(true)
const [url, init] = fetchImpl.mock.calls[0]!
expect(url).toBe('/api/agent/feedback')
expect(init.method).toBe('POST')
expect(JSON.parse(init.body)).toEqual({
conversation_id: 'c1',
sentiment: 'negative',
message_index: 3,
})
})
it('omits the message index rather than sending null for it', async () => {
// The route validates message_index as an integer when present; sending
// null would fail validation and lose the vote for no reason.
const fetchImpl = vi.fn().mockResolvedValue({ ok: true })
await sendFeedback({
conversationId: 'c1',
sentiment: 'positive',
fetchImpl: fetchImpl as unknown as typeof fetch,
})
expect(JSON.parse(fetchImpl.mock.calls[0]![1].body)).toEqual({
conversation_id: 'c1',
sentiment: 'positive',
})
})
it('reports failure for a non-2xx instead of assuming it landed', async () => {
const fetchImpl = vi.fn().mockResolvedValue({ ok: false, status: 404 })
expect(
await sendFeedback({
conversationId: 'c1',
sentiment: 'positive',
fetchImpl: fetchImpl as unknown as typeof fetch,
}),
).toBe(false)
})
it('reports failure instead of throwing when the request dies', async () => {
// Offline, or the request cut off by a navigation. An unhandled rejection
// here would surface as an error in the middle of reading an answer.
const fetchImpl = vi.fn().mockRejectedValue(new TypeError('Failed to fetch'))
await expect(
sendFeedback({
conversationId: 'c1',
sentiment: 'negative',
fetchImpl: fetchImpl as unknown as typeof fetch,
}),
).resolves.toBe(false)
})
})
@@ -1,124 +0,0 @@
import { describe, it, expect } from 'vitest'
import { isInternalHref } from '../markdown-links'
import { ANNOUNCEMENT_LIMIT, announceableAnswer } from '../AgentChat'
import { intentLabel } from '../conversation-display'
describe('isInternalHref', () => {
it('routes app paths client-side', () => {
expect(isInternalHref('/invoices/abc-123')).toBe(true)
expect(isInternalHref('/bookkeeping/year-end?step=2')).toBe(true)
expect(isInternalHref('/kpi#marginal')).toBe(true)
})
it('does not treat a protocol-relative url as internal', () => {
// The href comes out of a model that reads customer documents. "//host"
// starts with a slash but leaves the site, and handing it to the router as
// an app path is the one failure mode worth engineering against.
expect(isInternalHref('//evil.example/login')).toBe(false)
expect(isInternalHref('/\\evil.example')).toBe(false)
})
it('leaves absolute and non-http schemes external', () => {
expect(isInternalHref('https://skatteverket.se')).toBe(false)
expect(isInternalHref('http://example.com')).toBe(false)
expect(isInternalHref('mailto:a@b.se')).toBe(false)
expect(isInternalHref('javascript:alert(1)')).toBe(false)
expect(isInternalHref('')).toBe(false)
})
})
describe('announceableAnswer', () => {
const msg = (role: 'user' | 'assistant', text: string) =>
({ role, text }) as Parameters<typeof announceableAnswer>[0][number]
it('announces the finished answer, not the question', () => {
expect(
announceableAnswer([msg('user', 'Hur gick juli?'), msg('assistant', 'Juli gick 12 % bättre.')]),
).toBe('Juli gick 12 % bättre.')
})
it('reads the LAST assistant turn when the thread has several', () => {
expect(
announceableAnswer([
msg('assistant', 'Första svaret.'),
msg('user', 'Och augusti?'),
msg('assistant', 'Andra svaret.'),
]),
).toBe('Andra svaret.')
})
it('caps the WHOLE announcement, suffix included, and says where the rest is', () => {
// A screen reader reads a live region straight through: a full bokslut
// explanation announced in one uninterruptible burst is worse than not
// announcing at all. Asserted against the constant, and at the real limit
// rather than a looser number the suffix could sneak past.
const out = announceableAnswer([msg('assistant', 'a'.repeat(1000))])
expect(out.length).toBeLessThanOrEqual(ANNOUNCEMENT_LIMIT)
expect(out).toContain('Svaret fortsätter i meddelandet')
})
it('does not read an interrupted answer as a finished one', () => {
// Stop leaves the partial text with a visible marker. Announcing it as the
// answer tells a screen-reader user the opposite of what everyone else sees.
const out = announceableAnswer([
{ role: 'assistant', text: 'Momsen för juli blev 12 4', interrupted: true } as Parameters<
typeof announceableAnswer
>[0][number],
])
expect(out).toContain('avbröts')
expect(out).not.toContain('12 4')
})
it('never re-announces an earlier answer for a turn that produced no text', () => {
// The caller passes only THIS turn's messages. Given the whole thread, a
// tool-only turn would find the previous answer and read it out again as
// though it were new: the user hears a stale answer to a new question.
const thisTurn = [msg('user', 'Boka detta')]
expect(announceableAnswer(thisTurn)).toBe('Assistenten är klar.')
})
it('still says something when the turn produced no text', () => {
// Silence would be indistinguishable from the request never having been
// sent. An assistant bubble that only ever held whitespace counts as none.
expect(announceableAnswer([msg('assistant', ' ')])).toBe('Assistenten är klar.')
expect(announceableAnswer([])).toBe('Assistenten är klar.')
})
})
describe('intentLabel', () => {
it('never shows the raw intent id', () => {
// It used to return the id itself, so an unmapped intent put
// "bokslut.step" in front of the user as the name of their conversation.
expect(intentLabel('some.unmapped.intent')).toBe('Fråga din assistent')
expect(intentLabel('some.unmapped.intent', 'Anna')).toBe('Fråga Anna')
})
it('gives the panel and the history list the SAME name for a thread', () => {
// The two maps had drifted: the panel titled a bokslut thread "Fråga Anna"
// while the history list called it "Hjälp med bokslut".
expect(intentLabel('bokslut.step')).toBe('Hjälp med bokslut')
expect(intentLabel('bokslut.step', 'Anna')).toBe('Hjälp med bokslut')
expect(intentLabel('kpi.explain', 'Anna')).toBe('Förklara nyckeltal')
})
it('personalises general help and falls back without a name', () => {
expect(intentLabel('general.help', 'Anna')).toBe('Fråga Anna')
expect(intentLabel('general.help')).toBe('Fråga din assistent')
expect(intentLabel('general.help', ' ')).toBe('Fråga din assistent')
})
it('does not resolve inherited Object keys as labels', () => {
// A plain object literal inherits from Object.prototype, so a lookup of
// 'toString' returned a FUNCTION, passed the truthiness check and reached
// React as a conversation title. intent_id comes from the database.
expect(intentLabel('toString')).toBe('Fråga din assistent')
expect(intentLabel('constructor', 'Anna')).toBe('Fråga Anna')
expect(intentLabel('__proto__')).toBe('Fråga din assistent')
})
it('keeps momsdeklaration spelled correctly through the soft hyphen', () => {
// The label carries a U+00AD so it can break across the narrow panel.
// Stripping it must leave a real word.
expect(intentLabel('vat.review').replace(/­/g, '')).toBe('Granska momsdeklaration')
})
})
@@ -1,80 +0,0 @@
import { describe, it, expect } from 'vitest'
import type { ChatMessage } from '../AgentChat'
/**
* The pure state transitions behind PR4's message anatomy. The rendering is
* covered by a visual pass (this repo has no component tests), but the state
* rules are exactly where the regressions would hide, so they are pinned here.
*/
/** Mirrors handleStop: mark the last assistant turn as interrupted, once. */
function markInterrupted(prev: ChatMessage[]): ChatMessage[] {
const last = prev[prev.length - 1]
if (!last || last.role !== 'assistant' || last.interrupted) return prev
return [...prev.slice(0, -1), { ...last, interrupted: true }]
}
/** Mirrors handleSend's recovery: drop the bubble that was never persisted. */
function dropUnsentBubble(prev: ChatMessage[], text: string): ChatMessage[] {
const last = prev[prev.length - 1]
return last?.role === 'user' && last.text === text ? prev.slice(0, -1) : prev
}
describe('stop keeps partial content', () => {
it('marks the streaming assistant turn as interrupted', () => {
const out = markInterrupted([
{ role: 'user', text: 'hur gick juli?' },
{ role: 'assistant', text: 'Juli gick 12 procent' },
])
expect(out[1]!.interrupted).toBe(true)
// The partial text must survive: a truncated answer is still useful, it
// just must not look complete.
expect(out[1]!.text).toBe('Juli gick 12 procent')
})
it('is idempotent', () => {
const once = markInterrupted([{ role: 'assistant', text: 'delvis' }])
expect(markInterrupted(once)).toBe(once)
})
it('does not mark a user turn', () => {
const messages: ChatMessage[] = [{ role: 'user', text: 'vänta' }]
expect(markInterrupted(messages)).toBe(messages)
})
it('does nothing on an empty thread', () => {
const messages: ChatMessage[] = []
expect(markInterrupted(messages)).toBe(messages)
})
})
describe('failed send returns the text', () => {
it('removes the bubble that was never persisted', () => {
const out = dropUnsentBubble(
[
{ role: 'assistant', text: 'tidigare svar' },
{ role: 'user', text: 'boka om Circle K' },
],
'boka om Circle K',
)
// Nothing reached the server, so nothing was persisted: leaving the bubble
// would show a question that vanishes on the next reload.
expect(out).toHaveLength(1)
expect(out[0]!.role).toBe('assistant')
})
it('leaves the thread alone when the last turn is something else', () => {
const messages: ChatMessage[] = [
{ role: 'user', text: 'boka om Circle K' },
{ role: 'assistant', text: 'hann svara' },
]
expect(dropUnsentBubble(messages, 'boka om Circle K')).toBe(messages)
})
it('only removes the matching text', () => {
const messages: ChatMessage[] = [{ role: 'user', text: 'en annan fråga' }]
expect(dropUnsentBubble(messages, 'boka om Circle K')).toBe(messages)
})
})
-121
View File
@@ -1,121 +0,0 @@
/**
* One channel for "what is the assistant doing right now".
*
* Today the only publisher is the streaming turn inside AgentSheet, and the
* only subscriber is the floating trigger. Both used to be blind: collapsing
* the panel mid-answer hid the fact that the agent was still working, and the
* moment it finished nothing said so, so the user either sat watching a static
* pill or reopened the panel repeatedly to check.
*
* It is a reducer over a small event set rather than a pair of booleans in the
* provider because the same channel has to carry a durable background run
* later: a run publishes the same turn_start / step / turn_end events from a
* poll or a socket, and the pill needs no changes. `detached` is that state,
* built and rendered now even though v1 never dispatches it, so adding runs is
* a publisher and not a redesign.
*
* React-free on purpose: this repo's unit project is node-only, so the state
* machine is tested directly rather than through a component harness.
*/
export type AgentActivity =
/** Nothing running, nothing waiting to be read. */
| 'idle'
/** A turn is streaming and the user can see it. */
| 'working'
/** A turn finished while the panel was hidden: there is something to read. */
| 'done'
/** Work is running somewhere the user cannot see it (durable runs, later). */
| 'detached'
export interface AgentStatus {
activity: AgentActivity
/** What the agent is doing, already human-readable, e.g. "Bokar…". */
step: string | null
/** True while the panel showing this work is on screen. */
visible: boolean
}
export type AgentStatusEvent =
| { type: 'turn_start' }
| { type: 'step'; label: string }
| { type: 'turn_end' }
| { type: 'visibility'; visible: boolean }
/** Reserved for durable runs; v1 never dispatches it. */
| { type: 'detached'; label?: string }
/** Session ended (panel closed): forget everything. */
| { type: 'reset' }
export const INITIAL_AGENT_STATUS: AgentStatus = {
activity: 'idle',
step: null,
visible: true,
}
export function reduceAgentStatus(state: AgentStatus, event: AgentStatusEvent): AgentStatus {
switch (event.type) {
case 'turn_start':
return { ...state, activity: 'working', step: null }
case 'step':
// A step can arrive for work that started before this channel was
// listening (a resumed stream), so it implies working rather than
// requiring it.
return { ...state, activity: 'working', step: event.label }
case 'turn_end':
// Finishing on screen is not news: the answer is right there. Finishing
// behind a collapsed panel is the whole point of this channel.
return state.visible
? { ...state, activity: 'idle', step: null }
: { ...state, activity: 'done', step: null }
case 'visibility':
if (!event.visible) return { ...state, visible: false }
// Coming back into view consumes the notification, but must not cancel
// work that is still running.
return {
...state,
visible: true,
activity: state.activity === 'done' ? 'idle' : state.activity,
step: state.activity === 'done' ? null : state.step,
}
case 'detached':
return { ...state, activity: 'detached', step: event.label ?? null }
case 'reset':
return { ...INITIAL_AGENT_STATUS, visible: state.visible }
default:
return state
}
}
/**
* The trigger's label for a session that is hidden but alive.
*
* Returns null when the status has nothing to add, so the caller keeps its
* ordinary "Fråga X" / "Fortsätt med X" wording instead of this function
* inventing a second copy of it.
*/
export function collapsedStatusLabel(status: AgentStatus, name: string): string | null {
switch (status.activity) {
case 'working':
case 'detached':
return status.step ? stripEllipsis(status.step) : `${name} arbetar`
case 'done':
return `${name} är klar`
default:
return null
}
}
/**
* Tool labels are written as live narration ("Bokar avskrivningar…") because
* they sit in the message trace. On the pill the same text is a state, and the
* trailing ellipsis reads as a second spinner next to the real one.
*/
function stripEllipsis(label: string): string {
return label.replace(/[….]+$/, '').trim()
}
-50
View File
@@ -1,50 +0,0 @@
// Avatar registry for the specialized accountant agent.
//
// The dicebear "notionists" style: clean line illustrations that match the
// editorial monochrome brand without the cartoony feel of most avatar
// libraries. 8 hand-picked seeds give distinct faces without being
// overwhelming. The user picks one during Phase B review; the choice is
// persisted as agent_profiles.avatar_id.
//
// The SVGs are SELF-HOSTED under public/agent-avatars, generated once from the
// dicebear API with the seeds recorded below. They used to be loaded from
// api.dicebear.com on every render, which meant every authenticated page view
// of an accounting product sent the user's IP, user-agent and referer to a
// third party, and put a CDN this app does not control on the path of a
// logged-in surface. A self-hosted or firewalled install simply showed no
// faces at all.
//
// Licence: the Notionists set is by Zoish under CC0 1.0 (public domain, no
// attribution required). Each file carries that statement in its own RDF
// metadata, so the terms travel with the asset.
//
// To regenerate or add a seed:
// curl -o public/agent-avatars/<id>.svg \
// "https://api.dicebear.com/9.x/notionists/svg?seed=<seed>&radius=50&backgroundColor=f5f3ed"
export interface AvatarOption {
id: string
label: string
url: string
/** The dicebear seed this file was generated from. Documentation, not runtime. */
seed: string
}
// Labels are just for the picker tooltip; the user names the agent themselves
// in the adjacent text field. `seed` is not read at runtime: it records what
// each file was generated from, so the set can be regenerated reproducibly.
export const AVATAR_OPTIONS: readonly AvatarOption[] = [
{ id: 'notionists-1', label: 'Linn', url: '/agent-avatars/notionists-1.svg', seed: 'linn-revisor-1' },
{ id: 'notionists-2', label: 'Erik', url: '/agent-avatars/notionists-2.svg', seed: 'erik-revisor-2' },
{ id: 'notionists-3', label: 'Maja', url: '/agent-avatars/notionists-3.svg', seed: 'maja-revisor-3' },
{ id: 'notionists-4', label: 'Anders', url: '/agent-avatars/notionists-4.svg', seed: 'anders-revisor-4' },
{ id: 'notionists-5', label: 'Karin', url: '/agent-avatars/notionists-5.svg', seed: 'karin-revisor-5' },
{ id: 'notionists-6', label: 'Johan', url: '/agent-avatars/notionists-6.svg', seed: 'johan-revisor-6' },
{ id: 'notionists-7', label: 'Eva', url: '/agent-avatars/notionists-7.svg', seed: 'eva-revisor-7' },
{ id: 'notionists-8', label: 'Per', url: '/agent-avatars/notionists-8.svg', seed: 'per-revisor-8' },
]
export function getAvatarUrl(avatarId: string | null | undefined): string | null {
if (!avatarId) return null
return AVATAR_OPTIONS.find((a) => a.id === avatarId)?.url ?? null
}
-116
View File
@@ -1,116 +0,0 @@
// Shared display helpers for the agent conversation list: used by both the
// full-page /chat sidebar (ChatSidebar) and the in-sheet "resume conversation"
// list (AgentSessionList). Pure functions; no React. Keeping them in one place
// means the Idag / Igår / Denna vecka / Äldre grouping and the relative-time
// labels stay identical across both surfaces.
export interface ConversationRow {
id: string
intent_id: string
context_ref: string | null
title: string | null
pinned: boolean
archived: boolean
last_message_at: string | null
last_message_preview: string | null
created_at: string
}
// Time buckets for date grouping. Computed once per render against now().
// Mirrors the Idag / Igår / Denna vecka / Äldre pattern users know from
// Mail and iMessage.
export type DateBucket = 'pinned' | 'today' | 'yesterday' | 'thisWeek' | 'older'
export const BUCKET_LABELS: Record<DateBucket, string> = {
pinned: 'Fästade',
today: 'Idag',
yesterday: 'Igår',
thisWeek: 'Denna vecka',
older: 'Äldre',
}
export const BUCKET_ORDER: DateBucket[] = ['pinned', 'today', 'yesterday', 'thisWeek', 'older']
export function bucketFor(c: ConversationRow): DateBucket {
if (c.pinned) return 'pinned'
const when = c.last_message_at ?? c.created_at
if (!when) return 'older'
const t = new Date(when)
const now = new Date()
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const yesterdayStart = new Date(todayStart.getTime() - 24 * 60 * 60 * 1000)
const weekStart = new Date(todayStart.getTime() - 6 * 24 * 60 * 60 * 1000)
if (t >= todayStart) return 'today'
if (t >= yesterdayStart) return 'yesterday'
if (t >= weekStart) return 'thisWeek'
return 'older'
}
// Compact relative-time label shown to the right of each row. Locale-tuned
// to feel native in Swedish without going full date-fns.
export function relativeTime(iso: string | null | undefined): string {
if (!iso) return ''
const t = new Date(iso).getTime()
const now = Date.now()
const diffMin = Math.round((now - t) / 60000)
if (diffMin < 1) return 'nu'
if (diffMin < 60) return `${diffMin} min`
const diffHr = Math.round(diffMin / 60)
if (diffHr < 24) return `${diffHr} h`
const diffDay = Math.round(diffHr / 24)
if (diffDay < 7) return `${diffDay} d`
return new Date(iso).toLocaleDateString('sv-SE', { month: 'short', day: 'numeric' })
}
/**
* One label per intent, for every surface that names a conversation.
*
* There were two of these: this map and an intentToTitle in AgentSheet. They
* had already drifted, so the panel opened on the bokslut wizard titled
* "Fråga Anna" while the same thread in the history list read "Hjälp med
* bokslut", and this one's fallback returned the raw intent id, putting
* "bokslut.step" in front of the user as the name of their own conversation.
*/
// Null-prototype: a plain literal inherits from Object.prototype, so
// intentLabel('toString') would resolve to a FUNCTION, pass the truthiness
// check, and be handed to React as a title. intent_id comes from the database.
const INTENT_LABELS: Record<string, string> = Object.assign(Object.create(null), {
'transaction.categorization': 'Hjälp med transaktion',
'invoice.draft': 'Hjälp med faktura',
'supplier_invoice.review': 'Granska leverantörsfaktura',
'vat.review': 'Granska moms\u00addeklaration',
'bokslut.step': 'Hjälp med bokslut',
'verifikation.draft': 'Hjälp med verifikation',
'kpi.explain': 'Förklara nyckeltal',
'settings.help': 'Hjälp med inställningar',
'inbox.bulk-book': 'Bokför från inkorgen',
})
/**
* `agentName` personalises the general-help and unknown cases ("Fråga Anna").
* Omit it where the agent's name is not to hand: the wording stays correct,
* just less personal. An unknown intent NEVER falls through to its id.
*/
export function intentLabel(intentId: string, agentName?: string | null): string {
const known = INTENT_LABELS[intentId]
if (known) return known
const name = agentName?.trim()
return name ? `Fråga ${name}` : 'Fråga din assistent'
}
// Group a flat (already server-sorted: pinned first, then last_message_at desc)
// list into ordered, non-empty buckets. Shared so both list surfaces render
// the same section order.
export function groupConversations(
rows: ConversationRow[],
): { bucket: DateBucket; rows: ConversationRow[] }[] {
const buckets: Record<DateBucket, ConversationRow[]> = {
pinned: [],
today: [],
yesterday: [],
thisWeek: [],
older: [],
}
for (const c of rows) buckets[bucketFor(c)].push(c)
return BUCKET_ORDER.map((b) => ({ bucket: b, rows: buckets[b] })).filter((g) => g.rows.length > 0)
}
-129
View File
@@ -1,129 +0,0 @@
import type { ConversationRow } from './conversation-display'
/**
* The list transforms and the optimistic-write coordinator behind
* useConversationList. Pure and React-free so they can be tested directly:
* the hook is a thin binding over these, which means a test that deletes the
* rollback here fails, rather than passing against a copy of the logic.
*/
export function setPinned(
list: ConversationRow[],
id: string,
pinned: boolean,
): ConversationRow[] {
return list.map((c) => (c.id === id ? { ...c, pinned } : c))
}
export function setTitle(
list: ConversationRow[],
id: string,
title: string | null,
): ConversationRow[] {
return list.map((c) => (c.id === id ? { ...c, title } : c))
}
export function removeRow(list: ConversationRow[], id: string): ConversationRow[] {
return list.filter((c) => c.id !== id)
}
/**
* Put a row back after a failed archive, into whatever the list looks like NOW.
*
* Restoring a render-time snapshot of the whole list would discard any pin,
* rename or archive the user made while the request was in flight. Position
* follows the server's ordering (pinned first, then most recent first) so the
* row reappears where it belongs rather than at the end.
*/
export function restoreRow(list: ConversationRow[], row: ConversationRow): ConversationRow[] {
if (list.some((c) => c.id === row.id)) return list
const sortKey = (c: ConversationRow) => c.last_message_at ?? c.created_at ?? ''
const idx = list.findIndex((c) => {
if (row.pinned !== c.pinned) return row.pinned && !c.pinned
return sortKey(row) > sortKey(c)
})
if (idx === -1) return [...list, row]
return [...list.slice(0, idx), row, ...list.slice(idx)]
}
/** PATCH one conversation. Resolves false for a non-2xx AND for a thrown fetch. */
export async function patchConversation(
id: string,
body: Record<string, unknown>,
): Promise<boolean> {
try {
const res = await fetch(`/api/agent/conversations/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
return res.ok
} catch {
return false
}
}
/**
* Per-row revision guard.
*
* Two writes to the same row can overlap (a double-click on pin, a rename
* while an archive is in flight). Without this, a failing FIRST request would
* roll back over the SECOND request's newer value. Each write claims a
* revision; a rollback only applies while its revision is still the latest for
* that row.
*/
export function createRevisionGuard() {
const revisions = new Map<string, number>()
return {
claim(id: string): number {
const next = (revisions.get(id) ?? 0) + 1
revisions.set(id, next)
return next
},
isCurrent(id: string, revision: number): boolean {
return revisions.get(id) === revision
},
}
}
export interface OptimisticPatchArgs {
id: string
body: Record<string, unknown>
/** Optimistic transform, applied immediately. */
apply: (list: ConversationRow[]) => ConversationRow[]
/** Undo, applied to the CURRENT list only if this write is still the latest. */
revert: (list: ConversationRow[]) => ConversationRow[]
setList: (updater: (prev: ConversationRow[]) => ConversationRow[]) => void
guard: ReturnType<typeof createRevisionGuard>
onError: () => void
patch?: typeof patchConversation
}
/**
* Apply a change optimistically, send it, and undo it if the server refuses.
* Returns whether the change stuck.
*/
export async function runOptimisticPatch({
id,
body,
apply,
revert,
setList,
guard,
onError,
patch = patchConversation,
}: OptimisticPatchArgs): Promise<boolean> {
const revision = guard.claim(id)
setList(apply)
const ok = await patch(id, body)
if (ok) return true
// A newer write for this row has since been issued: undoing here would clobber
// it. That write owns the row's state and will report its own failure.
if (!guard.isCurrent(id, revision)) return false
setList(revert)
onError()
return false
}
-35
View File
@@ -1,35 +0,0 @@
/**
* Send one thumbs vote on an assistant answer.
*
* Kept out of the component so it is testable without a React harness (this
* repo's unit project is node-only), and so the failure contract is stated in
* one place: this resolves false rather than throwing, because a vote that
* cannot be sent must never interrupt reading the answer it was about.
*/
export type FeedbackSentiment = 'positive' | 'negative'
export async function sendFeedback(args: {
conversationId: string
sentiment: FeedbackSentiment
messageIndex?: number
fetchImpl?: typeof fetch
}): Promise<boolean> {
const { conversationId, sentiment, messageIndex, fetchImpl = fetch } = args
try {
const res = await fetchImpl('/api/agent/feedback', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
conversation_id: conversationId,
sentiment,
...(messageIndex === undefined ? {} : { message_index: messageIndex }),
}),
})
return res.ok
} catch {
// Offline, or the request was cut off by a navigation. Reported as a
// failed vote so the button can go back to unpressed rather than claiming
// a report that never arrived.
return false
}
}
-22
View File
@@ -1,22 +0,0 @@
/**
* Is this href a link back into the app?
*
* Kept out of MarkdownMessage so it is testable without the markdown parser
* (that component exists to be lazily imported, and this repo's unit project
* is node-only).
*
* The href comes from a language model that reads customer documents and
* supplier invoices, so "starts with a slash" is not a sufficient test:
* "//evil.example" is protocol-relative and leaves the site entirely. Anything
* this returns false for is rendered as an external link, which is the safe
* direction to be wrong in: an external link that could have been routed
* costs a page load, whereas an external URL treated as internal would be
* handed to the router as an app path.
*/
export function isInternalHref(href: string): boolean {
if (!href.startsWith('/')) return false
// Protocol-relative ("//host/path"), and the backslash variant browsers
// normalise to the same thing.
if (href.startsWith('//') || href.startsWith('/\\')) return false
return true
}
-171
View File
@@ -1,171 +0,0 @@
'use client'
import { useCallback, useMemo, useRef, useState } from 'react'
import { useToast } from '@/components/ui/use-toast'
import { type ConversationRow, type DateBucket, groupConversations } from './conversation-display'
import {
createRevisionGuard,
removeRow,
restoreRow,
runOptimisticPatch,
setPinned,
setTitle,
} from './conversation-mutations'
/**
* Shared state and mutations for the agent conversation list.
*
* The two surfaces that show conversations (the full-page /chat sidebar and the
* in-sheet resume list) had drifted apart in behaviour, not just chrome: the
* sheet rolled a failed rename back and toasted, while the sidebar fired pin,
* archive and rename blind, with no res.ok check, no rollback and no message.
* A failed archive there removed a conversation from the list while it still
* existed on the server, and a failed rename displayed a title the server never
* saved, both until the next reload.
*
* Owning the state and all three mutations here means the two surfaces cannot
* diverge again, and the sheet gains pin/archive it never had. The chrome
* stays with each surface: a 320px sidebar that collapses to a rail and a sheet
* panel are legitimately different shapes.
*
* The transforms and the write coordinator live in conversation-mutations.ts so
* they are testable without a React harness (this repo's unit project is
* node-only).
*/
export interface ConversationListApi {
conversations: ConversationRow[]
setConversations: React.Dispatch<React.SetStateAction<ConversationRow[]>>
query: string
setQuery: (q: string) => void
grouped: { bucket: DateBucket; rows: ConversationRow[] }[]
togglePin: (id: string, current: boolean) => Promise<void>
archive: (id: string) => Promise<boolean>
rename: (id: string, title: string) => Promise<void>
// Inline rename plumbing, shared so Esc-to-cancel behaves identically.
editingId: string | null
editValue: string
setEditValue: (v: string) => void
startEdit: (c: ConversationRow) => void
cancelEdit: () => void
commitEdit: (id: string) => Promise<void>
}
export function useConversationList(initial: ConversationRow[]): ConversationListApi {
const [conversations, setConversations] = useState<ConversationRow[]>(initial)
const [query, setQuery] = useState('')
const { toast } = useToast()
const guard = useRef(createRevisionGuard()).current
const [editingId, setEditingId] = useState<string | null>(null)
const [editValue, setEditValue] = useState('')
// Set by Esc so the blur fired when the input unmounts doesn't save.
const cancelRef = useRef(false)
const filtered = useMemo(() => {
const q = query.trim().toLowerCase()
if (!q) return conversations
return conversations.filter(
(c) =>
(c.title ?? '').toLowerCase().includes(q) ||
(c.last_message_preview ?? '').toLowerCase().includes(q) ||
(c.context_ref ?? '').toLowerCase().includes(q) ||
c.intent_id.toLowerCase().includes(q),
)
}, [conversations, query])
const grouped = useMemo(() => groupConversations(filtered), [filtered])
const togglePin = useCallback(
async (id: string, current: boolean) => {
await runOptimisticPatch({
id,
body: { pinned: !current },
apply: (list) => setPinned(list, id, !current),
revert: (list) => setPinned(list, id, current),
setList: setConversations,
guard,
onError: () => toast({ variant: 'destructive', title: 'Kunde inte ändra fästningen.' }),
})
},
[guard, toast],
)
/** Resolves true when the row is really archived, so callers can navigate. */
const archive = useCallback(
async (id: string) => {
const row = conversations.find((c) => c.id === id)
return runOptimisticPatch({
id,
body: { archived: true },
apply: (list) => removeRow(list, id),
// Restore into the CURRENT list, not a snapshot: changes made while the
// request was in flight must survive.
revert: (list) => (row ? restoreRow(list, row) : list),
setList: setConversations,
guard,
onError: () => toast({ variant: 'destructive', title: 'Kunde inte arkivera konversationen.' }),
})
},
[conversations, guard, toast],
)
const rename = useCallback(
async (id: string, title: string) => {
const previousTitle = conversations.find((c) => c.id === id)?.title ?? null
await runOptimisticPatch({
id,
body: { title },
apply: (list) => setTitle(list, id, title),
revert: (list) => setTitle(list, id, previousTitle),
setList: setConversations,
guard,
onError: () =>
toast({ variant: 'destructive', title: 'Kunde inte byta namn på konversationen.' }),
})
},
[conversations, guard, toast],
)
const startEdit = useCallback((c: ConversationRow) => {
setEditingId(c.id)
setEditValue(c.title ?? '')
cancelRef.current = false
}, [])
const cancelEdit = useCallback(() => {
cancelRef.current = true
setEditingId(null)
}, [])
const commitEdit = useCallback(
async (id: string) => {
if (cancelRef.current) {
cancelRef.current = false
return
}
setEditingId(null)
const title = editValue.trim()
const current = conversations.find((c) => c.id === id)
if (!title || title === current?.title) return
await rename(id, title)
},
[conversations, editValue, rename],
)
return {
conversations,
setConversations,
query,
setQuery,
grouped,
togglePin,
archive,
rename,
editingId,
editValue,
setEditValue,
startEdit,
cancelEdit,
commitEdit,
}
}
-590
View File
@@ -1,590 +0,0 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useAccounts, useCompanySettings } from '@/lib/reference-data/hooks'
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import {
SettingsGroup,
SettingsInput,
SettingsRow,
SettingsSeg,
SettingsSelect,
SettingsTextarea,
} from '@/components/settings/SettingsRows'
import { ChevronDown, Loader2, Lock } from 'lucide-react'
import { cn, formatCurrency } from '@/lib/utils'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { createClient } from '@/lib/supabase/client'
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import { AddAccountDialog } from '@/components/bookkeeping/AddAccountDialog'
import type { CreateArticleInput } from '@/types'
import { INVOICE_POSTING_ACCOUNT_REGEX } from '@/lib/invoices/posting-account'
import {
ROT_WORK_TYPES,
RUT_WORK_TYPES,
normalizeHouseworkType,
} from '@/lib/invoices/rot-rut-rules'
// A row from the currencies reference table (lib migration
// 20260630110000_currencies_reference_table.sql).
interface CurrencyOption {
code: string
name: string
}
// Unit list mirrors the invoice line editor (app/(dashboard)/invoices/new/page.tsx).
const UNITS = ['st', 'tim', 'dag', 'månad', 'km', 'kg'] as const
// Legal Swedish VAT rates as integer percent. Matches vatRatePercent in
// lib/api/schemas.ts (25 | 12 | 6 | 0).
const VAT_RATES = [25, 12, 6, 0] as const
/** Money is rounded to öre with arithmetic, never toFixed (CLAUDE.md rule 6). */
function round2(value: number): number {
return Math.round(value * 100) / 100
}
// SettingsInput is a bare input, so it does not carry the wheel guard that
// components/ui/input.tsx applies to type="number". Without it, scrolling the
// page with the cursor over a focused price field silently edits the amount.
function blurOnWheel(e: React.WheelEvent<HTMLInputElement>) {
e.currentTarget.blur()
}
interface ArticleFormProps {
onSubmit: (data: CreateArticleInput) => Promise<void>
isLoading: boolean
initialData?: Partial<CreateArticleInput>
/** Closes the host dialog. When omitted the cancel button is not rendered. */
onCancel?: () => void
}
export default function ArticleForm({
onSubmit,
isLoading,
initialData,
onCancel,
}: ArticleFormProps) {
const { canWrite } = useCanWrite()
const supabase = createClient()
const t = useTranslations('form_article')
const tCommon = useTranslations('common')
// Active class 1-3 posting accounts for the combobox. The combobox accepts
// unknown 4-digit numbers optimistically: the API answers with
// ACCOUNTS_NOT_IN_CHART for activatable BAS accounts, and the host page's
// ActivateAccountsDialog flow takes over (same UX as the journal entry form).
// Balance-sheet and revenue accounts for the posting override, from the
// session cache (lib/reference-data): populated on the first paint.
const { accounts: activeAccounts } = useAccounts()
const postingAccounts = useMemo(
() => activeAccounts.filter((account) => account.account_class >= 1 && account.account_class <= 3),
[activeAccounts],
)
// Inline account creation: what the user typed in the combobox when they hit
// "Skapa konto": non-null opens AddAccountDialog prefilled with it.
const [createAccountPrefill, setCreateAccountPrefill] = useState<string | null>(null)
// Momsregistrerad? A non-VAT-registered company never charges moms, so the
// VAT field is hidden and the rate forced to 0: mirrors the invoice editor.
// Icke momsregistrerad verksamhet: VAT controls hidden and lines at 0 %.
// Derived from the session-cached settings row (lib/reference-data); a
// missing column keeps the registered-company behaviour, as before.
const { settings: companySettings } = useCompanySettings()
const vatRegistered = typeof companySettings?.vat_registered === 'boolean' ? companySettings.vat_registered : true
// Supported currencies, fetched from the currencies reference table rather
// than hard-coded. Falls back to the article's own currency (or SEK) if the
// fetch fails so the Select is never empty.
const [currencies, setCurrencies] = useState<CurrencyOption[]>([])
// Currency options come from the currencies reference table: one source of
// truth, no hard-coded list.
useEffect(() => {
let cancelled = false
supabase
.from('currencies')
.select('code, name')
.eq('active', true)
.order('sort_order', { ascending: true })
.then(({ data }) => {
if (!cancelled && data) setCurrencies(data as CurrencyOption[])
})
return () => {
cancelled = true
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// Open "Fler fält" by default when it already holds data, so an edit never
// hides a value the user previously set. Currency and posting account are no
// longer in here: both are permanent rows.
const [moreOpen, setMoreOpen] = useState(
Boolean(
initialData?.article_number ||
initialData?.name_en ||
initialData?.cost_price != null ||
initialData?.ean ||
initialData?.housework_type ||
initialData?.notes,
),
)
// UI-local schema mirroring CreateArticleSchema (lib/api/schemas.ts).
const schema = useMemo(
() =>
z.object({
article_number: z.string().trim().max(64, t('number_too_long')).optional(),
name: z.string().min(1, t('name_required')),
name_en: z.string().optional(),
type: z.enum(['vara', 'tjanst']),
unit: z.string().min(1),
price_excl_vat: z.number({ message: t('price_required') }).nonnegative(t('price_required')),
vat_rate: z.union([z.literal(25), z.literal(12), z.literal(6), z.literal(0)]),
// ISO 4217 alpha-3; the authoritative allow-list is the currencies
// table (the DB FK rejects unknown codes).
currency: z.string().regex(/^[A-Z]{3}$/),
revenue_account: z
.string()
.regex(INVOICE_POSTING_ACCOUNT_REGEX, t('posting_account_invalid'))
.or(z.literal(''))
.optional(),
cost_price: z.number().nonnegative().optional(),
ean: z.string().optional(),
housework_type: z.string().optional(),
notes: z.string().optional(),
}),
[t],
)
type FormData = z.infer<typeof schema>
const {
register,
handleSubmit,
watch,
control,
setValue,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
article_number: initialData?.article_number || '',
name: initialData?.name || '',
name_en: initialData?.name_en || '',
type: initialData?.type || 'tjanst',
unit: initialData?.unit || 'st',
price_excl_vat: initialData?.price_excl_vat ?? 0,
vat_rate: (initialData?.vat_rate as FormData['vat_rate']) ?? 25,
currency: initialData?.currency ?? 'SEK',
revenue_account: initialData?.revenue_account || '',
cost_price: initialData?.cost_price ?? undefined,
ean: initialData?.ean || '',
// Canonical form (work-type code, bare ROT/RUT, or ''): a stray value
// from an import must not sit invisibly in the select as "Ingen".
housework_type: normalizeHouseworkType(initialData?.housework_type) ?? '',
notes: initialData?.notes || '',
},
})
// Legacy articles carry only the kind ('ROT'/'RUT'), stored before this
// form offered Skatteverket work types. Keep that choice selectable so an
// edit never silently drops the flag; the user upgrades it to a real
// arbetstyp when they want the invoice row's work type pre-filled too.
const legacyHouseworkKind = (() => {
const v = normalizeHouseworkType(initialData?.housework_type)
return v === 'ROT' || v === 'RUT' ? v : null
})()
const type = watch('type')
const watchedName = watch('name')
const watchedUnit = watch('unit')
const watchedPrice = watch('price_excl_vat')
const watchedVat = watch('vat_rate')
const watchedCurrency = watch('currency')
const watchedAccount = watch('revenue_account')
const watchedNumber = watch('article_number')
// The summary strip: what this article becomes as a line on an invoice.
// Display only, so it never posts anything, but it is the reason currency is
// impossible to miss here.
const price = Number.isFinite(watchedPrice) ? Number(watchedPrice) : 0
const effectiveVat = vatRegistered ? Number(watchedVat) || 0 : 0
const vatAmount = round2((price * effectiveVat) / 100)
const totalInclVat = round2(price + vatAmount)
const currency = watchedCurrency || 'SEK'
// Keep the article's own currency selectable even before the fetch resolves
// or if it has since been deactivated.
const currencyCodes = useMemo(() => {
const codes = currencies.map((c) => c.code)
return codes.includes(currency) ? codes : [currency, ...codes]
}, [currencies, currency])
const onFormSubmit = (data: FormData) => {
onSubmit({
article_number: data.article_number?.trim() || null,
name: data.name,
name_en: data.name_en || null,
type: data.type,
unit: data.unit,
price_excl_vat: data.price_excl_vat,
vat_rate: vatRegistered ? data.vat_rate : 0,
currency: data.currency,
revenue_account: data.revenue_account || null,
cost_price: data.cost_price ?? null,
ean: data.ean || null,
housework_type: type === 'tjanst' ? data.housework_type || null : null,
notes: data.notes || null,
})
}
const fieldError = (message?: string) =>
message ? <p className="basis-full text-xs text-destructive">{message}</p> : null
return (
<form onSubmit={handleSubmit(onFormSubmit)}>
<SettingsGroup label={t('group_article')}>
<SettingsRow label={t('type_label')}>
<Controller
name="type"
control={control}
render={({ field }) => (
<SettingsSeg
value={field.value}
onChange={field.onChange}
aria-label={t('type_label')}
options={[
{ value: 'tjanst', label: t('type_tjanst') },
{ value: 'vara', label: t('type_vara') },
]}
/>
)}
/>
</SettingsRow>
<SettingsRow label={t('name_label')} htmlFor="article-name" align="baseline">
<SettingsInput
id="article-name"
placeholder={t('name_placeholder')}
{...register('name')}
/>
{fieldError(errors.name?.message)}
</SettingsRow>
<SettingsRow label={t('price_label')} htmlFor="article-price" align="baseline">
<span className="flex items-center gap-2">
<SettingsInput
id="article-price"
type="number"
step="0.01"
min="0"
className="w-28 flex-none tabular-nums"
onWheel={blurOnWheel}
{...register('price_excl_vat', { valueAsNumber: true })}
/>
<Controller
name="currency"
control={control}
render={({ field }) => (
<SettingsSelect
aria-label={t('currency_label')}
className="text-muted-foreground"
value={field.value}
onChange={(e) => field.onChange(e.target.value)}
>
{currencyCodes.map((code) => (
<option key={code} value={code}>
{code}
</option>
))}
</SettingsSelect>
)}
/>
</span>
{fieldError(errors.price_excl_vat?.message)}
</SettingsRow>
{/* Enhet closes the group when the company charges no moms, so the
group never ends on a dangling hairline. */}
<SettingsRow label={t('unit_label')} htmlFor="article-unit" borderless={!vatRegistered}>
<Controller
name="unit"
control={control}
render={({ field }) => (
<SettingsSelect
id="article-unit"
value={field.value}
onChange={(e) => field.onChange(e.target.value)}
>
{UNITS.map((u) => (
<option key={u} value={u}>
{u}
</option>
))}
</SettingsSelect>
)}
/>
</SettingsRow>
{vatRegistered && (
<SettingsRow label={t('vat_rate_label')} htmlFor="article-vat" borderless>
<Controller
name="vat_rate"
control={control}
render={({ field }) => (
<SettingsSelect
id="article-vat"
value={String(field.value)}
onChange={(e) => field.onChange(Number(e.target.value))}
>
{VAT_RATES.map((rate) => (
<option key={rate} value={String(rate)}>
{rate} %
</option>
))}
</SettingsSelect>
)}
/>
</SettingsRow>
)}
</SettingsGroup>
<SettingsGroup label={t('group_accounting')}>
<SettingsRow
label={t('revenue_account_label')}
align="baseline"
borderless
help={t('revenue_account_hint')}
>
<Controller
name="revenue_account"
control={control}
render={({ field }) => (
<AccountCombobox
flat
value={field.value || ''}
accounts={postingAccounts}
onChange={field.onChange}
onCreateAccount={(prefill) => setCreateAccountPrefill(prefill)}
/>
)}
/>
{fieldError(errors.revenue_account?.message)}
</SettingsRow>
</SettingsGroup>
{moreOpen && (
<SettingsGroup label={t('more_fields')}>
<SettingsRow
label={t('number_label')}
htmlFor="article-number"
align="baseline"
help={t('number_hint')}
>
<SettingsInput id="article-number" className="tabular-nums" {...register('article_number')} />
{fieldError(errors.article_number?.message)}
</SettingsRow>
<SettingsRow
label={t('name_en_label')}
htmlFor="article-name-en"
align="baseline"
help={t('name_en_hint')}
>
<SettingsInput
id="article-name-en"
placeholder={t('name_en_placeholder')}
{...register('name_en')}
/>
</SettingsRow>
<SettingsRow
label={t('cost_price_label')}
htmlFor="article-cost"
align="baseline"
help={t('cost_price_hint')}
>
<SettingsInput
id="article-cost"
type="number"
step="0.01"
min="0"
className="w-28 flex-none tabular-nums"
onWheel={blurOnWheel}
{...register('cost_price', {
setValueAs: (v) => (v === '' || v == null ? undefined : Number(v)),
})}
/>
</SettingsRow>
<SettingsRow label={t('ean_label')} htmlFor="article-ean" align="baseline">
<SettingsInput
id="article-ean"
placeholder={t('ean_placeholder')}
className="tabular-nums"
{...register('ean')}
/>
</SettingsRow>
{type === 'tjanst' && (
<SettingsRow
label={t('housework_label')}
htmlFor="article-housework"
help={t('housework_hint')}
>
<Controller
name="housework_type"
control={control}
render={({ field }) => (
<SettingsSelect
id="article-housework"
value={field.value || ''}
onChange={(e) => field.onChange(e.target.value)}
>
<option value="">{t('housework_none')}</option>
{legacyHouseworkKind && (
<option value={legacyHouseworkKind}>
{legacyHouseworkKind === 'ROT'
? t('housework_legacy_rot')
: t('housework_legacy_rut')}
</option>
)}
<optgroup label={t('housework_rot')}>
{ROT_WORK_TYPES.map((w) => (
<option key={w.code} value={w.code}>
{w.label}
</option>
))}
</optgroup>
<optgroup label={t('housework_rut')}>
{RUT_WORK_TYPES.map((w) => (
<option key={w.code} value={w.code}>
{w.label}
</option>
))}
</optgroup>
</SettingsSelect>
)}
/>
</SettingsRow>
)}
<SettingsRow label={t('notes_label')} htmlFor="article-notes" align="baseline" borderless>
<SettingsTextarea
id="article-notes"
rows={2}
placeholder={t('notes_placeholder')}
{...register('notes')}
/>
</SettingsRow>
</SettingsGroup>
)}
<div className="px-1 pt-6">
<button
type="button"
onClick={() => setMoreOpen((open) => !open)}
className="inline-flex items-center gap-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground transition-colors duration-150 hover:text-foreground"
aria-expanded={moreOpen}
>
<ChevronDown
className={cn('h-3.5 w-3.5 transition-transform duration-200', moreOpen && 'rotate-180')}
aria-hidden="true"
/>
{t('more_fields')}
</button>
</div>
{/* The line this article becomes. Full-bleed against the dialog's p-6. */}
<div className="-mx-6 mt-6 flex flex-wrap items-baseline gap-x-3 gap-y-1 border-t border-border bg-muted/60 px-6 py-3 text-xs text-muted-foreground">
<span className="max-w-[46%] break-words font-display text-[15px] leading-snug text-foreground">
{watchedName || t('summary_unnamed')}
</span>
<span aria-hidden="true" className="opacity-50">·</span>
<span className="tabular-nums">1 {watchedUnit}</span>
<span aria-hidden="true" className="opacity-50">·</span>
<span className="tabular-nums text-foreground">{formatCurrency(price, currency)}</span>
{effectiveVat > 0 && (
<>
<span>{t('summary_plus_vat')}</span>
<span className="tabular-nums text-foreground">{formatCurrency(vatAmount, currency)}</span>
</>
)}
{watchedAccount ? (
<>
<span aria-hidden="true" className="opacity-50">·</span>
<span className="tabular-nums">
{t('summary_booked_on')} {watchedAccount}
</span>
</>
) : null}
<span className="ml-auto font-display text-[17px] tabular-nums text-foreground">
{formatCurrency(totalInclVat, currency)}
</span>
</div>
<div className="-mx-6 -mb-6 flex flex-wrap items-center gap-3 px-6 pb-6 pt-4">
{!watchedNumber && (
<p className="max-w-[30ch] text-xs leading-relaxed text-muted-foreground">
{t('number_hint')}
</p>
)}
<div className="ml-auto flex items-center gap-2">
{onCancel && (
<Button type="button" variant="ghost" onClick={onCancel}>
{tCommon('cancel')}
</Button>
)}
<Button
type="submit"
disabled={isLoading || !canWrite}
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('submit_saving')}
</>
) : !canWrite ? (
<>
<Lock className="mr-2 h-4 w-4" />
{t('submit_save')}
</>
) : (
t('submit_save')
)}
</Button>
</div>
</div>
{/* Inline custom-account creation (renders in a portal, outside the form).
After create: refresh the chart and select the new number as the
article's posting account: mirrors the journal entry form. */}
<AddAccountDialog
open={createAccountPrefill != null}
onOpenChange={(next) => {
if (!next) setCreateAccountPrefill(null)
}}
initialAccountNumber={
createAccountPrefill && /^\d{1,4}$/.test(createAccountPrefill)
? createAccountPrefill
: undefined
}
initialAccountName={
createAccountPrefill && !/^\d{1,4}$/.test(createAccountPrefill)
? createAccountPrefill
: undefined
}
onCreated={async (account) => {
// The new account must be in the shared chart before the field points at it.
await invalidateReferenceData('ref:accounts')
setValue('revenue_account', account.account_number, { shouldDirty: true })
setCreateAccountPrefill(null)
}}
/>
</form>
)
}
-35
View File
@@ -1,35 +0,0 @@
'use client'
import type { ReactNode } from 'react'
import { CircleAlert } from 'lucide-react'
/**
* Inline error line for the auth forms (login, register, reset).
*
* Auth failures render here, adjacent to the form, instead of in a toast:
* a toast in the corner auto-dismisses, sits far from the locus of attention,
* and is easy to miss entirely. Styled as one quiet destructive sentence with
* an icon, mirroring the AttnLine pattern, never as a boxed banner: the box
* reads louder than the message and breaks the panel's rhythm. role="alert"
* makes screen readers announce the message when it appears.
*/
export function AuthFormError({
message,
action,
}: {
message: string
action?: ReactNode
}) {
return (
<p
role="alert"
className="animate-fade-in flex items-start gap-2 text-[13px] leading-5 text-destructive"
>
<CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />
<span>
{message}
{action && <> {action}</>}
</span>
</p>
)
}
-16
View File
@@ -1,16 +0,0 @@
import { Skeleton } from '@/components/ui/skeleton'
export function AuthPageSkeleton() {
return (
<main className="flex min-h-dvh items-center justify-center bg-frame p-4" aria-busy="true">
<div className="w-full max-w-sm">
<Skeleton className="mx-auto mb-8 h-12 w-48" />
<div className="space-y-4 rounded-xl border border-border bg-background p-6">
<Skeleton className="h-11 w-full" />
<Skeleton className="h-11 w-full" />
<Skeleton className="h-10 w-full" />
</div>
</div>
</main>
)
}
-743
View File
@@ -1,743 +0,0 @@
'use client'
import { useState, useEffect, useRef, useCallback } from 'react'
import Image from 'next/image'
import { useTranslations } from 'next-intl'
import { BankIdQrCode } from './BankIdQrCode'
import { Button } from '@/components/ui/button'
import { Smartphone, Monitor, AlertTriangle, Loader2 } from 'lucide-react'
type BankIdStatus =
| 'idle'
| 'scanning'
| 'complete'
| 'failed'
| 'no_account'
| 'service_unavailable'
/** A flow exists in this browser that this browsing context did not start. */
| 'resumable'
/** Avbryt pressed: waiting out /cancel before a new flow may be started. */
| 'cancelling'
/** Max consecutive poll failures before we declare service unavailable */
const MAX_POLL_FAILURES = 3
/**
* Abandon a session that never reaches a terminal state. Safety net for TIC
* responses that carry no `status` (e.g. an expired-session 410 body): without
* it the poll loop would spin forever on a dead QR code.
*/
const POLL_DEADLINE_MS = 6 * 60 * 1000
/** Min spacing between billable TIC session starts (mirrors the server cooldown). */
const START_COOLDOWN_MS = 5_000
/**
* What the client is allowed to know about a BankID order. Note the absence
* of a session id: it is a bearer credential for the holder's personnummer
* and for a Supabase session, so it stays in a signed HttpOnly cookie the
* server sets at /start (extensions/general/tic/lib/bankid-flow-cookie.ts).
* The tokens below are the ones the BankID app and the QR code need, and
* neither identifies anybody.
*/
interface BankIdSession {
flowId: string
autoStartToken: string
qrStartToken: string
qrStartSecret: string
}
export interface BankIdResult {
tokenHash?: string
type?: string
isNewUser?: boolean
error?: 'no_account' | 'already_linked' | 'session_invalid' | 'service_unavailable' | 'email_unconfirmed'
/** Server-provided Swedish explanation for errors that carry one (e.g. email_unconfirmed). */
message?: string
givenName?: string
surname?: string
/** Non-secret id that binds this tab to the shared server-held flow. */
flowId?: string
}
interface BankIdAuthProps {
mode: 'login' | 'signup' | 'link'
onComplete: (result: BankIdResult) => void
/**
* Render the idle button as the panel's primary action (filled pill) instead
* of the default outline. Used by the login page, where BankID owns the
* primary zone; register and settings keep the quieter outline.
*/
hero?: boolean
}
const API_BASE = '/api/extensions/ext/tic/bankid'
const FLOW_ID_HEADER = 'x-bankid-flow-id'
function isMobile(): boolean {
if (typeof navigator === 'undefined') return false
return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent)
}
/**
* Launch the BankID app on the same (mobile) device.
*
* Uses the universal link https://app.bankid.com/: NOT the bankid:/// custom
* scheme. A custom-scheme launch has no association with the originating Safari
* tab, so on iOS the post-auth redirect opens in a NEW tab (git history: commit
* 3bc652cc reverted a redirect for exactly that reason).
*
* redirect:
* • iOS → current URL, so the app navigates back here on success. In
* Safari that is this very tab; in a third-party browser or an
* in-app web view the OS hands the URL to the default browser
* and it lands in a NEW tab. Both work: the flow lives in a
* cookie, which every tab of the origin shares, so whichever tab
* the user ends up in simply polls and carries on.
* • Android → "null": the BankID app returns via the task stack, and a real
* redirect URL would spawn a new tab / Chrome instance instead.
*/
function launchBankIdApp(autoStartToken: string): void {
const ua = typeof navigator !== 'undefined' ? navigator.userAgent : ''
const isIOS = /iPad|iPhone|iPod/.test(ua)
const redirect = isIOS ? encodeURIComponent(window.location.href) : 'null'
window.location.href = `https://app.bankid.com/?autostarttoken=${autoStartToken}&redirect=${redirect}`
}
/**
* BankID authentication flow component.
* Handles QR code display (desktop) or app deep link (mobile),
* polling, and result handling.
*/
export function BankIdAuth({ mode, onComplete, hero = false }: BankIdAuthProps) {
const t = useTranslations('auth')
const [status, setStatus] = useState<BankIdStatus>('idle')
const [session, setSession] = useState<BankIdSession | null>(null)
const [activeFlowId, setActiveFlowId] = useState<string | null>(null)
const [hintMessage, setHintMessage] = useState<string>('')
const [errorMessage, setErrorMessage] = useState<string>('')
const [launchedApp, setLaunchedApp] = useState(false)
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)
const abortRef = useRef<AbortController | null>(null)
const lastStartRef = useRef<number>(0)
const onCompleteRef = useRef(onComplete)
onCompleteRef.current = onComplete
const pollFailureCount = useRef(0)
/** True while a poll response is being processed: prevents overlapping ticks. */
const pollInFlightRef = useRef(false)
/** Set once a terminal poll result has been handled: the completion branch must run at most once. */
const completedRef = useRef(false)
/** When the current poll loop began, for the POLL_DEADLINE_MS cap. */
const pollStartedAtRef = useRef(0)
/** Bumped by cancel/unmount so an in-flight startSession stops touching state. */
const startGenRef = useRef(0)
/** True while startSession is running: collapses double-clicks into one billable session. */
const startingRef = useRef(false)
/**
* True when this tab is polling a flow it did not start, on the strength of
* the hint cookie alone. Decides how a 404 reads: nothing to resume (quietly
* show the button) versus this tab's own order expiring (say so).
*/
const resumedRef = useRef(false)
const cleanup = useCallback(() => {
if (pollRef.current) {
clearInterval(pollRef.current)
pollRef.current = null
}
if (abortRef.current) {
abortRef.current.abort()
abortRef.current = null
}
pollFailureCount.current = 0
pollInFlightRef.current = false
}, [])
useEffect(
() => () => {
startGenRef.current++
cleanup()
},
[cleanup]
)
// Poll the flow this browser holds until it completes, fails, or the service
// gives up. Extracted from startSession so the resume effect (the tab BankID
// returned the user to) can attach to a flow it did not start.
const beginPolling = useCallback((flowId: string) => {
// Never leave a previous interval running: two loops would share
// pollFailureCount and completedRef, and the orphan would eventually
// declare a healthy session unavailable and clear the live one.
cleanup()
abortRef.current = new AbortController()
pollStartedAtRef.current = Date.now()
completedRef.current = false
pollInFlightRef.current = false
pollRef.current = setInterval(async () => {
// Never process two ticks concurrently: a slow response overlapping the
// next tick could otherwise run the completion branch twice (double
// /complete → double generateLink, which invalidates the first magic
// link and fails the login intermittently).
if (pollInFlightRef.current || completedRef.current) return
// Hard cap: a session that never reaches a terminal state (expired
// order, TIC response without `status`) must not poll forever.
if (Date.now() - pollStartedAtRef.current > POLL_DEADLINE_MS) {
cleanup()
setStatus('failed')
setErrorMessage('BankID-sessionen löpte ut. Försök igen.')
return
}
pollInFlightRef.current = true
try {
// The server reads the secret session from the cookie. The body and
// non-secret header bind this polling loop to its mode and flow id.
const pollRes = await fetch(`${API_BASE}/poll`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
[FLOW_ID_HEADER]: flowId,
},
body: JSON.stringify({ mode }),
signal: abortRef.current?.signal,
})
// The server says this browser holds no live flow: it finished in
// another tab, was cancelled, or expired. Terminal, and NOT a service
// failure, so settle instead of spinning until the deadline.
//
// Matched on the body code, not the bare status: 404 is also what the
// extension dispatcher returns for an unknown route and what the CDN
// returns mid-deploy, and treating those as "your session died" would
// abandon a live order and cost a second billable one.
if (pollRes.status === 404) {
const reason = await pollRes.json().catch(() => null)
if (reason?.error !== 'no_session') {
pollFailureCount.current++
return
}
completedRef.current = true
cleanup()
if (resumedRef.current) {
// We only probed on the chance a flow existed. It does not, so
// quietly offer the start button.
setStatus('idle')
} else {
// This tab watched its own order die. Say so: silently reverting to
// the start button reads as "it just did nothing".
setStatus('failed')
setErrorMessage('BankID-sessionen löpte ut. Försök igen.')
}
setSession(null)
setActiveFlowId(null)
return
}
if (!pollRes.ok) {
// Count EVERY failed poll (5xx, 429, unexpected 4xx): errors that
// never increment the counter would otherwise leave the user
// silently polling a dead session forever.
pollFailureCount.current++
if (pollFailureCount.current >= MAX_POLL_FAILURES) {
cleanup()
setStatus('service_unavailable')
setErrorMessage('BankID-tjänsten är inte tillgänglig just nu')
onCompleteRef.current({ error: 'service_unavailable' })
}
return
}
// Reset failure counter on successful poll
pollFailureCount.current = 0
const pollJson = await pollRes.json()
const pollData = pollJson.data
if (!pollData) {
console.warn('[bankid] poll returned no data:', pollJson)
return
}
// Update hint message from TIC API
if (pollData.message) {
setHintMessage(pollData.message)
}
// Token refresh (the order regenerates roughly every 25s). Adopted
// even when this tab has no session of its own: that is how a resumed
// tab (a reload, or the tab BankID returned the user to) gets a
// renderable QR code instead of a spinner with nothing under it.
if (pollData.qrStartToken && pollData.qrStartSecret) {
setSession((prev) => ({
flowId,
autoStartToken: prev?.autoStartToken ?? '',
qrStartToken: pollData.qrStartToken,
qrStartSecret: pollData.qrStartSecret,
}))
}
if (pollData.status === 'complete') {
completedRef.current = true
cleanup()
setStatus('complete')
if (mode === 'login') {
// For login, call /complete to exchange for Supabase session.
// Session and mode come from the flow cookie; the server clears it
// as it answers, so this is single-use and a second tab that also
// saw 'complete' gets session_invalid rather than minting a rival
// magic link that would invalidate this one.
try {
const completeRes = await fetch(`${API_BASE}/complete`, {
method: 'POST',
headers: { [FLOW_ID_HEADER]: flowId },
})
const completeJson = await completeRes.json()
if (!completeRes.ok) {
const errorCode = completeJson.error === 'service_unavailable' || completeRes.status === 502 || completeRes.status === 503
? 'service_unavailable' as const
: completeJson.error
if (errorCode === 'service_unavailable') {
setStatus('service_unavailable')
setErrorMessage('BankID-tjänsten är inte tillgänglig just nu')
}
onCompleteRef.current({
error: errorCode,
message: typeof completeJson.message === 'string' ? completeJson.message : undefined,
givenName: completeJson.givenName,
surname: completeJson.surname,
})
return
}
onCompleteRef.current({
tokenHash: completeJson.data.tokenHash,
type: completeJson.data.type,
isNewUser: completeJson.data.isNewUser,
})
} catch {
onCompleteRef.current({ error: 'session_invalid' })
}
} else if (mode === 'link') {
// For link, call /link to associate BankID with current user. The
// server requires the flow cookie to have been opened in 'link'
// mode, so a session started to sign someone in cannot be turned
// into a binding against whoever is logged in here.
try {
const linkRes = await fetch(`${API_BASE}/link`, {
method: 'POST',
headers: { [FLOW_ID_HEADER]: flowId },
})
const linkJson = await linkRes.json()
if (!linkRes.ok) {
onCompleteRef.current({ error: linkJson.error })
return
}
onCompleteRef.current({})
} catch {
onCompleteRef.current({ error: 'session_invalid' })
}
} else {
// For signup, hand the parent the verified name so it can collect
// an e-mail. The flow itself stays in the cookie, so the parent
// posts only that e-mail to /complete.
onCompleteRef.current({
givenName: pollData.user?.givenName,
surname: pollData.user?.surname,
flowId,
})
}
} else if (pollData.status === 'failed' || pollData.status === 'cancelled') {
completedRef.current = true
cleanup()
setStatus('failed')
setErrorMessage(pollData.message || 'BankID-identifieringen misslyckades')
}
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') return
pollFailureCount.current++
if (pollFailureCount.current >= MAX_POLL_FAILURES) {
cleanup()
setStatus('service_unavailable')
setErrorMessage('BankID-tjänsten är inte tillgänglig just nu')
onCompleteRef.current({ error: 'service_unavailable' })
}
} finally {
pollInFlightRef.current = false
}
}, 2000)
}, [cleanup, mode])
const startSession = useCallback(async () => {
// Collapse double-clicks: one billable TIC session per intent.
if (startingRef.current) return
startingRef.current = true
const gen = ++startGenRef.current
cleanup()
resumedRef.current = false
setActiveFlowId(null)
setLaunchedApp(false)
setStatus('scanning')
setHintMessage('Starta BankID-appen')
setErrorMessage('')
try {
// Respect the billable-session cooldown by waiting out the remainder
// instead of silently dropping the click: a retry button that does
// nothing reads as "BankID is broken". Also keeps us under the
// server-side per-IP cooldown on /start.
const sinceLast = Date.now() - lastStartRef.current
if (sinceLast < START_COOLDOWN_MS) {
await new Promise((resolve) => setTimeout(resolve, START_COOLDOWN_MS - sinceLast))
}
if (gen !== startGenRef.current) return // cancelled/unmounted while waiting
lastStartRef.current = Date.now()
// The mode is pinned server-side into the flow cookie, so the session
// this opens can only ever be finished as this kind of flow.
const res = await fetch(`${API_BASE}/start`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode }),
})
if (gen !== startGenRef.current) return
if (!res.ok) {
const err = await res.json().catch(() => ({}))
if (err.error === 'service_unavailable' || err.error === 'not_configured' || res.status === 502 || res.status === 503) {
cleanup()
setStatus('service_unavailable')
setErrorMessage('BankID-tjänsten är inte tillgänglig just nu')
onCompleteRef.current({ error: 'service_unavailable' })
return
}
if (res.status === 429 || err.error === 'rate_limit') {
setStatus('failed')
setErrorMessage('För många försök. Vänta en stund och försök igen.')
return
}
// Unknown error: server messages are not user-facing copy; keep the
// detail in the console and show Swedish.
console.error('[bankid] start failed', res.status, err)
setStatus('failed')
setErrorMessage('Ett oväntat fel uppstod. Försök igen.')
return
}
const { data } = await res.json()
const newSession: BankIdSession = data
setSession(newSession)
setActiveFlowId(newSession.flowId)
// On mobile, open the BankID app on this device. Nothing needs saving
// first: /start already set the flow cookie, and a cookie is shared by
// every tab of the origin, so whichever tab BankID returns the user to
// (this one reloaded, or a brand new one) can resume from it.
if (isMobile()) {
setLaunchedApp(true)
launchBankIdApp(newSession.autoStartToken)
}
beginPolling(newSession.flowId)
} catch (error) {
if (gen !== startGenRef.current) return
console.error('[bankid] start failed', error)
setStatus('failed')
setErrorMessage('Ett oväntat fel uppstod. Försök igen.')
} finally {
startingRef.current = false
}
}, [cleanup, mode, beginPolling])
/**
* Start (or continue) polling the flow this browser holds. Called from the
* "Fortsätt" confirm button and from startSession, never automatically on
* mount: see the probe effect below for why.
*/
const resumePolling = useCallback(() => {
if (!activeFlowId) return
resumedRef.current = true
setStatus('scanning')
setHintMessage(t('bankid_resume_hint'))
beginPolling(activeFlowId)
}, [activeFlowId, beginPolling, t])
/**
* On mount, ask ONCE whether this browser is mid-flow, and if so present a
* confirm card rather than continuing automatically.
*
* This is the fix for the reported bug and the safe shape for it. BankID does
* not reliably return the user to the tab that started the flow: on iOS
* outside plain Safari the redirect opens a NEW tab, and even the same tab is
* reloaded. The flow lives in a shared cookie now, so any of those tabs can
* pick it up. But a shared cookie plus a shared machine means the tab that
* finds a completed identification cannot prove the person sitting at it is
* the one who made it: nothing the client can store survives an iOS reload
* yet dies on "reopen closed tab" / session restore / tab duplication, so a
* completed flow could otherwise be auto-consumed by the next person to open
* the page and sign them into, or bind their account to, a stranger.
*
* So a resume is never automatic: a found flow routes to the confirm card
* ("Fortsätt bara om det var du"), and only that click consumes it. The cost
* is one tap after returning from the BankID app on iOS, which is where the
* reported bug lives; desktop QR (no reload) and Android (returns to the live
* tab) never hit this path and are unchanged. `link` never resumes at all.
*/
useEffect(() => {
if (mode === 'link') return
let cancelled = false
const gen = startGenRef.current
void (async () => {
try {
const res = await fetch(`${API_BASE}/poll`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ mode, probe: true }),
})
// No live flow this browser can point to (no cookie, or one for a
// different mode): leave the start button.
if (cancelled || res.status === 404 || !res.ok) return
const json = await res.json().catch(() => null)
const status = json?.data?.status
if (!status || status === 'failed' || status === 'cancelled') return
// A start begun while the probe was in flight owns the panel; do not
// override it with a confirm card for the flow it is replacing.
if (cancelled || gen !== startGenRef.current || startingRef.current) return
// A live flow exists. It may be this person returning from the BankID
// app, or a stranger's identification left on a shared machine; the two
// are indistinguishable from here, so it is theirs to confirm, never
// ours to spend. The probe deliberately gets no holder name from /poll,
// so the card cannot reveal whose identification it is.
const flowId = json?.data?.flowId
if (typeof flowId !== 'string' || !flowId) return
setActiveFlowId(flowId)
setStatus('resumable')
} catch {
// Offline or a blip: leave the start button. A flow that really is
// live will still be there when they press it (or on the next load).
}
})()
return () => {
cancelled = true
}
// Mount only: we are asking whether this browser is mid-flow, which cannot
// change without one of this component's own actions.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const handleCancel = useCallback(async () => {
startGenRef.current++ // stop an in-flight startSession from resuming
cleanup()
setSession(null)
// Hold a 'cancelling' state until /cancel resolves, rather than going
// straight to 'idle'. /cancel clears the flow cookie with an UNTARGETED
// Set-Cookie, and it round-trips to TIC before responding, so if the start
// button were reachable now the user could open a new flow whose fresh
// cookie the late clear would then delete. No start button is rendered in
// 'cancelling', so a new /start cannot race the clear.
setStatus('cancelling')
try {
await fetch(`${API_BASE}/cancel`, {
method: 'POST',
headers: activeFlowId ? { [FLOW_ID_HEADER]: activeFlowId } : undefined,
})
} catch {
// Unreachable server: the flow expires on its own.
} finally {
setActiveFlowId(null)
setStatus('idle')
}
}, [activeFlowId, cleanup])
if (status === 'cancelling') {
return (
<div className="flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
{t('bankid_cancelling')}
</div>
)
}
if (status === 'resumable') {
return (
<div className="rounded-lg border border-border bg-muted/30 p-4">
<div className="space-y-3">
<div className="space-y-2">
<p className="text-sm font-medium">{t('bankid_resume_title')}</p>
<p className="text-sm text-muted-foreground">
{/* Deliberately does not say who: naming the holder would leak a
stranger's identity to whoever sits down at a shared machine.
Signup shows the verified name on the next step, after the
person here has claimed the identification as theirs. */}
{t('bankid_resume_description')}
</p>
</div>
<div className="flex flex-wrap gap-2">
<Button onClick={resumePolling} variant="default" className="h-11 gap-2">
<BankIdIcon className="invert dark:invert-0" />
{t('bankid_resume_continue')}
</Button>
<Button onClick={handleCancel} variant="outline" className="h-11">
{t('bankid_resume_restart')}
</Button>
</div>
</div>
</div>
)
}
if (status === 'complete') {
return (
<div className="flex items-center justify-center gap-2 py-6 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
{t('bankid_completing')}
</div>
)
}
if (status === 'idle') {
const label = mode === 'login'
? 'Logga in med BankID'
: mode === 'link'
? 'Koppla BankID'
: 'Skapa konto med BankID'
return (
<Button
onClick={startSession}
variant={hero ? 'default' : 'outline'}
className={hero ? 'h-11 w-full gap-2' : 'w-full gap-2 border-[1.5px] py-6 text-base'}
>
{/* On the filled pill the logo must counter-invert: primary is dark in
light mode (white logo) and light in dark mode (black logo). */}
<BankIdIcon className={hero ? 'invert dark:invert-0' : undefined} />
{label}
</Button>
)
}
if (status === 'service_unavailable') {
return (
<div className="rounded-lg border border-border bg-muted/30 p-4">
<div className="flex items-start gap-3">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-attn" />
<div className="space-y-1.5">
<p className="text-sm font-medium">
BankID är inte tillgängligt just nu
</p>
<p className="text-sm text-muted-foreground">
{mode === 'login'
? 'Logga in med e-post och lösenord nedan, eller använd "Glömt lösenord?" för en inloggningslänk via e-post.'
: mode === 'signup'
? 'Skapa konto med e-post och lösenord nedan istället.'
: 'Försök igen senare.'}
</p>
<Button
onClick={startSession}
variant="ghost"
size="sm"
className="mt-1 h-auto px-0 py-0 text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground"
>
Försök med BankID igen
</Button>
</div>
</div>
</div>
)
}
if (status === 'failed') {
return (
<div className="flex flex-col items-center gap-4">
<p className="text-sm text-destructive">{errorMessage}</p>
<Button onClick={startSession} variant="outline" className="gap-2">
<BankIdIcon />
Försök igen
</Button>
</div>
)
}
const openBankIdOnDevice = () => {
if (!session) return
// Open BankID app on the same device via deep link
// redirect=null tells BankID not to redirect after completion
window.location.href = `bankid:///?autostarttoken=${session.autoStartToken}&redirect=null`
}
// Scanning / waiting for user
return (
<div className="flex flex-col items-center gap-4">
{session && !isMobile() && (
<>
<BankIdQrCode
qrStartToken={session.qrStartToken}
qrStartSecret={session.qrStartSecret}
/>
{/* A resumed tab never called /start, so it has the rotating QR
tokens but no autostart token. Rendering the button anyway would
deep-link `autostarttoken=` empty, which does nothing and says
nothing. The QR above still works. */}
{session.qrStartToken && session.qrStartSecret && session.autoStartToken && (
<Button
onClick={openBankIdOnDevice}
variant="ghost"
size="sm"
className="gap-1.5 text-muted-foreground"
>
<Monitor className="h-3.5 w-3.5" />
BankID på den här enheten
</Button>
)}
</>
)}
{isMobile() && (
<div className="flex flex-col items-center gap-2">
<Smartphone className="h-8 w-8 text-muted-foreground" />
{/* A resumed tab never launched anything, so saying "opening the
BankID app" would be a lie followed by silence. */}
<p className="text-sm text-muted-foreground">
{launchedApp
? 'Öppnar BankID-appen...'
: t('bankid_finish_in_app')}
</p>
</div>
)}
<p className="text-sm text-muted-foreground">{hintMessage}</p>
<Button
onClick={handleCancel}
disabled={!activeFlowId}
variant="ghost"
size="sm"
className="text-muted-foreground"
>
Avbryt
</Button>
</div>
)
}
function BankIdIcon({ className }: { className?: string }) {
return (
<Image
src="/logos/bankid-seeklogo.svg"
alt="BankID"
width={20}
height={20}
loading="eager"
className={className ?? 'dark:invert'}
/>
)
}
-86
View File
@@ -1,86 +0,0 @@
'use client'
import { useEffect, useRef, useState, useCallback } from 'react'
import QRCode from 'qrcode'
interface BankIdQrCodeProps {
qrStartToken: string
qrStartSecret: string
}
/**
* Animated BankID QR code component.
* Computes HMAC-SHA256 every second per BankID spec:
* bankid.{qrStartToken}.{time}.{hmac_sha256(qrStartSecret, time)}
*/
export function BankIdQrCode({ qrStartToken, qrStartSecret }: BankIdQrCodeProps) {
const [svgData, setSvgData] = useState<string>('')
const elapsedRef = useRef(0)
const tokenRef = useRef(qrStartToken)
const secretRef = useRef(qrStartSecret)
// Update refs when tokens change (order regeneration)
useEffect(() => {
tokenRef.current = qrStartToken
secretRef.current = qrStartSecret
elapsedRef.current = 0
}, [qrStartToken, qrStartSecret])
const generateQr = useCallback(async () => {
const token = tokenRef.current
const secret = secretRef.current
const time = elapsedRef.current
try {
// Compute HMAC-SHA256 using Web Crypto API
const encoder = new TextEncoder()
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
)
const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(time.toString()))
const qrAuthCode = Array.from(new Uint8Array(signature))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
const qrData = `bankid.${token}.${time}.${qrAuthCode}`
const svg = await QRCode.toString(qrData, {
type: 'svg',
margin: 1,
width: 200,
color: { dark: '#141414', light: '#ffffff' },
})
setSvgData(svg)
} catch {
// Silently fail: next tick will retry
}
elapsedRef.current++
}, [])
useEffect(() => {
// Generate immediately, then every second
generateQr()
const interval = setInterval(generateQr, 1000)
return () => clearInterval(interval)
}, [generateQr])
if (!svgData) {
return (
<div className="flex h-[200px] w-[200px] items-center justify-center rounded-lg border bg-white">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
)
}
return (
<div
className="inline-flex rounded-lg border bg-white p-2"
dangerouslySetInnerHTML={{ __html: svgData }}
/>
)
}
-98
View File
@@ -1,98 +0,0 @@
'use client'
import { useState } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import { createClient } from '@/lib/supabase/client'
import { Button } from '@/components/ui/button'
import { Loader2, KeyRound } from 'lucide-react'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { GitHubMark, GoogleMark, MicrosoftMark } from '@/components/ui/provider-marks'
import type { ResolvedProvider } from '@/lib/auth/gotrue-providers'
/**
* Render the brand mark for a known provider, or a generic key icon for
* custom OIDC providers.
*/
function ProviderMark({ provider }: { provider: ResolvedProvider }) {
if (provider.id === 'google') return <GoogleMark />
else if (provider.id === 'azure') return <MicrosoftMark />
else if (provider.id === 'github') return <GitHubMark />
else return <KeyRound className="h-4 w-4 text-muted-foreground" />
}
/**
* Generic OAuth login button. Works with any Supabase GoTrue provider.
*
* For known providers (Google, GitHub, etc.) the button shows the brand
* name; for custom OIDC providers it shows "Sign in with SSO" style text.
*
* Kicks off the Supabase OAuth redirect, with flow=oauth so
* /auth/callback can tag failures.
*/
export function OAuthButton({
provider,
onError,
compact = false,
next,
}: {
provider: ResolvedProvider
onError: (message: string) => void
compact?: boolean
/**
* Post-auth destination, already passed through safeReturnTo by the caller.
* Forwarded to /auth/callback as `next` so an OAuth sign-in or sign-up that
* started from the MCP consent page (/login?next=/api/mcp-oauth/authorize…)
* resumes the consent flow instead of landing on the dashboard. '/' (the
* safeReturnTo fallback) means no destination and is not forwarded.
*/
next?: string
}) {
const [isRedirecting, setIsRedirecting] = useState(false)
const supabase = createClient()
const tAuth = useTranslations('auth')
const errorLocale = useLocale() as ErrorLocale
const handleClick = async () => {
setIsRedirecting(true)
try {
const callback = new URL('/auth/callback', window.location.origin)
callback.searchParams.set('flow', 'oauth')
if (next && next !== '/') callback.searchParams.set('next', next)
const { error } = await supabase.auth.signInWithOAuth({
provider: provider.id as Parameters<typeof supabase.auth.signInWithOAuth>[0]['provider'],
options: {
redirectTo: callback.toString(),
},
})
if (error) {
onError(getErrorMessage(error, { context: 'auth', locale: errorLocale }))
setIsRedirecting(false)
}
} catch (error) {
onError(getErrorMessage(error, { context: 'auth', locale: errorLocale }))
setIsRedirecting(false)
}
}
const label = tAuth('continue_with_provider', { provider: provider.label })
return (
<Button
type="button"
variant="outline"
className={compact ? 'h-10 w-full gap-2' : 'w-full h-11'}
onClick={handleClick}
disabled={isRedirecting}
aria-label={label}
>
{isRedirecting ? (
<Loader2 className={compact ? 'h-4 w-4 animate-spin' : 'mr-2 h-4 w-4 animate-spin'} />
) : (
<span className={compact ? 'flex items-center' : 'mr-2 flex items-center'}>
<ProviderMark provider={provider} />
</span>
)}
{compact ? provider.label : label}
</Button>
)
}
@@ -1,257 +0,0 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import { createClient } from '@/lib/supabase/client'
import { resetAnalyticsIdentity } from '@/lib/analytics/reset'
import {
SESSION_TIMEOUT_CHANNEL,
SESSION_TIMEOUT_REASON_HEADER,
type SessionTimeoutClientState,
type SessionTimeoutReason,
} from '@/lib/auth/session-timeout-shared'
import { SessionTimeoutModal } from './SessionTimeoutModal'
const ACTIVITY_HEARTBEAT_INTERVAL_MS = 15_000
const SERVER_RESYNC_INTERVAL_MS = 60_000
const ACTIVITY_EVENTS = ['pointerdown', 'keydown', 'scroll', 'touchstart'] as const
type Warning = { reason: SessionTimeoutReason; seconds: number }
function timeoutDeadline(
state: SessionTimeoutClientState,
lastActivityAt: number,
): { at: number; reason: SessionTimeoutReason } {
const absoluteAt = state.absoluteTimeoutMs > 0
? state.startedAt + state.absoluteTimeoutMs
: Number.POSITIVE_INFINITY
const idleAt = state.idleTimeoutMs > 0
? lastActivityAt + state.idleTimeoutMs
: Number.POSITIVE_INFINITY
return absoluteAt <= idleAt
? { at: absoluteAt, reason: 'absolute' }
: { at: idleAt, reason: 'idle' }
}
export function SessionTimeoutController() {
const [warning, setWarning] = useState<Warning | null>(null)
const [isExtending, setIsExtending] = useState(false)
const stateRef = useRef<SessionTimeoutClientState | null>(null)
const lastActivityAtRef = useRef(0)
const lastHeartbeatAtRef = useRef(0)
const heartbeatInFlightRef = useRef(false)
const expiringRef = useRef(false)
const warningOpenRef = useRef(false)
const channelRef = useRef<BroadcastChannel | null>(null)
const expire = useCallback(async (reason: SessionTimeoutReason) => {
if (expiringRef.current) return
expiringRef.current = true
resetAnalyticsIdentity()
try {
await createClient().auth.signOut({ scope: 'local' })
} catch {
// Middleware remains authoritative and clears the server cookies.
}
const method = stateRef.current?.method ?? 'password'
const url = new URL('/login', window.location.origin)
url.searchParams.set('reason', reason)
url.searchParams.set('method', method)
const next = window.location.pathname + window.location.search
if (next !== '/') url.searchParams.set('next', next)
window.location.assign(url.toString())
}, [])
const applyServerState = useCallback((state: SessionTimeoutClientState) => {
if (!state.enabled) {
stateRef.current = null
lastActivityAtRef.current = 0
warningOpenRef.current = false
setWarning(null)
return
}
const clockOffset = Date.now() - state.serverNow
stateRef.current = {
...state,
startedAt: state.startedAt + clockOffset,
lastActivityAt: state.lastActivityAt + clockOffset,
serverNow: Date.now(),
}
lastActivityAtRef.current = state.lastActivityAt + clockOffset
}, [])
const handleExpiredResponse = useCallback((response: Response) => {
const reason = response.headers.get(SESSION_TIMEOUT_REASON_HEADER) === 'idle'
? 'idle'
: 'absolute'
void expire(reason)
}, [expire])
const syncFromServer = useCallback(async () => {
try {
const response = await fetch('/api/auth/heartbeat', {
method: 'GET',
cache: 'no-store',
credentials: 'same-origin',
})
if (response.status === 401) {
handleExpiredResponse(response)
return
}
if (!response.ok) return
const payload = await response.json() as { data: SessionTimeoutClientState }
applyServerState(payload.data)
} catch {
// A later resync or protected request will retry server enforcement.
}
}, [applyServerState, handleExpiredResponse])
const sendHeartbeat = useCallback(async (showProgress = false) => {
if (heartbeatInFlightRef.current || !stateRef.current) return false
heartbeatInFlightRef.current = true
if (showProgress) setIsExtending(true)
try {
const response = await fetch('/api/auth/heartbeat', {
method: 'POST',
cache: 'no-store',
credentials: 'same-origin',
})
if (response.status === 401) {
handleExpiredResponse(response)
return false
}
if (!response.ok) return false
const payload = await response.json() as { data: SessionTimeoutClientState }
applyServerState(payload.data)
lastHeartbeatAtRef.current = Date.now()
warningOpenRef.current = false
setWarning(null)
channelRef.current?.postMessage({ type: 'heartbeat', state: payload.data })
return true
} catch {
return false
} finally {
heartbeatInFlightRef.current = false
if (showProgress) setIsExtending(false)
}
}, [applyServerState, handleExpiredResponse])
const recordActivity = useCallback(() => {
const state = stateRef.current
if (!state || warningOpenRef.current || expiringRef.current) return
const now = Date.now()
lastActivityAtRef.current = now
channelRef.current?.postMessage({ type: 'activity', at: now })
if (now - lastHeartbeatAtRef.current >= ACTIVITY_HEARTBEAT_INTERVAL_MS) {
void sendHeartbeat()
}
}, [sendHeartbeat])
useEffect(() => {
void syncFromServer()
const channel = typeof BroadcastChannel === 'undefined'
? null
: new BroadcastChannel(SESSION_TIMEOUT_CHANNEL)
channelRef.current = channel
if (channel) {
channel.onmessage = (event: MessageEvent<{
type: 'activity' | 'heartbeat' | 'expired'
at?: number
reason?: SessionTimeoutReason
state?: SessionTimeoutClientState
}>) => {
// 'expired' comes from notifySessionExpired(): a data request hit the
// middleware 401 before our own timers noticed, which is the normal
// order of events in a backgrounded tab where they are throttled.
if (event.data.type === 'expired') {
void expire(event.data.reason === 'idle' ? 'idle' : 'absolute')
} else if (event.data.type === 'heartbeat' && event.data.state) {
applyServerState(event.data.state)
lastHeartbeatAtRef.current = Date.now()
warningOpenRef.current = false
setWarning(null)
} else if (
event.data.type === 'activity' &&
typeof event.data.at === 'number' &&
!warningOpenRef.current
) {
lastActivityAtRef.current = Math.max(
lastActivityAtRef.current,
event.data.at,
)
}
}
}
for (const eventName of ACTIVITY_EVENTS) {
window.addEventListener(eventName, recordActivity, { passive: true })
}
const onVisibilityChange = () => {
if (document.visibilityState === 'visible') void syncFromServer()
}
document.addEventListener('visibilitychange', onVisibilityChange)
const timer = window.setInterval(() => {
const state = stateRef.current
if (!state) return
const deadline = timeoutDeadline(state, lastActivityAtRef.current)
const remainingMs = deadline.at - Date.now()
if (remainingMs <= 0) {
void expire(deadline.reason)
return
}
if (state.warningMs > 0 && remainingMs <= state.warningMs) {
warningOpenRef.current = true
setWarning({
reason: deadline.reason,
seconds: Math.max(1, Math.ceil(remainingMs / 1000)),
})
} else if (warningOpenRef.current) {
warningOpenRef.current = false
setWarning(null)
}
}, 1000)
const resyncTimer = window.setInterval(() => {
if (document.visibilityState === 'visible') void syncFromServer()
}, SERVER_RESYNC_INTERVAL_MS)
return () => {
window.clearInterval(timer)
window.clearInterval(resyncTimer)
document.removeEventListener('visibilitychange', onVisibilityChange)
for (const eventName of ACTIVITY_EVENTS) {
window.removeEventListener(eventName, recordActivity)
}
channel?.close()
channelRef.current = null
}
}, [applyServerState, expire, recordActivity, syncFromServer])
if (!warning) return null
return (
<SessionTimeoutModal
reason={warning.reason}
seconds={warning.seconds}
isExtending={isExtending}
onContinue={() => {
if (warning.reason === 'absolute') {
void expire('absolute')
} else {
lastActivityAtRef.current = Date.now()
void sendHeartbeat(true)
}
}}
/>
)
}
-57
View File
@@ -1,57 +0,0 @@
'use client'
import { Loader2, ShieldAlert } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import type { SessionTimeoutReason } from '@/lib/auth/session-timeout-shared'
export function SessionTimeoutModal({
reason,
seconds,
isExtending,
onContinue,
}: {
reason: SessionTimeoutReason
seconds: number
isExtending: boolean
onContinue: () => void
}) {
const t = useTranslations('session_timeout')
return (
<Dialog open onOpenChange={() => {}}>
<DialogContent
className="max-w-md [&>button]:hidden"
onEscapeKeyDown={(event) => event.preventDefault()}
onPointerDownOutside={(event) => event.preventDefault()}
onInteractOutside={(event) => event.preventDefault()}
>
<DialogHeader>
<div className="mb-2 flex h-10 w-10 items-center justify-center rounded-full bg-muted text-attn">
<ShieldAlert className="h-5 w-5" aria-hidden="true" />
</div>
<DialogTitle>{t('warning_title')}</DialogTitle>
<DialogDescription>
{reason === 'idle'
? t('idle_warning', { seconds })
: t('absolute_warning', { seconds })}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button onClick={onContinue} disabled={isExtending} autoFocus>
{isExtending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{reason === 'idle' ? t('continue') : t('sign_in_again')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
-181
View File
@@ -1,181 +0,0 @@
'use client'
import Script from 'next/script'
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useRef,
useState,
} from 'react'
import { useTranslations } from 'next-intl'
import {
getTurnstileRolloutState,
resolveTurnstileSiteKey,
} from '@/lib/auth/turnstile'
const TURNSTILE_SCRIPT_URL =
'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit'
export type TurnstileAction =
| 'accounted_login'
| 'accounted_password_reset'
| 'accounted_signup'
| 'accounted_sandbox'
type TurnstileWidgetState = 'loading' | 'ready' | 'verified' | 'error'
type TurnstileRenderOptions = {
sitekey: string
action: TurnstileAction
appearance: 'interaction-only'
execution: 'render'
size: 'compact'
theme: 'auto'
callback: (token: string) => void
'error-callback': () => void
'expired-callback': () => void
'timeout-callback': () => void
}
type TurnstileApi = {
render: (
container: HTMLElement,
options: TurnstileRenderOptions,
) => string | undefined
remove: (widgetId: string) => void
reset: (widgetId: string) => void
}
declare global {
interface Window {
turnstile?: TurnstileApi
}
}
export type TurnstileChallengeHandle = {
reset: () => void
}
type TurnstileChallengeProps = {
action: TurnstileAction
onTokenChange: (token: string | null) => void
}
export const TurnstileChallenge = forwardRef<
TurnstileChallengeHandle,
TurnstileChallengeProps
>(function TurnstileChallenge({ action, onTokenChange }, ref) {
const t = useTranslations('auth')
const siteKey = resolveTurnstileSiteKey()
const rolloutState = getTurnstileRolloutState()
const containerRef = useRef<HTMLDivElement>(null)
const widgetIdRef = useRef<string | null>(null)
const onTokenChangeRef = useRef(onTokenChange)
const [widgetState, setWidgetState] = useState<TurnstileWidgetState>('loading')
useEffect(() => {
onTokenChangeRef.current = onTokenChange
}, [onTokenChange])
const clearToken = useCallback((state: TurnstileWidgetState) => {
onTokenChangeRef.current(null)
setWidgetState(state)
}, [])
const reset = useCallback(() => {
clearToken('ready')
const widgetId = widgetIdRef.current
if (!widgetId || !window.turnstile) return
try {
window.turnstile.reset(widgetId)
} catch {
clearToken('error')
}
}, [clearToken])
useImperativeHandle(ref, () => ({ reset }), [reset])
const renderWidget = useCallback(() => {
if (!siteKey || !containerRef.current || !window.turnstile) return
if (widgetIdRef.current) return
try {
setWidgetState('ready')
const widgetId = window.turnstile.render(containerRef.current, {
sitekey: siteKey,
action,
appearance: 'interaction-only',
execution: 'render',
size: 'compact',
theme: 'auto',
callback: (token) => {
onTokenChangeRef.current(token)
setWidgetState('verified')
},
'error-callback': () => clearToken('error'),
'expired-callback': reset,
'timeout-callback': reset,
})
if (!widgetId) {
clearToken('error')
return
}
widgetIdRef.current = widgetId
} catch {
clearToken('error')
}
}, [action, clearToken, reset, siteKey])
useEffect(() => {
return () => {
const widgetId = widgetIdRef.current
if (!widgetId || !window.turnstile) return
try {
window.turnstile.remove(widgetId)
} catch {
// The provider may already have removed an expired widget.
}
widgetIdRef.current = null
}
}, [])
if (!siteKey) {
return (
<span
aria-hidden="true"
className="hidden"
data-turnstile-rollout-state={rolloutState}
/>
)
}
return (
<div
className="flex flex-col items-center gap-2"
data-turnstile-rollout-state={rolloutState}
data-turnstile-widget-state={widgetState}
>
<Script
id="cloudflare-turnstile"
src={TURNSTILE_SCRIPT_URL}
strategy="afterInteractive"
onReady={renderWidget}
onError={() => clearToken('error')}
/>
<div ref={containerRef} />
{(widgetState === 'loading' || widgetState === 'ready') && (
<p className="sr-only" role="status">
{t('turnstile_checking')}
</p>
)}
{widgetState === 'error' && (
<p className="text-center text-xs text-destructive" role="alert">
{t('turnstile_error')}
</p>
)}
</div>
)
})
@@ -1,66 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
/**
* Multi-user grace countdown: shown to EVERYONE in a company whose
* multi_user entitlement has lapsed but is still inside its 20-day grace
* window, and only when the company actually has affected people (at least
* one non-owner member). The affected member reads their own version; the
* owner (and everyone else) reads which accounts pause and when.
*
* Server-gated: the dashboard layout renders this only in the grace state
* with a non-empty affected list, so the component itself only formats.
* Same chrome treatment as SandboxBanner: environment notice on secondary,
* never a warning fill (status colors are data, not chrome).
*/
export function MultiUserGraceBanner({
graceEndsAt,
affectedEmails,
isAffectedUser,
companyName,
}: {
graceEndsAt: string
affectedEmails: string[]
/** True when the signed-in user is one of the accounts that will pause. */
isAffectedUser: boolean
companyName: string
}) {
const t = useTranslations('multi_user')
// Computed in an effect so server and client markup agree at hydration;
// an hourly tick keeps a long-lived tab honest (same pattern as
// SubscriptionTouchpoint).
const [daysLeft, setDaysLeft] = useState<number | null>(null)
useEffect(() => {
const update = () => {
const msLeft = new Date(graceEndsAt).getTime() - Date.now()
setDaysLeft(Math.max(0, Math.ceil(msLeft / 86_400_000)))
}
update()
const id = setInterval(update, 3_600_000)
return () => clearInterval(id)
}, [graceEndsAt])
if (daysLeft === null) return null
const message = isAffectedUser
? t('banner_affected', { companyName, days: daysLeft })
: t('banner_owner', { emails: affectedEmails.join(', '), days: daysLeft })
return (
<div className="relative z-50 flex flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-border bg-secondary px-4 py-2 text-sm text-secondary-foreground">
<span className="text-center text-xs font-medium sm:text-sm">{message}</span>
<Link
href="/settings/billing"
className="shrink-0 rounded-full bg-foreground/10 px-3 py-0.5 text-xs font-semibold transition-colors hover:bg-foreground/15"
>
{t('banner_cta')}
</Link>
</div>
)
}
export default MultiUserGraceBanner
@@ -1,121 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { ChevronRight, Clock, Lock } from 'lucide-react'
import { useCompany } from '@/contexts/CompanyContext'
/**
* The chrome-level subscription touchpoint: the paywall is a lifecycle flow,
* not a settings page, so trial state stays quietly visible in the chrome
* instead of only inside Inställningar -> Abonnemang.
*
* trial -> the countdown pill ("Provperiod: N dagar kvar").
* trial_expired /
* lapsed_subscription -> a muted pill linking to /settings/billing. This is
* the navigation affordance a lapsed user could not
* find (2026-08-18 report), so it is NOT dismissable
* and, unlike the countdown, stays visible when the
* sidebar is collapsed (icon-only with aria-label).
*
* Hidden for sandbox/demo (no checkout; sandbox companies carry trial grants
* too) and for paying companies. Muted chrome tone throughout: status colors
* are data, never chrome.
*/
export function SubscriptionTouchpoint({
variant,
collapsed = false,
onNavigate,
}: {
variant: 'sidebar' | 'mobile'
collapsed?: boolean
onNavigate?: () => void
}) {
const { entitlementState, trialEndsAt, isSandbox } = useCompany()
const tNav = useTranslations('nav')
// Trial countdown. Computed in an effect (not during render) so server and
// client markup agree at hydration; an hourly tick keeps a long-lived tab
// from showing yesterday's count.
const [trialDaysLeft, setTrialDaysLeft] = useState<number | null>(null)
useEffect(() => {
if (!trialEndsAt) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setTrialDaysLeft(null)
return
}
const update = () => {
const msLeft = new Date(trialEndsAt).getTime() - Date.now()
setTrialDaysLeft(msLeft > 0 ? Math.ceil(msLeft / 86_400_000) : null)
}
update()
const id = setInterval(update, 3_600_000)
return () => clearInterval(id)
}, [trialEndsAt])
if (isSandbox) return null
const lapsed =
entitlementState === 'trial_expired' || entitlementState === 'lapsed_subscription'
const showCountdown =
entitlementState === 'trial' && trialDaysLeft !== null
if (!lapsed && !showCountdown) return null
const label = lapsed
? tNav(
entitlementState === 'lapsed_subscription'
? 'subscription_lapsed_cta'
: 'trial_expired_cta',
)
: tNav('trial_days_left', { days: trialDaysLeft ?? 0 })
const Icon = lapsed ? Lock : Clock
if (variant === 'mobile') {
return (
<Link
href="/settings/billing"
onClick={onNavigate}
className="flex items-center gap-3 px-3 min-h-[44px] rounded-lg text-foreground transition-colors active:bg-muted/60"
>
<Icon className="h-[18px] w-[18px] flex-shrink-0 text-muted-foreground" />
<span className="text-sm flex-1">{label}</span>
<ChevronRight className="h-4 w-4 flex-shrink-0 text-muted-foreground/50" />
</Link>
)
}
// Sidebar. The countdown keeps its pre-existing behavior of hiding when the
// rail is collapsed; the lapsed CTA must not vanish, so it collapses to an
// icon-only link instead.
if (collapsed) {
if (!lapsed) return null
return (
<div className="flex flex-shrink-0 justify-center pb-2">
<Link
href="/settings/billing"
title={label}
aria-label={label}
className="flex h-9 w-9 items-center justify-center rounded-lg text-muted-foreground hover:bg-secondary/60 hover:text-foreground transition-colors duration-150"
>
<Icon className="h-[17px] w-[17px]" />
</Link>
</div>
)
}
return (
<div className="flex-shrink-0 px-3 pb-2">
<Link
href="/settings/billing"
className="flex items-center gap-2 rounded-lg border border-border px-3 py-2 text-xs text-muted-foreground hover:bg-secondary/60 hover:text-foreground transition-colors duration-150"
>
<Icon className="h-3.5 w-3.5 shrink-0" />
<span className="flex-1 truncate">{label}</span>
<ChevronRight className="h-3.5 w-3.5 shrink-0 opacity-50" />
</Link>
</div>
)
}
export default SubscriptionTouchpoint
-92
View File
@@ -1,92 +0,0 @@
'use client'
import { useState } from 'react'
import { usePathname, useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { persistUiState } from '@/lib/ui-state/client'
import { useFormat } from '@/lib/hooks/use-format'
import type { EntitlementState } from '@/lib/entitlements/has-capability'
/**
* One-time on-entry notice that the trial (or a cancelled subscription) has
* lapsed, with the path to Abonnemang. Shown once per user AND company:
* the acknowledgement persists in user_preferences.ui_state
* (trial_expired_ack[companyId]), read server-side by the dashboard layout so
* an acked dialog never mounts (no flash). Both dismissing and clicking
* through count as acknowledged; afterwards the persistent
* SubscriptionTouchpoint in the chrome carries the CTA. The layout gates
* sandbox/anonymous users (no billing); this component additionally skips
* /settings/* so it never stacks on the routed settings modal.
*/
export function TrialExpiredDialog({
state,
trialExpiredAt,
companyId,
initialAcknowledged,
}: {
state: EntitlementState
trialExpiredAt: string | null
companyId: string
initialAcknowledged: boolean
}) {
const t = useTranslations('trial_expired_dialog')
const { formatDateLong } = useFormat()
const router = useRouter()
const pathname = usePathname()
const [open, setOpen] = useState(true)
const lapsed = state === 'trial_expired' || state === 'lapsed_subscription'
if (!lapsed || initialAcknowledged || pathname.startsWith('/settings')) {
return null
}
const acknowledge = () => {
setOpen(false)
persistUiState({
trial_expired_ack: { [companyId]: new Date().toISOString() },
})
}
const goToBilling = () => {
acknowledge()
router.push('/settings/billing')
}
return (
<Dialog open={open} onOpenChange={(next) => { if (!next) acknowledge() }}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="font-display text-xl tracking-tight">
{state === 'lapsed_subscription'
? t('title_lapsed')
: trialExpiredAt
? t('title_dated', { date: formatDateLong(trialExpiredAt) })
: t('title')}
</DialogTitle>
<DialogDescription className="sr-only">{t('body_paused')}</DialogDescription>
</DialogHeader>
<div className="space-y-3 text-sm text-muted-foreground">
<p>{t('body_paused')}</p>
<p>{t('body_free')}</p>
</div>
<DialogFooter>
<Button variant="ghost" onClick={acknowledge}>
{t('cta_secondary')}
</Button>
<Button onClick={goToBilling}>{t('cta_primary')}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
export default TrialExpiredDialog
-46
View File
@@ -1,46 +0,0 @@
import Link from 'next/link'
import { Lock } from 'lucide-react'
import { cn } from '@/lib/utils'
import { isSelfHosted } from '@/lib/env/public-flags'
/**
* Inline paywall note for a feature that is visible but not entitled.
* The feature stays on screen (conversion surface: never hide, disable
* with an upsell), this note explains why it's disabled and links to
* /settings/billing. Copy mirrors CAPABILITY_BLOCKED_MESSAGE_SV.
*
* On a SELF-HOST the note never mentions a subscription or links to the
* hosted Stripe billing page: the only capabilities that can be blocked
* there are the connector ones (everything local is always on), and their
* remedy is a connector key or the instance's own upstream credentials.
* Copy mirrors CAPABILITY_BLOCKED_MESSAGE_SELF_HOSTED_SV.
*/
export function UpgradeNote({ children, className }: { children?: React.ReactNode; className?: string }) {
const frame = (content: React.ReactNode) => (
<div
className={cn(
'flex items-start gap-2.5 rounded-lg border border-border bg-secondary/40 px-3 py-2.5 text-sm text-muted-foreground',
className,
)}
>
<Lock className="h-4 w-4 mt-0.5 shrink-0" />
<span>{content}</span>
</div>
)
if (isSelfHosted()) {
return frame(
<>
Den här funktionen kräver en connector-nyckel från Accounted (GNUBOK_CONNECTOR_KEY) eller
instansens egna API-uppgifter för tjänsten.
</>,
)
}
return frame(
<>
{children ?? 'Den här funktionen kräver ett abonnemang.'}{' '}
<Link href="/settings/billing" className="underline underline-offset-2 text-foreground">
Uppgradera
</Link>
</>,
)
}
-618
View File
@@ -1,618 +0,0 @@
'use client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { AlertCircle, CheckCircle2, FileClock, Loader2, LockKeyhole, Save } from 'lucide-react'
import { AttnLine } from '@/components/ui/attn-line'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { useBranding } from '@/lib/branding/brand-context'
import type {
AnnualReportComplianceIssue,
AnnualReportProfile,
AnnualReportValidationResult,
AnnualReportVersionSummary,
} from '@/lib/bokslut/arsredovisning/compliance-types'
interface ComplianceResponse {
profile: AnnualReportProfile
eligibility: {
k2_eligible: boolean
digital_filing_eligible: boolean
size_classification: 'smaller' | 'larger' | 'unknown'
issues: AnnualReportComplianceIssue[]
digital_issues: AnnualReportComplianceIssue[]
}
validation: AnnualReportValidationResult
report_summary: {
proposed_dividend: number
distributable_equity: number
}
}
interface AnnualReportStudioProps {
periodId: string
periodStart: string
periodEnd: string
framework: 'k2' | 'k3'
hasUnsavedNarrative: boolean
narrativeRevision: string | null
onVersionsChanged?: (versions: AnnualReportVersionSummary[]) => void
/** Blocking-issue count once the compliance check has loaded, null while loading. */
onBlockingCountChanged?: (count: number | null) => void
}
type NullableBoolean = boolean | null
function BooleanQuestion({
id,
label,
value,
onChange,
}: {
id: string
label: string
value: NullableBoolean
onChange: (value: NullableBoolean) => void
}) {
const t = useTranslations('annualReportStudio')
return (
<div className="space-y-2">
<Label htmlFor={id}>{label}</Label>
<Select
value={value === null ? '' : value ? 'yes' : 'no'}
onValueChange={(next) => onChange(next === 'yes')}
>
<SelectTrigger id={id}>
<SelectValue placeholder={t('choose')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="no">{t('no')}</SelectItem>
<SelectItem value="yes">{t('yes')}</SelectItem>
</SelectContent>
</Select>
</div>
)
}
export function AnnualReportStudio({
periodId,
periodStart,
periodEnd,
framework,
hasUnsavedNarrative,
narrativeRevision,
onVersionsChanged,
onBlockingCountChanged,
}: AnnualReportStudioProps) {
const t = useTranslations('annualReportStudio')
const { appName } = useBranding()
const { toast } = useToast()
const [compliance, setCompliance] = useState<ComplianceResponse | null>(null)
const [profile, setProfile] = useState<AnnualReportProfile | null>(null)
const [versions, setVersions] = useState<AnnualReportVersionSummary[]>([])
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [creatingVersion, setCreatingVersion] = useState<'snapshot' | 'finalize' | null>(null)
const complianceUrl = `/api/bookkeeping/fiscal-periods/${periodId}/arsredovisning/compliance`
const versionsUrl = `/api/bookkeeping/fiscal-periods/${periodId}/arsredovisning/versions`
const load = useCallback(async () => {
setLoading(true)
try {
const [complianceResponse, versionsResponse] = await Promise.all([
fetch(complianceUrl),
fetch(versionsUrl),
])
const [complianceBody, versionsBody] = await Promise.all([
complianceResponse.json(),
versionsResponse.json(),
])
if (!complianceResponse.ok) throw new Error(getUserErrorMessage(complianceBody.error))
if (!versionsResponse.ok) throw new Error(getUserErrorMessage(versionsBody.error))
setCompliance(complianceBody.data as ComplianceResponse)
setProfile((complianceBody.data as ComplianceResponse).profile)
const nextVersions = (versionsBody.data ?? []) as AnnualReportVersionSummary[]
setVersions(nextVersions)
onVersionsChanged?.(nextVersions)
} catch (err) {
toast({
title: t('load_error'),
description: err instanceof Error ? getUserErrorMessage(err) : undefined,
variant: 'destructive',
})
} finally {
setLoading(false)
}
}, [complianceUrl, versionsUrl, onVersionsChanged, t, toast])
useEffect(() => {
void load()
}, [load, narrativeRevision])
const showNewK2Questions =
periodStart > '2025-12-31' || (periodStart > '2025-06-30' && periodEnd >= '2026-12-31')
const blockingIssues = useMemo(
() => compliance?.validation.issues.filter((issue) => issue.severity === 'error') ?? [],
[compliance],
)
// The signature section further down explains why "Låst version" is empty
// in terms of this count, so it must not read 0 while we are still loading.
useEffect(() => {
onBlockingCountChanged?.(compliance ? blockingIssues.length : null)
}, [compliance, blockingIssues.length, onBlockingCountChanged])
const digitalOnlyIssues = useMemo(() => {
const generalCodes = new Set(compliance?.validation.issues.map((issue) => issue.code) ?? [])
return (
compliance?.eligibility.digital_issues.filter((issue) => !generalCodes.has(issue.code)) ?? []
)
}, [compliance])
const updateProfile = <K extends keyof AnnualReportProfile>(
key: K,
value: AnnualReportProfile[K],
) => {
setProfile((current) => (current ? { ...current, [key]: value } : current))
}
const saveProfile = async () => {
if (!profile) return
setSaving(true)
try {
const response = await fetch(complianceUrl, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
is_public_limited_company: profile.is_public_limited_company,
is_in_liquidation: profile.is_in_liquidation,
securities_traded_on_regulated_market:
profile.securities_traded_on_regulated_market,
is_parent_company: profile.is_parent_company,
parent_group_size: profile.is_parent_company ? profile.parent_group_size : null,
prepares_consolidated_accounts: profile.is_parent_company
? profile.prepares_consolidated_accounts
: null,
has_foreign_branch: profile.has_foreign_branch,
has_crypto_assets: profile.has_crypto_assets,
has_share_based_payments: profile.has_share_based_payments,
has_convertible_debt: profile.has_convertible_debt,
building_revenue_share_pct: profile.building_revenue_share_pct,
has_material_deferred_tax: profile.has_material_deferred_tax,
reporting_currency: profile.reporting_currency,
auditor_report_required: profile.auditor_report_required,
auditor_report_included: profile.auditor_report_included,
dividend_prudence_confirmed: profile.dividend_prudence_confirmed,
k2_assessment_confirmed: true,
}),
})
const body = await response.json()
if (!response.ok) throw new Error(getUserErrorMessage(body.error))
const next = body.data as ComplianceResponse
setCompliance(next)
setProfile(next.profile)
toast({ title: t('scope_saved') })
} catch (err) {
toast({
title: t('save_error'),
description: err instanceof Error ? getUserErrorMessage(err) : undefined,
variant: 'destructive',
})
} finally {
setSaving(false)
}
}
const confirmNarrative = async () => {
if (hasUnsavedNarrative) {
toast({ title: t('save_content_first'), variant: 'destructive' })
return
}
setSaving(true)
try {
const response = await fetch(complianceUrl, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ narrative_confirmed: true }),
})
const body = await response.json()
if (!response.ok) throw new Error(getUserErrorMessage(body.error))
const next = body.data as ComplianceResponse
setCompliance(next)
setProfile(next.profile)
toast({ title: t('content_confirmed') })
} catch (err) {
toast({
title: t('save_error'),
description: err instanceof Error ? getUserErrorMessage(err) : undefined,
variant: 'destructive',
})
} finally {
setSaving(false)
}
}
const confirmSignerRoster = async () => {
setSaving(true)
try {
const response = await fetch(complianceUrl, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ signer_roster_confirmed: true }),
})
const body = await response.json()
if (!response.ok) throw new Error(getUserErrorMessage(body.error))
const next = body.data as ComplianceResponse
setCompliance(next)
setProfile(next.profile)
toast({ title: t('signer_roster_confirmed') })
} catch (err) {
toast({
title: t('save_error'),
description: err instanceof Error ? getUserErrorMessage(err) : undefined,
variant: 'destructive',
})
} finally {
setSaving(false)
}
}
const createVersion = async (action: 'snapshot' | 'finalize') => {
if (hasUnsavedNarrative) {
toast({ title: t('save_content_first'), variant: 'destructive' })
return
}
setCreatingVersion(action)
try {
const response = await fetch(versionsUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ action }),
})
const body = await response.json()
if (!response.ok) {
if (body.error?.details?.issues) {
setCompliance((current) =>
current
? { ...current, validation: body.error.details as AnnualReportValidationResult }
: current,
)
}
throw new Error(getUserErrorMessage(body.error))
}
toast({ title: action === 'finalize' ? t('version_locked') : t('snapshot_created') })
await load()
} catch (err) {
toast({
title: action === 'finalize' ? t('lock_error') : t('snapshot_error'),
description: err instanceof Error ? getUserErrorMessage(err) : undefined,
variant: 'destructive',
})
} finally {
setCreatingVersion(null)
}
}
if (loading || !profile || !compliance) {
return (
<div className="flex min-h-24 items-center justify-center px-1 py-6 text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> {t('loading')}
</div>
)
}
return (
<div className="space-y-8">
<div className="space-y-3 px-1">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 className="font-sans text-sm font-medium">{t('title')}</h3>
<p className="mt-1 text-sm text-muted-foreground">{t('description')}</p>
</div>
{blockingIssues.length === 0 ? (
<span className="text-xs text-muted-foreground">{t('no_blockers')}</span>
) : (
<Badge variant="warning">{t('blocker_count', { count: blockingIssues.length })}</Badge>
)}
</div>
{framework === 'k3' && <AttnLine>{t('k3_draft_notice')}</AttnLine>}
<div className="grid gap-2 sm:grid-cols-4">
{[
[
t('step_scope'),
compliance.eligibility.issues.every((issue) => issue.severity !== 'error'),
],
[t('step_content'), Boolean(profile.narrative_confirmed_at)],
[t('step_signatures'), versions.some((version) => version.status === 'signed')],
[t('step_filing'), versions.some((version) => ['filed', 'registered'].includes(version.status))],
].map(([label, complete], index) => (
<div key={String(label)} className="flex items-center gap-2 border-b border-border/60 px-1 py-2 text-sm">
{complete ? (
<CheckCircle2 className="h-4 w-4 shrink-0 text-success" />
) : (
<span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full border border-border text-xs">
{index + 1}
</span>
)}
<span>{label}</span>
</div>
))}
</div>
</div>
<section>
<div className="mb-1 flex items-center gap-2 px-1">
<h3 className="font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">{t('scope_title')}</h3>
<div className="h-px flex-1 bg-border/60" />
</div>
<p className="px-1 text-sm text-muted-foreground">{t('scope_description', { appName })}</p>
<div className="space-y-6 px-1 pt-4">
<div className="grid gap-4 md:grid-cols-2">
<BooleanQuestion
id="ar-public"
label={t('public_company')}
value={profile.is_public_limited_company}
onChange={(value) => updateProfile('is_public_limited_company', value)}
/>
<BooleanQuestion
id="ar-liquidation"
label={t('in_liquidation')}
value={profile.is_in_liquidation}
onChange={(value) => updateProfile('is_in_liquidation', value)}
/>
<BooleanQuestion
id="ar-listed"
label={t('listed_securities')}
value={profile.securities_traded_on_regulated_market}
onChange={(value) => updateProfile('securities_traded_on_regulated_market', value)}
/>
<BooleanQuestion
id="ar-parent"
label={t('parent_company')}
value={profile.is_parent_company}
onChange={(value) => updateProfile('is_parent_company', value)}
/>
<BooleanQuestion
id="ar-audit"
label={t('audit_required')}
value={profile.auditor_report_required}
onChange={(value) => updateProfile('auditor_report_required', value)}
/>
<div className="space-y-2">
<Label htmlFor="ar-reporting-currency">{t('reporting_currency')}</Label>
<Select
value={profile.reporting_currency}
onValueChange={(next) =>
updateProfile(
'reporting_currency',
next as AnnualReportProfile['reporting_currency'],
)
}
>
<SelectTrigger id="ar-reporting-currency">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="SEK">SEK</SelectItem>
<SelectItem value="EUR">EUR</SelectItem>
</SelectContent>
</Select>
</div>
{profile.auditor_report_required && (
<BooleanQuestion
id="ar-auditor-report-included"
label={t('auditor_report_included')}
value={profile.auditor_report_included}
onChange={(value) => updateProfile('auditor_report_included', Boolean(value))}
/>
)}
</div>
{profile.is_parent_company && (
<div className="grid gap-4 border-t border-border pt-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="ar-group-size">{t('group_size')}</Label>
<Select
value={profile.parent_group_size ?? ''}
onValueChange={(next) =>
updateProfile(
'parent_group_size',
next as AnnualReportProfile['parent_group_size'],
)
}
>
<SelectTrigger id="ar-group-size">
<SelectValue placeholder={t('choose')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="small">{t('group_small')}</SelectItem>
<SelectItem value="large">{t('group_large')}</SelectItem>
</SelectContent>
</Select>
</div>
<BooleanQuestion
id="ar-consolidated"
label={t('consolidated_accounts')}
value={profile.prepares_consolidated_accounts}
onChange={(value) => updateProfile('prepares_consolidated_accounts', value)}
/>
</div>
)}
{framework === 'k2' && showNewK2Questions && (
<div className="space-y-4 border-t border-border pt-4">
<p className="text-sm font-medium">{t('k2_2026_title')}</p>
<div className="grid gap-4 md:grid-cols-2">
<BooleanQuestion id="ar-foreign-branch" label={t('foreign_branch')} value={profile.has_foreign_branch} onChange={(value) => updateProfile('has_foreign_branch', value)} />
<BooleanQuestion id="ar-crypto" label={t('crypto_assets')} value={profile.has_crypto_assets} onChange={(value) => updateProfile('has_crypto_assets', value)} />
<BooleanQuestion id="ar-share-payments" label={t('share_payments')} value={profile.has_share_based_payments} onChange={(value) => updateProfile('has_share_based_payments', value)} />
<BooleanQuestion id="ar-convertible" label={t('convertible_debt')} value={profile.has_convertible_debt} onChange={(value) => updateProfile('has_convertible_debt', value)} />
<BooleanQuestion id="ar-deferred-tax" label={t('material_deferred_tax')} value={profile.has_material_deferred_tax} onChange={(value) => updateProfile('has_material_deferred_tax', value)} />
<div className="space-y-2">
<Label htmlFor="ar-building-revenue">{t('building_revenue')}</Label>
<Input
id="ar-building-revenue"
type="number"
min={0}
max={100}
value={profile.building_revenue_share_pct ?? ''}
onChange={(event) =>
updateProfile(
'building_revenue_share_pct',
event.target.value === '' ? null : Number(event.target.value),
)
}
/>
</div>
</div>
</div>
)}
{compliance.report_summary.proposed_dividend > 0 && (
<div className="space-y-3 border-t border-border pt-4">
<BooleanQuestion
id="ar-dividend-prudence"
label={t('dividend_prudence')}
value={profile.dividend_prudence_confirmed}
onChange={(value) => updateProfile('dividend_prudence_confirmed', value)}
/>
<p className="text-xs text-muted-foreground">
{t('dividend_prudence_description', {
dividend: compliance.report_summary.proposed_dividend,
equity: compliance.report_summary.distributable_equity,
})}
</p>
</div>
)}
<div className="flex justify-end">
<Button onClick={() => void saveProfile()} disabled={saving}>
{saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
{t('save_scope')}
</Button>
</div>
</div>
</section>
<section id="ar-fullstandighetskontroll" className="scroll-mt-24">
<div className="mb-1 flex items-center gap-2 px-1">
<h3 className="font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">{t('checks_title')}</h3>
<div className="h-px flex-1 bg-border/60" />
</div>
<div className="space-y-4 px-1 pt-2">
{blockingIssues.length === 0 ? (
<div className="flex items-center gap-2 text-sm text-success">
<CheckCircle2 className="h-4 w-4" /> {t('no_blockers')}
</div>
) : (
<ul className="space-y-3">
{blockingIssues.map((issue) => (
<li key={issue.code} className="flex gap-3 text-sm">
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-warning" />
<div>
<p>{issue.message}</p>
{issue.remediation && <p className="mt-1 text-xs text-muted-foreground">{issue.remediation}</p>}
</div>
</li>
))}
</ul>
)}
{digitalOnlyIssues.length > 0 && (
<div className="space-y-2">
<p className="text-[12.5px] font-medium leading-5 text-attn">{t('digital_checks_title')}</p>
<ul className="space-y-2">
{digitalOnlyIssues.map((issue) => (
<li key={issue.code} className="text-sm text-muted-foreground">
{issue.message}
</li>
))}
</ul>
</div>
)}
<div className="flex flex-wrap justify-end gap-3 border-t border-border/60 pt-4">
<Button
variant="outline"
onClick={() => void confirmSignerRoster()}
disabled={saving || Boolean(profile.signer_roster_confirmed_at)}
>
<CheckCircle2 className="mr-2 h-4 w-4" />
{profile.signer_roster_confirmed_at
? t('signer_roster_confirmed')
: t('confirm_signer_roster')}
</Button>
<Button
variant="outline"
onClick={() => void confirmNarrative()}
disabled={saving || hasUnsavedNarrative || Boolean(profile.narrative_confirmed_at)}
>
<CheckCircle2 className="mr-2 h-4 w-4" />
{profile.narrative_confirmed_at ? t('content_confirmed') : t('confirm_content')}
</Button>
<Button variant="outline" onClick={() => void createVersion('snapshot')} disabled={creatingVersion !== null}>
{creatingVersion === 'snapshot' ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <FileClock className="mr-2 h-4 w-4" />}
{t('create_snapshot')}
</Button>
<Button onClick={() => void createVersion('finalize')} disabled={creatingVersion !== null || blockingIssues.length > 0 || hasUnsavedNarrative}>
{creatingVersion === 'finalize' ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <LockKeyhole className="mr-2 h-4 w-4" />}
{t('lock_version')}
</Button>
</div>
{(blockingIssues.length > 0 || hasUnsavedNarrative) && (
<p className="text-right text-xs leading-5 text-muted-foreground">
{hasUnsavedNarrative
? t('lock_hint_unsaved')
: t('lock_hint_blocked', { count: blockingIssues.length })}
</p>
)}
</div>
</section>
<section>
<div className="mb-1 flex items-center gap-2 px-1">
<h3 className="font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">{t('versions_title')}</h3>
<div className="h-px flex-1 bg-border/60" />
</div>
<div className="px-1 pt-2">
{versions.length === 0 ? (
<p className="text-sm text-muted-foreground">{t('versions_empty')}</p>
) : (
<div className="divide-y divide-border">
{versions.map((version) => (
<div key={version.id} className="flex min-h-14 flex-wrap items-center justify-between gap-3 py-3 text-sm">
<div>
<p className="font-medium">{t('version_label', { number: version.version_number })}</p>
<p className="text-xs text-muted-foreground">{version.content_hash.slice(0, 12)}</p>
</div>
<div className="flex items-center gap-2">
<Badge variant={version.status === 'registered' ? 'success' : version.status === 'draft' ? 'outline' : 'secondary'}>
{t(`status_${version.status}`)}
</Badge>
<Button variant="outline" size="sm" asChild>
<a href={`/api/bookkeeping/fiscal-periods/${periodId}/arsredovisning/pdf?version=${version.id}`} target="_blank" rel="noopener noreferrer">
{t('open_pdf')}
</a>
</Button>
</div>
</div>
))}
</div>
)}
</div>
</section>
</div>
)
}
-900
View File
@@ -1,900 +0,0 @@
'use client'
/**
* Digital inlämning av årsredovisning (iXBRL → Bolagsverket).
*
* Three steps below the year-end ÅR editors:
* 1. Granska: the generated iXBRL rendered in an iframe (the XHTML *is*
* the filed presentation) + pre-flight validation results + download
* for technical inspection and support diagnostics.
* 2. Skicka in: only when the bolagsverket extension responds: avtalstext
* acceptance → kontrollera-utfall → upload till eget utrymme → kvittens
* with "signera hos Bolagsverket"-link. The fastställelseintyg is signed
* with e-legitimation at Bolagsverket, never here.
* 3. Status: submission history driven by webhooks + polling fallback.
*
* Year-end surface: copy stays Swedish in both locales (see i18n rules).
*/
import { useCallback, useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useToast } from '@/components/ui/use-toast'
import { formatDate } from '@/lib/utils'
import {
ExternalLink,
FileDown,
Loader2,
RefreshCcw,
SearchCheck,
Send,
ShieldCheck,
} from 'lucide-react'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { CONNECTED_FILING_PUBLIC_RELEASED } from '@/lib/bokslut/arsredovisning/capabilities'
import type { AnnualReportVersionSummary } from '@/lib/bokslut/arsredovisning/compliance-types'
/** Inlämningen till Bolagsverket väntar på avtal + organisationscertifikat
* (M0). Tills dess visas hela digital inlämning-sektionen blurrad med en
* "Kommer snart"-skylt: endast PDF-nedladdningen på ÅR-sidan är användbar.
* Flippa till false när integrationen är godkänd. Importeras också av
* ÅR-sidan som blurrar sina Bolagsverket-delar med samma flagga. */
export const INLAMNING_COMING_SOON = !CONNECTED_FILING_PUBLIC_RELEASED
interface PreflightIssue {
code: string
severity: 'error' | 'warn'
message: string
}
interface ValidateResponse {
ok: boolean
issues: PreflightIssue[]
error_count: number
warning_count: number
generated_bytes: number
entry_point: string
}
interface KontrolleraUtfall {
kod: string
text: string
typ: string
}
interface SubmissionRow {
id: string
status: string
environment: string
kontrollsumma: string | null
sha256_checksumma: string | null
bolagsverket_url: string | null
undertecknare_namn: string | null
kontrollera_utfall: KontrolleraUtfall[] | null
error_message: string | null
uploaded_at: string | null
registered_at: string | null
created_at: string
annual_report_version_id: string | null
archive_status: 'pending' | 'stored' | 'failed'
}
interface RegistryInformation {
namn: string
status: Array<{ kod?: string; text?: string }>
rakenskapsperioder: Array<{
from: string
tom: string
kravPaRevisionsberattelse: 'ja' | 'nej' | 'uppgift_saknas'
revisorsplikt: 'ja' | 'nej' | 'uppgift_saknas'
}>
}
interface RegistryCaseStatus {
typ: string
arendenummer: string | null
rakenskapsperiod: { from: string; tom: string } | null
}
type SubmitOutcome =
| { outcome: 'avtal_required'; avtalstext: string; avtalstextAndrad: string }
| { outcome: 'preflight_failed'; issues: PreflightIssue[] }
| { outcome: 'kontrollera_stopped'; submissionId: string; utfall: KontrolleraUtfall[] }
| { outcome: 'uploaded'; submissionId: string; url: string; utfall: KontrolleraUtfall[] }
| { outcome: 'state_unknown'; submissionId: string; url: string | null; message: string }
/**
* Normalize a Swedish personnummer to the 12-digit ÅÅÅÅMMDDNNNN form the
* Bolagsverket token API requires. 10-digit input gets its century inferred:
* a 2-digit year greater than the current year's last two digits → 19xx,
* otherwise 20xx; the '+' separator (person 100+ years) shifts one more
* century back. Returns null when the input is neither 10 nor 12 digits.
*/
function normalizePnr(raw: string): string | null {
const trimmed = raw.trim()
const digits = trimmed.replace(/\D/g, '')
if (digits.length === 12) return digits
if (digits.length !== 10) return null
const now = new Date()
const currentCentury = Math.floor(now.getFullYear() / 100)
const currentYy = now.getFullYear() % 100
const yy = Number(digits.slice(0, 2))
let century = yy > currentYy ? currentCentury - 1 : currentCentury
if (trimmed.includes('+')) century -= 1
return `${century}${digits}`
}
const STATUS_BADGES: Record<string, { label: string; variant: 'default' | 'secondary' | 'success' | 'warning' | 'destructive' | 'outline' }> = {
draft: { label: 'Utkast', variant: 'outline' },
kontrollerad: { label: 'Kontrollerad', variant: 'secondary' },
sending: { label: 'Skickar: avvakta', variant: 'warning' },
uploaded: { label: 'Uppladdad: väntar på signering', variant: 'warning' },
unknown: { label: 'Okänd extern status: skicka inte igen', variant: 'destructive' },
inkommen: { label: 'Inkommen till Bolagsverket', variant: 'secondary' },
forelagd: { label: 'Föreläggande: åtgärd krävs', variant: 'destructive' },
komplettering: { label: 'Komplettering inlämnad', variant: 'secondary' },
registrerad: { label: 'Registrerad', variant: 'success' },
avslutad: { label: 'Avslutad utan registrering', variant: 'destructive' },
error: { label: 'Fel', variant: 'destructive' },
}
export function DigitalInlamning({ periodId }: { periodId: string }) {
const { toast } = useToast()
const tStudio = useTranslations('annualReportStudio')
const ixbrlUrl = `/api/bookkeeping/fiscal-periods/${periodId}/arsredovisning/ixbrl`
const [showPreview, setShowPreview] = useState(false)
const [validating, setValidating] = useState(false)
const [validation, setValidation] = useState<ValidateResponse | null>(null)
// Extension availability: probe the status route; 404 = not enabled.
const [extensionActive, setExtensionActive] = useState<boolean | null>(null)
const [filingEnabled, setFilingEnabled] = useState(false)
const [environment, setEnvironment] = useState<string>('test')
// Submission form
const [avsandarePnr, setAvsandarePnr] = useState('')
const [pnr, setPnr] = useState('')
const [fornamn, setFornamn] = useState('')
const [efternamn, setEfternamn] = useState('')
const [roll, setRoll] = useState('Styrelseledamot')
const [epost, setEpost] = useState('')
const [submitting, setSubmitting] = useState(false)
const [avtal, setAvtal] = useState<{ text: string; andrad: string; accepted: boolean } | null>(null)
const [utfall, setUtfall] = useState<KontrolleraUtfall[] | null>(null)
const [kvittens, setKvittens] = useState<{ url: string } | null>(null)
const [versions, setVersions] = useState<AnnualReportVersionSummary[]>([])
const [selectedVersionId, setSelectedVersionId] = useState('')
const [registryInformation, setRegistryInformation] = useState<RegistryInformation | null>(null)
const [registryCase, setRegistryCase] = useState<RegistryCaseStatus | null>(null)
const versionQuery = selectedVersionId
? `version=${encodeURIComponent(selectedVersionId)}`
: ''
const previewUrl = versionQuery ? `${ixbrlUrl}?${versionQuery}` : ixbrlUrl
const downloadUrl = `${ixbrlUrl}?download=1${versionQuery ? `&${versionQuery}` : ''}`
const [submissions, setSubmissions] = useState<SubmissionRow[]>([])
const [loadingSubmissions, setLoadingSubmissions] = useState(false)
const [submissionsError, setSubmissionsError] = useState<string | null>(null)
const [pollingEvents, setPollingEvents] = useState(false)
useEffect(() => {
const signer = versions.find((version) => version.id === selectedVersionId)
?.certificate_signer
if (!signer) return
setFornamn(signer.first_name)
setEfternamn(signer.last_name)
setRoll(signer.role)
}, [selectedVersionId, versions])
const loadSubmissions = useCallback(async () => {
setLoadingSubmissions(true)
try {
const res = await fetch(
`/api/extensions/ext/bolagsverket/submissions?fiscal_period_id=${periodId}`,
)
if (res.ok) {
const body = await res.json()
setSubmissions((body.data ?? []) as SubmissionRow[])
setSubmissionsError(null)
} else {
setSubmissionsError('Kunde inte hämta inlämningshistoriken: försök igen.')
}
} catch {
// Non-blocking: the call sites fire-and-forget (`void loadSubmissions()`),
// so a network failure must surface here instead of as an unhandled
// rejection.
setSubmissionsError('Kunde inte hämta inlämningshistoriken: försök igen.')
} finally {
setLoadingSubmissions(false)
}
}, [periodId])
const loadVersions = useCallback(async () => {
try {
const res = await fetch(
`/api/bookkeeping/fiscal-periods/${periodId}/arsredovisning/versions`,
)
if (!res.ok) return
const body = await res.json()
const rows = (body.data ?? []) as AnnualReportVersionSummary[]
setVersions(rows)
const latestSigned = rows.find(
(version) => version.status === 'signed' && version.digital_filing_eligible,
)
if (latestSigned) setSelectedVersionId((current) => current || latestSigned.id)
} catch {
// The version list is also visible in the studio. Submission stays
// disabled here until a signed version can be selected.
}
}, [periodId])
useEffect(() => {
let cancelled = false
fetch('/api/extensions/ext/bolagsverket/status')
.then(async (res) => {
if (cancelled) return
if (!res.ok) {
setExtensionActive(false)
return
}
const body = await res.json()
setExtensionActive(true)
setFilingEnabled(body.data?.filing_enabled === true)
setEnvironment(body.data?.environment ?? 'test')
void loadSubmissions()
void Promise.all([
fetch('/api/extensions/ext/bolagsverket/grunduppgifter'),
fetch('/api/extensions/ext/bolagsverket/arendestatus'),
])
.then(async ([informationResponse, caseResponse]) => {
if (informationResponse.ok) {
const informationBody = await informationResponse.json()
if (!cancelled) setRegistryInformation(informationBody.data as RegistryInformation)
}
if (caseResponse.ok) {
const caseBody = await caseResponse.json()
if (!cancelled) setRegistryCase(caseBody.data as RegistryCaseStatus)
}
})
.catch(() => undefined)
})
.catch(() => {
if (!cancelled) setExtensionActive(false)
})
void loadVersions()
return () => {
cancelled = true
}
}, [loadSubmissions, loadVersions])
const handleValidate = async () => {
setValidating(true)
try {
const res = await fetch(
`${ixbrlUrl}/validate${versionQuery ? `?${versionQuery}` : ''}`,
)
const body = await res.json()
if (body?.error) {
toast({ title: 'Kunde inte validera', description: getUserErrorMessage(body.error), variant: 'destructive' })
return
}
setValidation(body.data as ValidateResponse)
} catch {
toast({ title: 'Kunde inte validera', variant: 'destructive' })
} finally {
setValidating(false)
}
}
const handleSubmit = async (opts: { ignoreWarnings?: boolean } = {}) => {
// The Bolagsverket token API needs 12 digits (ÅÅÅÅMMDDNNNN); 10-digit
// input is normalized client-side with a century pivot.
const normalizedAvsandare = normalizePnr(avsandarePnr)
const normalizedPnr = normalizePnr(pnr)
if (!normalizedAvsandare || !normalizedPnr) {
toast({ title: 'Ange personnummer med 10 eller 12 siffror', variant: 'destructive' })
return
}
if (!fornamn.trim() || !efternamn.trim() || !epost.trim()) {
toast({ title: 'Fyll i undertecknarens namn och e-post', variant: 'destructive' })
return
}
if (!selectedVersionId) {
toast({ title: 'Lås och underteckna en version före inlämning', variant: 'destructive' })
return
}
setSubmitting(true)
setUtfall(null)
try {
const res = await fetch('/api/extensions/ext/bolagsverket/submissions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
fiscal_period_id: periodId,
annual_report_version_id: selectedVersionId,
avsandare_pnr: normalizedAvsandare,
undertecknare: {
pnr: normalizedPnr,
fornamn: fornamn.trim(),
efternamn: efternamn.trim(),
roll,
epost: epost.trim(),
},
...(avtal?.accepted ? { accepted_avtalstext_andrad: avtal.andrad } : {}),
...(opts.ignoreWarnings ? { ignore_warnings: true } : {}),
}),
})
const body = await res.json()
if (body?.error) {
toast({ title: 'Inlämningen misslyckades', description: getUserErrorMessage(body.error), variant: 'destructive' })
return
}
const result = body.data as SubmitOutcome
if (result.outcome === 'avtal_required') {
setAvtal({ text: result.avtalstext, andrad: result.avtalstextAndrad, accepted: false })
return
}
if (result.outcome === 'preflight_failed') {
setValidation({
ok: false,
issues: result.issues,
error_count: result.issues.filter((issue) => issue.severity === 'error').length,
warning_count: result.issues.filter((issue) => issue.severity === 'warn').length,
generated_bytes: 0,
entry_point: '',
})
toast({
title: 'Årsredovisningen är inte komplett',
description: 'Åtgärda punkterna under Granska & validera och försök igen.',
variant: 'destructive',
})
return
}
if (result.outcome === 'kontrollera_stopped') {
setUtfall(result.utfall)
void loadSubmissions()
return
}
if (result.outcome === 'state_unknown') {
setKvittens(result.url ? { url: result.url } : null)
void loadSubmissions()
toast({
title: 'Okänd status hos Bolagsverket',
description: result.message,
variant: 'destructive',
})
return
}
setKvittens({ url: result.url })
setUtfall(result.utfall.length > 0 ? result.utfall : null)
setAvtal(null)
void loadSubmissions()
toast({ title: 'Uppladdad till Bolagsverkets eget utrymme' })
} catch {
toast({ title: 'Inlämningen misslyckades', variant: 'destructive' })
} finally {
setSubmitting(false)
}
}
const handlePollEvents = async () => {
setPollingEvents(true)
try {
const res = await fetch('/api/extensions/ext/bolagsverket/poll-events', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
})
const body = await res.json()
if (body?.error) {
toast({ title: 'Kunde inte hämta händelser', description: getUserErrorMessage(body.error), variant: 'destructive' })
return
}
void loadSubmissions()
toast({ title: 'Status uppdaterad från Bolagsverket' })
} catch {
toast({ title: 'Kunde inte hämta händelser', variant: 'destructive' })
} finally {
setPollingEvents(false)
}
}
const blockingErrors = validation !== null && validation.error_count > 0
const utfallHasErrors = (utfall ?? []).some((item) => item.typ?.toLowerCase() === 'error')
return (
<div className="relative">
<div
inert={INLAMNING_COMING_SOON}
aria-hidden={INLAMNING_COMING_SOON}
className={
INLAMNING_COMING_SOON
? 'pointer-events-none select-none blur-[3px] opacity-60 space-y-8'
: 'space-y-8'
}
>
{/* Steg: Granska & validera */}
<section>
<div className="mb-1 flex items-center gap-2 px-1">
<h3 className="font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">Digital inlämning: granska &amp; validera (iXBRL)</h3>
<div className="h-px flex-1 bg-border/60" />
</div>
<p className="px-1 text-sm text-muted-foreground">
Bolagsverket tar emot årsredovisningen som iXBRL (XHTML). Dokumentet nedan är
exakt det som lämnas in: granska det som den slutliga presentationen.
</p>
<div className="space-y-4 px-1 pt-4 text-sm">
<div className="flex flex-wrap gap-3">
<Button variant="outline" onClick={() => setShowPreview((value) => !value)}>
{showPreview ? 'Dölj förhandsgranskning' : 'Förhandsgranska iXBRL'}
</Button>
<Button variant="outline" asChild>
<a href={downloadUrl}>
<FileDown className="mr-2 h-4 w-4" /> Ladda ner tekniskt iXBRL-underlag
</a>
</Button>
<Button onClick={() => void handleValidate()} disabled={validating}>
{validating ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<SearchCheck className="mr-2 h-4 w-4" />
)}
Validera
</Button>
</div>
{showPreview && (
<iframe
src={previewUrl}
title="Förhandsgranskning av årsredovisning (iXBRL)"
className="w-full h-[640px] rounded-lg border border-border bg-white"
/>
)}
{validation && (
<div className="space-y-2">
<div className="flex items-center gap-2">
{validation.ok ? (
<Badge variant="success">Klar för inlämning</Badge>
) : (
<Badge variant="destructive">{validation.error_count} fel</Badge>
)}
{validation.warning_count > 0 && (
<Badge variant="warning">{validation.warning_count} varningar</Badge>
)}
</div>
{validation.issues.length > 0 && (
<ul className="space-y-1.5">
{validation.issues.map((issue, index) => (
<li key={`${issue.code}-${index}`} className="flex gap-2 items-start">
<Badge
variant={issue.severity === 'error' ? 'destructive' : 'warning'}
className="mt-0.5 shrink-0"
>
{issue.code}
</Badge>
<span className="text-muted-foreground">{issue.message}</span>
</li>
))}
</ul>
)}
</div>
)}
</div>
</section>
{/* Steg: Skicka in */}
<section>
<div className="mb-1 flex items-center gap-2 px-1">
<h3 className="font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">Skicka in till Bolagsverket</h3>
<div className="h-px flex-1 bg-border/60" />
</div>
<p className="px-1 text-sm text-muted-foreground">
Årsredovisningen laddas upp till företagets eget utrymme hos Bolagsverket.
Undertecknaren får ett e-postmeddelande och signerar fastställelseintyget med
e-legitimation hos Bolagsverket: först då är årsredovisningen inlämnad.
</p>
<div className="space-y-4 px-1 pt-4 text-sm">
{extensionActive === null && (
<p className="text-muted-foreground">
<Loader2 className="inline h-4 w-4 animate-spin mr-2" />
Kontrollerar anslutningen till Bolagsverket …
</p>
)}
{extensionActive === false && (
<div className="space-y-3">
<p className="text-muted-foreground">
Bolagsverket-integrationen är inte aktiverad i den här installationen.
Digital inlämning kräver en ansluten programvara. Använd PDF-flödet för
pappersinlämning per post, eller aktivera integrationen efter avtal,
organisationscertifikat och godkänt acceptanstest.
</p>
<Button variant="outline" asChild>
<a
href="https://bolagsverket.se/foretag/aktiebolag/arsredovisningforaktiebolag.759.html"
target="_blank"
rel="noopener noreferrer"
>
<ExternalLink className="mr-2 h-4 w-4" /> Lämna in hos Bolagsverket
</a>
</Button>
</div>
)}
{extensionActive === true && !filingEnabled && (
<p className="text-muted-foreground">
Anslutningen finns installerad men säkerhetsgrinden för inlämning är stängd.
Den öppnas först efter genomförd acceptanstest och produktionsgodkännande.
</p>
)}
{extensionActive === true && filingEnabled && (
<>
{environment !== 'prod' && (
<Badge variant="warning">
{environment === 'test' ? 'Testmiljö (statiskt testdata)' : 'Acceptansmiljö'}
</Badge>
)}
<div className="space-y-1.5">
<Label htmlFor="di-version">Undertecknad årsredovisningsversion</Label>
<Select
value={selectedVersionId}
onValueChange={(versionId) => {
setSelectedVersionId(versionId)
const signer = versions.find((version) => version.id === versionId)
?.certificate_signer
if (signer) {
setFornamn(signer.first_name)
setEfternamn(signer.last_name)
setRoll(signer.role)
}
}}
>
<SelectTrigger id="di-version">
<SelectValue placeholder="Välj undertecknad version" />
</SelectTrigger>
<SelectContent>
{versions
.filter(
(version) =>
version.status === 'signed' && version.digital_filing_eligible,
)
.map((version) => (
<SelectItem key={version.id} value={version.id}>
Version {version.version_number}: skapad {formatDate(version.created_at)}
</SelectItem>
))}
</SelectContent>
</Select>
{versions.every(
(version) =>
version.status !== 'signed' || !version.digital_filing_eligible,
) && (
<p className="text-xs text-muted-foreground">
{tStudio('no_digital_version')}
</p>
)}
{selectedVersionId && (
<p className="text-xs text-muted-foreground">
Namn och roll för fastställelseintyget kommer från den låsta versionen och
måste vara oförändrade vid inlämning.
</p>
)}
</div>
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-1.5">
<Label htmlFor="di-avsandare-pnr">Ditt personnummer (avsändare)</Label>
<Input
id="di-avsandare-pnr"
inputMode="numeric"
placeholder="ÅÅÅÅMMDDNNNN eller ÅÅMMDD-NNNN"
value={avsandarePnr}
onChange={(event) => setAvsandarePnr(event.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="di-pnr">Undertecknarens personnummer</Label>
<Input
id="di-pnr"
inputMode="numeric"
placeholder="ÅÅÅÅMMDDNNNN eller ÅÅMMDD-NNNN"
value={pnr}
onChange={(event) => setPnr(event.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="di-fornamn">Undertecknarens förnamn</Label>
<Input
id="di-fornamn"
value={fornamn}
onChange={(event) => setFornamn(event.target.value)}
readOnly={Boolean(selectedVersionId)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="di-efternamn">Undertecknarens efternamn</Label>
<Input
id="di-efternamn"
value={efternamn}
onChange={(event) => setEfternamn(event.target.value)}
readOnly={Boolean(selectedVersionId)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="di-roll">Roll</Label>
<Select
value={roll}
onValueChange={setRoll}
disabled={Boolean(selectedVersionId)}
>
<SelectTrigger id="di-roll">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="Styrelseledamot">Styrelseledamot</SelectItem>
<SelectItem value="Styrelseordförande">Styrelseordförande</SelectItem>
<SelectItem value="Verkställande direktör">Verkställande direktör</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="di-epost">Undertecknarens e-post</Label>
<Input
id="di-epost"
type="email"
placeholder="namn@foretag.se"
value={epost}
onChange={(event) => setEpost(event.target.value)}
/>
</div>
</div>
<p className="text-xs text-muted-foreground">
Personnumren skickas till Bolagsverket för att skapa eget utrymme och bjuda
in undertecknaren. De sparas inte i Accounted och skrivs inte till loggar.
</p>
{registryInformation && (
<div className="border-t border-border/60 pt-3 text-xs">
<p className="font-medium">Grunduppgifter från Bolagsverket</p>
<p className="mt-1 text-muted-foreground">
{registryInformation.namn}
{registryInformation.status[0]?.text
? `: ${registryInformation.status[0].text}`
: ''}
</p>
{registryInformation.rakenskapsperioder[0] && (
<p className="mt-1 text-muted-foreground">
Senaste period: {registryInformation.rakenskapsperioder[0].from} till{' '}
{registryInformation.rakenskapsperioder[0].tom}. Krav på
revisionsberättelse:{' '}
{registryInformation.rakenskapsperioder[0].kravPaRevisionsberattelse}.
</p>
)}
{registryCase && (
<p className="mt-1 text-muted-foreground">
Senaste ärendestatus: {registryCase.typ}
{registryCase.arendenummer ? `, ärende ${registryCase.arendenummer}` : ''}.
</p>
)}
</div>
)}
{avtal && (
<div className="space-y-3 border-y border-border/60 py-4">
<p className="font-medium">Villkor för eget utrymme hos Bolagsverket</p>
<p className="text-muted-foreground whitespace-pre-wrap text-xs max-h-48 overflow-y-auto">
{avtal.text}
</p>
<label className="flex cursor-pointer items-start gap-3 text-sm">
<input
type="checkbox"
className="mt-0.5"
checked={avtal.accepted}
onChange={(event) =>
setAvtal({ ...avtal, accepted: event.target.checked })
}
/>
<span>
Jag har tagit del av villkoren och är behörig att företräda företaget.
</span>
</label>
</div>
)}
{utfall && utfall.length > 0 && (
<div className="space-y-2">
<p className="font-medium">Bolagsverkets kontroll hittade följande:</p>
<ul className="space-y-1.5">
{utfall.map((item, index) => (
<li key={`${item.kod}-${index}`} className="flex gap-2 items-start">
<Badge
variant={item.typ?.toLowerCase() === 'error' ? 'destructive' : 'warning'}
className="mt-0.5 shrink-0"
>
{item.kod}
</Badge>
<span className="text-muted-foreground">{item.text}</span>
</li>
))}
</ul>
{!utfallHasErrors && (
<p className="text-xs text-muted-foreground">
Varningarna hindrar inte inlämning, men minskar risken för
föreläggande om de åtgärdas.
</p>
)}
</div>
)}
<div className="flex flex-wrap gap-3">
<Button
onClick={() => void handleSubmit()}
disabled={
submitting ||
blockingErrors ||
!selectedVersionId ||
(avtal !== null && !avtal.accepted)
}
>
{submitting ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Send className="mr-2 h-4 w-4" />
)}
{avtal ? 'Godkänn villkoren och skicka in' : 'Kontrollera och skicka in'}
</Button>
{utfall && utfall.length > 0 && !utfallHasErrors && (
<Button
variant="outline"
onClick={() => void handleSubmit({ ignoreWarnings: true })}
disabled={submitting}
>
Skicka in trots varningar
</Button>
)}
</div>
{kvittens && (
<div className="space-y-2 border-t border-border/60 pt-4">
<div className="flex items-center gap-2">
<ShieldCheck className="h-4 w-4 text-success" />
<p className="font-medium">Uppladdad till eget utrymme</p>
</div>
<p className="text-muted-foreground text-xs">
Undertecknaren har fått e-post från Bolagsverket och signerar
fastställelseintyget där. Ärendet startar först efter signering.
</p>
<Button variant="outline" size="sm" asChild>
<a href={kvittens.url} target="_blank" rel="noopener noreferrer">
<ExternalLink className="mr-2 h-4 w-4" /> Signera hos Bolagsverket
</a>
</Button>
</div>
)}
</>
)}
</div>
</section>
{/* Steg: Status */}
{extensionActive === true && (
<section>
<div className="mb-1 flex items-center gap-2 px-1">
<h3 className="font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">Inlämningsstatus</h3>
<div className="h-px flex-1 bg-border/60" />
</div>
<p className="px-1 text-sm text-muted-foreground">
Status uppdateras automatiskt via händelseaviseringar från Bolagsverket.
</p>
<div className="space-y-4 px-1 pt-4 text-sm">
<div className="flex justify-end">
<Button
variant="outline"
size="sm"
disabled={pollingEvents}
onClick={() => void handlePollEvents()}
>
{pollingEvents ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<RefreshCcw className="mr-2 h-4 w-4" />
)}
{pollingEvents ? 'Uppdaterar …' : 'Uppdatera status'}
</Button>
</div>
{submissionsError && <p className="text-xs text-destructive">{submissionsError}</p>}
{loadingSubmissions && submissions.length === 0 && (
<p className="text-muted-foreground">
<Loader2 className="inline h-4 w-4 animate-spin mr-2" /> Hämtar …
</p>
)}
{!loadingSubmissions && submissions.length === 0 && !submissionsError && (
<p className="text-muted-foreground italic">Inga inlämningar ännu.</p>
)}
{submissions.map((submission) => {
const badge = STATUS_BADGES[submission.status] ?? {
label: submission.status,
variant: 'outline' as const,
}
const envLabel =
submission.environment === 'prod'
? ''
: submission.environment === 'test'
? 'Testmiljö'
: submission.environment === 'acceptans'
? 'Acceptansmiljö'
: submission.environment.charAt(0).toUpperCase() +
submission.environment.slice(1)
return (
<div
key={submission.id}
className="flex flex-col gap-3 border-b border-border pb-3 last:border-b-0 last:pb-0 sm:flex-row sm:items-start sm:justify-between"
>
<div className="space-y-1">
<Badge variant={badge.variant}>{badge.label}</Badge>
<p className="text-xs text-muted-foreground tabular-nums">
{envLabel ? `${envLabel} · ` : ''}
{formatDate(submission.created_at)}
{submission.undertecknare_namn ? ` · ${submission.undertecknare_namn}` : ''}
</p>
{submission.status === 'forelagd' && (
<p className="text-xs text-destructive">
Bolagsverket har skickat ett föreläggande: läs brevet, åtgärda
bristerna och lämna in en komplettering (ny inlämning ovan).
</p>
)}
{submission.error_message && (
<p className="text-xs text-destructive">{submission.error_message}</p>
)}
</div>
{submission.bolagsverket_url && submission.status === 'uploaded' && (
<Button variant="outline" size="sm" asChild>
<a href={submission.bolagsverket_url} target="_blank" rel="noopener noreferrer">
<ExternalLink className="mr-1 h-3.5 w-3.5" /> Signera
</a>
</Button>
)}
</div>
)
})}
</div>
</section>
)}
</div>
{INLAMNING_COMING_SOON && (
<div className="absolute inset-0 z-10 flex items-center justify-center">
<div className="rounded-lg border border-border bg-background px-8 py-6 text-center">
<p className="font-display text-2xl">Kommer snart</p>
<p className="mt-2 max-w-xs text-sm text-muted-foreground">
Digital inlämning till Bolagsverket öppnar så snart integrationen
är godkänd. Tills dess: ladda ner PDF-utkastet ovan.
</p>
</div>
</div>
)}
</div>
)
}
-518
View File
@@ -1,518 +0,0 @@
'use client'
import { useState, useRef, useEffect, useLayoutEffect, useMemo, useCallback, useId } from 'react'
import { createPortal } from 'react-dom'
import { Plus } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import { getAccountClassName } from '@/lib/bookkeeping/account-descriptions'
import {
buildAccountIndex,
searchAccounts,
type SearchableAccount,
type AccountSearchItem,
} from '@/lib/bookkeeping/account-search'
import {
computeDropdownPosition,
isSameDropdownPosition,
type DropdownPosition,
} from '@/components/bookkeeping/account-combobox-position'
import type { BASAccount } from '@/types'
// Shared by every portaled panel instance: only stops propagation so the
// browser's default scrolling still runs on the panel itself.
function stopScrollPropagation(e: Event) {
e.stopPropagation()
}
interface AccountComboboxProps {
value: string
accounts: BASAccount[]
onChange: (accountNumber: string) => void
// Fired when the user definitively commits an account: selecting from the
// dropdown (Enter or click) or typing a full 4-digit number. Distinct from
// onChange, which also fires on intermediate edits. Callers use this to
// auto-advance focus (e.g. to the amount field).
onCommit?: (accountNumber: string) => void
// When provided, an inline "Skapa nytt konto" affordance appears in the
// dropdown's empty state. The current search string is passed so the caller
// can prefill the create dialog.
onCreateAccount?: (prefill: string) => void
// The full BAS catalogue. When provided, accounts not yet in `accounts`
// (the company's active chart) become searchable by name and are surfaced
// with the `notActivatedLabel` marker; picking one activates it at commit
// via the existing ACCOUNTS_NOT_IN_CHART rail.
catalog?: SearchableAccount[]
// Label shown next to catalogue-only (not-yet-activated) accounts. Defaults
// to Swedish; bilingual hosts pass a localized string.
notActivatedLabel?: string
// Extra classes merged into the trigger Input: callers pass `h-8` for dense
// table rows, omit it to use the default Input height.
className?: string
// Optional callback ref to the underlying <input>, invoked alongside the
// internal one. Lets a parent imperatively focus the field (e.g. auto-advance
// to the next konteringsrad's account on Enter: see JournalEntryForm.focusAccount).
inputRef?: React.RefCallback<HTMLInputElement>
disabled?: boolean
// Optional always-visible label for compact editors where the selected
// account name must remain readable after the dropdown closes.
selectedName?: string
// Renders the trigger in the flat row language (SettingsRows): no box, a
// dashed underline on hover, solid on focus. For hosts that compose
// SettingsRow, where a bordered Input would be the only box in the form.
// The dropdown also narrows to the row's width so it cannot overflow a
// dialog. Default (false) keeps the boxed Input every existing caller uses.
flat?: boolean
}
export default function AccountCombobox({ value, accounts, onChange, onCommit, onCreateAccount, catalog, notActivatedLabel = 'Aktiveras vid bokföring', className, inputRef, disabled = false, selectedName, flat = false }: AccountComboboxProps) {
const [search, setSearch] = useState(value)
const [isOpen, setIsOpen] = useState(false)
const [highlightedIndex, setHighlightedIndex] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const internalInputRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLDivElement | null>(null)
// The portaled (non-flat) dropdown panel. It is not a DOM descendant of
// containerRef, so outside-click detection must check it separately.
const portalPanelRef = useRef<HTMLDivElement | null>(null)
const [dropdownPos, setDropdownPos] = useState<DropdownPosition | null>(null)
const selectedNameId = useId()
// Whether the user has typed or arrow-navigated since the field was focused.
// Enter only selects the highlighted item after an actual interaction: a
// bare Enter on a freshly-focused field must not grab the first account in
// the list (it either re-commits the current value or bubbles to the form).
const hasInteractedRef = useRef(false)
// Attach the internal ref (used for focus bookkeeping) and forward the element
// to any external callback ref the parent passed.
const setInputRef = useCallback((el: HTMLInputElement | null) => {
internalInputRef.current = el
inputRef?.(el)
}, [inputRef])
// Sync external value changes into the search field
useEffect(() => {
setSearch(value)
}, [value])
// Index the active chart + the full BAS catalogue once per source change.
// Searching it per keystroke is then just substring checks over pre-folded
// haystacks (number + name + description, diacritics stripped).
const accountIndex = useMemo(
() => buildAccountIndex({ active: accounts, catalog }),
[accounts, catalog]
)
const filteredAccounts = useMemo(
() => searchAccounts(accountIndex, search),
[accountIndex, search]
)
// Group filtered accounts by class
const groupedAccounts = useMemo(() => {
const groups: { className: string; accounts: AccountSearchItem[] }[] = []
const groupMap = new Map<string, AccountSearchItem[]>()
for (const account of filteredAccounts) {
const className = getAccountClassName(account.account_class)
if (!groupMap.has(className)) {
groupMap.set(className, [])
}
groupMap.get(className)!.push(account)
}
for (const [className, accts] of groupMap) {
groups.push({ className, accounts: accts })
}
return groups
}, [filteredAccounts])
// Flat list for keyboard navigation
const flatList = useMemo(() => filteredAccounts, [filteredAccounts])
// Reset highlight when filtered results change
useEffect(() => {
setHighlightedIndex(0)
}, [filteredAccounts])
// Scroll highlighted item into view
useEffect(() => {
if (!isOpen || !listRef.current) return
const highlighted = listRef.current.querySelector('[data-highlighted="true"]')
if (highlighted) {
highlighted.scrollIntoView({ block: 'nearest' })
}
}, [highlightedIndex, isOpen])
// Keep the portaled (non-flat) dropdown glued to the trigger: measure off
// containerRef when it opens, and re-measure while anything scrolls or the
// window resizes underneath it. The capture-phase scroll listener also
// catches scrolling ancestors such as DialogContent's overflow-y-auto body.
const updateDropdownPosition = useCallback(() => {
if (flat || !containerRef.current) return
const rect = containerRef.current.getBoundingClientRect()
const next = computeDropdownPosition(
{ top: rect.top, bottom: rect.bottom, left: rect.left, width: rect.width },
{ width: window.innerWidth, height: window.innerHeight },
)
// Bail out when nothing moved (e.g. scroll ticks that did not shift the
// anchor): returning the previous reference lets React skip the re-render.
setDropdownPos((prev) => (isSameDropdownPosition(prev, next) ? prev : next))
}, [flat])
useLayoutEffect(() => {
if (!isOpen || flat) return
updateDropdownPosition()
const handleScroll = (e: Event) => {
// Scrolling the portaled panel's own list never moves the anchor (the
// panel is position: fixed): repositioning on it would just churn state
// while the user scrolls the account list.
if (e.target instanceof Node && portalPanelRef.current?.contains(e.target)) return
updateDropdownPosition()
}
window.addEventListener('scroll', handleScroll, true)
window.addEventListener('resize', updateDropdownPosition)
return () => {
window.removeEventListener('scroll', handleScroll, true)
window.removeEventListener('resize', updateDropdownPosition)
}
}, [isOpen, flat, updateDropdownPosition])
// react-remove-scroll (active inside every modal dialog) preventDefaults
// wheel/touchmove events that reach document from outside the dialog's DOM
// tree, and the portaled panel lives outside that tree. Stopping the events
// at the panel lets the browser scroll it natively; overscroll-contain on
// the panel stops chained page scrolling at the list's edges.
const attachPortalPanel = useCallback((el: HTMLDivElement | null) => {
const prev = portalPanelRef.current
if (prev) {
prev.removeEventListener('wheel', stopScrollPropagation)
prev.removeEventListener('touchmove', stopScrollPropagation)
}
portalPanelRef.current = el
if (el) {
el.addEventListener('wheel', stopScrollPropagation)
el.addEventListener('touchmove', stopScrollPropagation)
}
}, [])
const attachPortalListPanel = useCallback((el: HTMLDivElement | null) => {
listRef.current = el
attachPortalPanel(el)
}, [attachPortalPanel])
// Close dropdown when clicking/tapping outside
useEffect(() => {
function handleClickOutside(e: MouseEvent | TouchEvent) {
const target = e.target as Node
// The non-flat dropdown is portaled to document.body, so it is not a
// DOM descendant of containerRef: check the portaled panel too.
if (
containerRef.current &&
!containerRef.current.contains(target) &&
!(portalPanelRef.current && portalPanelRef.current.contains(target))
) {
setIsOpen(false)
}
}
document.addEventListener('mousedown', handleClickOutside)
document.addEventListener('touchstart', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
document.removeEventListener('touchstart', handleClickOutside)
}
}, [])
const selectAccount = useCallback(
(accountNumber: string) => {
onChange(accountNumber)
setSearch(accountNumber)
setIsOpen(false)
onCommit?.(accountNumber)
},
[onChange, onCommit]
)
const handleKeyDown = (e: React.KeyboardEvent) => {
if (!isOpen) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
hasInteractedRef.current = true
setIsOpen(true)
e.preventDefault()
} else if (e.key === 'Enter' && /^\d{4}$/.test(search)) {
// Dropdown closed but a full account number sits in the field: treat
// Enter as a re-commit so focus advances to the amount field.
e.preventDefault()
onCommit?.(search)
}
return
}
switch (e.key) {
case 'ArrowDown':
e.preventDefault()
hasInteractedRef.current = true
setHighlightedIndex((prev) => Math.min(prev + 1, flatList.length - 1))
break
case 'ArrowUp':
e.preventDefault()
hasInteractedRef.current = true
setHighlightedIndex((prev) => Math.max(prev - 1, 0))
break
case 'Enter':
if (hasInteractedRef.current && flatList[highlightedIndex]) {
e.preventDefault()
selectAccount(flatList[highlightedIndex].account_number)
} else if (/^\d{4}$/.test(search)) {
// Committed number, no new interaction: advance without re-selecting.
e.preventDefault()
setIsOpen(false)
onCommit?.(search)
} else {
// Nothing actively chosen: close the list and let the event bubble
// so the form-level Enter (open review when balanced) can take over.
setIsOpen(false)
}
break
case 'Escape':
e.preventDefault()
setIsOpen(false)
break
}
}
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value
hasInteractedRef.current = true
setSearch(newValue)
// Emit any 4-digit numeric value to the parent. Unknown BAS numbers are
// accepted optimistically: the submit-time ActivateAccountsDialog lets
// the user activate missing accounts without leaving the form. A complete
// 4-digit number is treated as a commit so focus can advance to the amount.
if (/^\d{4}$/.test(newValue)) {
onChange(newValue)
// Only treat as a commit when the value newly becomes this account, so
// editing an already-committed number doesn't keep stealing focus. On
// commit, close the dropdown too: focus advances to the amount field, so
// a lingering open list would just cover the rows below.
//
// Unless the number matches nothing. Then the dropdown is showing the
// empty state, which carries the only way forward for a number outside
// BAS (a retired account such as 8022, or a company-specific
// underkonto): the "Skapa konto" affordance. Closing on the fourth
// keystroke used to hide it before it was ever painted, which made the
// affordance unreachable for exactly the numbers that need it.
if (newValue !== value) {
onCommit?.(newValue)
if (searchAccounts(accountIndex, newValue).length > 0) {
setIsOpen(false)
return
}
setIsOpen(true)
return
}
}
if (!isOpen) {
setIsOpen(true)
}
}
const handleFocus = () => {
hasInteractedRef.current = false
setIsOpen(true)
}
const handleBlur = () => {
// Close the dropdown as soon as focus leaves, so it never lingers open over
// the rows below when focus advances via keyboard (Enter/Tab).
setIsOpen(false)
// Small delay to allow dropdown click to fire first. Keep any 4-digit
// numeric value even if it's not in the currently-active chart: the
// submit handler will prompt to activate it.
setTimeout(() => {
const isFourDigit = /^\d{4}$/.test(search)
if (!isFourDigit && !accounts.some(a => a.account_number === search)) {
setSearch(value)
}
}, 150)
}
const showSelectedName = Boolean(selectedName && value && search === value)
// Flat mode keeps the dropdown as an absolute child that follows the
// trigger's width: inside a SettingsRow a fixed width would overflow the
// dialog. The non-flat dropdown is portaled to document.body with an
// explicit viewport-clamped geometry (computeDropdownPosition) instead, so
// a scrollable DialogContent can never clip it or grow a horizontal
// scrollbar around it (the fix info-tooltip.tsx already applies to
// TooltipContent, extended to this dropdown).
const flatListWidthClass = 'w-full min-w-0'
const portalPanelStyle: React.CSSProperties | undefined = dropdownPos
? {
left: dropdownPos.left,
width: dropdownPos.width,
maxHeight: dropdownPos.maxHeight,
...(dropdownPos.top !== undefined
? { top: dropdownPos.top }
: { bottom: dropdownPos.bottom }),
}
: undefined
// data-dialog-companion: DialogContent/SheetContent treat a pointerdown
// inside a node carrying this attribute as an inside interaction, so
// clicking the portaled panel never dismisses the dialog hosting it.
const listPanelContent = groupedAccounts.map((group) => (
<div key={group.className}>
<div className="sticky top-0 px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted border-b border-input">
{group.className}
</div>
{group.accounts.map((item) => {
const flatIndex = flatList.indexOf(item)
const isHighlighted = flatIndex === highlightedIndex
return (
<button
key={item.account_number}
type="button"
data-highlighted={isHighlighted}
className={`w-full text-left px-2 py-1.5 text-sm cursor-pointer flex items-baseline gap-2 ${
isHighlighted ? 'bg-primary/10 text-primary' : 'hover:bg-muted/50'
}`}
onMouseDown={(e) => {
e.preventDefault()
selectAccount(item.account_number)
}}
onMouseEnter={() => setHighlightedIndex(flatIndex)}
>
<span className={`font-mono shrink-0 ${item.isActive ? '' : 'text-muted-foreground'}`}>
{item.account_number}
</span>
<span className="flex-1 min-w-0 break-words">{item.account_name}</span>
{!item.isActive && (
<span className="shrink-0 self-center text-[11px] text-muted-foreground whitespace-nowrap">
{notActivatedLabel}
</span>
)}
</button>
)
})}
</div>
))
const emptyPanelContent = (
<>
<p className="text-sm text-muted-foreground">
Hittade inget konto som matchar.
</p>
{/^\d{4}$/.test(search.trim()) ? (
<p className="text-xs text-muted-foreground mt-1">
Om det är ett giltigt BAS-konto aktiveras det när du bokför.
</p>
) : (
<p className="text-xs text-muted-foreground mt-1">
Kontot kan behöva aktiveras i din kontoplan.
</p>
)}
{onCreateAccount && (
<button
type="button"
className="mt-2 flex w-full items-center gap-2 rounded-sm border border-input bg-card px-2 py-1.5 text-left text-sm hover:bg-muted/50"
onMouseDown={(e) => {
e.preventDefault()
setIsOpen(false)
onCreateAccount(search.trim())
}}
>
<Plus className="h-3.5 w-3.5 shrink-0" />
<span className="truncate">Skapa konto &quot;{search.trim()}&quot;</span>
</button>
)}
</>
)
const triggerProps = {
ref: setInputRef,
value: search,
onChange: handleInputChange,
onFocus: handleFocus,
onBlur: handleBlur,
onKeyDown: handleKeyDown,
placeholder: 'Sök konto…',
autoComplete: 'off',
disabled,
'aria-describedby': showSelectedName ? selectedNameId : undefined,
className: flat
? cn(
'min-w-0 flex-1 rounded-none border-0 border-b border-dashed border-transparent bg-transparent px-0 py-1 font-mono text-sm text-foreground',
'placeholder:text-muted-foreground/60 hover:border-border',
'focus:border-solid focus:border-foreground/50 focus:outline-none',
'disabled:cursor-not-allowed disabled:border-transparent disabled:opacity-60',
className,
)
: `font-mono ${className ?? ''}`.trim(),
}
return (
<div ref={containerRef} className="relative">
{flat ? <input {...triggerProps} /> : <Input {...triggerProps} />}
{showSelectedName ? (
<p id={selectedNameId} className="mt-1 break-words px-1 text-sm leading-snug text-foreground">
{selectedName}
</p>
) : null}
{/* Dropdown */}
{isOpen && !disabled && flatList.length > 0 && (flat ? (
<div
ref={listRef}
className={cn(
'absolute z-50 top-full left-0 mt-1 max-h-[300px] overflow-y-auto rounded-lg border border-input bg-card shadow-md',
flatListWidthClass,
)}
>
{listPanelContent}
</div>
) : (
dropdownPos &&
createPortal(
<div
ref={attachPortalListPanel}
data-dialog-companion=""
className="fixed z-50 overflow-y-auto overscroll-contain pointer-events-auto rounded-lg border border-input bg-card shadow-md"
style={portalPanelStyle}
>
{listPanelContent}
</div>,
document.body,
)
))}
{/* Empty state */}
{isOpen && !disabled && search.trim() && flatList.length === 0 && (flat ? (
<div
className={cn(
'absolute z-50 top-full left-0 mt-1 rounded-lg border border-input bg-card shadow-md p-3',
flatListWidthClass,
)}
>
{emptyPanelContent}
</div>
) : (
dropdownPos &&
createPortal(
<div
ref={attachPortalPanel}
data-dialog-companion=""
className="fixed z-50 overflow-y-auto overscroll-contain pointer-events-auto rounded-lg border border-input bg-card p-3 shadow-md"
style={portalPanelStyle}
>
{emptyPanelContent}
</div>,
document.body,
)
))}
</div>
)
}
@@ -1,52 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import {
vatTreatmentsForAccountClass,
type AccountVatTreatment,
} from '@/lib/vat/account-vat-treatment'
interface AccountVatTreatmentSelectProps {
value: AccountVatTreatment | 'none'
onValueChange: (value: AccountVatTreatment | 'none') => void
accountClass: number | null
}
export function AccountVatTreatmentSelect({
value,
onValueChange,
accountClass,
}: AccountVatTreatmentSelectProps) {
const t = useTranslations('chart_of_accounts')
const isRelevant = accountClass === 3 ||
(accountClass !== null && accountClass >= 4 && accountClass <= 6)
const treatments = vatTreatmentsForAccountClass(accountClass)
return (
<div className="space-y-2">
<Label>{t('vat_treatment_label')}</Label>
<Select
value={value}
onValueChange={(next) => onValueChange(next as AccountVatTreatment | 'none')}
disabled={!isRelevant}
>
<SelectTrigger aria-label={t('vat_treatment_label')}>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">{t('vat_treatment_none')}</SelectItem>
{treatments.map((treatment) => (
<SelectItem key={treatment} value={treatment}>
{t(`vat_treatment_${treatment}`)}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
{isRelevant ? t('vat_treatment_help') : t('vat_treatment_not_applicable')}
</p>
</div>
)
}
@@ -1,193 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import { X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { formatCurrency } from '@/lib/utils'
import {
computeInstallmentAmounts,
countCalendarMonths,
} from '@/lib/bookkeeping/accruals/compute'
import { accrualHintKey, shouldShowK2AccrualHint } from '@/components/bookkeeping/accrual-k2-hint'
import type { AccrualDirection, EntityType } from '@/types'
export interface AccrualFormValue {
start: string
end: string
balanceAccount: string
}
// The statutory BAS interim accounts per direction: a fixed list reads
// better than a full account combobox and mirrors the DB CHECK (17xx/29xx).
const BALANCE_ACCOUNT_OPTIONS: Record<AccrualDirection, Array<{ value: string; label: string }>> = {
expense: [
{ value: '1710', label: '1710 Förutbetalda hyreskostnader' },
{ value: '1720', label: '1720 Förutbetalda leasingavgifter' },
{ value: '1730', label: '1730 Förutbetalda försäkringspremier' },
{ value: '1740', label: '1740 Förutbetalda räntekostnader' },
{ value: '1790', label: '1790 Övriga förutbetalda kostnader' },
],
revenue: [
{ value: '2970', label: '2970 Förutbetalda intäkter' },
{ value: '2971', label: '2971 Förutbetalda hyresintäkter' },
{ value: '2972', label: '2972 Förutbetalda medlemsavgifter' },
{ value: '2979', label: '2979 Övriga förutbetalda intäkter' },
],
}
/**
* Per-line periodisering panel for the invoice editors: service period +
* interim balance account + a live "N månader × X kr" preview. The parent
* owns the toggle; this renders only while periodisering is active on the
* line. VAT is never affected: only the net amount is deferred.
*/
export default function AccrualPeriodControl({
direction,
amount,
currency,
exchangeRate,
value,
onChange,
onRemove,
idPrefix,
entityType,
}: {
direction: AccrualDirection
/** Net line amount (ex VAT), in `currency`: drives the preview and the K2 hint. */
amount: number
/** ISO code of `amount`. Missing is treated as SEK (the editors' default). */
currency?: string | null
/**
* SEK per unit of `currency`. Only the supplier-invoice form has one; the
* customer-invoice editor carries no rate, so the K2 hint stays hidden on
* its foreign-currency lines instead of comparing kronor to euros.
*/
exchangeRate?: number | null
value: AccrualFormValue
onChange: (next: AccrualFormValue) => void
onRemove: () => void
idPrefix: string
/**
* Picks the regelverk the materiality hint cites: K1 (BFNAR 2006:1) for
* enskild firma, K2 (BFNAR 2016:10) otherwise. Missing keeps the K2
* wording (the historical default).
*/
entityType?: EntityType | null
}) {
const t = useTranslations('accruals')
let preview: string | null = null
let previewInvalid: string | null = null
if (value.start && value.end) {
if (value.end < value.start) {
previewInvalid = t('preview_invalid_period')
} else {
try {
const months = countCalendarMonths(value.start, value.end)
if (months < 2) {
previewInvalid = t('preview_min_months')
} else if (amount > 0) {
const amounts = computeInstallmentAmounts(amount, months)
preview = t('preview', {
months,
amount: formatCurrency(amounts[0], currency || 'SEK'),
})
}
} catch {
previewInvalid = t('preview_invalid_period')
}
}
}
// The 5 000 kr vasentlighetsgrans (K1/K2) is measured in kronor, and it is
// a simplification the company may use, not an obligation. So when the line
// is in a foreign currency and no rate is available, show nothing at all
// rather than compare the raw foreign amount against a SEK threshold.
const showMaterialityHint = shouldShowK2AccrualHint({ amount, currency, exchangeRate })
const materialityHintKey = accrualHintKey(entityType)
return (
<div className="rounded-lg border bg-muted/30 p-3 space-y-3">
<div className="flex items-center justify-between">
<span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
{t('panel_title')}
</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={onRemove}
aria-label={t('remove_aria')}
>
<X className="h-3.5 w-3.5 text-muted-foreground" />
</Button>
</div>
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
<div className="space-y-1.5">
<Label htmlFor={`${idPrefix}-start`} className="text-xs">
{t('start_label')}
</Label>
<Input
id={`${idPrefix}-start`}
type="date"
className="h-9"
value={value.start}
onChange={(e) => onChange({ ...value, start: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor={`${idPrefix}-end`} className="text-xs">
{t('end_label')}
</Label>
<Input
id={`${idPrefix}-end`}
type="date"
className="h-9"
value={value.end}
onChange={(e) => onChange({ ...value, end: e.target.value })}
/>
</div>
<div className="space-y-1.5">
<Label className="text-xs">{t('account_label')}</Label>
<Select
value={value.balanceAccount}
onValueChange={(account) => onChange({ ...value, balanceAccount: account })}
>
<SelectTrigger className="h-9" aria-label={t('account_label')}>
<SelectValue />
</SelectTrigger>
<SelectContent>
{BALANCE_ACCOUNT_OPTIONS[direction].map((option) => (
<SelectItem key={option.value} value={option.value}>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{(preview || previewInvalid) && (
<p
className={
previewInvalid ? 'text-xs text-destructive' : 'text-xs text-muted-foreground tabular-nums'
}
>
{previewInvalid ?? preview}
</p>
)}
{showMaterialityHint && (
<p className="text-xs text-muted-foreground">{t(materialityHintKey)}</p>
)}
</div>
)
}
@@ -1,181 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Loader2, Plus } from 'lucide-react'
export interface ActivateAccountsDialogProps {
open: boolean
accountNumbers: string[]
onConfirm: () => Promise<void> | void
onCancel: () => void
// Optional: invoked when the user wants to create a custom (non-BAS) account
// for a number that isn't in the BAS catalogue. The host should close this
// dialog and open AddAccountDialog prefilled with the number.
onCreateUnknown?: (accountNumber: string) => void
// Confirm button label. Defaults to the bookkeeping wording; non-booking
// hosts (e.g. the article register) pass their own.
confirmLabel?: string
}
interface BasLookupRow {
account_number: string
account_name: string | null
known: boolean
// Present since the lookup learned about the company's own chart: an account
// that is in_chart but not is_active is being reactivated, not added.
in_chart?: boolean
is_active?: boolean
}
export function ActivateAccountsDialog({
open,
accountNumbers,
onConfirm,
onCancel,
onCreateUnknown,
confirmLabel,
}: ActivateAccountsDialogProps) {
const [rows, setRows] = useState<BasLookupRow[]>([])
const [loading, setLoading] = useState(false)
const [submitting, setSubmitting] = useState(false)
useEffect(() => {
if (!open || accountNumbers.length === 0) return
let cancelled = false
setLoading(true)
fetch(`/api/bookkeeping/accounts/bas-lookup?numbers=${encodeURIComponent(accountNumbers.join(','))}`)
.then((r) => r.json())
.then((body) => {
if (cancelled) return
setRows((body?.data as BasLookupRow[]) || [])
})
.catch(() => {
if (cancelled) return
setRows(
accountNumbers.map((n) => ({
account_number: n,
account_name: null,
known: false,
in_chart: false,
is_active: false,
})),
)
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [open, accountNumbers])
const knownRows = rows.filter((r) => r.known)
const unknownRows = rows.filter((r) => !r.known)
// Disable confirm when any entered number isn't a valid BAS account: activating
// only the knowns would leave the unknowns to fail again on retry.
const canConfirm = knownRows.length > 0 && unknownRows.length === 0 && !submitting
async function handleConfirm() {
setSubmitting(true)
try {
await onConfirm()
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={(next) => { if (!next) onCancel() }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Aktivera konton</DialogTitle>
<DialogDescription>
{knownRows.length > 0
? 'Följande konton behöver aktiveras i din kontoplan innan bokföringen kan slutföras.'
: 'Inga giltiga BAS-konton att aktivera.'}
</DialogDescription>
</DialogHeader>
<div className="space-y-2 text-sm">
{loading && (
<div className="flex items-center gap-2 text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Hämtar kontouppgifter...
</div>
)}
{!loading && knownRows.length > 0 && (
<ul className="divide-y divide-border rounded-lg border">
{knownRows.map((r) => (
<li key={r.account_number} className="flex items-baseline gap-3 px-3 py-2">
<span className="font-mono text-foreground w-14 shrink-0">{r.account_number}</span>
<span className="truncate">{r.account_name}</span>
{r.in_chart && !r.is_active && (
<span className="ml-auto shrink-0 text-xs text-muted-foreground">
Aktiveras igen
</span>
)}
</li>
))}
</ul>
)}
{!loading && unknownRows.length > 0 && (
<div className="rounded-lg border border-border bg-muted/30 px-3 py-2 text-xs text-attn">
<p className="font-medium">Finns inte i BAS-katalogen:</p>
<p className="mt-1 font-mono">{unknownRows.map((r) => r.account_number).join(', ')}</p>
<p className="mt-1 text-attn/80">
Skapa dem som egna konton, eller kontrollera inmatningen.
</p>
{onCreateUnknown && (
<div className="mt-2 flex flex-wrap gap-1.5">
{unknownRows.map((r) => (
<Button
key={r.account_number}
type="button"
variant="outline"
size="sm"
className="h-8 text-xs"
onClick={() => onCreateUnknown(r.account_number)}
>
<Plus className="mr-1 h-3 w-3" />
Skapa <span data-ph-mask="">{r.account_number}</span>
</Button>
))}
</div>
)}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={onCancel} disabled={submitting}>
Avbryt
</Button>
<Button onClick={handleConfirm} disabled={!canConfirm}>
{submitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Aktiverar...
</>
) : (
<>
<Plus className="mr-2 h-4 w-4" />
{confirmLabel ?? 'Aktivera och bokför'}
</>
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
-361
View File
@@ -1,361 +0,0 @@
'use client'
import { useEffect, useState } 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 { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Loader2, AlertTriangle } from 'lucide-react'
import { isStandardBASAccountNumber } from '@/lib/bookkeeping/bas-account-numbers'
import { classifyAccountClient as classifyAccount } from '@/lib/bookkeeping/account-classifier-client'
import { useBasReference } from '@/lib/bookkeeping/use-bas-reference'
import type { BASAccount } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { AccountVatTreatmentSelect } from './AccountVatTreatmentSelect'
import {
defaultRateForVatTreatment,
isVatTreatmentAllowedForAccountClass,
type AccountVatTreatment,
} from '@/lib/vat/account-vat-treatment'
/**
* The create path hands back the full row the API inserted. The reactivate
* path only learns the account number back from /accounts/activate, and the
* stored account is deliberately left untouched, so the rest is unknown here.
* Every host refetches its own list and reads only account_number.
*/
type CreatedAccount = Partial<BASAccount> & { account_number: string }
interface AddAccountDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onCreated: (account: CreatedAccount) => void
initialAccountNumber?: string
initialAccountName?: string
}
export function AddAccountDialog({
open,
onOpenChange,
onCreated,
initialAccountNumber,
initialAccountName,
}: AddAccountDialogProps) {
// Loads the BAS chart chunk after mount so classification and the
// standard-account check get the authoritative answer once it lands.
useBasReference()
const [accountNumber, setAccountNumber] = useState('')
const [accountName, setAccountName] = useState('')
const [description, setDescription] = useState('')
// "Standard moms": the moms-sats a booking line defaults to when this konto is
// picked. 'none' = no default. SelectItem values are stringified decimals.
const [defaultVatRate, setDefaultVatRate] = useState('none')
const [defaultVatTreatment, setDefaultVatTreatment] = useState<AccountVatTreatment | 'none'>('none')
const [sruCode, setSruCode] = useState('')
const [normalBalance, setNormalBalance] = useState<'debit' | 'credit'>('debit')
const [isSaving, setIsSaving] = useState(false)
const [error, setError] = useState('')
// Set when the create failed because the number belongs to a deactivated
// account. Creating it can never succeed (the unique constraint counts
// inactive rows), so the dialog offers reactivation instead of a dead end.
const [inactiveConflict, setInactiveConflict] = useState(false)
// Apply prefill values whenever the dialog opens. Resetting on close happens
// implicitly after a successful create; here we only need to seed inputs so
// the user doesn't retype what the combobox already captured.
useEffect(() => {
if (!open) return
const num = (initialAccountNumber ?? '').replace(/\D/g, '').slice(0, 4)
setAccountNumber(num)
setAccountName(initialAccountName ?? '')
setDefaultVatRate('none')
setDefaultVatTreatment('none')
setError('')
setInactiveConflict(false)
if (num.length === 4) {
setNormalBalance(classifyAccount(num).normal_balance)
}
}, [open, initialAccountNumber, initialAccountName])
const isBASMatch = accountNumber.length === 4 && isStandardBASAccountNumber(accountNumber)
const derived = accountNumber.length === 4 ? classifyAccount(accountNumber) : null
async function handleCreate() {
setError('')
setInactiveConflict(false)
if (!/^\d{4}$/.test(accountNumber)) {
setError('Kontonumret måste vara exakt 4 siffror')
return
}
if (!accountName.trim()) {
setError('Kontonamn krävs')
return
}
setIsSaving(true)
try {
const response = await fetch('/api/bookkeeping/accounts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
account_number: accountNumber,
account_name: accountName.trim(),
account_type: derived?.account_type || 'expense',
normal_balance: normalBalance,
description: description || null,
default_vat_rate: defaultVatRate === 'none' ? null : parseFloat(defaultVatRate),
default_vat_treatment: defaultVatTreatment === 'none' ? null : defaultVatTreatment,
sru_code: sruCode || null,
}),
})
if (!response.ok) {
// Map the response itself, not `new Error(data.error)`: the route
// answers thrown errors with the canonical envelope
// `{ error: { code, message } }`, and the Error constructor would
// stringify that object to "[object Object]", throwing away the
// route's own Swedish reason. Passing the parsed body plus the status
// resolves all three shapes (envelope, bare string, no body).
const body = await response.json().catch(() => null)
const code = (body as { error?: { code?: string } } | null)?.error?.code
setInactiveConflict(code === 'ACCOUNT_EXISTS_INACTIVE')
setError(getUserErrorMessage(body, { statusCode: response.status }))
return
}
const { data: createdAccount } = await response.json() as { data: BASAccount }
// Reset form
setAccountNumber('')
setAccountName('')
setDescription('')
setDefaultVatRate('none')
setDefaultVatTreatment('none')
setSruCode('')
onCreated(createdAccount)
onOpenChange(false)
} catch (err) {
setError(err instanceof Error ? getUserErrorMessage(err) : 'Något gick fel')
} finally {
setIsSaving(false)
}
}
// Recovery for ACCOUNT_EXISTS_INACTIVE: flip the existing account back on
// instead of trying to insert a second row. The values typed into this form
// are intentionally dropped — the account comes back exactly as it was, and
// renaming it is the kontoplan's job, not a side effect of a failed create.
async function handleReactivate() {
setError('')
setIsSaving(true)
try {
const response = await fetch('/api/bookkeeping/accounts/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_numbers: [accountNumber] }),
})
if (!response.ok) {
const body = await response.json().catch(() => null)
setError(getUserErrorMessage(body, { statusCode: response.status }))
return
}
setInactiveConflict(false)
setAccountNumber('')
setAccountName('')
setDescription('')
setDefaultVatRate('none')
setDefaultVatTreatment('none')
setSruCode('')
onCreated({ account_number: accountNumber })
onOpenChange(false)
} catch (err) {
setError(err instanceof Error ? getUserErrorMessage(err) : 'Något gick fel')
} finally {
setIsSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Lägg till eget konto</DialogTitle>
<DialogDescription>
Skapa ett eget konto utanför BAS-standarden
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
{isBASMatch && (
<div className="flex items-start gap-2 rounded-lg bg-muted/30 border border-border p-3">
<AlertTriangle className="h-4 w-4 text-attn mt-0.5 shrink-0" />
<p className="text-sm text-attn">
Kontonummer {accountNumber} finns i BAS-standarden. Använd &quot;BAS-katalog&quot;-fliken för att aktivera standardkonton istället.
</p>
</div>
)}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Kontonummer</Label>
<Input
value={accountNumber}
onChange={(e) => {
const v = e.target.value.replace(/\D/g, '').slice(0, 4)
setAccountNumber(v)
const nextClass = v.length > 0 ? Number(v[0]) : null
if (
defaultVatTreatment !== 'none' &&
(nextClass === null || !isVatTreatmentAllowedForAccountClass(
defaultVatTreatment,
nextClass,
))
) {
setDefaultVatTreatment('none')
}
// The conflict is about a specific number; editing it makes
// the reactivate offer stale.
setInactiveConflict(false)
setError('')
if (v.length === 4) {
setNormalBalance(classifyAccount(v).normal_balance)
}
}}
placeholder="T.ex. 1935"
maxLength={4}
className="font-mono"
/>
</div>
<div className="space-y-2">
<Label>Normal saldo</Label>
<Select value={normalBalance} onValueChange={(v) => { if (v) setNormalBalance(v as 'debit' | 'credit') }}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="debit">Debet</SelectItem>
<SelectItem value="credit">Kredit</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{derived && (
<p className="text-xs text-muted-foreground">
Auto-detekterad typ:{' '}
<span className="font-medium">
{derived.account_type === 'asset' ? 'Tillgång'
: derived.account_type === 'liability' ? 'Skuld'
: derived.account_type === 'equity' ? 'Eget kapital'
: derived.account_type === 'untaxed_reserves' ? 'Obeskattade reserver'
: derived.account_type === 'revenue' ? 'Intäkt'
: 'Kostnad'}
</span>
</p>
)}
<div className="space-y-2">
<Label>Kontonamn</Label>
<Input
value={accountName}
onChange={(e) => setAccountName(e.target.value)}
placeholder="T.ex. Sparkonto företag"
/>
</div>
<div className="space-y-2">
<Label>Beskrivning <span className="text-muted-foreground">(valfritt)</span></Label>
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Kort beskrivning av kontots användning"
rows={2}
/>
</div>
<AccountVatTreatmentSelect
value={defaultVatTreatment}
accountClass={derived ? Number(accountNumber.charAt(0)) : null}
onValueChange={(treatment) => {
setDefaultVatTreatment(treatment)
if (treatment !== 'none' && defaultVatRate === 'none') {
const rate = defaultRateForVatTreatment(treatment, Number(accountNumber.charAt(0)))
if (rate !== null) setDefaultVatRate(String(rate))
}
}}
/>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Standard moms <span className="text-muted-foreground">(valfritt)</span></Label>
<Select value={defaultVatRate} onValueChange={setDefaultVatRate}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">Ingen standard</SelectItem>
<SelectItem value="0">Ingen moms</SelectItem>
<SelectItem value="0.25">25 %</SelectItem>
<SelectItem value="0.12">12 %</SelectItem>
<SelectItem value="0.06">6 %</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>SRU-kod <span className="text-muted-foreground">(valfritt)</span></Label>
<Input
value={sruCode}
onChange={(e) => setSruCode(e.target.value)}
placeholder="T.ex. 7201"
/>
</div>
</div>
{error && !inactiveConflict && (
<p className="text-sm text-destructive">{error}</p>
)}
{inactiveConflict && (
<div className="space-y-3 rounded-lg border border-border p-3">
<p className="text-sm text-foreground">{error}</p>
<Button
type="button"
onClick={() => void handleReactivate()}
disabled={isSaving}
>
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Aktivera kontot istället
</Button>
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Avbryt
</Button>
<Button
onClick={handleCreate}
disabled={isSaving || inactiveConflict || accountNumber.length !== 4 || !accountName.trim()}
>
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Skapa konto
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,114 +0,0 @@
'use client'
import { ArrowDown, AlertTriangle } from 'lucide-react'
import { formatCurrency, formatDate } from '@/lib/utils'
import { DocumentViewButton } from './DocumentViewButton'
interface AttachDocumentPreviewProps {
data: Record<string, unknown>
params: Record<string, unknown>
}
/**
* Two-card preview for `attach_document_to_transaction` operations. Renders
* the transaction and the document side by side so the reviewer can confirm
* the pairing without cross-referencing IDs.
*/
export function AttachDocumentPreview({ data, params }: AttachDocumentPreviewProps) {
const txDescription = (data.transaction_description as string) || '-'
const txAmount = data.transaction_amount as number | undefined
const txCurrency = (data.transaction_currency as string) || 'SEK'
const txDate = data.transaction_date as string | undefined
const docFileName = (data.document_file_name as string) || '-'
const docVendor = data.document_vendor_name as string | undefined
const docAmount = data.document_amount as number | undefined
const docCurrency = (data.document_currency as string) || txCurrency
const docInvoiceDate = data.document_invoice_date as string | undefined
const willOverwrite = data.will_overwrite_existing === true
const existingDocName = data.existing_document_file_name as string | undefined
// Fail safe: if the staging tool didn't explicitly assert the existing doc
// is NOT räkenskapsinformation (i.e. `=== false`), treat overwrite as a
// BFL 7 kap event. A missing/undefined flag must not silently downgrade
// the destructive warning.
const existingIsAccounting =
willOverwrite && data.existing_document_is_rakenskapsinformation !== false
const documentId = params.document_id as string | undefined
return (
<div className="space-y-3 text-sm">
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<PreviewCard label="Transaktion">
<Row label="Datum" value={txDate ? formatDate(txDate) : '-'} tabular />
<Row label="Beskrivning" value={txDescription} />
<Row
label="Belopp"
value={typeof txAmount === 'number' ? formatCurrency(txAmount, txCurrency) : '-'}
tabular
/>
</PreviewCard>
<PreviewCard label="Dokument">
<Row label="Fil" value={docFileName} />
{docVendor && <Row label="Leverantör" value={docVendor} />}
{docInvoiceDate && <Row label="Fakturadatum" value={formatDate(docInvoiceDate)} tabular />}
{typeof docAmount === 'number' && (
<Row label="Belopp" value={formatCurrency(docAmount, docCurrency)} tabular />
)}
{documentId && (
<div className="pt-1">
<DocumentViewButton documentId={documentId} />
</div>
)}
</PreviewCard>
</div>
<div className="flex items-center justify-center text-xs text-muted-foreground">
<ArrowDown className="h-3.5 w-3.5 mr-1" />
kopplas till transaktionen
</div>
{willOverwrite && existingIsAccounting && (
<div className="flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
<div>
<p className="font-medium">Ersätter räkenskapsinformation</p>
<p className="mt-1 text-xs">
Befintligt dokument{existingDocName ? ` (${existingDocName})` : ''} är markerat som
räkenskapsinformation enligt BFL 7 kap. Att ersätta det här gör det tidigare
verifikationsunderlaget otillgängligt: bekräfta att du har originalet sparat innan
du godkänner.
</p>
</div>
</div>
)}
{willOverwrite && !existingIsAccounting && (
<div className="rounded-lg border border-border bg-muted/30 p-2 text-xs text-muted-foreground">
Ersätter befintligt dokument{existingDocName ? `: ${existingDocName}` : ''}.
</div>
)}
</div>
)
}
function PreviewCard({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="rounded-lg border border-border p-3 space-y-1.5">
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
{label}
</p>
{children}
</div>
)
}
function Row({ label, value, tabular }: { label: string; value: string; tabular?: boolean }) {
return (
<div className="flex justify-between gap-3">
<span className="text-xs text-muted-foreground shrink-0">{label}</span>
<span className={`text-sm ${tabular ? 'tabular-nums' : ''} text-right truncate`}>{value}</span>
</div>
)
}
@@ -1,465 +0,0 @@
'use client'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslations } from 'next-intl'
import {
AlertTriangle,
ExternalLink,
FileText,
ImageIcon,
Loader2,
Lock,
Paperclip,
RefreshCw,
Trash2,
} from 'lucide-react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { Skeleton } from '@/components/ui/skeleton'
interface DocumentRecord {
id: string
file_name: string
file_size_bytes: number
mime_type: string | null
storage_path: string
created_at: string
download_url?: string
}
interface AttachmentPreviewSheetProps {
entryId: string | null
open: boolean
onOpenChange: (open: boolean) => void
}
// Tri-state integrity result so a transport/parse failure does not get
// collapsed into "valid". Document bytes are immutable (WORM), so once we
// have a definitive valid/invalid we can also memoise across re-opens of
// the sheet: the integrity probe is the most expensive call on this
// surface and there's no need to re-run it for the same document twice in
// a session.
type IntegrityState = 'valid' | 'invalid' | 'error'
const integrityCache = new Map<string, IntegrityState>()
function isImageType(type: string | null, fileName?: string): boolean {
if (type?.startsWith('image/')) return true
// Legacy uploads and browsers that fail to sniff sometimes leave mime_type
// null or set it to application/octet-stream: fall back to filename.
if (type === null || type === 'application/octet-stream') {
return /\.(jpe?g|png|gif|webp|svg)$/i.test(fileName ?? '')
}
return false
}
function isPdfType(type: string | null, fileName?: string): boolean {
if (type === 'application/pdf') return true
if (type === null || type === 'application/octet-stream') {
return fileName?.toLowerCase().endsWith('.pdf') ?? false
}
return false
}
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
export default function AttachmentPreviewSheet({
entryId,
open,
onOpenChange,
}: AttachmentPreviewSheetProps) {
const t = useTranslations('attachment_preview_sheet')
const tj = useTranslations('journal_attachments')
const { toast } = useToast()
const [documents, setDocuments] = useState<DocumentRecord[]>([])
const [loading, setLoading] = useState(false)
const [integrity, setIntegrity] = useState<Record<string, IntegrityState>>({})
const [blockedDoc, setBlockedDoc] = useState<DocumentRecord | null>(null)
const [replacingDocId, setReplacingDocId] = useState<string | null>(null)
const replaceFileInputRef = useRef<HTMLInputElement | null>(null)
const replaceTargetIdRef = useRef<string | null>(null)
const fetchAttachments = useCallback(async (id: string) => {
setLoading(true)
try {
const res = await fetch(
`/api/documents?journal_entry_id=${id}&current_only=true`
)
const { data } = await res.json()
const list: DocumentRecord[] = data || []
// Pull a signed download_url for each: used by the
// "open in new tab" link. The iframe/img sources use the
// same-origin inline proxy and do not need download_url.
const enriched = await Promise.all(
list.map(async (doc) => {
try {
const r = await fetch(`/api/documents/${doc.id}`)
const { data: detail } = await r.json()
return detail?.download_url
? { ...doc, download_url: detail.download_url as string }
: doc
} catch {
return doc
}
})
)
setDocuments(enriched)
// Probe storage bytes for PDFs that we haven't already classified in
// this session. Legacy MCP uploads from before magic-byte validation
// can have non-PDF bytes stored under mime_type='application/pdf';
// Chrome's PDF viewer surfaces this as "Failed to load PDF document"
// only after the user has tried to view the file, so we want a
// clearer warning up front.
//
// Why per-session caching: document bytes are immutable (WORM) once
// uploaded, so a definitive valid/invalid result never changes for
// the same document id. Re-running the probe every time the sheet
// opens would be wasted bandwidth and unnecessary processing of
// financial documents (GDPR Art. 5(1)(b) data minimisation).
const seeded: Record<string, IntegrityState> = {}
const needsProbe: DocumentRecord[] = []
for (const doc of enriched) {
if (doc.mime_type !== 'application/pdf') continue
const cached = integrityCache.get(doc.id)
if (cached) {
seeded[doc.id] = cached
} else {
needsProbe.push(doc)
}
}
if (Object.keys(seeded).length > 0) {
setIntegrity(seeded)
}
const results = await Promise.all(
needsProbe.map(async (doc) => {
try {
const r = await fetch(`/api/documents/${doc.id}/integrity`)
if (!r.ok) {
// Server reachable but returned a non-2xx: treat as unknown.
// Caching the error would stick across reloads of the sheet,
// which is not what we want for transient 5xx.
return [doc.id, 'error' as const, false] as const
}
const { data } = await r.json()
const state: IntegrityState = data?.valid === false ? 'invalid' : 'valid'
return [doc.id, state, true] as const
} catch {
return [doc.id, 'error' as const, false] as const
}
})
)
const next: Record<string, IntegrityState> = { ...seeded }
for (const [docId, state, cache] of results) {
next[docId] = state
if (cache) integrityCache.set(docId, state)
}
setIntegrity(next)
} catch {
setDocuments([])
setIntegrity({})
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
if (open && entryId) {
fetchAttachments(entryId)
} else if (!open) {
setDocuments([])
setIntegrity({})
setBlockedDoc(null)
}
}, [open, entryId, fetchAttachments])
const handleOpenReplacePicker = (docId: string) => {
replaceTargetIdRef.current = docId
replaceFileInputRef.current?.click()
}
const handleReplaceFileSelected = async (file: File | null) => {
const docId = replaceTargetIdRef.current
replaceTargetIdRef.current = null
if (replaceFileInputRef.current) {
replaceFileInputRef.current.value = ''
}
if (!file || !docId || !entryId) return
setReplacingDocId(docId)
try {
const fd = new FormData()
fd.append('file', file)
const res = await fetch(`/api/documents/${docId}/versions`, {
method: 'POST',
body: fd,
})
if (!res.ok) {
const { error } = await res.json().catch(() => ({ error: undefined }))
toast({
title: tj('replace_failed'),
description: error || undefined,
variant: 'destructive',
})
} else {
await fetchAttachments(entryId)
setBlockedDoc(null)
}
} catch {
toast({ title: tj('replace_failed'), variant: 'destructive' })
} finally {
setReplacingDocId(null)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90vh] w-[95vw] max-w-4xl overflow-y-auto">
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
</DialogHeader>
<input
ref={replaceFileInputRef}
type="file"
accept="application/pdf,image/jpeg,image/png,image/webp"
className="hidden"
onChange={(e) => handleReplaceFileSelected(e.target.files?.[0] ?? null)}
/>
{loading ? (
<div className="space-y-3">
<Skeleton className="h-5 w-2/3" />
<Skeleton className="h-[60vh] w-full rounded-lg" />
</div>
) : documents.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<div className="mb-3 rounded-full bg-muted p-3">
<Paperclip className="h-5 w-5 text-muted-foreground" />
</div>
<p className="text-sm text-muted-foreground">{t('empty')}</p>
</div>
) : (
<div className="space-y-6">
{documents.map((doc) => {
const inlineSrc = `/api/documents/${doc.id}/inline`
const previewable =
isImageType(doc.mime_type, doc.file_name) ||
isPdfType(doc.mime_type, doc.file_name)
const isReplacing = replacingDocId === doc.id
return (
<div key={doc.id} className="space-y-2">
<div className="flex items-start justify-between gap-3">
<div className="flex min-w-0 items-start gap-2">
{isImageType(doc.mime_type, doc.file_name) ? (
<ImageIcon className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
) : (
<FileText className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
)}
<div className="min-w-0">
<p className="truncate text-sm font-medium">
{doc.file_name}
</p>
<p className="text-xs text-muted-foreground">
{formatFileSize(doc.file_size_bytes)}
</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
onClick={() => handleOpenReplacePicker(doc.id)}
disabled={isReplacing}
title={t('replace')}
aria-label={t('replace')}
>
{isReplacing ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="h-3.5 w-3.5" />
)}
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
onClick={() => setBlockedDoc(doc)}
title={t('remove')}
aria-label={t('remove')}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
{doc.download_url && (
<a
href={doc.download_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 px-2 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
>
<ExternalLink className="h-3.5 w-3.5" />
{t('open_in_new_tab')}
</a>
)}
</div>
</div>
{isPdfType(doc.mime_type, doc.file_name) && integrity[doc.id] === 'invalid' && (
<div className="flex h-[70vh] w-full flex-col items-center justify-center gap-4 rounded-lg border border-border bg-muted/30 p-6 text-center">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted">
<AlertTriangle className="h-5 w-5 text-attn" />
</div>
<div className="max-w-md space-y-2">
<p className="text-sm font-medium">{t('corrupt_title')}</p>
<p className="text-sm text-muted-foreground">{t('corrupt_body')}</p>
</div>
<Button
onClick={() => handleOpenReplacePicker(doc.id)}
disabled={isReplacing}
>
{isReplacing ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{tj('replace_uploading')}
</>
) : (
t('corrupt_replace_cta')
)}
</Button>
</div>
)}
{isPdfType(doc.mime_type, doc.file_name) && integrity[doc.id] !== 'invalid' && (
// <object> + type="application/pdf" invokes Chrome's PDF
// plugin directly. <iframe> went through Chrome's frame
// pipeline first and intermittently surfaced
// "Det här innehållet har blockerats" even with a
// permissive CSP. Firefox/Edge handled both fine; Chrome
// is the odd one. See crbug.com/271452.
<>
{integrity[doc.id] === 'error' && (
// Non-blocking indicator when the integrity probe
// could not complete (network blip, 5xx). The PDF
// preview still renders; the user can fall back to
// Chrome's own viewer error UI if the bytes are
// also corrupt. Surfacing this rather than falling
// through silently to "valid" satisfies SOC 2 CC8.1:
// failed checks must not be masked.
<p className="text-xs text-muted-foreground">
{t('integrity_unknown')}
</p>
)}
<object
data={inlineSrc}
type="application/pdf"
aria-label={doc.file_name}
className="h-[70vh] w-full rounded-lg border border-border"
>
<div className="flex h-[70vh] w-full items-center justify-center rounded-lg border border-border bg-muted/30 p-4 text-center text-sm text-muted-foreground">
{t('not_previewable')}
{doc.download_url && (
<>
{': '}
<a
href={doc.download_url}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
{t('open_in_new_tab')}
</a>
</>
)}
</div>
</object>
</>
)}
{isImageType(doc.mime_type, doc.file_name) && (
<div className="overflow-hidden rounded-lg border border-border bg-muted/30">
<img
src={inlineSrc}
alt={doc.file_name}
className="mx-auto max-h-[70vh] w-full object-contain"
/>
</div>
)}
{!previewable && (
<p className="rounded-lg border border-border bg-muted/30 p-4 text-sm text-muted-foreground">
{t('not_previewable')}
</p>
)}
</div>
)
})}
</div>
)}
<Dialog
open={blockedDoc !== null}
onOpenChange={(o) => {
if (!o) setBlockedDoc(null)
}}
>
<DialogContent>
<DialogHeader>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted shrink-0">
<Lock className="h-5 w-5 text-attn" />
</div>
<DialogTitle>{tj('remove_blocked_title')}</DialogTitle>
</div>
<DialogDescription className="pt-3 text-sm text-muted-foreground">
{tj('remove_blocked_body')}
</DialogDescription>
</DialogHeader>
<div className="rounded-lg border border-border bg-muted/30 p-3 text-sm">
<div className="flex items-start gap-2">
<AlertTriangle className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
<p className="text-muted-foreground">{tj('remove_blocked_hint')}</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setBlockedDoc(null)}>
{tj('remove_blocked_cancel_cta')}
</Button>
<Button
onClick={() => {
if (blockedDoc) handleOpenReplacePicker(blockedDoc.id)
}}
disabled={blockedDoc !== null && replacingDocId === blockedDoc.id}
>
{blockedDoc !== null && replacingDocId === blockedDoc.id ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{tj('replace_uploading')}
</>
) : (
tj('remove_blocked_replace_cta')
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</DialogContent>
</Dialog>
)
}
@@ -1,257 +0,0 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { useBookingTemplates } from '@/lib/reference-data/hooks'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useToast } from '@/components/ui/use-toast'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog'
import { BookOpen, Search, Users, Globe, Briefcase } from 'lucide-react'
import { TEMPLATE_CATEGORY_LABELS, SCOPE_LABELS, getTemplateScope, applyTemplate } from '@/lib/bookkeeping/template-library'
import type { BookingTemplateCategory, EntityType } from '@/types'
import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
// Statutory short forms, kept in Swedish in both locales.
const ENTITY_SHORT_LABELS: Record<EntityType, string> = {
enskild_firma: 'EF',
aktiebolag: 'AB',
ideell_forening: 'Förening',
}
interface Props {
onApply: (lines: FormLine[], description: string, category?: BookingTemplateCategory) => void
entityType?: EntityType
/** Prefill the "total amount" field when the caller already knows it (e.g.
* booking from an underlag with a known total). The user can still edit it. */
defaultAmount?: number
}
const SCOPE_ICONS = {
system: Globe,
team: Users,
company: Briefcase,
} as const
export default function BookingTemplatePicker({ onApply, entityType, defaultAmount }: Props) {
const { toast } = useToast()
const [open, setOpen] = useState(false)
// Session-cached (lib/reference-data): the list is there on the first
// open and reopening costs no request; writes in the settings panel
// invalidate it.
const { templates, isLoading, error: templatesError } = useBookingTemplates()
const [search, setSearch] = useState('')
const [selectedCategory, setSelectedCategory] = useState<BookingTemplateCategory | 'all'>('all')
const [amount, setAmount] = useState('')
const [selectedId, setSelectedId] = useState<string | null>(null)
// Prefill the amount from the caller's known total each time the picker
// opens. Only when provided: callers without a known amount (e.g. the
// journal-entry form) keep the blank-then-type behaviour.
useEffect(() => {
if (open && defaultAmount != null && defaultAmount > 0) {
setAmount(String(Math.round(defaultAmount * 100) / 100))
}
}, [open, defaultAmount])
useEffect(() => {
if (open && templatesError) toast({ title: 'Kunde inte hämta mallar', variant: 'destructive' })
}, [open, templatesError, toast])
const filtered = useMemo(() => {
// Templates hidden for this company (opt-in via the settings panel)
// never surface in the picker; only settings shows them, for restore.
let result = templates.filter((t) => !t.is_hidden)
// Filter by entity type
if (entityType) {
result = result.filter((t) => t.entity_type === 'all' || t.entity_type === entityType)
}
// Filter by category
if (selectedCategory !== 'all') {
result = result.filter((t) => t.category === selectedCategory)
}
// Filter by search
if (search) {
const lower = search.toLowerCase()
result = result.filter(
(t) =>
t.name.toLowerCase().includes(lower) ||
t.description.toLowerCase().includes(lower),
)
}
return result
}, [templates, entityType, selectedCategory, search])
// Unique categories present in visible templates. Built from the
// hidden-filtered list so a category whose templates are all hidden does
// not render a chip that can only ever match nothing.
const availableCategories = useMemo(() => {
const cats = new Set(templates.filter((t) => !t.is_hidden).map((t) => t.category))
return Array.from(cats).sort()
}, [templates])
const selected = selectedId ? templates.find((t) => t.id === selectedId) : null
function handleApply() {
if (!selected) return
const totalAmount = parseFloat(amount)
if (!totalAmount || totalAmount <= 0) {
toast({ title: 'Ange belopp', description: 'Ange ett belopp för att använda mallen.', variant: 'destructive' })
return
}
const lines = applyTemplate(selected.lines, totalAmount)
// Fire-and-forget MRU bump so this template surfaces at the top next time.
fetch(`/api/settings/booking-templates/${selected.id}/touch`, { method: 'POST' }).catch(() => {})
onApply(lines, selected.name, selected.category)
setOpen(false)
setSelectedId(null)
setAmount('')
setSearch('')
}
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm" type="button">
<BookOpen className="h-3.5 w-3.5 mr-1.5" />
Använd mall
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl max-h-[80vh] flex flex-col">
<DialogHeader>
<DialogTitle>Bokföringsmallar</DialogTitle>
</DialogHeader>
{/* Search + category filter */}
<div className="flex flex-col gap-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Sök mall..."
className="pl-9"
autoFocus
/>
</div>
<div className="flex gap-1 flex-wrap">
<Button
variant={selectedCategory === 'all' ? 'default' : 'outline'}
size="sm"
onClick={() => setSelectedCategory('all')}
type="button"
>
Alla
</Button>
{availableCategories.map((cat) => (
<Button
key={cat}
variant={selectedCategory === cat ? 'default' : 'outline'}
size="sm"
onClick={() => setSelectedCategory(cat as BookingTemplateCategory)}
type="button"
>
{TEMPLATE_CATEGORY_LABELS[cat as BookingTemplateCategory]}
</Button>
))}
</div>
</div>
{/* Template list */}
<div className="flex-1 overflow-y-auto space-y-1 min-h-0">
{isLoading ? (
<p className="text-sm text-muted-foreground py-8 text-center">Laddar mallar...</p>
) : filtered.length === 0 ? (
<p className="text-sm text-muted-foreground py-8 text-center">Inga mallar hittades.</p>
) : (
filtered.map((t) => {
const scope = getTemplateScope(t)
const ScopeIcon = SCOPE_ICONS[scope]
const isSelected = selectedId === t.id
return (
<button
key={t.id}
type="button"
onClick={() => setSelectedId(isSelected ? null : t.id)}
className={`w-full text-left rounded-lg border p-3 transition-colors ${
isSelected
? 'border-primary bg-primary/5'
: 'border-border hover:border-primary/40 hover:bg-muted/50'
}`}
>
<div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0">
<div className="font-medium text-sm">{t.name}</div>
<div className="flex items-center gap-1 text-[11px] text-muted-foreground mt-0.5">
<ScopeIcon className="h-3 w-3 shrink-0" />
<span>
{SCOPE_LABELS[scope]}
{t.entity_type !== 'all' && ` · ${ENTITY_SHORT_LABELS[t.entity_type] ?? t.entity_type}`}
</span>
</div>
{t.description && (
<p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
{t.description}
</p>
)}
</div>
</div>
{/* Show lines preview when selected */}
{isSelected && (
<div className="mt-2 pt-2 border-t space-y-1">
{t.lines.map((line, i) => (
<div key={i} className="flex items-center gap-2 text-xs font-mono text-muted-foreground">
<span className="w-10">{line.account}</span>
<span className="flex-1 truncate">{line.label}</span>
<span className={line.side === 'debit' ? 'text-foreground' : ''}>
{line.side === 'debit' ? (line.type === 'vat' && line.vat_rate ? `${(line.vat_rate * 100).toFixed(0)}% moms` : 'D') : ''}
</span>
<span className={line.side === 'credit' ? 'text-foreground' : ''}>
{line.side === 'credit' ? (line.type === 'vat' && line.vat_rate ? `${(line.vat_rate * 100).toFixed(0)}% moms` : 'K') : ''}
</span>
</div>
))}
</div>
)}
</button>
)
})
)}
</div>
{/* Apply section */}
{selected && (
<div className="flex items-end gap-3 pt-3 border-t">
<div className="flex-1">
<label className="text-xs font-medium text-muted-foreground mb-1 block">
Totalt belopp (inkl. moms)
</label>
<Input
type="number"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="0,00"
min="0"
step="0.01"
inputMode="decimal"
autoFocus
/>
</div>
<Button onClick={handleApply} type="button">
Använd mall
</Button>
</div>
)}
</DialogContent>
</Dialog>
)
}
@@ -1,961 +0,0 @@
'use client'
import { Fragment, useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { SegmentedControl } from '@/components/ui/segmented-control'
import { ToolbarSearch } from '@/components/ui/toolbar-search'
import { Switch } from '@/components/ui/switch'
import { Skeleton } from '@/components/ui/skeleton'
import { TH_CLASS, TD_CLASS, QUIET_LINK_CLASS, CHECKBOX_REVEAL_CLASS } from '@/components/ui/dry-table'
import { Checkbox } from '@/components/ui/checkbox'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { useToast } from '@/components/ui/use-toast'
import { AccountNumber } from '@/components/ui/account-number'
import {
DestructiveConfirmDialog,
useDestructiveConfirm,
} from '@/components/ui/destructive-confirm-dialog'
import { AddAccountDialog } from './AddAccountDialog'
import { EditAccountDialog } from './EditAccountDialog'
import { PruneAccountsDialog } from './PruneAccountsDialog'
import {
ChevronRight,
ListFilter,
Plus,
Pencil,
Trash2,
Loader2,
CheckCircle2,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import type { BASAccount } from '@/types'
import { useCompanySettings } from '@/lib/reference-data/hooks'
import type { BASReferenceAccount } from '@/lib/bookkeeping/bas-reference'
import { isStandardBASAccountNumber } from '@/lib/bookkeeping/bas-account-numbers'
import { ensureBasLoaded } from '@/lib/bookkeeping/bas-lazy'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface ReferenceAccount extends BASReferenceAccount {
is_activated: boolean
is_active: boolean
is_system_account: boolean
}
/**
* Column-header filter on "Verifikat" (#2186). "unused" means the account is
* absent from get_account_usage_counts, i.e. never posted to: the set a
* migrated chart wants pruned, since a short kontoplan is what keeps manual
* bookings off the wrong account.
*/
type UsageFilter = 'all' | 'unused' | 'used'
const USAGE_FILTER_KEY = {
all: 'usage_filter_all',
unused: 'usage_filter_unused',
used: 'usage_filter_used',
} as const
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
export default function ChartOfAccountsManager() {
const { toast } = useToast()
const t = useTranslations('chart_of_accounts')
const tNav = useTranslations('nav')
const tCommon = useTranslations('common')
const { dialogProps: confirmDialogProps, confirm } = useDestructiveConfirm()
const classLabel = (cls: number): string => {
if (cls < 1 || cls > 8) return ''
return t(`class_${cls}` as const)
}
const typeLabel = (type: string): string => {
const key = `type_${type}` as const
try {
return t(key)
} catch {
return type
}
}
// View state. Mina konton renders flat (concept scene 30), so its band
// rows track the classes the user has explicitly FOLDED AWAY; the BAS
// catalog (~1300 rows) keeps the inverse default and tracks the classes
// the user has opened.
const [view, setView] = useState<'my-accounts' | 'bas-catalog'>('my-accounts')
const [searchQuery, setSearchQuery] = useState('')
const [collapsedMyClasses, setCollapsedMyClasses] = useState<Set<number>>(new Set())
const [expandedCatalogClasses, setExpandedCatalogClasses] = useState<Set<number>>(new Set())
const [hideK2Excluded, setHideK2Excluded] = useState<boolean | null>(null)
const { settings: companySettings } = useCompanySettings()
// Off by default: the list endpoint's `?active=false` means "no filter", so
// leaving it off keeps first paint on the smaller active-only payload.
// A deactivated account is otherwise invisible everywhere and unrecoverable.
const [showInactive, setShowInactive] = useState(false)
const [usageFilter, setUsageFilter] = useState<UsageFilter>('all')
// Row selection for the bulk inactivate (#2186), keyed by account number
// (the PUT/deactivate routes key on it too). Cleared on view switch.
const [selectedNumbers, setSelectedNumbers] = useState<Set<string>>(new Set())
const [bulkDeactivating, setBulkDeactivating] = useState(false)
// The usage map loads after first paint; until it has, "utan verifikat"
// would match every account, so the filter stays disabled.
const [usageLoaded, setUsageLoaded] = useState(false)
// Data state
const [accounts, setAccounts] = useState<BASAccount[]>([])
const [referenceAccounts, setReferenceAccounts] = useState<ReferenceAccount[]>([])
const [usageCounts, setUsageCounts] = useState<Map<string, number>>(new Map())
const [loading, setLoading] = useState(true)
// The BAS catalog + K2 default are fetched lazily the first time the user
// opens that tab, so they never block the default "Mina konton" view.
const [referenceLoaded, setReferenceLoaded] = useState(false)
const [referenceLoading, setReferenceLoading] = useState(false)
// Dialog state
const [addDialogOpen, setAddDialogOpen] = useState(false)
const [editAccount, setEditAccount] = useState<BASAccount | null>(null)
const [pruneDialogOpen, setPruneDialogOpen] = useState(false)
// Action states
const [togglingAccount, setTogglingAccount] = useState<string | null>(null)
const [deletingAccount, setDeletingAccount] = useState<string | null>(null)
const [activatingAccounts, setActivatingAccounts] = useState<Set<string>>(new Set())
// -------------------------------------------
// Data fetching
// -------------------------------------------
// Read through a ref, not the state value: making fetchAccounts depend on
// showInactive would put it in the mount effect's dep list and re-run the
// whole blocking load on every toggle (the same double-fetch the comment
// below warns about for hideK2Excluded).
const showInactiveRef = useRef(showInactive)
showInactiveRef.current = showInactive
const fetchAccounts = useCallback(async () => {
// `?active=false` disables the filter entirely (active + inactive), it does
// not select inactive rows only — see list_company_accounts.
const res = await fetch(
showInactiveRef.current ? '/api/bookkeeping/accounts?active=false' : '/api/bookkeeping/accounts',
)
const { data } = await res.json()
setAccounts(data || [])
}, [])
// The server sends only the company's per-account activation status; the BAS
// catalog is static and already bundled here, so we merge client-side rather
// than re-download ~1,300 catalog rows on every load.
const fetchReference = useCallback(async () => {
const res = await fetch('/api/bookkeeping/accounts/reference')
const { data } = await res.json()
const userMap = new Map<string, { account_number: string; is_active: boolean; is_system_account: boolean }>(
(data || []).map(
(a: { account_number: string; is_active: boolean; is_system_account: boolean }) => [a.account_number, a],
),
)
// The full chart is a lazily loaded chunk: only the BAS-katalog tab pays
// for it, not every route that renders this component's parent.
const BAS_REFERENCE = await ensureBasLoaded()
const merged: ReferenceAccount[] = BAS_REFERENCE.map((ref) => {
const userAccount = userMap.get(ref.account_number)
return {
...ref,
is_activated: !!userAccount,
is_active: userAccount?.is_active ?? false,
is_system_account: userAccount?.is_system_account ?? false,
}
})
setReferenceAccounts(merged)
}, [])
// Per-account posting counts — drives the "Verifikat" column. Non-fatal:
// the page works without it, cells just show a dash.
const fetchUsage = useCallback(async () => {
try {
const res = await fetch('/api/bookkeeping/accounts/usage')
if (!res.ok) return
const { data } = await res.json()
setUsageCounts(
new Map(
(data || []).map((u: { account_number: string; usage_count: number }) => [
u.account_number,
Number(u.usage_count),
]),
),
)
setUsageLoaded(true)
} catch {
// Leave the map empty — usage display is informational only.
}
}, [])
// First paint blocks only on the user's own chart (the default view). Usage
// counts drive the informational "Verifikat" column and load in the
// background; the BAS catalog + K2 setting are deferred to tab open. This
// must NOT depend on hideK2Excluded: doing so re-ran the whole load a second
// time once the K2 default was set, doubling every fetch on each visit.
useEffect(() => {
let cancelled = false
async function load() {
setLoading(true)
await fetchAccounts()
if (!cancelled) setLoading(false)
}
load()
void fetchUsage()
return () => {
cancelled = true
}
}, [fetchAccounts, fetchUsage])
// Refetch when the inactive filter flips. Skips the first run (the mount
// effect above already fetched) and deliberately does not raise `loading`:
// swapping a filter should not blank the table back to the skeleton.
const showInactiveInitial = useRef(true)
useEffect(() => {
if (showInactiveInitial.current) {
showInactiveInitial.current = false
return
}
void fetchAccounts()
}, [showInactive, fetchAccounts])
// Loads the BAS catalog and the K2 default on demand, once, the first time
// the user opens the "BAS-katalog" tab.
const ensureReferenceLoaded = useCallback(async () => {
if (referenceLoaded || referenceLoading) return
setReferenceLoading(true)
try {
await Promise.all([
fetchReference(),
(async () => {
if (hideK2Excluded !== null) return
// Default to hiding K2-excluded accounts if the company uses K2
// (plan_type === 'k1'). Settings come from the session cache.
setHideK2Excluded(
(companySettings as { plan_type?: string } | null)?.plan_type === 'k1',
)
})(),
])
setReferenceLoaded(true)
} finally {
setReferenceLoading(false)
}
}, [referenceLoaded, referenceLoading, fetchReference, hideK2Excluded, companySettings])
const refreshAll = useCallback(async () => {
await Promise.all([
fetchAccounts(),
fetchUsage(),
// Only refresh the catalog if the user has actually opened that tab.
...(referenceLoaded ? [fetchReference()] : []),
])
}, [fetchAccounts, fetchUsage, fetchReference, referenceLoaded])
// -------------------------------------------
// Actions
// -------------------------------------------
async function toggleActive(account: BASAccount) {
// Deactivating an account that carries postings hides it from the
// kontoplan and from new verifikat while its balances stay in the books.
// That is legal and reversible, but it should never happen silently: it is
// what made a used account unreachable in the first place. The count is
// already in memory from fetchUsage, so no extra request.
const usage = usageCounts.get(account.account_number) ?? 0
if (account.is_active && usage > 0) {
const confirmed = await confirm({
title: t('deactivate_confirm_title', { number: account.account_number }),
description: t('deactivate_confirm', { count: usage }),
confirmLabel: t('deactivate_confirm_action'),
variant: 'warning',
})
if (!confirmed) return
}
setTogglingAccount(account.account_number)
try {
const res = await fetch(`/api/bookkeeping/accounts/${account.account_number}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ is_active: !account.is_active }),
})
if (!res.ok) throw new Error(t('toast_update_failed'))
await refreshAll()
} catch {
toast({ title: t('toast_update_failed'), variant: 'destructive' })
} finally {
setTogglingAccount(null)
}
}
// Bulk inactivate of the selection (#2186). Only never-used, non-system,
// active accounts go: a used account hides its balances from the kontoplan,
// so it keeps the per-row toggle with its own confirm. The route enforces
// the same partition server-side; the client partitions first so the
// confirm can say exactly what will and will not happen (convention 10).
async function bulkDeactivate() {
const byNumber = new Map(accounts.map((a) => [a.account_number, a]))
const unused: string[] = []
let used = 0
let system = 0
for (const number of selectedNumbers) {
const account = byNumber.get(number)
if (!account || !account.is_active) continue
if (account.is_system_account) {
system += 1
continue
}
if (usageCounts.has(number)) {
used += 1
continue
}
unused.push(number)
}
if (unused.length === 0) {
toast({ title: t('bulk_deactivate_none_unused') })
return
}
const skippedNote = [
used > 0 ? t('bulk_deactivate_skipped_used', { count: used }) : null,
system > 0 ? t('bulk_deactivate_skipped_system', { count: system }) : null,
]
.filter(Boolean)
.join(' ')
const confirmed = await confirm({
title: t('bulk_deactivate_confirm_title', { count: unused.length }),
description: [t('bulk_deactivate_confirm', { count: unused.length }), skippedNote]
.filter(Boolean)
.join(' '),
confirmLabel: t('deactivate_confirm_action'),
variant: 'warning',
})
if (!confirmed) return
setBulkDeactivating(true)
try {
const res = await fetch('/api/bookkeeping/accounts/deactivate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_numbers: unused }),
})
if (!res.ok) throw new Error(t('toast_update_failed'))
const body = (await res.json().catch(() => ({}))) as { deactivated?: number }
toast({ title: t('bulk_deactivate_done', { count: Number(body.deactivated ?? 0) }) })
setSelectedNumbers(new Set())
await refreshAll()
} catch {
toast({ title: t('toast_update_failed'), variant: 'destructive' })
} finally {
setBulkDeactivating(false)
}
}
async function deleteAccount(account: BASAccount) {
const confirmed = await confirm({
title: t('delete_confirm_title'),
description: t('delete_confirm', { number: account.account_number, name: account.account_name }),
confirmLabel: t('delete_confirm_action'),
cancelLabel: tCommon('cancel'),
})
if (!confirmed) return
setDeletingAccount(account.account_number)
try {
const res = await fetch(`/api/bookkeeping/accounts/${account.account_number}`, {
method: 'DELETE',
})
if (!res.ok) {
// The route answers thrown errors with the canonical envelope
// `{ error: { code, message } }`. `new Error(data.error)` would
// stringify that object to "[object Object]" and the reason would be
// lost; hand getErrorMessage the parsed body plus the status instead.
const body = await res.json().catch(() => null)
toast({
title: getUserErrorMessage(body, { statusCode: res.status }),
variant: 'destructive',
})
return
}
toast({ title: t('toast_account_deleted'), description: `${account.account_number} ${account.account_name}` })
await refreshAll()
} catch (err) {
toast({
title: err instanceof Error ? getUserErrorMessage(err) : t('toast_delete_failed'),
variant: 'destructive',
})
} finally {
setDeletingAccount(null)
}
}
async function activateBASAccount(accountNumber: string) {
setActivatingAccounts((prev) => new Set(prev).add(accountNumber))
try {
const res = await fetch('/api/bookkeeping/accounts/activate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account_numbers: [accountNumber] }),
})
if (!res.ok) throw new Error(t('toast_activate_failed'))
// `reactivated` covers an account the company already had but had turned
// off. Without it the catalog tab flipped the row back on in silence.
const { activated, reactivated } = await res.json()
if (activated > 0) {
toast({ title: t('toast_activated_title'), description: t('toast_activated_description', { number: accountNumber }) })
} else if (reactivated > 0) {
toast({ title: t('toast_reactivated_title'), description: t('toast_reactivated_description', { number: accountNumber }) })
}
await refreshAll()
} catch {
toast({ title: t('toast_activate_failed'), variant: 'destructive' })
} finally {
setActivatingAccounts((prev) => {
const next = new Set(prev)
next.delete(accountNumber)
return next
})
}
}
// -------------------------------------------
// Toggle class expansion (band rows)
// -------------------------------------------
function toggleMyClass(cls: number) {
setCollapsedMyClasses((prev) => {
const next = new Set(prev)
if (next.has(cls)) next.delete(cls)
else next.add(cls)
return next
})
}
function toggleCatalogClass(cls: number) {
setExpandedCatalogClasses((prev) => {
const next = new Set(prev)
if (next.has(cls)) next.delete(cls)
else next.add(cls)
return next
})
}
// -------------------------------------------
// Filtered & grouped data
// -------------------------------------------
const filteredAccounts = useMemo(() => {
const q = searchQuery.toLowerCase()
return accounts.filter((a) => {
if (q && !(a.account_number.includes(q) || a.account_name.toLowerCase().includes(q))) {
return false
}
// Absence from the usage map means never posted to (see /usage).
if (usageFilter === 'unused' && usageCounts.has(a.account_number)) return false
if (usageFilter === 'used' && !usageCounts.has(a.account_number)) return false
return true
})
}, [accounts, searchQuery, usageFilter, usageCounts])
const visibleNumbers = useMemo(
() => filteredAccounts.map((a) => a.account_number),
[filteredAccounts],
)
const allVisibleSelected =
visibleNumbers.length > 0 && visibleNumbers.every((n) => selectedNumbers.has(n))
const toggleSelect = (number: string) =>
setSelectedNumbers((prev) => {
const next = new Set(prev)
if (next.has(number)) next.delete(number)
else next.add(number)
return next
})
const toggleSelectAllVisible = () =>
setSelectedNumbers(allVisibleSelected ? new Set() : new Set(visibleNumbers))
const groupedAccounts = useMemo(() => {
const grouped: Record<number, BASAccount[]> = {}
for (const a of filteredAccounts) {
const cls = a.account_class
if (!grouped[cls]) grouped[cls] = []
grouped[cls].push(a)
}
return grouped
}, [filteredAccounts])
const filteredReference = useMemo(() => {
let filtered = referenceAccounts
if (hideK2Excluded) {
filtered = filtered.filter((a) => !a.k2_excluded)
}
if (searchQuery) {
const q = searchQuery.toLowerCase()
filtered = filtered.filter(
(a) => a.account_number.includes(q) || a.account_name.toLowerCase().includes(q)
)
}
return filtered
}, [referenceAccounts, searchQuery, hideK2Excluded])
const groupedReference = useMemo(() => {
const grouped: Record<number, ReferenceAccount[]> = {}
for (const a of filteredReference) {
const cls = a.account_class
if (!grouped[cls]) grouped[cls] = []
grouped[cls].push(a)
}
return grouped
}, [filteredReference])
// -------------------------------------------
// Render
// -------------------------------------------
const shownCount = view === 'my-accounts' ? filteredAccounts.length : filteredReference.length
const totalCount = view === 'my-accounts' ? accounts.length : referenceAccounts.length
// Page header + toolbar render even while loading so the chrome is stable.
const header = (
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<h1 className="font-display text-2xl leading-8 tracking-tight">{tNav('chart_of_accounts')}</h1>
<div className="flex items-center gap-4">
<Badge variant="outline" className="font-normal">{t('bas_version_chip')}</Badge>
<button type="button" className={QUIET_LINK_CLASS} onClick={() => setPruneDialogOpen(true)}>
{t('prune_button')}
</button>
<Button onClick={() => setAddDialogOpen(true)}>
<Plus className="mr-2 h-4 w-4" />
{t('add_own')}
</Button>
</div>
</div>
)
const switchView = (next: 'my-accounts' | 'bas-catalog') => {
setView(next)
setSelectedNumbers(new Set())
setCollapsedMyClasses(new Set())
setExpandedCatalogClasses(new Set())
if (next === 'bas-catalog') void ensureReferenceLoaded()
}
// Concept band row (Klass N: label), clickable to fold the class away.
// It carries no per-class counter: the old "{active}/{total} aktiva" was
// derived from the filtered list and read as full coverage under the
// Verifikat filter (#2263). Shown/total lives once, in the page footer.
const bandRow = (
cls: number,
open: boolean,
onToggle: () => void,
colSpan: number,
) => (
<tr key={`band-${cls}`}>
<td colSpan={colSpan} className="border-b border-border p-0">
<button
type="button"
onClick={onToggle}
aria-expanded={open}
className="flex w-full items-center gap-1.5 bg-muted/40 px-3 py-[7px] text-left text-[11px] font-semibold uppercase tracking-[0.06em] text-muted-foreground transition-colors duration-150 hover:bg-muted/60"
>
<ChevronRight className={cn('h-3 w-3 shrink-0 transition-transform duration-200', open && 'rotate-90')} />
{t('class_heading', { cls, label: classLabel(cls) })}
</button>
</td>
</tr>
)
return (
<div className="space-y-8">
{header}
{/* Toolbar: seg + search; the K2 filter rides far right in catalog view */}
<div className="flex flex-wrap items-center gap-2">
<SegmentedControl
value={view}
onChange={switchView}
options={[
{ value: 'my-accounts', label: t('tab_my_accounts'), count: accounts.length },
{ value: 'bas-catalog', label: t('tab_bas_catalog') },
]}
/>
<ToolbarSearch
placeholder={t('search_placeholder')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
containerClassName="min-w-[190px] max-w-xs flex-1"
/>
{view === 'my-accounts' && (
<label className="ml-auto flex items-center gap-2 text-sm">
<Switch
checked={showInactive}
onCheckedChange={setShowInactive}
className="scale-75"
/>
<span className="text-muted-foreground">{t('show_inactive')}</span>
</label>
)}
{view === 'bas-catalog' && (
<label className="ml-auto flex items-center gap-2 text-sm">
<Switch
checked={hideK2Excluded ?? false}
onCheckedChange={setHideK2Excluded}
className="scale-75"
/>
<span className="text-muted-foreground">{t('hide_k2_excluded')}</span>
</label>
)}
</div>
{loading ? (
<div className="space-y-2 py-2">
{[1, 2, 3, 4, 5, 6].map((i) => (
<Skeleton key={i} className="h-8 w-full" />
))}
</div>
) : view === 'my-accounts' ? (
filteredAccounts.length === 0 ? (
<p className="px-1 py-12 text-center text-sm text-muted-foreground">
{searchQuery || usageFilter !== 'all' ? t('no_matches') : t('no_accounts')}
</p>
) : (
<div>
{/* Bulk bar: appears with the first selection, carries the count
and the one action the selection exists for. */}
{selectedNumbers.size > 0 && (
<div className="flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-border px-1 py-2 text-[12.5px] animate-fade-in">
<span className="whitespace-nowrap">
<strong className="font-semibold tabular-nums">{selectedNumbers.size}</strong>{' '}
{t('bulkbar_selected', { count: selectedNumbers.size })}
</span>
<Button size="sm" onClick={bulkDeactivate} disabled={bulkDeactivating}>
{bulkDeactivating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t('deactivate_confirm_action')}
</Button>
{!allVisibleSelected && (
<button type="button" className={QUIET_LINK_CLASS} onClick={toggleSelectAllVisible}>
{t('bulk_select_all', { count: visibleNumbers.length })}
</button>
)}
<button
type="button"
className={QUIET_LINK_CLASS}
onClick={() => setSelectedNumbers(new Set())}
disabled={bulkDeactivating}
>
{t('bulk_clear_selection')}
</button>
</div>
)}
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={cn(TH_CLASS, 'w-[36px] pr-0')}>
<Checkbox
checked={allVisibleSelected}
onCheckedChange={toggleSelectAllVisible}
aria-label={t('select_all_aria')}
className="border-foreground"
/>
</th>
<th className={cn(TH_CLASS, 'w-[96px]')}>{t('col_account')}</th>
<th className={cn(TH_CLASS, 'w-full')}>{t('col_name')}</th>
<th className={cn(TH_CLASS, 'hidden text-right sm:table-cell')}>{t('col_sru')}</th>
<th className={cn(TH_CLASS, 'hidden md:table-cell')}>{t('col_type')}</th>
<th className={cn(TH_CLASS, 'hidden text-right sm:table-cell')}>
{/* The header is the filter (#2186): pick all / never
posted to / posted to, the way the verifikat list
filters from its headers. */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
type="button"
disabled={!usageLoaded}
aria-label={t('usage_filter_label')}
className={cn(
'inline-flex items-center gap-1 transition-colors duration-150 hover:text-foreground disabled:opacity-50',
usageFilter !== 'all' && 'text-foreground',
)}
>
{usageFilter === 'all' ? t('col_usage') : t(USAGE_FILTER_KEY[usageFilter])}
<ListFilter className="h-3 w-3" aria-hidden />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuRadioGroup
value={usageFilter}
onValueChange={(v) => setUsageFilter(v as UsageFilter)}
>
{(['all', 'unused', 'used'] as const).map((value) => (
<DropdownMenuRadioItem key={value} value={value}>
{t(USAGE_FILTER_KEY[value])}
</DropdownMenuRadioItem>
))}
</DropdownMenuRadioGroup>
</DropdownMenuContent>
</DropdownMenu>
</th>
<th className={TH_CLASS}>{t('col_active')}</th>
<th className={cn(TH_CLASS, 'w-[84px]')} aria-hidden="true"></th>
</tr>
</thead>
<tbody className="stagger-enter">
{Object.entries(groupedAccounts)
.sort(([a], [b]) => Number(a) - Number(b))
.map(([cls, classAccounts]) => {
const classNum = Number(cls)
const open = !collapsedMyClasses.has(classNum) || !!searchQuery
return (
<Fragment key={cls}>
{bandRow(classNum, open, () => toggleMyClass(classNum), 8)}
{open &&
classAccounts.map((account) => (
<tr
key={account.id}
className={cn(
'group transition-colors duration-150 hover:bg-secondary/35',
// Dim the text rather than the whole row: a
// row-level opacity would drag the "Inaktiv"
// chip below readable contrast with it.
!account.is_active && 'text-muted-foreground',
)}
>
<td className={cn(TD_CLASS, 'w-[36px] pr-0 py-[9px]')}>
<Checkbox
checked={selectedNumbers.has(account.account_number)}
onCheckedChange={() => toggleSelect(account.account_number)}
aria-label={t('select_row_aria', { number: account.account_number })}
className={cn(
'border-foreground',
CHECKBOX_REVEAL_CLASS,
selectedNumbers.has(account.account_number) && 'opacity-100',
)}
/>
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums')}>
<AccountNumber number={account.account_number} name={account.account_name} />
</td>
{/* overflow-hidden: see #2003, the shrink-0
markers cannot truncate. */}
<td className={cn(TD_CLASS, 'max-w-0 w-full overflow-hidden')}>
<span className="flex min-w-0 items-center gap-1.5">
<span className="truncate">{account.account_name}</span>
{account.is_system_account && (
<span className="shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">
{t('system_badge')}
</span>
)}
{!isStandardBASAccountNumber(account.account_number) && (
<span className="shrink-0 text-[10px] uppercase tracking-wider text-muted-foreground">
{t('own_badge')}
</span>
)}
{/* Exception chip: only visible while the
"Visa inaktiva" filter is on, so it never
lands on every row. */}
{!account.is_active && (
<Badge variant="secondary" className="shrink-0">
{t('prune_inactive_badge')}
</Badge>
)}
</span>
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-right tabular-nums text-muted-foreground sm:table-cell')}>
{account.sru_code || ''}
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-muted-foreground md:table-cell')}>
{typeLabel(account.account_type)}
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-right tabular-nums text-muted-foreground sm:table-cell')}>
{usageCounts.get(account.account_number) ?? ''}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap py-[9px]')}>
<Switch
checked={account.is_active}
onCheckedChange={() => toggleActive(account)}
disabled={togglingAccount === account.account_number}
aria-label={t('col_active') + ' ' + account.account_number}
className="scale-75"
/>
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right py-[5px]')}>
<span
className={cn(
'inline-flex items-center justify-end gap-1 transition-opacity duration-150',
'opacity-0 focus-within:opacity-100 group-hover:opacity-100',
)}
>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
aria-label={tCommon('edit')}
onClick={() => setEditAccount(account)}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
{!account.is_system_account && (
<Button
variant="ghost"
size="icon"
className="h-8 w-8 text-destructive hover:text-destructive"
aria-label={t('delete_confirm_action')}
onClick={() => deleteAccount(account)}
disabled={deletingAccount === account.account_number}
>
{deletingAccount === account.account_number ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="h-3.5 w-3.5" />
)}
</Button>
)}
</span>
</td>
</tr>
))}
</Fragment>
)
})}
</tbody>
</table>
</div>
</div>
)
) : (
<div>
{referenceLoading && referenceAccounts.length === 0 ? (
<div className="space-y-2 py-2">
{[1, 2, 3, 4, 5, 6].map((i) => (
<Skeleton key={i} className="h-8 w-full" />
))}
</div>
) : filteredReference.length === 0 ? (
<p className="px-1 py-12 text-center text-sm text-muted-foreground">{t('no_matches')}</p>
) : (
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={cn(TH_CLASS, 'w-[96px]')}>{t('col_account')}</th>
<th className={cn(TH_CLASS, 'w-full')}>{t('col_name')}</th>
<th className={cn(TH_CLASS, 'hidden text-right sm:table-cell')}>{t('col_sru')}</th>
<th className={cn(TH_CLASS, 'hidden md:table-cell')}>{t('col_type')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('col_status')}</th>
</tr>
</thead>
<tbody className="stagger-enter">
{Object.entries(groupedReference)
.sort(([a], [b]) => Number(a) - Number(b))
.map(([cls, classAccounts]) => {
const classNum = Number(cls)
const open = expandedCatalogClasses.has(classNum) || !!searchQuery
return (
<Fragment key={cls}>
{bandRow(classNum, open, () => toggleCatalogClass(classNum), 5)}
{open &&
classAccounts.map((account) => (
<tr
key={account.account_number}
className="group transition-colors duration-150 hover:bg-secondary/35"
>
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums')}>
<AccountNumber number={account.account_number} name={account.account_name} />
</td>
<td
className={cn(TD_CLASS, 'max-w-0 w-full')}
title={account.description || undefined}
>
<span className="block truncate">{account.account_name}</span>
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-right tabular-nums text-muted-foreground sm:table-cell')}>
{account.sru_code || ''}
</td>
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap text-muted-foreground md:table-cell')}>
{typeLabel(account.account_type)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right py-[9px]')}>
{/* An account the company holds but has
deactivated is NOT activated: it falls
through to the button, relabelled so the
user sees it is coming back, not new. */}
{account.is_activated && account.is_active ? (
<span className="inline-flex items-center gap-1 text-xs text-success">
<CheckCircle2 className="h-3.5 w-3.5" />
{t('activated')}
</span>
) : (
<Button
variant="outline"
size="sm"
className="h-7 px-3.5 text-xs"
onClick={() => activateBASAccount(account.account_number)}
disabled={activatingAccounts.has(account.account_number)}
>
{activatingAccounts.has(account.account_number) ? (
<Loader2 className="mr-1 h-3 w-3 animate-spin" />
) : (
<Plus className="mr-1 h-3 w-3" />
)}
{account.is_activated ? t('reactivate') : t('add')}
</Button>
)}
</td>
</tr>
))}
</Fragment>
)
})}
</tbody>
</table>
</div>
)}
</div>
)}
{/* Footer note (concept pgnote) */}
{!loading && totalCount > 0 && (
<p className="px-1 text-xs text-muted-foreground">
{t('footer_note', { shown: shownCount, total: totalCount })}
</p>
)}
{/* Dialogs */}
<DestructiveConfirmDialog {...confirmDialogProps} />
<AddAccountDialog
open={addDialogOpen}
onOpenChange={setAddDialogOpen}
onCreated={refreshAll}
/>
<PruneAccountsDialog
open={pruneDialogOpen}
onOpenChange={setPruneDialogOpen}
onPruned={refreshAll}
/>
{editAccount && (
<EditAccountDialog
open={!!editAccount}
onOpenChange={(open) => { if (!open) setEditAccount(null) }}
account={editAccount}
onSaved={refreshAll}
/>
)}
</div>
)
}
@@ -1,156 +0,0 @@
'use client'
import { useState, useEffect } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import RattelseExplainer from '@/components/bookkeeping/RattelseExplainer'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { JournalEntry } from '@/types'
interface Props {
entry: JournalEntry
open: boolean
onOpenChange: (open: boolean) => void
onCorrected: () => void
}
/**
* Metadata rättelse (BFL 5 kap 9 §): correct the verifikationstext and/or
* the date (within the same fiscal period) of a posted verifikat without an
* ändringsverifikation. Who/when is recorded in the immutable rättelse log
* and shown in the verifikat's history. Stays Swedish (verifikat surface,
* .claude/rules/i18n.md).
*/
export default function CorrectMetadataDialog({ entry, open, onOpenChange, onCorrected }: Props) {
const { toast } = useToast()
const [description, setDescription] = useState('')
const [entryDate, setEntryDate] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
useEffect(() => {
if (open) {
setDescription(entry.description || '')
setEntryDate(entry.entry_date?.slice(0, 10) || '')
}
}, [open, entry.id]) // eslint-disable-line react-hooks/exhaustive-deps
const descriptionChanged = description.trim() !== (entry.description || '')
const dateChanged = entryDate !== (entry.entry_date?.slice(0, 10) || '')
const hasChange = (descriptionChanged && description.trim().length > 0) || (dateChanged && entryDate.length > 0)
async function handleSubmit() {
if (!hasChange) return
setIsSubmitting(true)
try {
const payload: { description?: string; entry_date?: string } = {}
if (descriptionChanged && description.trim().length > 0) payload.description = description.trim()
if (dateChanged && entryDate.length > 0) payload.entry_date = entryDate
const res = await fetch(`/api/bookkeeping/journal-entries/${entry.id}/correct-metadata`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
})
const result = await res.json()
if (!res.ok) {
const error = new Error('Failed to correct metadata') as Error & { body?: unknown; status?: number }
error.body = result
error.status = res.status
throw error
}
toast({
title: 'Verifikationen rättad',
description: 'Ändringen har loggats i verifikatets rättelsehistorik.',
})
onOpenChange(false)
onCorrected()
} catch (err) {
const anyErr = err as { body?: unknown; status?: number }
toast({
title: 'Kunde inte rätta verifikationen',
description: getErrorMessage(anyErr.body ?? err, { context: 'journal_entry', statusCode: anyErr.status }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
{/* Convention 7: the how-it-works copy lives behind the "?", not in
the dialog flow. */}
<div className="flex items-center gap-2">
<DialogTitle>Ändra text eller datum</DialogTitle>
<RattelseExplainer>
<p>
Verifikationstexten och datumet kan rättas här utan
ändringsverifikation.
</p>
<p>
Varje rättelse loggas med vem och när, och det ursprungliga
innehållet förblir synligt i verifikatets rättelsehistorik.
</p>
<p>
Om månaden redan är momsdeklarerad kan en datumflytt påverka
den inlämnade deklarationen.
</p>
</RattelseExplainer>
</div>
<DialogDescription>
Datumet kan bara flyttas inom samma bokföringsperiod: använd
&quot;Flytta till annat datum&quot; för att byta period.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1">
<Label htmlFor="rattelse-description">Verifikationstext</Label>
<Input
id="rattelse-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
maxLength={500}
/>
</div>
<div className="space-y-1">
<Label htmlFor="rattelse-date">Datum</Label>
<Input
id="rattelse-date"
type="date"
value={entryDate}
onChange={(e) => setEntryDate(e.target.value)}
disabled={['storno', 'opening_balance', 'year_end'].includes(entry.source_type)}
/>
{['storno', 'opening_balance', 'year_end'].includes(entry.source_type) && (
<p className="text-xs text-muted-foreground">
Datumet på den här verifikationstypen kan inte ändras.
</p>
)}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
Avbryt
</Button>
<Button onClick={handleSubmit} disabled={!hasChange || isSubmitting}>
{isSubmitting ? 'Rättar...' : 'Spara rättelse'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,382 +0,0 @@
'use client'
import { useEffect, useMemo, useState, useCallback } from 'react'
import Link from 'next/link'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { getBasLoadedByNumber } from '@/lib/bookkeeping/bas-lazy'
import { useBasReference } from '@/lib/bookkeeping/use-bas-reference'
import OpeningBalanceRowEditor, {
type EditableRow,
type OpeningBalanceEditorState,
} from '@/components/import/OpeningBalanceRowEditor'
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
import type { JournalEntry, JournalEntryLine } from '@/types'
interface Props {
/** The currently-linked, posted opening-balance verifikat being corrected. */
entry: JournalEntry
open: boolean
onOpenChange: (open: boolean) => void
onCorrected: () => void
}
interface CascadeSummary {
corrected: Array<{ fiscal_period_id: string; period_name: string | null }>
skipped: Array<{ fiscal_period_id: string; period_name: string | null; reason: string }>
/** The cascade itself failed to run: later years are unverified. */
failed?: boolean
}
/** Error codes where the year itself blocks the correction: guide the user
* to the earliest open year instead of leaving them at a dead end. */
const BLOCKED_PERIOD_CODES = new Set([
'OB_PERIOD_CLOSED',
'OB_PERIOD_LOCKED',
'OB_COMPANY_LOCK_DATE',
'OB_CORRECT_YEAR_END_EXISTS',
])
let seedIdCounter = 0
// Map the booked IB's lines into editable rows. account_name isn't stored on
// the line, so resolve it from BAS for display (cosmetic: only account_number
// + amounts are sent on save). The chart is a lazily loaded chunk: the
// caller re-seeds once it has arrived.
function seedRowsFromEntry(entry: JournalEntry): EditableRow[] {
const lines = ((entry.lines || []) as JournalEntryLine[])
.slice()
.sort((a, b) => a.sort_order - b.sort_order)
return lines.map((l) => {
const bas = getBasLoadedByNumber(l.account_number)
return {
id: l.id || `seed_${++seedIdCounter}`,
account_number: l.account_number,
account_name: bas?.account_name ?? '',
debit_amount: Number(l.debit_amount) || 0,
credit_amount: Number(l.credit_amount) || 0,
validation_errors: [],
bas_match: bas?.account_name ?? null,
}
})
}
/**
* Inline correction of an already-booked opening-balance verifikat. The user
* edits the IB's lines directly; on save we POST to
* /api/import/opening-balance/correct, which (BFL-compliant) stornoes the old
* IB, books a corrected one, and relinks the period to it. Works regardless of
* how the IB was created (SIE import, CSV/Excel import, or year-end carry).
*
* SIE migrations book one IB verifikat per imported year, so later years'
* saldon build on this one. When later years have their own IB verifikat the
* dialog offers to cascade the same change to them (checked by default); the
* server skips years that are locked, closed, or have a bokslut.
*/
export default function CorrectOpeningBalanceDialog({
entry,
open,
onOpenChange,
onCorrected,
}: Props) {
const { toast } = useToast()
const basReady = useBasReference()
// basReady is a re-seed trigger: names fill in once the chart chunk lands.
// eslint-disable-next-line react-hooks/exhaustive-deps
const initialRows = useMemo(() => seedRowsFromEntry(entry), [entry, basReady])
const [state, setState] = useState<OpeningBalanceEditorState | null>(null)
const [isSubmitting, setIsSubmitting] = useState(false)
const [cascade, setCascade] = useState(true)
const [showBlockedGuidance, setShowBlockedGuidance] = useState(false)
// Shared reference cache: drives the later-years checkbox and the
// blocked-year guidance. Best-effort: the dialog works while it loads
// (the server remains the authority on what is correctable).
const { periods } = useFiscalPeriods()
// A fresh open starts without the server-refusal guidance from a prior try.
useEffect(() => {
if (open) setShowBlockedGuidance(false)
}, [open])
const currentPeriod = useMemo(
() => periods.find((p) => p.id === entry.fiscal_period_id) ?? null,
[periods, entry.fiscal_period_id],
)
/** Later years with their own linked IB verifikat: the cascade targets. */
const laterPeriodsWithIB = useMemo(() => {
if (!currentPeriod) return []
return periods
.filter(
(p) =>
p.period_start > currentPeriod.period_start && p.opening_balance_entry_id !== null,
)
.sort((a, b) => a.period_start.localeCompare(b.period_start))
}, [periods, currentPeriod])
/** Earliest year that still accepts corrections: the guidance target when
* this year is locked. Client-side approximation; the server re-checks. */
const earliestOpenPeriod = useMemo(() => {
return (
[...periods]
.sort((a, b) => a.period_start.localeCompare(b.period_start))
.find((p) => !p.is_closed && !p.locked_at && p.opening_balance_entry_id !== null) ?? null
)
}, [periods])
const currentPeriodBlocked =
currentPeriod !== null && (currentPeriod.is_closed || currentPeriod.locked_at !== null)
const guidancePeriod =
earliestOpenPeriod && earliestOpenPeriod.id !== entry.fiscal_period_id
? earliestOpenPeriod
: null
const handleSubmit = useCallback(async () => {
if (!state?.canSubmit || isSubmitting) return
setIsSubmitting(true)
try {
// Diff the edited rows against the booked lines: only changed rows are
// struck and re-added (inline rättelse in the SAME verifikat, no
// storno). Untouched rows keep their ids, descriptions and dimensions.
const originalLines = ((entry.lines || []) as JournalEntryLine[])
const rowById = new Map(state.rows.map((r) => [r.id, r]))
const strike_line_ids: string[] = []
const new_lines: Array<{
account_number: string
debit_amount: number
credit_amount: number
line_description?: string
dimensions?: Record<string, string>
}> = []
for (const orig of originalLines) {
const row = orig.id ? rowById.get(orig.id) : undefined
if (!row || (row.debit_amount <= 0 && row.credit_amount <= 0)) {
// Row removed or zeroed out by the user: strike without replacement.
if (orig.id) strike_line_ids.push(orig.id)
continue
}
const changed =
row.account_number !== orig.account_number ||
row.debit_amount !== (Number(orig.debit_amount) || 0) ||
row.credit_amount !== (Number(orig.credit_amount) || 0)
if (changed && orig.id) {
strike_line_ids.push(orig.id)
new_lines.push({
account_number: row.account_number,
debit_amount: row.debit_amount,
credit_amount: row.credit_amount,
line_description:
row.account_number === orig.account_number
? orig.line_description ?? undefined
: `IB ${row.account_number}`,
dimensions: orig.dimensions,
})
}
}
const originalIds = new Set(originalLines.map((l) => l.id))
for (const row of state.rows) {
if (originalIds.has(row.id)) continue
if (row.debit_amount <= 0 && row.credit_amount <= 0) continue
new_lines.push({
account_number: row.account_number,
debit_amount: row.debit_amount,
credit_amount: row.credit_amount,
line_description: `IB ${row.account_number}`,
})
}
if (strike_line_ids.length === 0 && new_lines.length === 0) {
toast({ title: 'Inga ändringar att spara' })
setIsSubmitting(false)
return
}
const res = await fetch('/api/import/opening-balance/correct-inline', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
// cascade is ALWAYS sent (default on): if the reference cache has not
// loaded yet the checkbox is simply not shown, and omitting the flag
// in that window would silently leave later years stale. The server
// returns an empty cascade result when no later period exists.
body: JSON.stringify({
fiscal_period_id: entry.fiscal_period_id,
strike_line_ids,
new_lines,
cascade,
}),
})
const result = await res.json()
if (!res.ok) {
const err = new Error('Failed to correct opening balances') as Error & {
body?: unknown
status?: number
}
err.body = result
err.status = res.status
throw err
}
const cascadeSummary = (result?.data?.cascade ?? null) as CascadeSummary | null
let description = 'Beloppen uppdaterades direkt i verifikationen. Ingen ny verifikation skapades.'
if (cascadeSummary) {
const done = cascadeSummary.corrected.length
// Blocked (locked/closed/bokslut) and failed skips are different
// situations for the user: blocked is expected and needs no action
// here; failed means the year was left untouched and needs a look.
const blocked = cascadeSummary.skipped.filter(
(s) => s.reason === 'closed' || s.reason === 'locked' || s.reason === 'lock_date' || s.reason === 'year_end',
)
const failed = cascadeSummary.skipped.filter(
(s) => s.reason === 'correction_failed' || s.reason === 'validation_failed',
)
if (done > 0) {
description += ` ${done} senare räkenskapsår uppdaterades också.`
}
if (blocked.length > 0) {
const names = blocked.map((s) => s.period_name).filter(Boolean).join(', ')
description += ` ${blocked.length} år hoppades över (låsta, stängda eller med bokslut)${names ? `: ${names}` : ''}.`
}
if (failed.length > 0) {
const names = failed.map((s) => s.period_name).filter(Boolean).join(', ')
description += ` ${failed.length} år kunde inte uppdateras och behöver kontrolleras${names ? `: ${names}` : ''}.`
}
if (cascadeSummary.failed) {
description +=
' Uppdateringen av senare räkenskapsår kunde inte genomföras: kontrollera deras ingående balanser.'
}
}
toast({ title: 'Ingående balanser korrigerade', description })
// The correction relinks fiscal_periods.opening_balance_entry_id (for
// every cascaded year too): refresh the shared reference cache.
await invalidateReferenceData('ref:fiscal-periods')
onOpenChange(false)
onCorrected()
} catch (err) {
const anyErr = err as { body?: unknown; status?: number }
const code = (anyErr.body as { error?: { code?: string } } | undefined)?.error?.code
if (code && BLOCKED_PERIOD_CODES.has(code)) {
setShowBlockedGuidance(true)
}
toast({
title: 'Kunde inte korrigera ingående balanser',
description: getErrorMessage(anyErr.body ?? err, {
context: 'journal_entry',
statusCode: anyErr.status,
}),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}, [state, isSubmitting, entry.fiscal_period_id, entry.lines, cascade, toast, onOpenChange, onCorrected])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Korrigera ingående balanser</DialogTitle>
<DialogDescription>
Ändra beloppen nedan och spara. Verifikationen (
<span data-ph-mask="">{formatVoucher(entry)}</span>) uppdateras direkt: ingen ny
verifikation skapas.
</DialogDescription>
</DialogHeader>
{/* Inline rättelse (BFL 5 kap 5 §): edited in place, original logged */}
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
<p className="text-sm text-muted-foreground">
Ändringen sparas som en spårbar rättelse i samma verifikation (Bokföringslagen 5 kap
5 §): de ursprungliga raderna bevaras i rättelseloggen.
</p>
</div>
{/* Blocked-year guidance: shown when this year is (or the server says
it is) locked, closed, or has a bokslut. Instead of a dead end,
point at the earliest year that still accepts corrections. */}
{(currentPeriodBlocked || showBlockedGuidance) && (
<div className="rounded-lg border border-border bg-muted/30 px-4 py-3 space-y-1">
<p className="text-sm">
Det här räkenskapsåret är låst, stängt eller har ett bokslut, så dess ingående
balanser kan inte korrigeras här.
</p>
{guidancePeriod ? (
<p className="text-sm">
Korrigera i stället ingående balansen för{' '}
<Link
href={`/bookkeeping/${guidancePeriod.opening_balance_entry_id}`}
className="underline underline-offset-2"
>
{guidancePeriod.name || guidancePeriod.period_start.slice(0, 4)}
</Link>
, det tidigaste öppna året. Då blir saldona rätt framåt. Tidigare, låsta år är
normalt redan deklarerade sedan tidigare; behöver ett sådant år ändå rättas
måste det först låsas upp.
</p>
) : (
<p className="text-sm text-muted-foreground">
För att korrigera behöver året först låsas upp (eller bokslutet återföras) under
Bokföring → Räkenskapsår.
</p>
)}
</div>
)}
<OpeningBalanceRowEditor initialRows={initialRows} onChange={setState} />
{/* Cascade opt-out: later years imported from SIE carry their own IB
verifikat with the old figures; without this they stay wrong. */}
{laterPeriodsWithIB.length > 0 && (
<label className="flex items-start gap-3 rounded-lg border border-border px-4 py-3 cursor-pointer">
<Checkbox
checked={cascade}
onCheckedChange={(v) => setCascade(v === true)}
className="mt-0.5"
/>
<span className="space-y-1">
<span className="block text-sm">
Uppdatera även senare räkenskapsår ({laterPeriodsWithIB.length})
</span>
<span className="block text-sm text-muted-foreground">
Samma ändring förs in i senare års ingående balanser så att saldona stämmer
framåt, utan nya verifikat. År som är låsta eller har bokslut hoppas över.
Avser rättelsen ett tidigare års resultat (t.ex. konto 2099) kan en omföring
till balanserat resultat fortfarande behöva bokföras som vanligt.
</span>
</span>
</label>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
Avbryt
</Button>
<Button onClick={handleSubmit} disabled={!state?.canSubmit || isSubmitting}>
{isSubmitting ? 'Sparar...' : 'Korrigera ingående balanser'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,95 +0,0 @@
'use client'
/**
* Lazy entry point for CorrectionEntryDialog when the user is not on the
* /bookkeeping/[id] page (e.g. invoice detail, transaction row). Renders a
* trigger (button or link slot) that, on click, fetches the journal entry
* with its lines and opens the existing CorrectionEntryDialog.
*
* Used by:
* - /invoices/[id] when invoice.journal_entry_id is set
* - /transactions row menu when transaction.journal_entry_id is set
*
* Surfacing the storno+rättelse flow at the point where users notice the
* mistake matters: the dialog itself was already correct (it pre-fills
* lines and emits the storno+correction pair per BFL), but it was hidden
* behind a deep-link the customer never reached.
*/
import { useState } from 'react'
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { JournalEntry } from '@/types'
interface Props {
journalEntryId: string
onCorrected?: () => void
/**
* Render prop: receives the click handler and current loading state.
* Letting the caller render its own trigger keeps the affordance visually
* native to its host page (link on invoice detail, menu item in dropdown).
*/
children: (args: { open: () => void; isLoading: boolean }) => React.ReactNode
}
export default function CorrectionAffordance({ journalEntryId, onCorrected, children }: Props) {
const { toast } = useToast()
const [entry, setEntry] = useState<JournalEntry | null>(null)
const [open, setOpen] = useState(false)
const [isLoading, setIsLoading] = useState(false)
async function handleOpen() {
if (isLoading) return
setIsLoading(true)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${journalEntryId}`)
const json = await res.json()
if (!res.ok) {
toast({
title: 'Kunde inte hämta verifikationen',
description: getErrorMessage(json, { context: 'journal_entry', statusCode: res.status }),
variant: 'destructive',
})
return
}
const fetched = json.data as JournalEntry
if (fetched.status !== 'posted') {
toast({
title: 'Verifikationen kan inte ändras',
description:
'Endast bokförda verifikationer kan rättas. Utkast hanteras direkt under bokföringen.',
variant: 'destructive',
})
return
}
setEntry(fetched)
setOpen(true)
} catch (err) {
toast({
title: 'Kunde inte hämta verifikationen',
description: getErrorMessage(err, { context: 'journal_entry' }),
variant: 'destructive',
})
} finally {
setIsLoading(false)
}
}
return (
<>
{children({ open: handleOpen, isLoading })}
{entry && (
<CorrectionEntryDialog
entry={entry}
open={open}
onOpenChange={setOpen}
onCorrected={() => {
setOpen(false)
setEntry(null)
onCorrected?.()
}}
/>
)}
</>
)
}
@@ -1,85 +0,0 @@
'use client'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { Badge } from '@/components/ui/badge'
import JournalEntryStatusBadge from '@/components/bookkeeping/JournalEntryStatusBadge'
import { formatDate, formatCurrency, cn } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import type { JournalEntry, JournalEntryLine } from '@/types'
interface Props {
currentEntryId: string
chain: JournalEntry[]
}
function useGetRole() {
const t = useTranslations('journal_correction')
return (entry: JournalEntry): string => {
if (entry.source_type === 'storno') return t('role_storno')
if (entry.source_type === 'correction') return t('role_correction')
return t('role_original')
}
}
function getTotal(entry: JournalEntry): number {
const lines = (entry.lines || []) as JournalEntryLine[]
return lines.reduce((sum, l) => sum + (Number(l.debit_amount) || 0), 0)
}
/**
* The storno/rättelse chain as a flat chronological list: one hairline row
* per verifikat (role, voucher, date, description, amount). The page owns the
* kicker and puts the explanatory copy behind its "?" (convention 7), so this
* renders no heading and no info box of its own.
*/
export default function CorrectionChain({ currentEntryId, chain }: Props) {
const t = useTranslations('journal_correction')
const getRole = useGetRole()
if (chain.length === 0) return null
// Combine current entry isn't in chain: chain is "other" entries
// Sort chronologically
const sorted = [...chain].sort(
(a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
)
return (
<ul className="divide-y divide-border text-sm">
{sorted.map((entry) => {
const total = getTotal(entry)
const isCurrent = entry.id === currentEntryId
// A cancelled entry is residue from an aborted correction attempt:
// it was voided before taking effect and its lines were removed, so
// it always sums to 0,00. Without the status chip it renders exactly
// like a live storno: dim it and say what it is. Live rows carry no
// chip at all (chips mark exceptions); the role label says storno
// or rättelse.
const isCancelled = entry.status === 'cancelled'
return (
<li
key={entry.id}
className={cn('flex flex-wrap items-center gap-x-4 gap-y-1 py-2', isCancelled && 'opacity-60')}
>
<span className="w-16 shrink-0 text-xs text-muted-foreground">{getRole(entry)}</span>
{isCurrent ? (
<span className="tabular-nums">{formatVoucher(entry)}</span>
) : (
<Link href={`/bookkeeping/${entry.id}`} className="tabular-nums hover:underline">
{formatVoucher(entry)}
</Link>
)}
<span className="tabular-nums text-muted-foreground">{formatDate(entry.entry_date)}</span>
{entry.description && (
<span className="min-w-0 flex-1 truncate text-muted-foreground">{entry.description}</span>
)}
{isCancelled && <JournalEntryStatusBadge entry={entry} />}
{isCurrent && <Badge variant="outline">{t('current')}</Badge>}
<span className="ml-auto tabular-nums text-muted-foreground">{formatCurrency(total)}</span>
</li>
)
})}
</ul>
)
}
@@ -1,491 +0,0 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import RattelseExplainer from '@/components/bookkeeping/RattelseExplainer'
import { AddAccountDialog } from '@/components/bookkeeping/AddAccountDialog'
import CorrectionPreview from '@/components/bookkeeping/CorrectionPreview'
import {
autoCorrectionDescription,
correctionDescriptionForSubmit,
} from '@/components/bookkeeping/correction-entry-description'
import { nextLineDescriptionForAccountChange } from '@/components/bookkeeping/correction-line-description'
import { useToast } from '@/components/ui/use-toast'
import { useAccounts } from '@/lib/reference-data/hooks'
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { Loader2, Plus, Trash2 } from 'lucide-react'
import { formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import {
changeCorrectionLineAccount,
getSelectableCorrectionCatalog,
} from '@/lib/bookkeeping/correction-line-account'
import { splitCreateAccountPrefill } from '@/lib/bookkeeping/create-account-prefill'
import { loadBasCatalog, type CatalogAccount } from '@/lib/bookkeeping/bas-catalog-client'
import type { JournalEntry, JournalEntryLine } from '@/types'
interface CorrectionLine {
account_number: string
debit_amount: string
credit_amount: string
line_description: string
}
interface Props {
entry: JournalEntry
open: boolean
onOpenChange: (open: boolean) => void
onCorrected: () => void
}
export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCorrected }: Props) {
const { toast } = useToast()
const router = useRouter()
const t = useTranslations('journal_detail')
// The full chart (deactivated rows included) comes from the session cache
// (lib/reference-data); only the static BAS catalogue is loaded per open,
// and it is module-cached after the first time.
const { accounts, isLoading: accountsLoading, error: accountsError, refresh: refreshAccounts } = useAccounts(false)
const [catalog, setCatalog] = useState<CatalogAccount[]>([])
const [catalogStatus, setCatalogStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const accountsStatus: 'loading' | 'ready' | 'error' =
accountsLoading || catalogStatus === 'loading'
? 'loading'
: accountsError || catalogStatus === 'error'
? 'error'
: 'ready'
const [lines, setLines] = useState<CorrectionLine[]>([])
const [description, setDescription] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
// Non-null when the server refused with CORRECTION_CHAIN_TOO_DEEP: holds the
// reported chain depth and opens the bypass confirm ("Rätta ändå").
const [deepChainDepth, setDeepChainDepth] = useState<number | null>(null)
// Index of the line whose combobox opened the create dialog, and the search
// string it was showing. Null index = the dialog is closed.
const [creatingAccountForLine, setCreatingAccountForLine] = useState<number | null>(null)
const [createAccountPrefill, setCreateAccountPrefill] = useState('')
const activeAccounts = useMemo(
() => accounts.filter((account) => account.is_active),
[accounts],
)
const selectableCatalog = useMemo(
() => getSelectableCorrectionCatalog(accounts, catalog),
[accounts, catalog],
)
const accountNameSources = useMemo(
() => [...accounts, ...catalog],
[accounts, catalog],
)
const originalLines = ((entry.lines || []) as JournalEntryLine[])
.slice()
.sort((a, b) => a.sort_order - b.sort_order)
useEffect(() => {
if (open) {
// Pre-fill with original entry's lines
setLines(
originalLines.map((l) => ({
account_number: l.account_number,
debit_amount: Number(l.debit_amount) > 0 ? String(Number(l.debit_amount)) : '',
credit_amount: Number(l.credit_amount) > 0 ? String(Number(l.credit_amount)) : '',
line_description: l.line_description || '',
}))
)
// Pre-fill the verifikationstext with the same auto text the server
// would generate; only a user edit is sent along (see handleSubmit).
setDescription(autoCorrectionDescription(entry.description))
void loadCatalog()
}
}, [open, entry.id]) // eslint-disable-line react-hooks/exhaustive-deps
async function loadCatalog() {
setCatalogStatus('loading')
try {
setCatalog(await loadBasCatalog())
setCatalogStatus('ready')
} catch {
setCatalog([])
setCatalogStatus('error')
}
}
const updateLine = (index: number, field: keyof CorrectionLine, value: string) => {
setLines((prev) =>
prev.map((l, i) => {
if (i !== index) return l
const next = { ...l, [field]: value }
// When the account changes, refresh the auto-filled description to the
// new account's name. Without this, a description carried over from the
// original entry (e.g. 2393 "Lån från närstående personer, långfristig
// del") stays stale on the newly chosen account (e.g. 2893, kortfristig).
if (field === 'account_number' && value) {
next.line_description = nextLineDescriptionForAccountChange(
l.line_description,
l.account_number,
value,
accounts,
)
}
return next
})
)
}
const updateLineAccount = (index: number, accountNumber: string) => {
setLines((prev) => prev.map((line, lineIndex) => (
lineIndex === index
? changeCorrectionLineAccount(line, accountNumber, accountNameSources)
: line
)))
}
const addLine = () => {
setLines((prev) => [...prev, { account_number: '', debit_amount: '', credit_amount: '', line_description: '' }])
}
const removeLine = (index: number) => {
setLines((prev) => prev.filter((_, i) => i !== index))
}
const closeCreateAccount = () => {
setCreatingAccountForLine(null)
setCreateAccountPrefill('')
}
// A number that is neither in the company chart nor in BAS 2026 (a retired
// account such as 8022, or a company-specific underkonto) would otherwise be
// a dead end here: the rättelse can only post to accounts that exist in the
// chart. Creating it inline keeps the half-finished rättelse intact.
const handleAccountCreated = async (account: { account_number: string; account_name?: string }) => {
await invalidateReferenceData('ref:accounts')
if (creatingAccountForLine != null) {
// The refreshed cache is not visible in this closure, so the
// fresh account's own name is passed alongside the stale sources. The
// reactivate path reports no name, but that account is already in
// `accounts` (the fetch includes deactivated rows).
const created = account.account_name
? [{ account_number: account.account_number, account_name: account.account_name }]
: []
setLines((prev) => prev.map((line, index) => (
index === creatingAccountForLine
? changeCorrectionLineAccount(line, account.account_number, [...accountNameSources, ...created])
: line
)))
}
closeCreateAccount()
}
const totalDebit = lines.reduce((sum, l) => sum + (parseFloat(l.debit_amount) || 0), 0)
const totalCredit = lines.reduce((sum, l) => sum + (parseFloat(l.credit_amount) || 0), 0)
const roundedDebit = Math.round(totalDebit * 100) / 100
const roundedCredit = Math.round(totalCredit * 100) / 100
const isBalanced = roundedDebit === roundedCredit && roundedDebit > 0
const hasValidLines = lines.length >= 2 && lines.every((l) => l.account_number.length === 4)
async function handleSubmit(allowDeepChain = false) {
if (!isBalanced || !hasValidLines) return
setIsSubmitting(true)
try {
const apiLines = lines.map((l) => ({
account_number: l.account_number,
debit_amount: parseFloat(l.debit_amount) || 0,
credit_amount: parseFloat(l.credit_amount) || 0,
line_description: l.line_description || undefined,
}))
const res = await fetch(`/api/bookkeeping/journal-entries/${entry.id}/correct`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
lines: apiLines,
// Only sent when the user changed the auto prefill: the server
// fallback ("Rättelse: <original>") stays the source of truth.
description: correctionDescriptionForSubmit(description, entry.description),
...(allowDeepChain ? { allow_deep_chain: true } : {}),
}),
})
const result = await res.json()
if (!res.ok) {
// Chain-depth guard: open the bypass confirm instead of a dead-end
// toast. "Rätta ändå" resubmits with allow_deep_chain=true.
const structured = (result as { error?: { code?: string; details?: { depth?: number } } })?.error
if (structured?.code === 'CORRECTION_CHAIN_TOO_DEEP') {
setDeepChainDepth(structured.details?.depth ?? 3)
return
}
const error = new Error('Failed to create correction') as Error & { body?: unknown; status?: number }
error.body = result
error.status = res.status
throw error
}
setDeepChainDepth(null)
const correctedId = result.data?.corrected?.id
toast({
title: 'Ändringsverifikation skapad',
description: 'Storno och rättelse har bokförts.',
action: correctedId ? (
<Button variant="outline" size="sm" onClick={() => router.push(`/bookkeeping/${correctedId}`)}>
Visa rättelsen
</Button>
) : undefined,
})
onOpenChange(false)
onCorrected()
} catch (err) {
const anyErr = err as { body?: unknown; status?: number }
toast({
title: 'Kunde inte spara ändringsverifikation',
description: getErrorMessage(anyErr.body ?? err, { context: 'journal_entry', statusCode: anyErr.status }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
<DialogHeader>
{/* Convention 7: the how-it-works copy lives behind the "?", not in
the dialog flow. */}
<div className="flex items-center gap-2">
<DialogTitle>Skapa ändringsverifikation</DialogTitle>
<RattelseExplainer>
<p>
Här skapas automatiskt en stornoverifikation som nollställer
originalet och en ny verifikation med dina rättade uppgifter.
Rättelsen bokförs i samma räkenskapsperiod som originalet: du
hittar den under originalets räkenskapsår.
</p>
<p>
Spårbarheten ligger i stornokedjan: originalet,
stornoverifikationen och ändringsverifikationen förblir synliga
i bokföringen och länkade till varandra.
</p>
<p>
Tar du bort ett konto ur de rättade raderna nollställs det
(stornon återför det). Vill du bara återföra hela verifikatet
utan att ersätta det, använd Återför (storno) istället.
</p>
</RattelseExplainer>
</div>
</DialogHeader>
{/* Original entry metadata: lines live inside CorrectionPreview below */}
<div className="space-y-1">
<div className="flex items-center gap-2 text-sm text-muted-foreground flex-wrap">
<span className="text-muted-foreground">Original</span>
<span className="font-mono">{formatVoucher(entry)}</span>
<span className="tabular-nums">{formatDate(entry.entry_date)}</span>
</div>
<p className="text-sm">{entry.description}</p>
</div>
{/* Live diff: original | storno | correction | förändring */}
<CorrectionPreview originalLines={originalLines} correctedLines={lines} />
{/* Verifikationstext for the new (corrected) entry. Pre-filled with
the auto text; editable so a header named after the wrong account
is not echoed on the correction (issue #1031). */}
<div className="space-y-1">
<Label htmlFor="correction-description">Verifikationstext</Label>
<Input
id="correction-description"
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder={autoCorrectionDescription(entry.description)}
// ph-no-capture: the placeholder echoes the posted entry's
// description, and replay masking covers values, not attributes.
className="ph-no-capture"
/>
<p className="text-xs text-muted-foreground">
Texten på den nya verifikationen. Ändra den om originalets beskrivning inte längre
stämmer, till exempel när rättelsen byter konto.
</p>
</div>
{/* Corrected lines (editable) */}
<div className="space-y-2">
<div className="space-y-1">
<p className="text-sm font-medium">Rättade rader</p>
<p className="text-xs text-muted-foreground">
Det här är hela den nya verifikationen: alla konton som ska finnas kvar måste stå kvar.
</p>
</div>
{accountsStatus !== 'ready' && (
<div className="flex items-center justify-between gap-3 rounded-lg border bg-muted/50 p-3 text-sm text-muted-foreground">
<span className="flex items-center gap-2">
{accountsStatus === 'loading' && <Loader2 className="h-4 w-4 animate-spin" />}
{accountsStatus === 'loading' ? t('accounts_loading') : t('accounts_load_failed')}
</span>
{accountsStatus === 'error' && (
<Button variant="outline" size="sm" onClick={() => void refreshAccounts()}>
{t('accounts_retry')}
</Button>
)}
</div>
)}
<div className="space-y-2">
{lines.map((line, index) => (
<div key={index} className="space-y-2 sm:space-y-0 sm:grid sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_120px_120px_auto] sm:gap-2 sm:items-start border-b sm:border-0 pb-3 sm:pb-0 last:border-0">
<div className="grid grid-cols-[minmax(0,1fr)_auto] sm:contents gap-2">
{/* min-w-0: at sm: the sm:contents wrapper promotes this cell
to a direct grid item; without it the combobox refuses to
shrink below its content and overflows the dialog (same
pattern as SendInvoiceDialog's desktop rows). */}
<div className="min-w-0">
<AccountCombobox
value={line.account_number}
accounts={activeAccounts}
catalog={selectableCatalog}
onChange={(v) => updateLineAccount(index, v)}
onCreateAccount={(prefill) => {
setCreatingAccountForLine(index)
setCreateAccountPrefill(prefill)
}}
disabled={accountsStatus !== 'ready'}
/>
</div>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 min-h-[44px] min-w-[44px] sm:order-last"
onClick={() => removeLine(index)}
disabled={lines.length <= 2}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<Input
value={line.line_description}
onChange={(e) => updateLine(index, 'line_description', e.target.value)}
placeholder="Beskrivning"
className="h-8"
/>
<div className="grid grid-cols-2 gap-2 sm:contents">
<Input
type="number"
value={line.debit_amount}
onChange={(e) => updateLine(index, 'debit_amount', e.target.value)}
placeholder="Debet"
className="h-8 text-right"
min={0}
step="0.01"
/>
<Input
type="number"
value={line.credit_amount}
onChange={(e) => updateLine(index, 'credit_amount', e.target.value)}
placeholder="Kredit"
className="h-8 text-right"
min={0}
step="0.01"
/>
</div>
</div>
))}
</div>
<Button variant="outline" size="sm" onClick={addLine}>
<Plus className="h-4 w-4 mr-1" />
Lägg till rad
</Button>
{/* Balance summary */}
<div className="flex justify-end gap-6 text-sm pt-2 border-t">
<div>
<span className="text-muted-foreground mr-2">Debet:</span>
<span className={!isBalanced ? 'text-destructive font-medium' : 'font-medium'}>
{roundedDebit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</span>
</div>
<div>
<span className="text-muted-foreground mr-2">Kredit:</span>
<span className={!isBalanced ? 'text-destructive font-medium' : 'font-medium'}>
{roundedCredit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</span>
</div>
</div>
{!isBalanced && roundedDebit + roundedCredit > 0 && (
<p className="text-sm text-destructive">
Debet och kredit måste vara lika och större än 0.
</p>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
Avbryt
</Button>
<Button
onClick={() => handleSubmit()}
disabled={!isBalanced || !hasValidLines || isSubmitting}
>
{isSubmitting ? 'Skapar...' : 'Skapa ändringsverifikation'}
</Button>
</DialogFooter>
{/* Chain-depth guard confirm: the server refused because this entry
already sits deep in a rättelse chain. Advisory, never a dead end:
"Rätta ändå" resubmits with allow_deep_chain=true. */}
<Dialog open={deepChainDepth != null} onOpenChange={(next) => { if (!next) setDeepChainDepth(null) }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t('deep_chain_title')}</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
{t('deep_chain_body', { depth: deepChainDepth ?? 3 })}
</p>
<DialogFooter>
<Button variant="outline" onClick={() => setDeepChainDepth(null)} disabled={isSubmitting}>
{t('deep_chain_cancel')}
</Button>
<Button
onClick={() => { setDeepChainDepth(null); void handleSubmit(true) }}
disabled={isSubmitting}
>
{t('deep_chain_correct_anyway')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</DialogContent>
{/* Nested on purpose: closing this one (Esc, click-outside, Avbryt) must
leave the half-filled ändringsverifikation behind it untouched. */}
<AddAccountDialog
open={creatingAccountForLine != null}
onOpenChange={(next) => {
if (!next) closeCreateAccount()
}}
onCreated={handleAccountCreated}
{...splitCreateAccountPrefill(createAccountPrefill)}
/>
</Dialog>
)
}
@@ -1,132 +0,0 @@
'use client'
import { AccountNumber } from '@/components/ui/account-number'
import {
buildCorrectionRows,
formatSignedAmount,
type AccountRow,
type CorrectionLineInput,
} from '@/components/bookkeeping/correction-preview-rows'
import type { JournalEntryLine } from '@/types'
interface Props {
originalLines: JournalEntryLine[]
correctedLines: CorrectionLineInput[]
}
function signClass(n: number): string {
if (n > 0) return 'text-success'
if (n < 0) return 'text-destructive'
return 'text-muted-foreground'
}
export default function CorrectionPreview({ originalLines, correctedLines }: Props) {
const rows = buildCorrectionRows(originalLines, correctedLines)
const hasAnyCorrection = correctedLines.some((l) => {
if (l.account_number.length !== 4) return false
const d = typeof l.debit_amount === 'string' ? parseFloat(l.debit_amount) : l.debit_amount
const c = typeof l.credit_amount === 'string' ? parseFloat(l.credit_amount) : l.credit_amount
return (Number.isFinite(d) && d > 0) || (Number.isFinite(c) && c > 0)
})
// An account that was on the original but the user dropped from the rättelse:
// the storno still drains it to zero (delta = −original). Flag it so the cell
// reads "tas bort" instead of a bare "-", which would imply "unchanged".
const isRemoved = (row: AccountRow) =>
hasAnyCorrection && !row.correctionPresent && Math.abs(row.original) >= 0.005
// The per-account deltas sum to the corrected lines' debit − credit. A non-zero
// sum means the proposed rättelse is not yet balanced: surface that here so the
// förändring column is read as a work-in-progress, not a miscalculation.
const netDelta = rows.reduce((sum, r) => sum + r.delta, 0)
const unbalanced = hasAnyCorrection && Math.abs(netDelta) >= 0.005
if (rows.length === 0) return null
return (
<div className="space-y-2">
<div className="flex items-center justify-between">
<p className="text-sm font-medium">Effekt per konto</p>
<p className="text-[11px] uppercase tracking-wider text-muted-foreground">
Debet − Kredit
</p>
</div>
<div className="hidden sm:block rounded-lg border overflow-hidden">
<table className="w-full text-sm">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground bg-muted/30">
<tr>
<th className="px-3 py-2 text-left w-56">Konto</th>
<th className="px-3 py-2 text-right">Original</th>
<th className="px-3 py-2 text-right">Storno</th>
<th className="px-3 py-2 text-right">Rättelse</th>
<th className="px-3 py-2 text-right border-l">Förändring</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.account_number} className="border-t">
<td className="px-3 py-1.5">
<AccountNumber number={row.account_number} showName size="sm" />
</td>
<td className={`px-3 py-1.5 text-right tabular-nums ${signClass(row.original)}`}>
{formatSignedAmount(row.original)}
</td>
<td className={`px-3 py-1.5 text-right tabular-nums ${signClass(row.storno)}`}>
{formatSignedAmount(row.storno)}
</td>
<td className={`px-3 py-1.5 text-right tabular-nums ${isRemoved(row) ? 'text-muted-foreground' : signClass(row.correction)}`}>
{!hasAnyCorrection ? '-' : isRemoved(row) ? 'tas bort' : formatSignedAmount(row.correction)}
</td>
<td
className={`px-3 py-1.5 text-right tabular-nums border-l font-medium ${signClass(row.delta)}`}
>
{hasAnyCorrection ? formatSignedAmount(row.delta) : '-'}
</td>
</tr>
))}
</tbody>
</table>
</div>
<div className="sm:hidden space-y-2">
{rows.map((row) => (
<div key={row.account_number} className="rounded-lg border p-3 space-y-1.5">
<div className="flex items-center justify-between gap-2">
<AccountNumber number={row.account_number} showName size="sm" />
<span className={`text-sm font-medium tabular-nums ${signClass(row.delta)}`}>
{hasAnyCorrection ? formatSignedAmount(row.delta) : '-'}
</span>
</div>
<dl className="grid grid-cols-3 gap-2 text-xs">
<div>
<dt className="text-muted-foreground">Original</dt>
<dd className={`tabular-nums ${signClass(row.original)}`}>{formatSignedAmount(row.original)}</dd>
</div>
<div>
<dt className="text-muted-foreground">Storno</dt>
<dd className={`tabular-nums ${signClass(row.storno)}`}>{formatSignedAmount(row.storno)}</dd>
</div>
<div>
<dt className="text-muted-foreground">Rättelse</dt>
<dd className={`tabular-nums ${isRemoved(row) ? 'text-muted-foreground' : signClass(row.correction)}`}>
{!hasAnyCorrection ? '-' : isRemoved(row) ? 'tas bort' : formatSignedAmount(row.correction)}
</dd>
</div>
</dl>
</div>
))}
</div>
<p className="text-xs text-muted-foreground">
Förändring = storno + rättelse. Det är det netto som tillkommer ovanpå originalet när du
bokför. Ett konto du tar bort nollställs av stornon.
</p>
{unbalanced && (
<p className="text-xs text-destructive">
Förslaget balanserar inte ännu: debet och kredit i rättelsen måste vara lika.
</p>
)}
</div>
)
}
@@ -1,227 +0,0 @@
'use client'
import { useState, useMemo } from 'react'
import { useTranslations } from 'next-intl'
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 { AttnLine } from '@/components/ui/attn-line'
import { useToast } from '@/components/ui/use-toast'
import { Loader2 } from 'lucide-react'
import { computeSuggestedPeriod, fiscalYearName } from '@/lib/bookkeeping/suggest-fiscal-period'
import { fiscalPeriodAdvisoryText } from '@/lib/bookkeeping/fiscal-period-warnings'
import type { FiscalPeriod } from '@/types'
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
entryDate: string
periods: FiscalPeriod[]
onCreated: () => void
}
/** A räkenskapsår that was just created, together with the non-blocking
* advisory the route attached to the 200. Only set when there is one. */
interface CreatedWithAdvisory {
name: string
periodStart: string
periodEnd: string
advisory: 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()
// The form copy below is pre-existing hardcoded Swedish and is left as it
// stands (out of scope here). Every string added for the created-state is
// keyed in both messages/sv.json and messages/en.json. The advisory itself is
// not keyed: the route emits one Swedish sentence and no English twin, and
// bokslut/räkenskapsår domain copy stays Swedish in both locales anyway
// (.claude/rules/i18n.md).
const t = useTranslations('bookkeeping')
const tCommon = useTranslations('common')
const suggested = useMemo(() => computeSuggestedPeriod(entryDate, periods), [entryDate, periods])
const [name, setName] = useState(suggested.name)
// The name follows the dates until the user types a name of their own.
// Without this the seed suggestion (the next forward year, e.g.
// "Räkenskapsår 2027") survived the user re-dating the form to a backfilled
// first year and was saved verbatim.
const [nameEdited, setNameEdited] = useState(false)
const [periodStart, setPeriodStart] = useState(suggested.period_start)
const [periodEnd, setPeriodEnd] = useState(suggested.period_end)
const [isSubmitting, setIsSubmitting] = useState(false)
// Set when the period was created AND the route attached an advisory. The
// dialog then holds on a done-state so the sentence is actually read.
const [created, setCreated] = useState<CreatedWithAdvisory | null>(null)
// 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)
setNameEdited(false)
setPeriodStart(suggested.period_start)
setPeriodEnd(suggested.period_end)
setLastSuggested(suggested)
setCreated(null)
}
// A date input yields '' while incomplete and a full YYYY-MM-DD otherwise:
// only derive a name once both ends are known.
const updateDates = (start: string, end: string) => {
setPeriodStart(start)
setPeriodEnd(end)
if (!nameEdited && start && end) setName(fiscalYearName(start, end))
}
// Close, and refetch in the parent if this session created a period. The
// refetch is deferred to here on the advisory path on purpose: it swaps the
// `periods` prop, which resets the form above, and that would pull the
// advisory off screen before it was read.
const handleClose = () => {
const didCreate = created !== null
setCreated(null)
onOpenChange(false)
if (didCreate) onCreated()
}
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) {
toast({
title: 'Kunde inte skapa räkenskapsår',
description: errorMessage(result?.error),
variant: 'destructive',
})
return
}
// Every picker and form reads periods from the session cache
// (lib/reference-data): refresh it now so the new year is selectable
// everywhere at once, not only in the caller that gets onCreated.
void invalidateReferenceData('ref:fiscal-periods')
// The 200 may carry non-blocking advisories (today: a prior räkenskapsår
// still open, which is the normal state while the bokslut runs). The
// period WAS created, so this is information, never a failure: show the
// done-state with one ochre sentence rather than flashing a toast past.
const advisory = fiscalPeriodAdvisoryText(result)
if (advisory) {
setCreated({ name, periodStart, periodEnd, advisory })
return
}
toast({ title: 'Räkenskapsår skapat', description: `${name} har skapats.` })
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)
}
}
return (
<Dialog open={open} onOpenChange={(next) => (next ? onOpenChange(true) : handleClose())}>
<DialogContent>
{created ? (
<>
<DialogHeader>
<DialogTitle>{t('period_created_title')}</DialogTitle>
<DialogDescription className="tabular-nums">
{t('period_created_range', {
name: created.name,
start: created.periodStart,
end: created.periodEnd,
})}
</DialogDescription>
</DialogHeader>
{/* Attention is one ochre sentence, not a banner (UI-migration
convention 6). The text is the route's own Swedish domain copy,
which stays Swedish in both locales. */}
<AttnLine>{created.advisory}</AttnLine>
<DialogFooter>
<Button onClick={handleClose}>{tCommon('close')}</Button>
</DialogFooter>
</>
) : (
<>
<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)
setNameEdited(true)
}}
className="mt-1"
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label>Startdatum</Label>
<Input type="date" value={periodStart} onChange={(e) => updateDates(e.target.value, periodEnd)} className="mt-1" />
</div>
<div>
<Label>Slutdatum</Label>
<Input type="date" value={periodEnd} onChange={(e) => updateDates(periodStart, e.target.value)} className="mt-1" />
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
Avbryt
</Button>
<Button onClick={handleCreate} disabled={isSubmitting || !name || !periodStart || !periodEnd}>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Skapa
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
)
}
@@ -1,345 +0,0 @@
'use client'
import { useState, useCallback, useRef } from 'react'
import { useLocale, useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Upload, FileText, ImageIcon, X, Loader2 } from 'lucide-react'
export interface UploadedFile {
id?: string
file: File
status: 'pending' | 'uploading' | 'uploaded' | 'error'
error?: string
fileName: string
fileSize: number
/** Unique key to track this upload (handles duplicate filenames) */
uploadKey: string
}
interface DocumentUploadZoneProps {
files: UploadedFile[]
onFilesChange: (files: UploadedFile[]) => void
journalEntryId?: string
maxFiles?: number
disabled?: boolean
compact?: boolean
}
let uploadCounter = 0
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
const ACCEPTED_TYPES = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp']
const ACCEPTED_EXTENSIONS = '.pdf,.jpg,.jpeg,.png,.webp'
const FILE_NAME_TAIL_LENGTH = 16
function TruncatedFileName({ fileName }: { fileName: string }) {
const characters = Array.from(fileName)
if (characters.length <= FILE_NAME_TAIL_LENGTH * 2) {
return (
<span className="min-w-0 flex-1 truncate" title={fileName}>
{fileName}
</span>
)
}
const splitAt = characters.length - FILE_NAME_TAIL_LENGTH
const start = characters.slice(0, splitAt).join('')
const end = characters.slice(splitAt).join('')
return (
<span
className="flex min-w-0 flex-1"
title={fileName}
>
<span className="sr-only">{fileName}</span>
<span aria-hidden="true" className="min-w-0 flex-1 truncate">
{start}
</span>
<span
aria-hidden="true"
className="max-w-1/2 shrink overflow-hidden whitespace-nowrap text-right"
>
{end}
</span>
</span>
)
}
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
function isImageType(type: string): boolean {
return type.startsWith('image/')
}
/**
* Extract a Swedish error message from the structured error envelope
* returned by /api/documents. Falls back to message_en or null if the
* shape is unexpected.
*/
function extractErrorMessage(err: unknown, locale: string): string | null {
if (typeof err === 'string') return err
if (err && typeof err === 'object') {
const e = err as { message?: unknown; message_en?: unknown; code?: unknown }
if (locale === 'en' && typeof e.message_en === 'string' && e.message_en.length > 0) {
return e.message_en
}
if (typeof e.message === 'string' && e.message.length > 0) return e.message
if (typeof e.message_en === 'string' && e.message_en.length > 0) return e.message_en
if (typeof e.code === 'string') return e.code
}
return null
}
export default function DocumentUploadZone({
files,
onFilesChange,
journalEntryId,
maxFiles = 5,
disabled = false,
compact = false,
}: DocumentUploadZoneProps) {
const t = useTranslations('document_upload')
const locale = useLocale()
const [isDragging, setIsDragging] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
const uploadFile = useCallback(async (file: UploadedFile): Promise<UploadedFile> => {
const formData = new FormData()
formData.append('file', file.file)
formData.append('upload_source', 'file_upload')
if (journalEntryId) {
formData.append('journal_entry_id', journalEntryId)
}
try {
const res = await fetch('/api/documents', {
method: 'POST',
body: formData,
})
// Try to parse JSON, but tolerate non-JSON responses (auth redirect HTML, 502 etc.)
let result: { data?: { id?: string }; error?: unknown } = {}
try {
result = await res.json()
} catch {
console.warn('[DocumentUploadZone] Non-JSON response', {
status: res.status,
fileName: file.fileName,
})
const reason = res.status === 401 || res.status === 403
? t('session_expired')
: t('server_status', { status: res.status })
return { ...file, status: 'error', error: reason }
}
if (!res.ok || result.error) {
const errMessage = extractErrorMessage(result.error, locale) || t('failed_status', { status: res.status })
console.warn('[DocumentUploadZone] Upload error', {
status: res.status,
error: result.error,
fileName: file.fileName,
})
return { ...file, status: 'error', error: errMessage }
}
return { ...file, status: 'uploaded', id: result.data?.id }
} catch (err) {
console.error('[DocumentUploadZone] Upload threw', {
error: err,
fileName: file.fileName,
})
return { ...file, status: 'error', error: t('network_error') }
}
}, [journalEntryId, locale, t])
const handleFiles = useCallback(async (newFiles: File[]) => {
const remaining = maxFiles - files.length
if (remaining <= 0) return
const validFiles: UploadedFile[] = []
for (const file of newFiles.slice(0, remaining)) {
if (!ACCEPTED_TYPES.includes(file.type)) {
validFiles.push({
file,
status: 'error',
error: t('unsupported_type'),
fileName: file.name,
fileSize: file.size,
uploadKey: `upload-${++uploadCounter}`,
})
continue
}
if (file.size > MAX_FILE_SIZE) {
validFiles.push({
file,
status: 'error',
error: t('too_large'),
fileName: file.name,
fileSize: file.size,
uploadKey: `upload-${++uploadCounter}`,
})
continue
}
validFiles.push({
file,
status: 'uploading',
fileName: file.name,
fileSize: file.size,
uploadKey: `upload-${++uploadCounter}`,
})
}
let currentFiles = [...files, ...validFiles]
onFilesChange(currentFiles)
// Upload files that passed validation
for (const f of validFiles.filter((f) => f.status === 'uploading')) {
const result = await uploadFile(f)
currentFiles = currentFiles.map((cf) =>
cf.uploadKey === f.uploadKey ? result : cf
)
onFilesChange([...currentFiles])
}
}, [files, maxFiles, onFilesChange, t, uploadFile])
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault()
if (!disabled) setIsDragging(true)
}, [disabled])
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault()
setIsDragging(false)
}, [])
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault()
setIsDragging(false)
if (disabled) return
const droppedFiles = Array.from(e.dataTransfer.files)
handleFiles(droppedFiles)
}, [disabled, handleFiles])
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFiles = e.target.files
if (selectedFiles) {
handleFiles(Array.from(selectedFiles))
}
// Reset input so the same file can be re-selected
if (inputRef.current) inputRef.current.value = ''
}, [handleFiles])
const removeFile = useCallback((index: number) => {
onFilesChange(files.filter((_, i) => i !== index))
}, [files, onFilesChange])
const isUploading = files.some((f) => f.status === 'uploading')
return (
<div className="min-w-0 space-y-2">
{/* Drop zone */}
<div
className={`
relative border-2 border-dashed rounded-lg text-center transition-colors
${compact ? 'p-3' : 'p-6'}
${isDragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25'}
${disabled ? 'pointer-events-none opacity-50' : 'cursor-pointer hover:border-primary/50'}
`}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={() => inputRef.current?.click()}
>
<input
ref={inputRef}
type="file"
multiple
accept={ACCEPTED_EXTENSIONS}
className="hidden"
onChange={handleInputChange}
disabled={disabled}
/>
<div className={compact ? 'flex items-center justify-center gap-2' : 'space-y-2'}>
<Upload className={compact ? 'h-4 w-4 text-muted-foreground' : 'mx-auto h-8 w-8 text-muted-foreground'} />
<div>
<p className={compact ? 'text-sm text-muted-foreground' : 'text-sm font-medium'}>
{compact ? t('compact_prompt') : t('prompt')}
</p>
{!compact && (
<p className="text-xs text-muted-foreground">
{t('format_hint')}
</p>
)}
</div>
</div>
</div>
{/* File list */}
{files.length > 0 && (
<div className="space-y-1">
{files.map((file, index) => (
<div
key={file.uploadKey}
className="flex min-w-0 items-center gap-2 text-sm py-1.5 px-2 rounded-sm bg-muted/50"
>
{isImageType(file.file.type) ? (
<ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
) : (
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
)}
<TruncatedFileName fileName={file.fileName} />
<span className="text-xs text-muted-foreground shrink-0">
{formatFileSize(file.fileSize)}
</span>
{file.status === 'uploading' && (
<Loader2 className="h-3.5 w-3.5 animate-spin text-primary shrink-0" />
)}
{file.status === 'uploaded' && (
<Badge variant="success" className="text-xs px-1.5 py-0">
{t('uploaded')}
</Badge>
)}
{file.status === 'error' && (
<>
<Badge variant="destructive" className="text-xs px-1.5 py-0">
{t('error')}
</Badge>
{file.error && (
<span className="text-xs text-destructive">{file.error}</span>
)}
</>
)}
<Button
variant="ghost"
size="sm"
aria-label={t('remove_file')}
className="h-6 w-6 p-0 shrink-0"
onClick={(e) => {
e.stopPropagation()
removeFile(index)
}}
disabled={file.status === 'uploading'}
>
<X className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
{isUploading && (
<p className="text-xs text-muted-foreground">{t('uploading')}</p>
)}
</div>
)
}
@@ -1,73 +0,0 @@
'use client'
import { UUID_RE } from '@/lib/invariants/uuid'
import { Eye } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { useBranding } from '@/lib/branding/brand-context'
interface DocumentViewButtonProps {
documentId: string
label?: string
className?: string
}
/**
* Opens a document in the browser through the same-origin inline proxy
* (/api/documents/:id/inline), which serves it with
* `Content-Disposition: inline`: PDFs land in the browser's viewer and images
* render, instead of the file dropping into the Downloads folder (#1190).
*
* The proxy authorizes with the caller's own client before the service-role
* client reads the bucket, and no URL has to be minted first: navigation
* happens straight from the click, so there is nothing for a popup blocker to
* catch (the previous signed-URL fetch needed openDeferredTab for exactly that
* reason). The browser's own viewer still offers saving the file.
*/
export function DocumentViewButton({ documentId, label = 'Visa dokument', className }: DocumentViewButtonProps) {
const { toast } = useToast()
const { appName } = useBranding()
const handleClick = () => {
// documentId originates from staged preview_data (Record<string, unknown>);
// validate the shape before interpolating into the URL so a malformed
// payload can't point the tab at another internal endpoint.
if (!UUID_RE.test(documentId)) {
toast({
title: 'Ogiltigt dokument-ID',
description: 'Försök ladda om sidan eller kontakta support.',
variant: 'destructive',
})
return
}
// window.open() returns null BY SPEC when 'noopener' is in the features
// string, even on success, so passing it here made this toast fire on
// every successful open. Open with a real return value and sever the
// reverse channel manually (same pattern as lib/browser/deferred-tab.ts).
const tab = window.open(`/api/documents/${documentId}/inline`, '_blank')
if (tab) {
tab.opener = null
} else {
toast({
title: 'Kunde inte öppna dokumentet',
description: `Tillåt popupfönster för ${appName} i webbläsaren och försök igen.`,
variant: 'destructive',
})
}
}
return (
<Button
type="button"
variant="outline"
size="sm"
onClick={handleClick}
className={className}
>
<Eye className="mr-1.5 h-3.5 w-3.5" />
{label}
</Button>
)
}
@@ -1,189 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { ExternalLink, FileText } from 'lucide-react'
import { Skeleton } from '@/components/ui/skeleton'
import { cn } from '@/lib/utils'
/**
* Side-by-side document viewer used while booking manually, so the user can
* read the figures off a receipt/invoice while filling in the journal entry.
*
* Renders by document id through the same-origin inline proxy
* (/api/documents/:id/inline). PDFs use <object type="application/pdf"> rather
* than <iframe>: Chrome intermittently blocks PDFs in a frame even with a
* permissive CSP (see the note in AttachmentPreviewSheet), and <object>
* invokes the PDF plugin directly. Images use <img>.
*
* Unlike AttachmentPreviewSheet this is keyed off a document id, not a
* journal_entry_id: during manual booking the entry does not exist yet.
*/
function isImageType(type: string | null, fileName?: string | null): boolean {
if (type?.startsWith('image/')) return true
// Legacy uploads sometimes leave mime_type null or application/octet-stream:
// fall back to the filename extension.
if (type === null || type === 'application/octet-stream') {
return /\.(jpe?g|png|gif|webp|svg)$/i.test(fileName ?? '')
}
return false
}
function isPdfType(type: string | null, fileName?: string | null): boolean {
if (type === 'application/pdf') return true
if (type === null || type === 'application/octet-stream') {
return fileName?.toLowerCase().endsWith('.pdf') ?? false
}
return false
}
interface DocumentViewerPaneProps {
/** Document id. Bytes are served via the same-origin inline proxy. */
documentId?: string | null
/** Pre-known mime type. When omitted it's fetched from /api/documents/:id. */
mime?: string | null
/** Pre-known signed URL for the "open in new tab" link. Optional. */
downloadUrl?: string | null
/** Optional filename: used for mime sniffing on legacy/octet-stream files. */
fileName?: string | null
className?: string
}
export default function DocumentViewerPane({
documentId,
mime: mimeProp = null,
downloadUrl: downloadUrlProp = null,
fileName = null,
className,
}: DocumentViewerPaneProps) {
const t = useTranslations('document_viewer')
// Fetched metadata is tagged with the document id it belongs to, so a stale
// response for a previously-shown document is ignored rather than flashed.
const [fetched, setFetched] = useState<
{ id: string; mime: string | null; url: string | null } | null
>(null)
// Resolve mime / download_url from the documents API only when the caller did
// not supply a mime (e.g. a pre-linked transaction document). When a mime is
// provided (fresh upload, inbox preview) we skip the round-trip entirely.
// setState happens only inside the async callbacks: never synchronously in
// the effect body: to avoid cascading renders (react-hooks/set-state-in-effect).
useEffect(() => {
if (!documentId || mimeProp) return
let cancelled = false
fetch(`/api/documents/${documentId}`)
.then((r) => (r.ok ? r.json() : null))
.then((body) => {
if (cancelled) return
setFetched({
id: documentId,
mime: body?.data?.mime_type ?? null,
url: body?.data?.download_url ?? null,
})
})
.catch(() => {
// preview is best-effort: record an empty result so we stop "loading"
if (!cancelled) setFetched({ id: documentId, mime: null, url: null })
})
return () => {
cancelled = true
}
}, [documentId, mimeProp])
const fetchedForThis = fetched?.id === documentId ? fetched : null
const mime = mimeProp ?? fetchedForThis?.mime ?? null
const downloadUrl = downloadUrlProp ?? fetchedForThis?.url ?? null
const loadingMeta = !!documentId && !mimeProp && !fetchedForThis
if (!documentId) {
return (
<div
className={cn(
'flex h-full w-full items-center justify-center rounded-lg border bg-muted/20 text-sm text-muted-foreground',
className,
)}
>
<FileText className="mr-2 h-5 w-5" />
{t('empty')}
</div>
)
}
const inlineSrc = `/api/documents/${documentId}/inline`
const newTabHref = downloadUrl ?? inlineSrc
const showAsImage = isImageType(mime, fileName)
const showAsPdf = isPdfType(mime, fileName)
return (
<div
className={cn(
'flex h-full w-full flex-col overflow-hidden rounded-lg border bg-muted/20',
className,
)}
>
<div className="flex shrink-0 items-center justify-between gap-2 border-b px-3 py-1.5">
<span className="truncate text-xs text-muted-foreground">
{fileName ?? t('header_label')}
</span>
<a
href={newTabHref}
target="_blank"
rel="noopener noreferrer"
className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
>
<ExternalLink className="h-3.5 w-3.5" />
{t('open_in_new_tab')}
</a>
</div>
<div className="min-h-0 flex-1 overflow-auto bg-background">
{loadingMeta ? (
<div className="p-3">
<Skeleton className="h-full min-h-[40vh] w-full" />
</div>
) : showAsPdf ? (
<object
data={inlineSrc}
type="application/pdf"
aria-label={fileName ?? t('header_label')}
className="h-full w-full"
>
<div className="flex h-full w-full items-center justify-center p-4 text-center text-sm text-muted-foreground">
{t('not_previewable')}
{': '}
<a
href={newTabHref}
target="_blank"
rel="noopener noreferrer"
className="ml-1 underline"
>
{t('open_in_new_tab')}
</a>
</div>
</object>
) : showAsImage ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={inlineSrc}
alt={fileName ?? t('header_label')}
className="mx-auto max-w-full object-contain"
/>
) : (
<div className="flex h-full w-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground">
<FileText className="h-6 w-6" />
<span>{t('not_previewable')}</span>
<a
href={newTabHref}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
{t('open_in_new_tab')}
</a>
</div>
)}
</div>
</div>
)
}
@@ -1,547 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { Loader2, Plus, X } from 'lucide-react'
import DimensionCombobox from '@/components/dimensions/DimensionCombobox'
import {
type AccountDimensionRuleDto,
type DimensionDto,
type DimensionRuleType,
} from '@/components/dimensions/types'
import type { BASAccount } from '@/types'
import { useCompanySettings, useDimensions } from '@/lib/reference-data/hooks'
import { fetchDimensions } from '@/lib/reference-data/fetchers'
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
import { AccountVatTreatmentSelect } from './AccountVatTreatmentSelect'
import {
defaultRateForVatTreatment,
type AccountVatTreatment,
} from '@/lib/vat/account-vat-treatment'
interface EditAccountDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
account: BASAccount
onSaved: () => void
}
// Hardcoded Swedish per the file's convention (chart-of-accounts editing is a
// bookkeeping surface). Labels mirror the rule semantics enforced by the
// engine at commit time.
const RULE_TYPE_LABELS: Record<DimensionRuleType, string> = {
required: 'Krävs',
default: 'Förval',
fixed: 'Låst',
}
const RULE_TYPE_HELP: Record<DimensionRuleType, string> = {
required: 'Krävs — verifikat på kontot kan inte bokföras utan värde',
default: 'Förval — värdet föreslås men kan ändras',
fixed: 'Låst — värdet sätts alltid automatiskt',
}
export function EditAccountDialog({ open, onOpenChange, account, onSaved }: EditAccountDialogProps) {
const { toast } = useToast()
const [accountName, setAccountName] = useState(account.account_name)
const [description, setDescription] = useState(account.description || '')
// "Standard moms": the moms-sats a booking line defaults to when this konto is
// picked (currently the leverantörsfaktura-rad). 'none' = no default. Stored
// as a decimal fraction; SelectItem values are the stringified decimals.
const [defaultVatRate, setDefaultVatRate] = useState(
account.default_vat_rate != null ? String(account.default_vat_rate) : 'none',
)
const [defaultVatTreatment, setDefaultVatTreatment] = useState<AccountVatTreatment | 'none'>(
account.default_vat_treatment ?? 'none',
)
const [sruCode, setSruCode] = useState(account.sru_code || '')
const [isActive, setIsActive] = useState(account.is_active)
const [isSaving, setIsSaving] = useState(false)
// Dimension rules ("Dimensionsregler") — visible only when the company has
// dimensions enabled (same /api/settings gate as JournalEntryForm). Rule
// mutations apply immediately via their own fetches + toasts; they are
// deliberately independent of the account PUT below.
// Settings and the dimension registry come from the session cache
// (lib/reference-data), so the section and its pickers are ready on open.
const { settings: companySettings } = useCompanySettings()
const dimensionsEnabled = companySettings?.dimensions_enabled === true
const { dimensions: dims } = useDimensions()
const [rules, setRules] = useState<AccountDimensionRuleDto[]>([])
const [rulesLoading, setRulesLoading] = useState(false)
const [addRuleOpen, setAddRuleOpen] = useState(false)
const [newRuleDimensionId, setNewRuleDimensionId] = useState('')
const [newRuleType, setNewRuleType] = useState<DimensionRuleType>('required')
const [newRuleValueCode, setNewRuleValueCode] = useState<string | null>(null)
const [isAddingRule, setIsAddingRule] = useState(false)
useEffect(() => {
if (!dimensionsEnabled) return
let cancelled = false
setRulesLoading(true)
fetch(`/api/dimensions/rules?account_number=${account.account_number}`)
.then(async (r) => ({ ok: r.ok, json: await r.json().catch(() => null) }))
.catch(() => ({ ok: false, json: null }))
.then((rulesRes) => {
if (cancelled) return
if (rulesRes.ok) {
setRules((rulesRes.json?.data?.rules ?? []) as AccountDimensionRuleDto[])
}
setRulesLoading(false)
})
return () => {
cancelled = true
}
}, [dimensionsEnabled, account.account_number])
const activeDims = dims.filter((d) => d.is_active)
const newRuleDim = activeDims.find((d) => d.id === newRuleDimensionId) ?? null
const newRuleNeedsValue = newRuleType === 'default' || newRuleType === 'fixed'
function resetAddRuleForm() {
setAddRuleOpen(false)
setNewRuleDimensionId('')
setNewRuleType('required')
setNewRuleValueCode(null)
}
async function handleAddRule() {
if (!newRuleDim) return
setIsAddingRule(true)
try {
// Resolve the picked code to a value id. The combobox can create values
// inline, so a code missing from the mount-time registry snapshot means
// we refetch once before giving up.
let valueId: string | null = null
if (newRuleNeedsValue) {
const code = newRuleValueCode
if (!code) return
const findValueId = (list: DimensionDto[]) =>
list
.find((d) => d.id === newRuleDim.id)
?.values.find((v) => v.code === code)?.id ?? null
valueId = findValueId(dims)
if (!valueId) {
const refreshed = await fetchDimensions().catch(() => null)
if (refreshed) {
// Hand the fresh registry to the shared cache as well.
void invalidateReferenceData('ref:dimensions')
valueId = findValueId(refreshed)
}
}
if (!valueId) {
toast({
title: 'Kunde inte lägga till regeln',
description: `Värdet ${code} hittades inte i registret.`,
variant: 'destructive',
})
return
}
}
const body: Record<string, unknown> = {
account_number: account.account_number,
dimension_id: newRuleDim.id,
rule_type: newRuleType,
}
if (valueId) body.value_id = valueId
const res = await fetch('/api/dimensions/rules', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
const json = await res.json().catch(() => null)
if (!res.ok) {
toast({
title: 'Kunde inte lägga till regeln',
description: getErrorMessage(json, { locale: 'sv' }),
variant: 'destructive',
})
return
}
const created = json?.data?.rule as AccountDimensionRuleDto | undefined
if (created) setRules((prev) => [...prev, created])
toast({ title: 'Regel tillagd' })
resetAddRuleForm()
} finally {
setIsAddingRule(false)
}
}
async function handleToggleRule(rule: AccountDimensionRuleDto, checked: boolean) {
const ruleId = rule.account_dimension_rule_id
// Optimistic — the switch flips immediately and reverts on failure.
setRules((prev) =>
prev.map((r) =>
r.account_dimension_rule_id === ruleId ? { ...r, is_active: checked } : r,
),
)
const res = await fetch(`/api/dimensions/rules/${ruleId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ is_active: checked }),
}).catch(() => null)
const json = await res?.json().catch(() => null)
if (!res?.ok) {
setRules((prev) =>
prev.map((r) =>
r.account_dimension_rule_id === ruleId ? { ...r, is_active: rule.is_active } : r,
),
)
toast({
title: 'Kunde inte uppdatera regeln',
description: getErrorMessage(json, { locale: 'sv' }),
variant: 'destructive',
})
return
}
const updated = json?.data?.rule as AccountDimensionRuleDto | undefined
if (updated) {
setRules((prev) =>
prev.map((r) => (r.account_dimension_rule_id === ruleId ? updated : r)),
)
}
}
async function handleDeleteRule(rule: AccountDimensionRuleDto) {
const ruleId = rule.account_dimension_rule_id
const res = await fetch(`/api/dimensions/rules/${ruleId}`, {
method: 'DELETE',
}).catch(() => null)
if (!res?.ok) {
const json = await res?.json().catch(() => null)
toast({
title: 'Kunde inte ta bort regeln',
description: getErrorMessage(json, { locale: 'sv' }),
variant: 'destructive',
})
return
}
setRules((prev) => prev.filter((r) => r.account_dimension_rule_id !== ruleId))
toast({ title: 'Regel borttagen' })
}
async function handleSave() {
setIsSaving(true)
try {
const response = await fetch(`/api/bookkeeping/accounts/${account.account_number}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
account_name: accountName,
description: description || null,
default_vat_rate: defaultVatRate === 'none' ? null : parseFloat(defaultVatRate),
default_vat_treatment: defaultVatTreatment === 'none' ? null : defaultVatTreatment,
sru_code: sruCode || null,
is_active: isActive,
}),
})
if (!response.ok) {
const data = await response.json().catch(() => null)
// Keep the dialog open so the user can correct and retry; map the
// server error to Swedish like the dimension-rule handlers above.
toast({
title: 'Kunde inte uppdatera kontot',
description: getErrorMessage(data, { locale: 'sv' }),
variant: 'destructive',
})
return
}
onSaved()
onOpenChange(false)
} catch {
toast({
title: 'Kunde inte uppdatera kontot',
variant: 'destructive',
})
} finally {
setIsSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>
Redigera konto <span data-ph-mask="">{account.account_number}</span>
</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label>Kontonamn</Label>
<Input
value={accountName}
onChange={(e) => setAccountName(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>Beskrivning</Label>
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Kort beskrivning av kontots användning"
rows={2}
/>
</div>
<AccountVatTreatmentSelect
value={defaultVatTreatment}
accountClass={account.account_class}
onValueChange={(treatment) => {
setDefaultVatTreatment(treatment)
if (treatment !== 'none' && defaultVatRate === 'none') {
const rate = defaultRateForVatTreatment(treatment, account.account_class)
if (rate !== null) setDefaultVatRate(String(rate))
}
}}
/>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Standard moms</Label>
<Select value={defaultVatRate} onValueChange={setDefaultVatRate}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="none">Ingen standard</SelectItem>
<SelectItem value="0">Ingen moms</SelectItem>
<SelectItem value="0.25">25 %</SelectItem>
<SelectItem value="0.12">12 %</SelectItem>
<SelectItem value="0.06">6 %</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>SRU-kod</Label>
<Input
value={sruCode}
onChange={(e) => setSruCode(e.target.value)}
placeholder="T.ex. 7201"
/>
</div>
</div>
{dimensionsEnabled && (
<div className="space-y-3">
<p className="text-sm font-medium">Dimensionsregler</p>
{rulesLoading ? (
<Skeleton className="h-10 w-full" />
) : (
<>
{rules.length === 0 && !addRuleOpen && (
<div className="flex items-center justify-between gap-3">
<p className="text-xs text-muted-foreground">
Inga dimensionsregler för det här kontot.
</p>
<Button
variant="ghost"
size="sm"
onClick={() => setAddRuleOpen(true)}
>
<Plus className="mr-1 h-3.5 w-3.5" />
Lägg till regel
</Button>
</div>
)}
{rules.map((rule) => (
<div
key={rule.account_dimension_rule_id}
className="flex items-center gap-3 rounded-lg border p-3"
>
<div className="min-w-0 flex-1">
<p className="text-sm font-medium truncate">
{rule.dimension_name}
</p>
<p className="text-xs text-muted-foreground truncate">
{RULE_TYPE_LABELS[rule.rule_type]}
{rule.value_code && (
<>
{' · '}
<span className="font-mono">{rule.value_code}</span>
{rule.value_name && rule.value_name !== rule.value_code
? ` ${rule.value_name}`
: ''}
</>
)}
</p>
</div>
<Switch
checked={rule.is_active}
onCheckedChange={(checked) => handleToggleRule(rule, checked)}
aria-label={`Regel för ${rule.dimension_name} aktiv`}
/>
<Button
variant="ghost"
size="icon"
aria-label={`Ta bort regel för ${rule.dimension_name}`}
onClick={() => handleDeleteRule(rule)}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
{addRuleOpen ? (
<div className="space-y-3 rounded-lg border border-dashed p-3">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">
Dimension
</Label>
<Select
value={newRuleDimensionId || undefined}
onValueChange={(id) => {
setNewRuleDimensionId(id)
setNewRuleValueCode(null)
}}
>
<SelectTrigger>
<SelectValue placeholder="Välj dimension" />
</SelectTrigger>
<SelectContent>
{activeDims.map((dim) => (
<SelectItem key={dim.id} value={dim.id}>
{dim.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Typ</Label>
<Select
value={newRuleType}
onValueChange={(v) => {
setNewRuleType(v as DimensionRuleType)
if (v === 'required') setNewRuleValueCode(null)
}}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{(Object.keys(RULE_TYPE_LABELS) as DimensionRuleType[]).map(
(type) => (
<SelectItem key={type} value={type}>
{RULE_TYPE_LABELS[type]}
</SelectItem>
),
)}
</SelectContent>
</Select>
</div>
</div>
<p className="text-xs text-muted-foreground">
{RULE_TYPE_HELP[newRuleType]}
</p>
{newRuleNeedsValue && newRuleDim && (
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Värde</Label>
<DimensionCombobox
sieDimNo={String(newRuleDim.sie_dim_no)}
value={newRuleValueCode}
onChange={setNewRuleValueCode}
/>
</div>
)}
<div className="flex justify-end gap-2">
<Button
variant="ghost"
size="sm"
disabled={isAddingRule}
onClick={resetAddRuleForm}
>
Avbryt
</Button>
<Button
size="sm"
disabled={
isAddingRule ||
!newRuleDim ||
(newRuleNeedsValue && !newRuleValueCode)
}
onClick={handleAddRule}
>
{isAddingRule && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
Lägg till
</Button>
</div>
</div>
) : (
rules.length > 0 && (
<Button
variant="ghost"
size="sm"
onClick={() => setAddRuleOpen(true)}
>
<Plus className="mr-1 h-3.5 w-3.5" />
Lägg till regel
</Button>
)
)}
</>
)}
</div>
)}
<div className="flex items-center justify-between rounded-lg border p-3">
<div>
<p className="text-sm font-medium">Aktivt konto</p>
<p className="text-xs text-muted-foreground">
Inaktiva konton visas inte i bokföringsformulär
</p>
</div>
<Switch checked={isActive} onCheckedChange={setIsActive} />
</div>
{account.is_system_account && (
<p className="text-xs text-muted-foreground bg-muted rounded-sm p-2">
Detta är ett systemkonto och kan inte tas bort.
</p>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Avbryt
</Button>
<Button onClick={handleSave} disabled={isSaving || !accountName.trim()}>
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Spara
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,85 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import JournalEntryForm, { type FormLine } from '@/components/bookkeeping/JournalEntryForm'
import type { Currency, JournalEntry, JournalEntryLine } from '@/types'
interface Props {
entry: JournalEntry
open: boolean
onOpenChange: (open: boolean) => void
/** Fired after the draft is successfully updated. */
onUpdated: () => void
}
/**
* Edit a DRAFT verifikat. Wraps JournalEntryForm in edit mode, pre-filled from
* the draft's header + lines; the form PATCHes the entry in place and it stays
* a draft (the user posts it separately). Only ever opened for status==='draft'
* entries: the engine + DB triggers reject edits on committed entries anyway.
*/
export default function EditDraftEntryDialog({ entry, open, onOpenChange, onUpdated }: Props) {
const t = useTranslations('bookkeeping')
const sortedLines = ((entry.lines || []) as JournalEntryLine[])
.slice()
.sort((a, b) => a.sort_order - b.sort_order)
// The PATCH replaces all lines wholesale, so EVERYTHING a line carries must
// round-trip through the form: dimensions, per-line FX metadata (currency /
// amount_in_currency / exchange_rate) and tax_code. Omitting any of them
// meant a plain text edit silently reset a foreign-currency draft to SEK
// and stripped its tax code (issue #1174).
const initialLines: FormLine[] = sortedLines.map((l) => ({
account_number: l.account_number,
debit_amount: Number(l.debit_amount) > 0 ? String(l.debit_amount) : '',
credit_amount: Number(l.credit_amount) > 0 ? String(l.credit_amount) : '',
line_description: l.line_description || '',
currency: l.currency && l.currency !== 'SEK' ? l.currency : undefined,
amount_in_currency: l.amount_in_currency ?? undefined,
exchange_rate: l.exchange_rate ?? undefined,
tax_code: l.tax_code ?? undefined,
dimensions:
l.dimensions && Object.keys(l.dimensions).length > 0 ? { ...l.dimensions } : undefined,
}))
// Hydrate the form's currency picker + FX fields from the stored FX line so
// a EUR draft is displayed as EUR instead of silently reading SEK.
const fxLine = sortedLines.find((l) => l.currency && l.currency !== 'SEK')
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto"
// Same guard as Ny verifikat: an accidental outside-click must not
// discard in-progress edits.
onPointerDownOutside={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
>
<DialogHeader>
<DialogTitle>{t('edit_draft_dialog_title')}</DialogTitle>
</DialogHeader>
<JournalEntryForm
key={entry.id}
bare
editEntryId={entry.id}
initialLines={initialLines}
initialDate={entry.entry_date}
initialDescription={entry.description}
initialNotes={entry.notes ?? undefined}
initialVoucherSeries={entry.voucher_series}
initialCurrency={fxLine ? (fxLine.currency as Currency) : undefined}
initialExchangeRate={fxLine?.exchange_rate ?? undefined}
initialForeignAmount={fxLine?.amount_in_currency ?? undefined}
onUpdated={onUpdated}
/>
</DialogContent>
</Dialog>
)
}
@@ -1,77 +0,0 @@
'use client'
import {
monthsBetween,
parseDateParts,
validatePeriodDuration,
} from '@/lib/bookkeeping/validate-period-duration'
import type { EntityType } from '@/types'
function endsOnDec31(end: string): boolean {
const e = parseDateParts(end)
return e.month === 12 && e.day === 31
}
/**
* Map validatePeriodDuration's English messages to user-facing Swedish copy.
*/
function toSwedishError(msg: string): string {
if (msg.includes('after period start')) return 'Slutdatum måste vara efter startdatum.'
if (msg.includes('1st of a month')) return 'Startdatum måste vara den första i månaden.'
if (msg.includes('last day of a month')) return 'Slutdatum måste vara den sista i månaden.'
if (msg.includes('exceeds maximum 18 months')) return 'Räkenskapsåret får vara högst 18 månader (BFL 3 kap.).'
return msg
}
export interface FiscalPeriodValidation {
/** User-facing Swedish error, or null if valid */
error: string | null
/** Integer month count, or null if inputs are incomplete/invalid */
months: number | null
/** True if inputs are complete enough to render the summary */
canSummarise: boolean
}
/**
* Validation for the first fiscal period, used by the settings
* FiscalPeriodEditor. Returns Swedish error copy.
*/
export function validateFirstPeriod(
startDate: string,
endDate: string,
entityType: EntityType | undefined
): FiscalPeriodValidation {
if (!startDate || !endDate) {
return { error: null, months: null, canSummarise: false }
}
if (endDate <= startDate) {
return {
error: 'Slutdatum måste vara efter startdatum.',
months: null,
canSummarise: false,
}
}
const baseError = validatePeriodDuration(startDate, endDate, { isFirstPeriod: true })
if (baseError) {
return {
error: toSwedishError(baseError),
months: monthsBetween(startDate, endDate),
canSummarise: true,
}
}
if (entityType === 'enskild_firma' && !endsOnDec31(endDate)) {
return {
error: 'Enskild firma måste ha slutdatum 31 december (BFL 3 kap.).',
months: monthsBetween(startDate, endDate),
canSummarise: true,
}
}
return {
error: null,
months: monthsBetween(startDate, endDate),
canSummarise: true,
}
}
@@ -1,348 +0,0 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import { Input } from '@/components/ui/input'
import { useToast } from '@/components/ui/use-toast'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import { FileText, ImageIcon, Loader2, Search, Inbox, Eye } from 'lucide-react'
// InboxDocumentPicker
//
// Lists invoice-inbox documents that have not yet been consumed (no supplier
// invoice, no journal entry, not matched to a transaction, document not
// already linked) so the user can attach one as underlag to a verifikat.
//
// Two modes:
// - Link mode (JournalEntryAttachments, "Välj från inkorgen"): `journalEntryId`
// is set and picking a document immediately links it to the journal entry AND
// stamps the inbox item so it drops out of the active inbox: see
// app/api/documents/[id]/link/route.ts.
// - Select mode (TransactionBookingDialog, "Välj befintligt underlag"): the
// journal entry does not exist yet, so `onSelect` is provided instead and the
// pick is reported to the parent, which links after the entry is created.
//
// Each row carries a preview button (eye) that opens a quick dialog rendering
// the document inline, so the user can confirm the right file before attaching.
// Attaching is the row's primary click (fast path) and is also offered from
// inside the preview dialog (preview → confirm).
export interface AvailableInboxDoc {
inbox_item_id: string
document_id: string
file_name: string
mime_type: string | null
file_size_bytes: number
source: string | null
created_at: string
supplier_name: string | null
amount: number | null
currency: string | null
invoice_date: string | null
}
interface Props {
open: boolean
onClose: () => void
/** Link mode: the journal entry to link the picked document to. */
journalEntryId?: string
/** Link mode: called after a successful link so the parent can refresh its document list. */
onLinked?: () => void
/** Select mode: report the picked document to the parent instead of linking. */
onSelect?: (doc: AvailableInboxDoc) => void
}
function isImageType(type: string | null): boolean {
return type?.startsWith('image/') ?? false
}
function isPdfType(type: string | null): boolean {
return type === 'application/pdf'
}
function DocIcon({ mime }: { mime: string | null }) {
if (isImageType(mime)) {
return <ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
}
return <FileText className="h-4 w-4 text-muted-foreground shrink-0" />
}
export default function InboxDocumentPicker({ open, onClose, journalEntryId, onLinked, onSelect }: Props) {
const t = useTranslations('journal_attachments')
const { toast } = useToast()
const [loading, setLoading] = useState(true)
const [items, setItems] = useState<AvailableInboxDoc[]>([])
const [search, setSearch] = useState('')
const [linkingId, setLinkingId] = useState<string | null>(null)
const [previewItem, setPreviewItem] = useState<AvailableInboxDoc | null>(null)
// Reset + fetch each time the dialog opens.
useEffect(() => {
if (!open) return
setSearch('')
setItems([])
setPreviewItem(null)
setLoading(true)
let cancelled = false
;(async () => {
try {
const res = await fetch('/api/documents/inbox-available')
const json = (await res.json().catch(() => ({}))) as { data?: AvailableInboxDoc[] }
if (cancelled) return
setItems(json.data ?? [])
} catch {
if (!cancelled) setItems([])
} finally {
if (!cancelled) setLoading(false)
}
})()
return () => {
cancelled = true
}
}, [open])
const filtered = useMemo(() => {
const q = search.trim().toLowerCase()
if (!q) return items
return items.filter((it) =>
`${it.supplier_name ?? ''} ${it.file_name}`.toLowerCase().includes(q),
)
}, [items, search])
async function handlePick(item: AvailableInboxDoc) {
// Select mode: the journal entry doesn't exist yet: hand the pick to the
// parent and let it link after creation. Clear the preview first: the
// preview dialog's open state is `previewItem !== null`, so leaving it set
// would strand a floating preview after the picker closes (the component
// stays mounted; the on-open reset only runs on the next open).
if (onSelect) {
setPreviewItem(null)
onSelect(item)
onClose()
return
}
if (!journalEntryId) return
setLinkingId(item.document_id)
try {
const res = await fetch(`/api/documents/${item.document_id}/link`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
journal_entry_id: journalEntryId,
inbox_item_id: item.inbox_item_id,
}),
})
if (!res.ok) {
const json = (await res.json().catch(() => ({}))) as {
error?: string | { message?: string }
}
const description =
typeof json.error === 'string' ? json.error : json.error?.message
toast({ title: t('picker_link_failed'), description, variant: 'destructive' })
return
}
toast({ title: t('picker_linked') })
setPreviewItem(null)
onLinked?.()
onClose()
} catch {
toast({ title: t('picker_link_failed'), variant: 'destructive' })
} finally {
setLinkingId(null)
}
}
const hasSearch = search.trim().length > 0
const previewSrc = previewItem ? `/api/documents/${previewItem.document_id}/inline` : null
return (
<>
<Dialog open={open} onOpenChange={(o) => !o && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{t('picker_title')}</DialogTitle>
</DialogHeader>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('picker_search_placeholder')}
className="pl-9"
/>
</div>
{!loading && filtered.length > 0 && (
<div className="flex justify-end px-1 text-[11px] text-muted-foreground tabular-nums">
{t('picker_results', { count: filtered.length })}
</div>
)}
<div className="max-h-[55vh] overflow-y-auto -mx-6 px-6 divide-y">
{loading ? (
<div className="space-y-3 py-3">
{Array.from({ length: 5 }).map((_, i) => (
<Skeleton key={i} className="h-12 w-full" />
))}
</div>
) : filtered.length === 0 ? (
<div className="py-10 flex flex-col items-center gap-2 text-center">
<Inbox className="h-6 w-6 text-muted-foreground" />
<p className="text-sm text-muted-foreground">
{hasSearch ? t('picker_empty_search', { query: search.trim() }) : t('picker_empty')}
</p>
</div>
) : (
filtered.map((it) => {
const isLinking = linkingId === it.document_id
const sourceLabel =
it.source === 'email' ? t('picker_source_email') : t('picker_source_upload')
return (
<div key={it.inbox_item_id} className="flex items-center gap-1">
<button
type="button"
onClick={() => void handlePick(it)}
disabled={!!linkingId}
className={cn(
'flex-1 min-w-0 text-left flex items-center gap-3 py-3 px-2 -ml-2 rounded-sm transition-colors hover:bg-secondary/60',
linkingId && !isLinking && 'opacity-50',
)}
>
<DocIcon mime={it.mime_type} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 min-w-0">
<span className="text-sm font-medium truncate">
{it.supplier_name ?? it.file_name}
</span>
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">
{it.invoice_date && <span>{formatDate(it.invoice_date)}</span>}
{it.supplier_name && (
<span className="truncate font-normal">{it.file_name}</span>
)}
<span className="shrink-0">{sourceLabel}</span>
</div>
</div>
{it.amount != null && (
<span className="text-sm font-medium tabular-nums shrink-0">
{formatCurrency(it.amount, it.currency ?? 'SEK')}
</span>
)}
{isLinking && (
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground shrink-0" />
)}
</button>
<Button
variant="ghost"
size="icon"
className="h-10 w-10 shrink-0"
aria-label={t('picker_preview')}
title={t('picker_preview')}
onClick={(e) => {
e.stopPropagation()
setPreviewItem(it)
}}
>
<Eye className="h-4 w-4" />
</Button>
</div>
)
})
)}
</div>
</DialogContent>
</Dialog>
<Dialog open={previewItem !== null} onOpenChange={(o) => !o && setPreviewItem(null)}>
<DialogContent className="max-w-3xl">
<DialogHeader>
{/* data-ph-mask: the file name and supplier details are user data */}
<DialogTitle data-ph-mask="" className="truncate pr-6">{previewItem?.file_name}</DialogTitle>
{previewItem && (previewItem.supplier_name || previewItem.amount != null) && (
<DialogDescription data-ph-mask="" className="flex items-center gap-2 tabular-nums">
{previewItem.supplier_name && <span>{previewItem.supplier_name}</span>}
{previewItem.amount != null && (
<span>{formatCurrency(previewItem.amount, previewItem.currency ?? 'SEK')}</span>
)}
{previewItem.invoice_date && <span>{formatDate(previewItem.invoice_date)}</span>}
</DialogDescription>
)}
</DialogHeader>
{previewItem && previewSrc && (
<div className="py-1">
{isImageType(previewItem.mime_type) ? (
<img
src={previewSrc}
alt={previewItem.file_name}
className="max-h-[70vh] w-full rounded-lg border object-contain"
/>
) : isPdfType(previewItem.mime_type) ? (
// <object> + type="application/pdf" invokes Chrome's PDF plugin
// directly; <iframe> intermittently shows a blocked-content
// notice even with a permissive CSP. Mirrors JournalEntryAttachments.
<object
data={previewSrc}
type="application/pdf"
aria-label={previewItem.file_name}
className="w-full h-[70vh] rounded-lg border"
>
<a
href={previewSrc}
target="_blank"
rel="noopener noreferrer"
className="block px-4 py-2 text-sm text-muted-foreground underline"
>
{t('picker_preview_unavailable')}
</a>
</object>
) : (
<a
href={previewSrc}
target="_blank"
rel="noopener noreferrer"
className="block px-4 py-6 text-sm text-muted-foreground underline text-center"
>
{t('picker_preview_unavailable')}
</a>
)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setPreviewItem(null)}>
{t('picker_close')}
</Button>
<Button
onClick={() => {
if (previewItem) void handlePick(previewItem)
}}
disabled={!!linkingId}
>
{previewItem && linkingId === previewItem.document_id ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('picker_attach')}
</>
) : (
t('picker_attach')
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
)
}
@@ -1,557 +0,0 @@
'use client'
import { useState, useEffect, useCallback, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import { cn } from '@/lib/utils'
import { openDeferredTab } from '@/lib/browser/deferred-tab'
import {
FileText,
ImageIcon,
Download,
ChevronDown,
ChevronUp,
Plus,
Trash2,
RefreshCw,
Loader2,
Lock,
AlertTriangle,
Inbox,
} from 'lucide-react'
import DocumentUploadZone from '@/components/bookkeeping/DocumentUploadZone'
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
import InboxDocumentPicker from '@/components/bookkeeping/InboxDocumentPicker'
import { useBranding } from '@/lib/branding/brand-context'
interface DocumentRecord {
id: string
file_name: string
file_size_bytes: number
mime_type: string | null
storage_path: string
created_at: string
sha256_hash?: string | null
download_url?: string
referenced?: boolean
}
interface JournalEntryAttachmentsProps {
journalEntryId: string
onCountChange?: (count: number) => void
/**
* 'section': embedded under a DetailSection kicker that already names the
* group and states the empty case (verifikat detail page). Drops the own
* border, heading and empty line so nothing is said twice; the action
* buttons and the document list stay. Default keeps the self-contained
* foldout look used by JournalEntryList.
*/
variant?: 'default' | 'section'
}
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
function isImageType(type: string | null): boolean {
return type?.startsWith('image/') ?? false
}
function isPdfType(type: string | null): boolean {
return type === 'application/pdf'
}
function isPreviewable(type: string | null): boolean {
return isImageType(type) || isPdfType(type)
}
export default function JournalEntryAttachments({
journalEntryId,
onCountChange,
variant = 'default',
}: JournalEntryAttachmentsProps) {
const embedded = variant === 'section'
const t = useTranslations('journal_attachments')
const tCommon = useTranslations('common')
const { appName } = useBranding()
const { toast } = useToast()
const [documents, setDocuments] = useState<DocumentRecord[]>([])
const [loading, setLoading] = useState(true)
const [expandedDoc, setExpandedDoc] = useState<string | null>(null)
const [showUpload, setShowUpload] = useState(false)
const [showInboxPicker, setShowInboxPicker] = useState(false)
const [uploadFiles, setUploadFiles] = useState<UploadedFile[]>([])
// Docs listed here are filtered by journal_entry_id, so every row is bound
// to a verifikation: BFL 7 kap 2§ blocks deletion. "Ta bort" therefore
// surfaces the educational modal; "Ersätt" goes through createNewVersion()
// so the original stays in the version chain.
const [blockedDoc, setBlockedDoc] = useState<DocumentRecord | null>(null)
const [replacingDocId, setReplacingDocId] = useState<string | null>(null)
const [detachingDocId, setDetachingDocId] = useState<string | null>(null)
const replaceFileInputRef = useRef<HTMLInputElement | null>(null)
const replaceTargetIdRef = useRef<string | null>(null)
const onCountChangeRef = useRef(onCountChange)
onCountChangeRef.current = onCountChange
const fetchDocuments = useCallback(async () => {
try {
const [documentsRes, referencesRes] = await Promise.all([
fetch(`/api/documents?journal_entry_id=${journalEntryId}&current_only=true`),
fetch(`/api/bookkeeping/journal-entries/${journalEntryId}/references`),
])
const { data: directDocuments } = await documentsRes.json()
const direct = (directDocuments || []) as DocumentRecord[]
const directIds = new Set(direct.map((document) => document.id))
let referenced: DocumentRecord[] = []
if (referencesRes.ok) {
const { data: referenceData } = await referencesRes.json()
const documentIds = Array.from(new Set<string>(
(referenceData?.references || [])
.map((reference: { document_id?: string }) => reference.document_id)
.filter((documentId: string | undefined): documentId is string => (
Boolean(documentId) && !directIds.has(documentId as string)
)),
))
const referencedDocuments = await Promise.all(
documentIds.map(async (documentId) => {
try {
const response = await fetch(`/api/documents/${documentId}`)
if (!response.ok) return null
const { data } = await response.json()
return data ? { ...data, referenced: true } as DocumentRecord : null
} catch {
return null
}
}),
)
referenced = referencedDocuments.filter(
(document): document is DocumentRecord => document !== null,
)
}
const allDocuments = [...direct, ...referenced]
setDocuments(allDocuments)
onCountChangeRef.current?.(allDocuments.length)
} catch {
// Non-critical: silently ignore
} finally {
setLoading(false)
}
}, [journalEntryId])
useEffect(() => {
fetchDocuments()
}, [fetchDocuments])
// Refresh documents when uploads complete
useEffect(() => {
const allDone = uploadFiles.length > 0 && uploadFiles.every((f) => f.status !== 'uploading')
const hasUploaded = uploadFiles.some((f) => f.status === 'uploaded')
if (allDone && hasUploaded) {
fetchDocuments()
setUploadFiles([])
setShowUpload(false)
}
}, [uploadFiles, fetchDocuments])
const handleDownload = async (docId: string) => {
// Pre-open inside the click's user activation: a window.open after the
// await is popup-blocked when the signed-URL fetch is slow.
const tab = openDeferredTab(tCommon('loading'))
try {
const res = await fetch(`/api/documents/${docId}`)
const { data } = await res.json()
if (!data?.download_url || !tab.navigate(data.download_url)) {
tab.close()
toast({
title: t('download_failed'),
description: tab.blocked ? tCommon('popup_blocked_description', { appName }) : undefined,
variant: 'destructive',
})
}
} catch {
tab.close()
toast({ title: t('download_failed'), variant: 'destructive' })
}
}
const handlePreviewToggle = async (doc: DocumentRecord) => {
if (expandedDoc === doc.id) {
setExpandedDoc(null)
return
}
if (!doc.download_url) {
try {
const res = await fetch(`/api/documents/${doc.id}`)
const { data } = await res.json()
if (data?.download_url) {
setDocuments((prev) =>
prev.map((d) => (d.id === doc.id ? { ...d, download_url: data.download_url } : d))
)
}
} catch {
return
}
}
setExpandedDoc(doc.id)
}
const handleRequestRemove = (doc: DocumentRecord) => {
setBlockedDoc(doc)
}
// A duplicate may be detached (not deleted) only when another directly
// anchored doc with the SAME content hash remains on the verifikat: the
// detach_underlag_duplicate RPC enforces sha256 equality, so the button is
// gated on the same condition. Referenced docs (via a supplier invoice)
// don't count: they are not anchored to this entry.
const hasDuplicateSibling = (doc: DocumentRecord) =>
Boolean(doc.sha256_hash) &&
documents.some(
(d) => !d.referenced && d.id !== doc.id && d.sha256_hash === doc.sha256_hash,
)
const handleDetach = async (doc: DocumentRecord) => {
setDetachingDocId(doc.id)
try {
const res = await fetch(`/api/documents/${doc.id}/detach`, { method: 'POST' })
if (!res.ok) {
const { error } = await res.json().catch(() => ({ error: undefined }))
toast({
title: t('detach_failed'),
description: typeof error === 'string' ? error : undefined,
variant: 'destructive',
})
} else {
await fetchDocuments()
setBlockedDoc(null)
}
} catch {
toast({ title: t('detach_failed'), variant: 'destructive' })
} finally {
setDetachingDocId(null)
}
}
const handleOpenReplacePicker = (docId: string) => {
replaceTargetIdRef.current = docId
replaceFileInputRef.current?.click()
}
const handleReplaceFileSelected = async (file: File | null) => {
const docId = replaceTargetIdRef.current
replaceTargetIdRef.current = null
if (replaceFileInputRef.current) {
replaceFileInputRef.current.value = ''
}
if (!file || !docId) return
setReplacingDocId(docId)
try {
const fd = new FormData()
fd.append('file', file)
const res = await fetch(`/api/documents/${docId}/versions`, {
method: 'POST',
body: fd,
})
if (!res.ok) {
const { error } = await res.json().catch(() => ({ error: undefined }))
toast({
title: t('replace_failed'),
description: error || undefined,
variant: 'destructive',
})
} else {
await fetchDocuments()
setBlockedDoc(null)
}
} catch {
toast({ title: t('replace_failed'), variant: 'destructive' })
} finally {
setReplacingDocId(null)
}
}
if (loading) {
return (
<div className="py-2 text-sm text-muted-foreground">
{t('loading')}
</div>
)
}
return (
<div className={embedded ? undefined : 'border-t pt-3 mt-3'}>
<input
ref={replaceFileInputRef}
type="file"
accept="application/pdf,image/jpeg,image/png,image/webp"
className="hidden"
onChange={(e) => handleReplaceFileSelected(e.target.files?.[0] ?? null)}
/>
<div className={cn('mb-2 flex items-center gap-2', embedded ? 'justify-end' : 'justify-between')}>
{!embedded && (
<h4 className="text-sm font-medium">
{t('title')} {documents.length > 0 && `(${documents.length})`}
</h4>
)}
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={() => setShowInboxPicker(true)}
>
<Inbox className="h-3 w-3 mr-1" />
{t('choose_from_inbox')}
</Button>
<Button
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={() => setShowUpload(!showUpload)}
>
<Plus className="h-3 w-3 mr-1" />
{t('add')}
</Button>
</div>
</div>
{showUpload && (
<div className="mb-3">
<DocumentUploadZone
files={uploadFiles}
onFilesChange={setUploadFiles}
journalEntryId={journalEntryId}
compact
/>
</div>
)}
{documents.length === 0 && !showUpload ? (
!embedded && (
<p className="text-sm text-muted-foreground py-1">
{t('empty')}
</p>
)
) : (
<div className="space-y-1">
{documents.map((doc) => {
const isReplacing = replacingDocId === doc.id
return (
<div key={doc.id}>
<div className="flex items-center gap-2 text-sm py-1.5 px-2 rounded-sm bg-muted/50">
{isPreviewable(doc.mime_type) ? (
<button
onClick={() => handlePreviewToggle(doc)}
className="shrink-0 hover:text-primary transition-colors"
>
{expandedDoc === doc.id ? (
<ChevronUp className="h-4 w-4" />
) : (
<ChevronDown className="h-4 w-4" />
)}
</button>
) : (
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
)}
{isPreviewable(doc.mime_type) && expandedDoc !== doc.id && (
isImageType(doc.mime_type) ? (
<ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
) : (
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
)
)}
<span className="truncate flex-1">{doc.file_name}</span>
{doc.referenced && (
<Badge variant="secondary" className="shrink-0">
{t('via_supplier_invoice')}
</Badge>
)}
<span className="text-xs text-muted-foreground shrink-0">
{formatFileSize(doc.file_size_bytes)}
</span>
{!doc.referenced && (
<>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleOpenReplacePicker(doc.id)}
disabled={isReplacing}
title={t('replace')}
aria-label={t('replace')}
>
{isReplacing ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<RefreshCw className="h-3 w-3" />
)}
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleRequestRemove(doc)}
title={t('remove')}
aria-label={t('remove')}
>
<Trash2 className="h-3 w-3" />
</Button>
</>
)}
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleDownload(doc.id)}
title={t('download')}
aria-label={t('download')}
>
<Download className="h-3 w-3" />
</Button>
</div>
{expandedDoc === doc.id && doc.download_url && isImageType(doc.mime_type) && (
<div className="px-2 py-2">
<img
src={`/api/documents/${doc.id}/inline`}
alt={doc.file_name}
className="max-h-48 rounded-lg object-contain"
/>
</div>
)}
{expandedDoc === doc.id && doc.download_url && isPdfType(doc.mime_type) && (
<div className="px-2 py-2">
{/* <object> + type="application/pdf" invokes Chrome's PDF
plugin directly. <iframe> intermittently surfaced
"Det här innehållet har blockerats" in Chrome even
with a permissive CSP. See crbug.com/271452. */}
<object
data={`/api/documents/${doc.id}/inline`}
type="application/pdf"
aria-label={doc.file_name}
className="w-full h-[60vh] rounded-lg border"
>
<a
href={doc.download_url}
target="_blank"
rel="noopener noreferrer"
className="block px-4 py-2 text-sm text-muted-foreground underline"
>
{t('download')}
</a>
</object>
</div>
)}
</div>
)
})}
</div>
)}
<Dialog
open={blockedDoc !== null}
onOpenChange={(o) => {
if (!o) setBlockedDoc(null)
}}
>
<DialogContent>
<DialogHeader>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-muted shrink-0">
<Lock className="h-5 w-5 text-attn" />
</div>
<DialogTitle>{t('remove_blocked_title')}</DialogTitle>
</div>
<DialogDescription className="pt-3 text-sm text-muted-foreground">
{t('remove_blocked_body')}
</DialogDescription>
</DialogHeader>
<div className="rounded-lg border border-border bg-muted/30 p-3 text-sm">
<div className="flex items-start gap-2">
<AlertTriangle className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
<p className="text-muted-foreground">
{blockedDoc !== null && hasDuplicateSibling(blockedDoc)
? t('detach_hint')
: t('remove_blocked_hint')}
</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setBlockedDoc(null)}>
{t('remove_blocked_cancel_cta')}
</Button>
{blockedDoc !== null && hasDuplicateSibling(blockedDoc) && (
<Button
variant="outline"
onClick={() => {
if (blockedDoc) handleDetach(blockedDoc)
}}
disabled={blockedDoc !== null && detachingDocId === blockedDoc.id}
>
{blockedDoc !== null && detachingDocId === blockedDoc.id ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('detaching')}
</>
) : (
t('detach_cta')
)}
</Button>
)}
<Button
onClick={() => {
if (blockedDoc) handleOpenReplacePicker(blockedDoc.id)
}}
disabled={blockedDoc !== null && replacingDocId === blockedDoc.id}
>
{blockedDoc !== null && replacingDocId === blockedDoc.id ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('replace_uploading')}
</>
) : (
t('remove_blocked_replace_cta')
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<InboxDocumentPicker
open={showInboxPicker}
onClose={() => setShowInboxPicker(false)}
journalEntryId={journalEntryId}
onLinked={fetchDocuments}
/>
</div>
)
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,165 +0,0 @@
'use client'
import { Badge } from '@/components/ui/badge'
import { AccountNumber } from '@/components/ui/account-number'
import { CheckCircle2, Paperclip } from 'lucide-react'
import { formatAmount, formatDate } from '@/lib/utils'
interface ReviewLine {
account_number: string
debit_amount: string
credit_amount: string
line_description: string
}
interface JournalEntryReviewContentProps {
periodName: string
entryDate: string
description: string
notes?: string
voucherSeries?: string
lines: ReviewLine[]
totalDebit: number
totalCredit: number
attachmentCount?: number
showBalanceBadge?: boolean
hideDate?: boolean
}
export function JournalEntryReviewContent({
periodName,
entryDate,
description,
notes,
voucherSeries,
lines,
totalDebit,
totalCredit,
attachmentCount,
showBalanceBadge = true,
hideDate = false,
}: JournalEntryReviewContentProps) {
const activeLines = lines.filter(
(l) => l.account_number && (l.debit_amount || l.credit_amount)
)
return (
<div className="space-y-4">
{/* Header info */}
<div className="bg-muted rounded-lg p-4 space-y-2">
<div className={`grid gap-4 text-sm ${hideDate && !voucherSeries ? 'grid-cols-1' : hideDate || !voucherSeries ? 'grid-cols-2' : 'grid-cols-3'}`}>
<div>
<span className="text-muted-foreground">Räkenskapsår</span>
<p className="font-medium">{periodName}</p>
</div>
{!hideDate && (
<div>
<span className="text-muted-foreground">Datum</span>
<p className="font-medium">{formatDate(entryDate)}</p>
</div>
)}
{voucherSeries && (
<div>
<span className="text-muted-foreground">Serie</span>
<p className="font-medium font-mono">{voucherSeries}</p>
</div>
)}
</div>
<div className="text-sm">
<span className="text-muted-foreground">Beskrivning</span>
<p className="font-medium">{description}</p>
</div>
{notes && (
<div className="text-sm">
<span className="text-muted-foreground">Intern anteckning</span>
<p className="text-muted-foreground italic">{notes}</p>
</div>
)}
</div>
{/* Balance status */}
{(showBalanceBadge || (attachmentCount != null && attachmentCount > 0)) && (
<div className="flex items-center gap-2">
{showBalanceBadge && (
<Badge variant="success">
<CheckCircle2 className="h-3 w-3 mr-1" />
Debet = Kredit
</Badge>
)}
{attachmentCount != null && attachmentCount > 0 && (
<Badge variant="outline">
<Paperclip className="h-3 w-3 mr-1" />
{attachmentCount} underlag
</Badge>
)}
</div>
)}
{/* Debit/Credit: table on desktop, cards on mobile */}
<div className="hidden sm:block">
<table className="w-full text-sm">
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="border-b text-left">
<th className="py-2 w-24">Konto</th>
<th className="py-2">Beskrivning</th>
<th className="py-2 w-28 text-right">Debet</th>
<th className="py-2 w-28 text-right">Kredit</th>
</tr>
</thead>
<tbody>
{activeLines.map((line, index) => (
<tr key={index} className="border-b last:border-0">
<td className="py-2">
<AccountNumber number={line.account_number} />
</td>
<td className="py-2 text-muted-foreground">
{line.line_description || ''}
</td>
<td className="py-2 text-right">
{parseFloat(line.debit_amount) > 0
? formatAmount(parseFloat(line.debit_amount))
: ''}
</td>
<td className="py-2 text-right">
{parseFloat(line.credit_amount) > 0
? formatAmount(parseFloat(line.credit_amount))
: ''}
</td>
</tr>
))}
</tbody>
<tfoot>
<tr className="font-semibold border-t-2">
<td colSpan={2} className="py-2">Summa</td>
<td className="py-2 text-right text-success">{formatAmount(totalDebit)}</td>
<td className="py-2 text-right text-success">{formatAmount(totalCredit)}</td>
</tr>
</tfoot>
</table>
</div>
<div className="sm:hidden space-y-1.5">
{activeLines.map((line, index) => (
<div key={index} className="flex items-center justify-between py-2 border-b last:border-0 text-sm">
<div className="min-w-0">
<div className="flex items-center gap-1.5">
<AccountNumber number={line.account_number} />
{line.line_description && (
<span className="text-muted-foreground text-xs truncate">{line.line_description}</span>
)}
</div>
</div>
<span className="font-mono text-sm shrink-0 ml-2">
{parseFloat(line.debit_amount) > 0
? `D ${formatAmount(parseFloat(line.debit_amount))}`
: `K ${formatAmount(parseFloat(line.credit_amount))}`}
</span>
</div>
))}
<div className="flex justify-between pt-2 border-t-2 font-semibold text-sm">
<span>Summa</span>
<span className="text-success">D {formatAmount(totalDebit)} / K {formatAmount(totalCredit)}</span>
</div>
</div>
</div>
)
}
@@ -1,91 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import { Badge } from '@/components/ui/badge'
import type { JournalEntry } from '@/types'
type BadgeVariant = 'default' | 'secondary' | 'success' | 'warning' | 'destructive'
const statusVariants: Record<string, BadgeVariant> = {
draft: 'secondary',
posted: 'success',
reversed: 'warning',
cancelled: 'secondary',
}
const sourceTypeVariants: Record<string, BadgeVariant> = {
storno: 'destructive',
correction: 'default',
}
const SOURCE_TYPES = [
'manual',
'bank_transaction',
'invoice_created',
'invoice_paid',
'credit_note',
'salary_payment',
'opening_balance',
'year_end',
'storno',
'correction',
'import',
'system',
'supplier_invoice_registered',
'supplier_invoice_paid',
'supplier_invoice_cash_payment',
'currency_revaluation',
'reminder_fee',
'vat_settlement',
] as const
/**
* Hook returning the translated source-type label map. Use this in client
* components that need to render the human-readable label for a source_type.
*/
export function useSourceTypeLabels(): Record<string, string> {
const t = useTranslations('journal_status')
const out: Record<string, string> = {}
for (const key of SOURCE_TYPES) {
out[key] = t(`source_label_${key}`)
}
return out
}
interface Props {
entry: JournalEntry
showStatus?: boolean
}
export default function JournalEntryStatusBadge({ entry, showStatus = true }: Props) {
const t = useTranslations('journal_status')
const statusVariant = statusVariants[entry.status]
const sourceVariant = sourceTypeVariants[entry.source_type]
const statusLabelKey =
entry.status === 'draft' ? 'status_draft'
: entry.status === 'posted' ? 'status_posted'
: entry.status === 'reversed' ? 'status_reversed'
: entry.status === 'cancelled' ? 'status_cancelled'
: null
const sourceLabelKey =
entry.source_type === 'storno' ? 'source_storno'
: entry.source_type === 'correction' ? 'source_correction'
: null
return (
<span className="inline-flex items-center gap-1">
{showStatus && statusVariant && statusLabelKey && (
<Badge variant={statusVariant} className="text-[10px] px-1.5 py-0">
{t(statusLabelKey)}
</Badge>
)}
{sourceVariant && sourceLabelKey && (
<Badge variant={sourceVariant} className="text-[10px] px-1.5 py-0">
{t(sourceLabelKey)}
</Badge>
)}
</span>
)
}
@@ -1,102 +0,0 @@
'use client'
import { ArrowDown } from 'lucide-react'
import { AttnLine } from '@/components/ui/attn-line'
import { formatCurrency, formatDate } from '@/lib/utils'
interface MatchTransactionInvoicePreviewProps {
data: Record<string, unknown>
}
/**
* Two-card preview for `match_transaction_invoice` operations. Mirrors
* AttachDocumentPreview's layout so reviewers learn one matching idiom.
*/
export function MatchTransactionInvoicePreview({ data }: MatchTransactionInvoicePreviewProps) {
const txDescription = (data.transaction_description as string) || '-'
const txAmount = data.transaction_amount as number | undefined
const txCurrency = (data.transaction_currency as string) || 'SEK'
const txDate = data.transaction_date as string | undefined
const invoiceNumber = (data.invoice_number as string) || '-'
const invoiceTotal = data.invoice_total as number | undefined
const invoiceCurrency = (data.invoice_currency as string) || txCurrency
const invoiceDate = data.invoice_date as string | undefined
const customerName = data.customer_name as string | undefined
// Staged by the MCP tool when the duplicate check could not run, or when
// force=true books over a voucher that already looks like this payment
// (issue #2294). The server owns the wording; rendered verbatim so the
// /pending card and the agent read the same warning.
const complianceWarning =
typeof data.compliance_warning === 'string' && data.compliance_warning.trim()
? data.compliance_warning
: null
// BFL 5 kap 4§ requires bookings to be made "so soon as possible" relative
// to the affärshändelse, so a transaction and invoice that diverge by more
// than a calendar month deserve a second look before the reviewer approves
// the match. The threshold is editorial, not legislated: it just nudges
// the reviewer; it doesn't block.
const showDateDriftHint =
txDate &&
invoiceDate &&
Math.abs(new Date(txDate).getTime() - new Date(invoiceDate).getTime()) > 31 * 24 * 60 * 60 * 1000
return (
<div className="space-y-3 text-sm">
{complianceWarning && <AttnLine>{complianceWarning}</AttnLine>}
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
<PreviewCard label="Transaktion">
{txDate && <Row label="Datum" value={formatDate(txDate)} tabular />}
<Row label="Beskrivning" value={txDescription} />
<Row
label="Belopp"
value={typeof txAmount === 'number' ? formatCurrency(txAmount, txCurrency) : '-'}
tabular
/>
</PreviewCard>
<PreviewCard label="Faktura">
<Row label="Nummer" value={invoiceNumber} tabular />
{invoiceDate && <Row label="Fakturadatum" value={formatDate(invoiceDate)} tabular />}
{customerName && <Row label="Kund" value={customerName} />}
{typeof invoiceTotal === 'number' && (
<Row label="Totalt" value={formatCurrency(invoiceTotal, invoiceCurrency)} tabular />
)}
</PreviewCard>
</div>
<div className="flex items-center justify-center text-xs text-muted-foreground">
<ArrowDown className="h-3.5 w-3.5 mr-1" />
matchas mot fakturan
</div>
{showDateDriftHint && (
<p className="text-xs text-muted-foreground">
Transaktionsdatum och fakturadatum skiljer sig med mer än en månad: kontrollera att
matchningen avser rätt affärshändelse.
</p>
)}
</div>
)
}
function PreviewCard({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="rounded-lg border border-border p-3 space-y-1.5">
<p className="text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
{label}
</p>
{children}
</div>
)
}
function Row({ label, value, tabular }: { label: string; value: string; tabular?: boolean }) {
return (
<div className="flex justify-between gap-3">
<span className="text-xs text-muted-foreground shrink-0">{label}</span>
<span className={`text-sm ${tabular ? 'tabular-nums' : ''} text-right truncate`}>{value}</span>
</div>
)
}
@@ -1,132 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import { Copy, Link2, Loader2 } from 'lucide-react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import JournalEntryForm, { type FormLine } from '@/components/bookkeeping/JournalEntryForm'
export interface CopyPrefill {
sourceId: string
sourceVoucherLabel: string
lines: FormLine[]
description: string
notes: string
}
/** Prefill for the skattekonto "Skapa verifikat manuellt" deep link. */
export interface SkvLinkPrefill {
transactionId: string
/** Row summary for the banner: date, text and amount, built by the caller. */
bannerLabel: string
lines: FormLine[]
description: string
date: string
}
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
/** Fired after a verifikat is created/saved as draft. */
onCreated: () => void
/** Fired with the created entry's id (both posted and draft saves). */
onEntryCreated?: (entryId: string) => void
/** When set, the form is pre-filled from a copied verifikat. */
copyPrefill?: CopyPrefill | null
/** When set, the form is pre-filled from a skattekonto row and the caller
* links the created entry back to it. copyPrefill wins if both are set. */
skvPrefill?: SkvLinkPrefill | null
/** True while the copy source is being fetched. */
isLoading?: boolean
}
/**
* "Ny verifikat" as a modal: the dialog you type a manual voucher into,
* instead of an inline tab. Wraps the standalone JournalEntryForm; the form's
* own review/confirm dialogs stack on top of this one.
*/
export default function NewJournalEntryDialog({
open,
onOpenChange,
onCreated,
onEntryCreated,
copyPrefill,
skvPrefill,
isLoading,
}: Props) {
const t = useTranslations('bookkeeping')
const activeSkvPrefill = copyPrefill ? null : (skvPrefill ?? null)
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
// Wide: the konteringsrader table (konto, radtext, debet, kredit,
// saldo) is the point of this dialog, and at 3xl the amount columns
// were squeezed against the account search. Capped at 6xl so it stays
// a dialog on an ultrawide screen.
className="sm:max-w-5xl lg:max-w-6xl max-h-[95dvh] sm:max-h-[92vh] overflow-y-auto"
// A half-typed verifikat must survive an accidental backdrop click or a
// stray Escape (easy to hit across multiple windows/screens, or when you
// only meant to dismiss a combobox dropdown). Closing is explicit: the
// header X. This also stops nested popovers (AccountCombobox, date
// pickers) and the form's own confirm dialogs from collapsing the parent
// when they portal outside it.
onEscapeKeyDown={(e) => e.preventDefault()}
onPointerDownOutside={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
>
<DialogHeader>
<DialogTitle>{t('new_entry_dialog_title')}</DialogTitle>
</DialogHeader>
{isLoading ? (
<div className="flex items-center justify-center gap-2 py-12 text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
<span className="text-sm">{t('loading_source_voucher')}</span>
</div>
) : (
<>
{copyPrefill && (
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 p-3 text-sm">
<Copy className="h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" />
<div className="flex-1">
<p className="font-medium">
{t('copy_banner_title', {
label: copyPrefill.sourceVoucherLabel || t('copy_banner_unknown_label'),
})}
</p>
<p className="text-muted-foreground mt-0.5">{t('copy_banner_body')}</p>
</div>
</div>
)}
{activeSkvPrefill && (
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 p-3 text-sm">
<Link2 className="h-4 w-4 mt-0.5 shrink-0 text-muted-foreground" />
<div className="flex-1">
<p className="font-medium">
{t('skv_link_banner_title', { label: activeSkvPrefill.bannerLabel })}
</p>
<p className="text-muted-foreground mt-0.5">{t('skv_link_banner_body')}</p>
</div>
</div>
)}
<JournalEntryForm
key={copyPrefill?.sourceId ?? activeSkvPrefill?.transactionId ?? 'fresh'}
bare
onCreated={onCreated}
onEntryCreated={onEntryCreated}
initialLines={copyPrefill?.lines ?? activeSkvPrefill?.lines}
initialDate={activeSkvPrefill?.date}
initialDescription={copyPrefill?.description ?? activeSkvPrefill?.description}
initialNotes={copyPrefill?.notes}
/>
</>
)}
</DialogContent>
</Dialog>
)
}
@@ -1,169 +0,0 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Loader2, CircleSlash, Lock } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
interface Props {
entryId: string
initialExempt: boolean
initialReason: string | null
canWrite: boolean
onChange: (exempted: boolean, reason: string | null) => void
}
/**
* Lets the bookkeeper mark a posted verifikation as not needing a separate
* underlag (bankavgift, ränta, intern överföring etc.). Toggling persists via
* /api/bookkeeping/journal-entries/[id]/no-document-required.
*
* The flag lives in journal_entry_no_doc_required (sidecar) so the underlying
* verifikation stays immutable per BFL.
*/
export default function NoDocRequiredToggle({
entryId,
initialExempt,
initialReason,
canWrite,
onChange,
}: Props) {
const t = useTranslations('journal_list')
const { toast } = useToast()
const [exempt, setExempt] = useState(initialExempt)
const [reason, setReason] = useState(initialReason ?? '')
const [saving, setSaving] = useState(false)
const [editingReason, setEditingReason] = useState(false)
const persistExempt = async (
nextExempt: boolean,
nextReason: string | null,
previousReason: string,
) => {
setSaving(true)
try {
const res = nextExempt
? await fetch(`/api/bookkeeping/journal-entries/${entryId}/no-document-required`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reason: nextReason ?? null }),
})
: await fetch(`/api/bookkeeping/journal-entries/${entryId}/no-document-required`, {
method: 'DELETE',
})
if (!res.ok) {
// Resolve via the parsed body plus the status: the route answers
// thrown errors with the canonical envelope `{ error: { code,
// message } }`, and rendering that object as the toast description
// would crash React ("Objects are not valid as a React child").
const body = await res.json().catch(() => null)
toast({
title: t('no_doc_required_save_failed'),
description: getErrorMessage(body, { statusCode: res.status }),
variant: 'destructive',
})
// Roll back UI state on failure: both the toggle AND the reason so
// the rendered state matches the DB row we failed to mutate.
setExempt(!nextExempt)
setReason(previousReason)
return
}
onChange(nextExempt, nextExempt ? nextReason : null)
} catch {
toast({ title: t('no_doc_required_save_failed'), variant: 'destructive' })
setExempt(!nextExempt)
setReason(previousReason)
} finally {
setSaving(false)
}
}
const handleToggle = (checked: boolean) => {
const previousReason = reason
setExempt(checked)
if (!checked) {
setReason('')
setEditingReason(false)
}
persistExempt(checked, checked ? (reason.trim() || null) : null, previousReason)
}
const handleSaveReason = () => {
setEditingReason(false)
persistExempt(true, reason.trim() || null, reason)
}
return (
<div className="mt-4 pt-3 border-t">
<div className="flex items-center gap-2">
<Switch
id={`no-doc-${entryId}`}
checked={exempt}
onCheckedChange={handleToggle}
disabled={!canWrite || saving}
/>
<Label
htmlFor={`no-doc-${entryId}`}
className="text-sm cursor-pointer flex items-center gap-1.5"
>
{!canWrite && <Lock className="h-3 w-3" />}
{saving && <Loader2 className="h-3 w-3 animate-spin" />}
{!saving && exempt && <CircleSlash className="h-3.5 w-3.5 text-muted-foreground" />}
{t('no_doc_required_toggle')}
</Label>
</div>
{exempt && (
<div className="mt-2 ml-10 space-y-1">
{editingReason ? (
<div className="flex items-center gap-2">
<Input
value={reason}
onChange={(e) => setReason(e.target.value)}
placeholder={t('no_doc_required_reason_placeholder')}
list={`no-doc-suggestions-${entryId}`}
maxLength={200}
className="h-8 text-xs flex-1 max-w-sm"
disabled={saving}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
handleSaveReason()
}
}}
/>
<datalist id={`no-doc-suggestions-${entryId}`}>
<option value={t('no_doc_required_suggestion_bank_fee')} />
<option value={t('no_doc_required_suggestion_interest')} />
<option value={t('no_doc_required_suggestion_internal_transfer')} />
<option value={t('no_doc_required_suggestion_tax_payment')} />
<option value={t('no_doc_required_suggestion_salary')} />
</datalist>
<Button size="sm" variant="outline" className="h-8" onClick={handleSaveReason} disabled={saving}>
{t('no_doc_required_save_reason')}
</Button>
</div>
) : (
<button
type="button"
onClick={() => canWrite && setEditingReason(true)}
disabled={!canWrite}
className="text-xs text-muted-foreground hover:text-foreground transition-colors text-left"
>
{reason
? `${t('no_doc_required_reason_label')}: ${reason}`
: t('no_doc_required_reason_add')}
</button>
)}
</div>
)}
</div>
)
}
@@ -1,342 +0,0 @@
'use client'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { useToast } from '@/components/ui/use-toast'
import {
DestructiveConfirmDialog,
useDestructiveConfirm,
} from '@/components/ui/destructive-confirm-dialog'
import { Loader2, Search, Trash2 } from 'lucide-react'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
interface PruneCandidate {
account_number: string
account_name: string
account_class: number
plan_type: string | null
is_active: boolean
in_bas_reference: boolean
}
interface PruneAccountsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** Called after a successful prune so the parent can refetch the chart. */
onPruned: () => void
}
/**
* Bulk deletion of unused accounts. Fetches the server-computed deletable set
* (dry run) and presents it in two groups — imported/custom accounts and
* untouched accounts from the seeded base plan. Nothing is preselected:
* deletion is opt-in per account or per group. Used accounts never appear
* here; the server re-verifies every guard at execute time anyway.
*/
export function PruneAccountsDialog({ open, onOpenChange, onPruned }: PruneAccountsDialogProps) {
const t = useTranslations('chart_of_accounts')
const tCommon = useTranslations('common')
const { toast } = useToast()
const { dialogProps: confirmDialogProps, confirm } = useDestructiveConfirm()
const [loading, setLoading] = useState(false)
const [candidates, setCandidates] = useState<PruneCandidate[]>([])
const [usedCount, setUsedCount] = useState(0)
const [selected, setSelected] = useState<Set<string>>(new Set())
const [searchQuery, setSearchQuery] = useState('')
const [isDeleting, setIsDeleting] = useState(false)
// Grouping only: imported/manually added accounts (the typical cleanup
// target) are listed separately from unused accounts in the seeded base
// plan, so users see what came from an import at a glance.
const isImportedOrCustom = useCallback(
(c: PruneCandidate) => !c.in_bas_reference || c.plan_type === 'full_bas',
[],
)
useEffect(() => {
if (!open) return
let cancelled = false
async function load() {
setLoading(true)
setCandidates([])
setSelected(new Set())
setSearchQuery('')
try {
const res = await fetch('/api/bookkeeping/accounts/prune', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ dry_run: true }),
})
if (!res.ok) throw new Error()
const { data } = await res.json()
if (cancelled) return
const deletable: PruneCandidate[] = data?.deletable ?? []
setCandidates(deletable)
setUsedCount((data?.used ?? []).length)
// Nothing starts selected — deletion is opt-in per account (or per
// group via the header checkbox), never a preloaded default.
} catch {
if (!cancelled) {
toast({ title: t('toast_prune_failed'), variant: 'destructive' })
onOpenChange(false)
}
} finally {
if (!cancelled) setLoading(false)
}
}
load()
return () => {
cancelled = true
}
}, [open, onOpenChange, t, toast])
// Charts bloated by an import easily reach hundreds of candidates — filter
// by number or name, same semantics as the kontoplan page search. Selection
// is keyed by account number, so it survives filter changes; the confirm
// button always shows the true selected count.
const filteredCandidates = useMemo(() => {
if (!searchQuery) return candidates
const q = searchQuery.toLowerCase()
return candidates.filter(
(c) => c.account_number.includes(q) || c.account_name.toLowerCase().includes(q),
)
}, [candidates, searchQuery])
const customGroup = useMemo(
() => filteredCandidates.filter(isImportedOrCustom),
[filteredCandidates, isImportedOrCustom],
)
const seedGroup = useMemo(
() => filteredCandidates.filter((c) => !isImportedOrCustom(c)),
[filteredCandidates, isImportedOrCustom],
)
// Master toggle spans both groups, scoped to the current filter so it only
// ever selects what the user can actually see.
const allFilteredChecked =
filteredCandidates.length > 0 &&
filteredCandidates.every((c) => selected.has(c.account_number))
function toggleAccount(accountNumber: string) {
setSelected((prev) => {
const next = new Set(prev)
if (next.has(accountNumber)) {
next.delete(accountNumber)
} else {
next.add(accountNumber)
}
return next
})
}
function toggleGroup(group: PruneCandidate[], checked: boolean) {
setSelected((prev) => {
const next = new Set(prev)
for (const c of group) {
if (checked) {
next.add(c.account_number)
} else {
next.delete(c.account_number)
}
}
return next
})
}
async function handlePrune() {
if (selected.size === 0) return
const confirmed = await confirm({
title: t('prune_confirm_title', { count: selected.size }),
description: t('prune_confirm_body'),
confirmLabel: t('prune_confirm', { count: selected.size }),
cancelLabel: tCommon('cancel'),
})
if (!confirmed) return
setIsDeleting(true)
try {
const res = await fetch('/api/bookkeeping/accounts/prune', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ dry_run: false, account_numbers: [...selected] }),
})
const body = await res.json().catch(() => null)
if (!res.ok) {
// `new Error(body.error)` collapses the canonical envelope
// `{ error: { code, message } }` to "[object Object]" and loses the
// route's own reason (an account still referenced by a posted entry
// is refused with a specific message). Map the body plus the status.
toast({
title: getUserErrorMessage(body, { statusCode: res.status }),
variant: 'destructive',
})
return
}
const deleted: string[] = body?.data?.deleted ?? []
const skipped: string[] = [
...(body?.data?.skipped ?? []),
...(body?.data?.not_found ?? []),
]
toast({
title: t('toast_pruned_title'),
description:
skipped.length > 0
? t('toast_pruned_with_skipped', { deleted: deleted.length, skipped: skipped.length })
: t('toast_pruned_description', { deleted: deleted.length }),
})
onPruned()
onOpenChange(false)
} catch (err) {
toast({
title: err instanceof Error && getUserErrorMessage(err) ? getUserErrorMessage(err) : t('toast_prune_failed'),
variant: 'destructive',
})
} finally {
setIsDeleting(false)
}
}
function renderGroup(group: PruneCandidate[], titleKey: 'prune_group_custom' | 'prune_group_seed', hintKey: 'prune_group_custom_hint' | 'prune_group_seed_hint') {
if (group.length === 0) return null
const allChecked = group.every((c) => selected.has(c.account_number))
return (
<div className="space-y-2">
<div className="flex items-start gap-3">
<Checkbox
checked={allChecked}
onCheckedChange={(checked) => toggleGroup(group, checked === true)}
className="mt-1"
aria-label={t(titleKey)}
/>
<div>
<p className="text-sm font-medium">
{t(titleKey)}{' '}
<span className="text-muted-foreground tabular-nums">({group.length})</span>
</p>
<p className="text-xs text-muted-foreground">{t(hintKey)}</p>
</div>
</div>
<div className="w-full rounded-lg border border-border divide-y divide-border">
{group.map((c) => (
<label
key={c.account_number}
className="flex min-w-0 items-center gap-3 px-3 py-2 text-sm cursor-pointer hover:bg-secondary/60 transition-colors duration-150"
>
<Checkbox
checked={selected.has(c.account_number)}
onCheckedChange={() => toggleAccount(c.account_number)}
/>
<span className="font-mono tabular-nums text-muted-foreground w-14 shrink-0">
{c.account_number}
</span>
<span className="min-w-0 flex-1 truncate">{c.account_name}</span>
{!c.is_active && (
<span className="ml-auto text-[10px] uppercase tracking-wider text-muted-foreground shrink-0">
{t('prune_inactive_badge')}
</span>
)}
</label>
))}
</div>
</div>
)
}
return (
<>
<Dialog open={open} onOpenChange={(v) => !isDeleting && onOpenChange(v)}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>{t('prune_title')}</DialogTitle>
<DialogDescription>{t('prune_description')}</DialogDescription>
</DialogHeader>
{loading ? (
<div className="py-8 text-center text-sm text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin mx-auto mb-2" />
{t('prune_loading')}
</div>
) : candidates.length === 0 ? (
<p className="py-8 text-center text-sm text-muted-foreground">{t('prune_empty')}</p>
) : (
// min-w-0: DialogContent is a grid, and grid items default to
// min-width auto — without this, the nowrap (truncate) account
// names propagate their full width up and blow the dialog open
// horizontally instead of truncating.
<div className="min-w-0 space-y-3">
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder={t('search_placeholder')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9"
/>
</div>
{filteredCandidates.length > 0 && (
<label className="flex items-center gap-3 text-sm cursor-pointer">
<Checkbox
checked={allFilteredChecked}
onCheckedChange={(checked) => toggleGroup(filteredCandidates, checked === true)}
aria-label={t('prune_select_all')}
/>
<span className="font-medium">
{t('prune_select_all')}{' '}
<span className="text-muted-foreground tabular-nums">
({filteredCandidates.length})
</span>
</span>
</label>
)}
<div className="space-y-4 max-h-[60vh] overflow-y-auto overflow-x-hidden pr-1">
{filteredCandidates.length === 0 ? (
<p className="py-6 text-center text-sm text-muted-foreground">{t('no_matches')}</p>
) : (
<>
{renderGroup(customGroup, 'prune_group_custom', 'prune_group_custom_hint')}
{renderGroup(seedGroup, 'prune_group_seed', 'prune_group_seed_hint')}
</>
)}
{usedCount > 0 && (
<p className="text-xs text-muted-foreground">
{t('prune_used_note', { count: usedCount })}
</p>
)}
</div>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isDeleting}>
{tCommon('cancel')}
</Button>
<Button
variant="destructive"
onClick={handlePrune}
disabled={loading || isDeleting || selected.size === 0}
>
{isDeleting ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
) : (
<Trash2 className="mr-1.5 h-3.5 w-3.5" />
)}
{t('prune_confirm', { count: selected.size })}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<DestructiveConfirmDialog {...confirmDialogProps} />
</>
)
}
@@ -1,39 +0,0 @@
'use client'
import { HelpPopover } from '@/components/ui/help-popover'
interface RattelseExplainerProps {
/** Per-dialog specifics, rendered after the shared framing paragraph. */
children: React.ReactNode
className?: string
}
/**
* Shared "?" help for the rättelse family of dialogs (CorrectionEntryDialog,
* StrikeLinesDialog, RecordateEntryDialog, CorrectMetadataDialog): one place
* for the "a posted verifikat cannot be edited directly" framing, so the four
* dialogs stop maintaining near-duplicate inline paragraphs. Rendered next to
* the DialogTitle per UI-migration convention 7 (help lives behind a "?",
* not in the dialog flow: see MatchVoucherDialog). Stays Swedish
* (verifikat surface, .claude/rules/i18n.md).
*
* Only the universally true framing lives here. The audit-trail sentence is
* mechanism-specific (BFL 5 kap 5 §: two distinct correction tracks) and must
* come from each dialog's children: the inline strike-and-replace dialogs
* (StrikeLinesDialog, CorrectMetadataDialog) write the who/when
* rättelsehistorik log, while the storno dialogs (CorrectionEntryDialog,
* RecordateEntryDialog) never touch that log: their trail is the storno chain
* of linked verifikat. Claiming the rättelsehistorik here would be false for
* the storno paths.
*/
export default function RattelseExplainer({ children, className }: RattelseExplainerProps) {
return (
<HelpPopover className={className}>
<p>
En bokförd verifikation kan inte ändras direkt: enligt bokföringslagen
måste varje rättelse vara spårbar i efterhand.
</p>
<div className="mt-2 space-y-2">{children}</div>
</HelpPopover>
)
}
@@ -1,293 +0,0 @@
'use client'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import RattelseExplainer from '@/components/bookkeeping/RattelseExplainer'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { AlertTriangle, Lock, ArrowRight } from 'lucide-react'
import { formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import type { JournalEntry } from '@/types'
interface Props {
entry: JournalEntry
open: boolean
onOpenChange: (open: boolean) => void
onMoved: () => void
}
type PeriodStatus = {
status: 'open' | 'locked' | 'closed'
period_id: string | null
lock_date: string | null
period_name: string | null
}
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/
export default function RecordateEntryDialog({ entry, open, onOpenChange, onMoved }: Props) {
const { toast } = useToast()
const router = useRouter()
const t = useTranslations('journal_detail')
const [newDate, setNewDate] = useState(entry.entry_date)
const [preview, setPreview] = useState<PeriodStatus | null>(null)
const [previewLoading, setPreviewLoading] = useState(false)
const [previewError, setPreviewError] = useState<string | null>(null)
const [isSubmitting, setIsSubmitting] = useState(false)
// Non-null when the server refused with CORRECTION_CHAIN_TOO_DEEP: holds the
// reported chain depth and opens the bypass confirm ("Flytta ändå").
const [deepChainDepth, setDeepChainDepth] = useState<number | null>(null)
// Reset to the original date each time the dialog opens.
useEffect(() => {
if (open) {
setNewDate(entry.entry_date)
setPreview(null)
setPreviewError(null)
}
}, [open, entry.entry_date])
// Resolve the target period status whenever a valid, changed date is entered.
useEffect(() => {
if (!open) return
if (!ISO_DATE.test(newDate) || newDate === entry.entry_date) {
setPreview(null)
setPreviewError(null)
return
}
let cancelled = false
setPreviewLoading(true)
setPreviewError(null)
const handle = setTimeout(async () => {
try {
const res = await fetch(
`/api/bookkeeping/fiscal-periods/period-status?date=${encodeURIComponent(newDate)}`
)
if (!res.ok) throw new Error('period_status_failed')
const { data } = await res.json()
if (!cancelled) {
setPreview((data as PeriodStatus) ?? null)
setPreviewError(null)
}
} catch {
if (!cancelled) {
setPreview(null)
setPreviewError('Kunde inte kontrollera perioden. Försök igen.')
}
} finally {
if (!cancelled) setPreviewLoading(false)
}
}, 250)
return () => {
cancelled = true
clearTimeout(handle)
}
}, [newDate, open, entry.entry_date])
const dateChanged = ISO_DATE.test(newDate) && newDate !== entry.entry_date
const targetOpen = preview?.status === 'open' && !!preview?.period_id
const noCoveringPeriod = preview?.status === 'open' && !preview?.period_id
// Soft, non-blocking advisory when moving into a past date: the moms for
// that period may already have been filed.
const today = new Date().toISOString().slice(0, 10)
const movingIntoPast = dateChanged && newDate < today
const canSubmit = dateChanged && targetOpen && !isSubmitting
async function handleSubmit(allowDeepChain = false) {
if (!canSubmit) return
setIsSubmitting(true)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${entry.id}/recordate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
new_entry_date: newDate,
...(allowDeepChain ? { allow_deep_chain: true } : {}),
}),
})
const result = await res.json()
if (!res.ok) {
// Chain-depth guard: open the bypass confirm instead of a dead-end
// toast. "Flytta ändå" resubmits with allow_deep_chain=true.
const structured = (result as { error?: { code?: string; details?: { depth?: number } } })?.error
if (structured?.code === 'CORRECTION_CHAIN_TOO_DEEP') {
setDeepChainDepth(structured.details?.depth ?? 3)
return
}
const error = new Error('Failed to move entry') as Error & { body?: unknown; status?: number }
error.body = result
error.status = res.status
throw error
}
setDeepChainDepth(null)
const correctedId = result.data?.corrected?.id
toast({
title: 'Verifikationen flyttad',
description: 'En storno och en rättelse med rätt datum har bokförts.',
action: correctedId ? (
<Button variant="outline" size="sm" onClick={() => router.push(`/bookkeeping/${correctedId}`)}>
Visa rättelsen
</Button>
) : undefined,
})
onOpenChange(false)
onMoved()
} catch (err) {
const anyErr = err as { body?: unknown; status?: number }
toast({
title: 'Kunde inte flytta verifikationen',
description: getErrorMessage(anyErr.body ?? err, { context: 'journal_entry', statusCode: anyErr.status }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
{/* Convention 7: the how-it-works copy lives behind the "?", not in
the dialog flow. */}
<div className="flex items-center gap-2">
<DialogTitle>Rätta datum</DialogTitle>
<RattelseExplainer>
<p>
Raderna behålls oförändrade: en stornoverifikation nollställer
originalet i sin period, och en ny verifikation bokförs med
samma rader på det nya datumet.
</p>
<p>
Spårbarheten ligger i stornokedjan: originalet,
stornoverifikationen och den nya verifikationen förblir synliga
i bokföringen och länkade till varandra.
</p>
</RattelseExplainer>
</div>
</DialogHeader>
{/* Original */}
<div className="space-y-1">
<div className="flex items-center gap-2 text-sm text-muted-foreground flex-wrap">
<span className="font-mono">{formatVoucher(entry)}</span>
<span className="tabular-nums">{formatDate(entry.entry_date)}</span>
<Badge variant="outline" className="text-xs">Original</Badge>
</div>
<p className="text-sm">{entry.description}</p>
</div>
{/* New date */}
<div className="space-y-2">
<label htmlFor="recordate-date" className="text-sm font-medium">
Nytt datum
</label>
<Input
id="recordate-date"
type="date"
value={newDate}
onChange={(e) => setNewDate(e.target.value)}
className="tabular-nums"
/>
{/* Target period feedback */}
{dateChanged && (
<div className="text-sm" aria-live="polite">
{previewLoading && <span className="text-muted-foreground">Kontrollerar period…</span>}
{!previewLoading && previewError && (
<span className="inline-flex items-center gap-1.5 text-destructive">
<AlertTriangle className="h-4 w-4" />
{previewError}
</span>
)}
{!previewLoading && !previewError && targetOpen && (
<span className="inline-flex items-center gap-1.5 text-muted-foreground">
<ArrowRight className="h-4 w-4" />
Flyttas till {preview?.period_name ?? 'rätt räkenskapsår'}
</span>
)}
{!previewLoading && noCoveringPeriod && (
<span className="text-destructive">
Det finns ingen räkenskapsperiod som täcker datumet. Skapa eller öppna räkenskapsåret först.
</span>
)}
{!previewLoading && preview?.status === 'closed' && (
<span className="text-destructive">
Räkenskapsåret är stängt (bokslut) och kan inte återöppnas. Bokför rättelsen i innevarande period istället.
</span>
)}
{!previewLoading && preview?.status === 'locked' && (
<span className="inline-flex items-center gap-1.5 text-destructive">
<Lock className="h-4 w-4" />
Perioden är låst{preview?.lock_date ? ` t.o.m. ${formatDate(preview.lock_date)}` : ''}. Lås upp perioden för att flytta verifikationen dit.
</span>
)}
</div>
)}
{/* Soft advisory: moving into a past period */}
{targetOpen && movingIntoPast && (
<p className="inline-flex items-start gap-1.5 text-sm text-muted-foreground">
<AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />
<span>
Om momsen för perioden redan är inlämnad kan du behöva lämna en rättad momsdeklaration.
</span>
</p>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
Avbryt
</Button>
<Button onClick={() => handleSubmit()} disabled={!canSubmit}>
{isSubmitting ? 'Flyttar…' : 'Flytta verifikationen'}
</Button>
</DialogFooter>
{/* Chain-depth guard confirm: the server refused because this entry
already sits deep in a rättelse chain. Advisory, never a dead end:
"Flytta ändå" resubmits with allow_deep_chain=true. */}
<Dialog open={deepChainDepth != null} onOpenChange={(next) => { if (!next) setDeepChainDepth(null) }}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t('deep_chain_title')}</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
{t('deep_chain_body', { depth: deepChainDepth ?? 3 })}
</p>
<DialogFooter>
<Button variant="outline" onClick={() => setDeepChainDepth(null)} disabled={isSubmitting}>
{t('deep_chain_cancel')}
</Button>
<Button
onClick={() => { setDeepChainDepth(null); void handleSubmit(true) }}
disabled={isSubmitting}
>
{t('deep_chain_move_anyway')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</DialogContent>
</Dialog>
)
}
@@ -1,429 +0,0 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { useTranslations } from 'next-intl'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import RattelseExplainer from '@/components/bookkeeping/RattelseExplainer'
import { AddAccountDialog } from '@/components/bookkeeping/AddAccountDialog'
import { AccountNumber } from '@/components/ui/account-number'
import { useToast } from '@/components/ui/use-toast'
import { useAccounts } from '@/lib/reference-data/hooks'
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { changeCorrectionLineAccount, getSelectableCorrectionCatalog } from '@/lib/bookkeeping/correction-line-account'
import { splitCreateAccountPrefill } from '@/lib/bookkeeping/create-account-prefill'
import { loadBasCatalog, type CatalogAccount } from '@/lib/bookkeeping/bas-catalog-client'
import { Loader2, Plus, Trash2 } from 'lucide-react'
import type { JournalEntry, JournalEntryLine } from '@/types'
interface NewLine {
account_number: string
debit_amount: string
credit_amount: string
line_description: string
}
interface Props {
entry: JournalEntry
open: boolean
onOpenChange: (open: boolean) => void
onCorrected: () => void
}
/**
* Inline line rättelse (BFL 5 kap 5 §): strike lines in a posted verifikat
* and add replacement lines in the SAME verifikat, without an
* ändringsverifikation. The struck originals stay visible (strikethrough)
* in the verifikat via the immutable rättelse log. Stays Swedish
* (verifikat surface, .claude/rules/i18n.md).
*/
export default function StrikeLinesDialog({ entry, open, onOpenChange, onCorrected }: Props) {
const { toast } = useToast()
const t = useTranslations('journal_detail')
// The full chart (deactivated rows included) comes from the session cache
// (lib/reference-data); only the static BAS catalogue is loaded per open,
// and it is module-cached after the first time.
const { accounts, isLoading: accountsLoading, error: accountsError, refresh: refreshAccounts } = useAccounts(false)
const [catalog, setCatalog] = useState<CatalogAccount[]>([])
const [catalogStatus, setCatalogStatus] = useState<'loading' | 'ready' | 'error'>('loading')
const accountsStatus: 'loading' | 'ready' | 'error' =
accountsLoading || catalogStatus === 'loading'
? 'loading'
: accountsError || catalogStatus === 'error'
? 'error'
: 'ready'
const [strikeIds, setStrikeIds] = useState<Set<string>>(new Set())
const [newLines, setNewLines] = useState<NewLine[]>([])
const [isSubmitting, setIsSubmitting] = useState(false)
// Index of the replacement line whose combobox opened the create dialog, and
// the search string it was showing. Null index = the dialog is closed.
const [creatingAccountForLine, setCreatingAccountForLine] = useState<number | null>(null)
const [createAccountPrefill, setCreateAccountPrefill] = useState('')
const activeAccounts = useMemo(
() => accounts.filter((account) => account.is_active),
[accounts],
)
const selectableCatalog = useMemo(
() => getSelectableCorrectionCatalog(accounts, catalog),
[accounts, catalog],
)
const originalLines = ((entry.lines || []) as JournalEntryLine[])
.slice()
.sort((a, b) => a.sort_order - b.sort_order)
useEffect(() => {
if (open) {
setStrikeIds(new Set())
setNewLines([])
void loadCatalog()
}
}, [open, entry.id])
async function loadCatalog() {
setCatalogStatus('loading')
try {
setCatalog(await loadBasCatalog())
setCatalogStatus('ready')
} catch {
setCatalog([])
setCatalogStatus('error')
}
}
const toggleStrike = (lineId: string) => {
setStrikeIds((prev) => {
const next = new Set(prev)
if (next.has(lineId)) next.delete(lineId)
else next.add(lineId)
return next
})
}
const updateNewLine = (index: number, field: keyof NewLine, value: string) => {
setNewLines((prev) => prev.map((l, i) => (i === index ? { ...l, [field]: value } : l)))
}
const updateNewLineAccount = (index: number, accountNumber: string) => {
setNewLines((prev) => prev.map((line, lineIndex) => (
lineIndex === index
? changeCorrectionLineAccount(line, accountNumber, [...accounts, ...catalog])
: line
)))
}
const addNewLine = () => {
setNewLines((prev) => [...prev, { account_number: '', debit_amount: '', credit_amount: '', line_description: '' }])
}
const removeNewLine = (index: number) => {
setNewLines((prev) => prev.filter((_, i) => i !== index))
}
const closeCreateAccount = () => {
setCreatingAccountForLine(null)
setCreateAccountPrefill('')
}
// A number that is neither in the company chart nor in BAS 2026 (a retired
// account such as 8022, or a company-specific underkonto) would otherwise be
// a dead end here: the rättelse can only post to accounts that exist in the
// chart. Creating it inline keeps the half-finished rättelse intact.
const handleAccountCreated = async (account: { account_number: string; account_name?: string }) => {
await invalidateReferenceData('ref:accounts')
if (creatingAccountForLine != null) {
// The refreshed cache is not visible in this closure, so the
// fresh account's own name is passed alongside the stale sources. The
// reactivate path reports no name, but that account is already in
// `accounts` (the fetch includes deactivated rows).
const created = account.account_name
? [{ account_number: account.account_number, account_name: account.account_name }]
: []
setNewLines((prev) => prev.map((line, index) => (
index === creatingAccountForLine
? changeCorrectionLineAccount(line, account.account_number, [...accounts, ...catalog, ...created])
: line
)))
}
closeCreateAccount()
}
// Effective verifikat after the rättelse: remaining original lines + new lines.
const remaining = originalLines.filter((l) => !strikeIds.has(l.id))
const remainingDebit = remaining.reduce((sum, l) => sum + (Number(l.debit_amount) || 0), 0)
const remainingCredit = remaining.reduce((sum, l) => sum + (Number(l.credit_amount) || 0), 0)
const newDebit = newLines.reduce((sum, l) => sum + (parseFloat(l.debit_amount) || 0), 0)
const newCredit = newLines.reduce((sum, l) => sum + (parseFloat(l.credit_amount) || 0), 0)
const totalDebit = Math.round((remainingDebit + newDebit) * 100) / 100
const totalCredit = Math.round((remainingCredit + newCredit) * 100) / 100
const isBalanced = totalDebit === totalCredit && totalDebit > 0
const newLinesValid = newLines.every((l) => {
const debit = parseFloat(l.debit_amount) || 0
const credit = parseFloat(l.credit_amount) || 0
return l.account_number.length === 4 && debit >= 0 && credit >= 0 && (debit > 0) !== (credit > 0)
})
const hasChange = strikeIds.size > 0 || newLines.length > 0
const effectiveCount = remaining.length + newLines.length
const canSubmit = hasChange && newLinesValid && isBalanced && effectiveCount >= 2
async function handleSubmit() {
if (!canSubmit) return
setIsSubmitting(true)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${entry.id}/strike-lines`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
strike_line_ids: [...strikeIds],
lines: newLines.map((l) => ({
account_number: l.account_number,
debit_amount: parseFloat(l.debit_amount) || 0,
credit_amount: parseFloat(l.credit_amount) || 0,
line_description: l.line_description || undefined,
})),
}),
})
const result = await res.json()
if (!res.ok) {
const error = new Error('Failed to strike lines') as Error & { body?: unknown; status?: number }
error.body = result
error.status = res.status
throw error
}
toast({
title: 'Verifikationen rättad',
description: 'De strukna raderna visas överstrukna i verifikatet.',
})
onOpenChange(false)
onCorrected()
} catch (err) {
const anyErr = err as { body?: unknown; status?: number }
toast({
title: 'Kunde inte rätta verifikationen',
description: getErrorMessage(anyErr.body ?? err, { context: 'journal_entry', statusCode: anyErr.status }),
variant: 'destructive',
})
} finally {
setIsSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-3xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
<DialogHeader>
{/* Convention 7: the how-it-works copy lives behind the "?", not in
the dialog flow. */}
<div className="flex items-center gap-2">
<DialogTitle>Stryk rader i verifikatet</DialogTitle>
<RattelseExplainer>
<p>
Här stryks felaktiga rader och ersätts direkt i samma verifikat,
utan ändringsverifikation. Det fungerar bara i öppna, olåsta
perioder.
</p>
<p>
Varje rättelse loggas med vem och när, och de ursprungliga
raderna förblir synliga i verifikatets rättelsehistorik.
</p>
<p>
Om månaden redan är momsdeklarerad kan en ändring av momskonton
påverka den inlämnade deklarationen.
</p>
</RattelseExplainer>
</div>
<DialogDescription>
De strukna raderna förblir synliga (överstrukna) i verifikatet.
</DialogDescription>
</DialogHeader>
{/* Original lines with strike checkboxes */}
<div className="space-y-1">
<p className="text-sm font-medium">Markera rader som ska strykas</p>
<div className="rounded-lg border divide-y">
{originalLines.map((line) => {
const struck = strikeIds.has(line.id)
// FX lines carry conversion data replacements cannot reproduce;
// the RPC rejects striking them, so the checkbox is disabled.
const isForeign = !!line.currency && line.currency !== 'SEK'
return (
<label
key={line.id}
className={`flex items-center gap-3 px-3 py-2 text-sm transition-colors ${isForeign ? 'opacity-60' : 'cursor-pointer hover:bg-secondary/60'}`}
title={isForeign ? 'Rader i utländsk valuta rättas med ändringsverifikat' : undefined}
>
<Checkbox
checked={struck}
disabled={isForeign}
onCheckedChange={() => toggleStrike(line.id)}
/>
<span className={`flex-1 min-w-0 ${struck ? 'line-through text-muted-foreground' : ''}`}>
<AccountNumber number={line.account_number} showName />
{line.line_description && (
<span className="text-muted-foreground ml-2">{line.line_description}</span>
)}
</span>
<span className={`tabular-nums shrink-0 ${struck ? 'line-through text-muted-foreground' : ''}`}>
{Number(line.debit_amount) > 0
? `${Number(line.debit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} D`
: `${Number(line.credit_amount).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} K`}
</span>
</label>
)
})}
</div>
</div>
{/* Replacement lines */}
<div className="space-y-2">
<div className="space-y-1">
<p className="text-sm font-medium">Ersättningsrader</p>
<p className="text-xs text-muted-foreground">
Lägg till de rader som ska gälla i stället. Verifikationen måste balansera efter rättelsen.
</p>
</div>
{accountsStatus !== 'ready' && (
<div className="flex items-center justify-between gap-3 rounded-lg border bg-muted/50 p-3 text-sm text-muted-foreground">
<span className="flex items-center gap-2">
{accountsStatus === 'loading' && <Loader2 className="h-4 w-4 animate-spin" />}
{accountsStatus === 'loading' ? t('accounts_loading') : t('accounts_load_failed')}
</span>
{accountsStatus === 'error' && (
<Button variant="outline" size="sm" onClick={() => void refreshAccounts()}>
{t('accounts_retry')}
</Button>
)}
</div>
)}
<div className="space-y-2">
{newLines.map((line, index) => (
<div key={index} className="space-y-2 sm:space-y-0 sm:grid sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_120px_120px_auto] sm:gap-2 sm:items-start border-b sm:border-0 pb-3 sm:pb-0 last:border-0">
<div className="grid grid-cols-[minmax(0,1fr)_auto] sm:contents gap-2">
{/* min-w-0: at sm: the sm:contents wrapper promotes this cell
to a direct grid item; without it the combobox refuses to
shrink below its content and overflows the dialog (same
pattern as SendInvoiceDialog's desktop rows). */}
<div className="min-w-0">
<AccountCombobox
value={line.account_number}
accounts={activeAccounts}
catalog={selectableCatalog}
onChange={(v) => updateNewLineAccount(index, v)}
onCreateAccount={(prefill) => {
setCreatingAccountForLine(index)
setCreateAccountPrefill(prefill)
}}
disabled={accountsStatus !== 'ready'}
/>
</div>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 min-h-[44px] min-w-[44px] sm:order-last"
onClick={() => removeNewLine(index)}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<Input
value={line.line_description}
onChange={(e) => updateNewLine(index, 'line_description', e.target.value)}
placeholder="Beskrivning"
className="h-8"
/>
<div className="grid grid-cols-2 gap-2 sm:contents">
<Input
type="number"
value={line.debit_amount}
onChange={(e) => updateNewLine(index, 'debit_amount', e.target.value)}
placeholder="Debet"
className="h-8 text-right"
min={0}
step="0.01"
/>
<Input
type="number"
value={line.credit_amount}
onChange={(e) => updateNewLine(index, 'credit_amount', e.target.value)}
placeholder="Kredit"
className="h-8 text-right"
min={0}
step="0.01"
/>
</div>
</div>
))}
</div>
<Button variant="outline" size="sm" onClick={addNewLine}>
<Plus className="h-4 w-4 mr-1" />
Lägg till rad
</Button>
</div>
{/* Effective balance after the rättelse */}
<div className="flex justify-end gap-6 text-sm pt-2 border-t">
<div>
<span className="text-muted-foreground mr-2">Debet efter rättelse:</span>
<span className={!isBalanced ? 'text-destructive font-medium' : 'font-medium'}>
{totalDebit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</span>
</div>
<div>
<span className="text-muted-foreground mr-2">Kredit efter rättelse:</span>
<span className={!isBalanced ? 'text-destructive font-medium' : 'font-medium'}>
{totalCredit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
</span>
</div>
</div>
{hasChange && !isBalanced && (
<p className="text-sm text-destructive">
Debet och kredit måste vara lika och större än 0 efter rättelsen.
</p>
)}
{hasChange && isBalanced && effectiveCount < 2 && (
<p className="text-sm text-destructive">
Verifikationen måste ha minst två rader efter rättelsen. Använd Återför (storno) för att
makulera hela verifikatet.
</p>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
Avbryt
</Button>
<Button onClick={handleSubmit} disabled={!canSubmit || isSubmitting}>
{isSubmitting ? 'Rättar...' : 'Rätta verifikatet'}
</Button>
</DialogFooter>
</DialogContent>
{/* Nested on purpose: closing this one (Esc, click-outside, Avbryt) must
leave the rättelse behind it untouched. */}
<AddAccountDialog
open={creatingAccountForLine != null}
onOpenChange={(next) => {
if (!next) closeCreateAccount()
}}
onCreated={handleAccountCreated}
{...splitCreateAccountPrefill(createAccountPrefill)}
/>
</Dialog>
)
}
@@ -1,298 +0,0 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { cn, formatCurrency } from '@/lib/utils'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} 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 { getErrorMessage } from '@/lib/errors/get-error-message'
import {
applyTemplate,
getTemplateScope,
SCOPE_LABELS,
TEMPLATE_CATEGORY_LABELS,
} from '@/lib/bookkeeping/template-library'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { roundOre } from '@/lib/money'
import { ArrowLeft, Check, ChevronRight, Loader2, Search } from 'lucide-react'
import type { BookingTemplateLibrary } from '@/types'
import { useBookingTemplates, useFiscalPeriods } from '@/lib/reference-data/hooks'
import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
/** Fired after a verifikat is booked from a template. */
onCreated: () => void
}
/** Sum a side of the computed lines in öre-safe steps. */
function sumSide(lines: FormLine[], side: 'debit_amount' | 'credit_amount'): number {
return lines.reduce((acc, l) => roundOre(acc + (parseFloat(l[side]) || 0)), 0)
}
/**
* "Bokför från mall" (UI-migration plan PR 4, scene 9): a centered modal
* with the template list (existing booking_template_library data, MRU
* ordering from the API), then date + editable amount that recomputes the
* kontering live via applyTemplate, a "Balanserar" row, and direct booking
* (user action, so no Granskning detour).
*/
export default function TemplateBookDialog({ open, onOpenChange, onCreated }: Props) {
const t = useTranslations('bookkeeping')
const { toast } = useToast()
// Session-cached (lib/reference-data): opening the dialog costs no
// requests once the lists are in the cache. null = still loading.
const { templates: cachedTemplates, isLoading: templatesLoading } = useBookingTemplates()
// Templates hidden for this company (settings panel opt-in) never show in
// the booking flow; the settings panel is the only surface that lists them.
const templates: BookingTemplateLibrary[] | null = templatesLoading
? null
: cachedTemplates.filter((tt) => !tt.is_hidden)
const { periods } = useFiscalPeriods()
const [search, setSearch] = useState('')
const [selected, setSelected] = useState<BookingTemplateLibrary | null>(null)
const [entryDate, setEntryDate] = useState(() => new Date().toISOString().split('T')[0])
const [amountInput, setAmountInput] = useState('')
const [submitting, setSubmitting] = useState(false)
// Reset per open so yesterday's half-typed amount never leaks into today.
useEffect(() => {
if (open) return
setSelected(null)
setSearch('')
setAmountInput('')
setEntryDate(new Date().toISOString().split('T')[0])
}, [open])
const amount = useMemo(() => {
const parsed = parseFloat(amountInput.replace(/\s/g, '').replace(',', '.'))
return Number.isFinite(parsed) && parsed > 0 ? roundOre(parsed) : 0
}, [amountInput])
// The live kontering: recomputed from the template's line pattern on
// every amount change (momssplit etc. handled by applyTemplate).
const lines = useMemo<FormLine[]>(
() => (selected && amount > 0 ? applyTemplate(selected.lines, amount) : []),
[selected, amount],
)
const totalDebit = sumSide(lines, 'debit_amount')
const totalCredit = sumSide(lines, 'credit_amount')
const balanced = lines.length >= 2 && totalDebit === totalCredit && totalDebit > 0
const filteredTemplates = (templates ?? []).filter((tpl) =>
tpl.name.toLowerCase().includes(search.trim().toLowerCase()),
)
const periodForDate = periods.find(
(p) => p.period_start <= entryDate && entryDate <= p.period_end,
)
const handleBook = async () => {
if (!selected || !balanced) return
if (!periodForDate) {
toast({ title: t('tpl_no_period'), variant: 'destructive' })
return
}
setSubmitting(true)
try {
const res = await fetch('/api/bookkeeping/journal-entries', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
fiscal_period_id: periodForDate.id,
entry_date: entryDate,
description: selected.name,
lines: lines.map((l) => ({
account_number: l.account_number,
debit_amount: parseFloat(l.debit_amount) || 0,
credit_amount: parseFloat(l.credit_amount) || 0,
line_description: l.line_description || undefined,
})),
}),
})
const result = await res.json()
if (!res.ok) {
toast({
title: t('toast_post_failed'),
description: getErrorMessage(result, { context: 'journal_entry' }),
variant: 'destructive',
})
return
}
// MRU ordering for the next open; fire-and-forget.
void fetch(`/api/settings/booking-templates/${selected.id}/touch`, {
method: 'POST',
}).catch(() => {})
toast({
title: t('toast_posted_title'),
description: t('toast_posted_description', {
voucher: formatVoucher(result.data ?? {}),
}),
})
onOpenChange(false)
onCreated()
} catch {
toast({ title: t('toast_post_failed_generic'), variant: 'destructive' })
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={(next) => !submitting && onOpenChange(next)}>
<DialogContent className="sm:min-w-[460px] sm:max-w-lg">
<DialogHeader>
{/* data-ph-mask: the template name is user data */}
<DialogTitle data-ph-mask="" className="font-display text-lg tracking-tight">
{selected ? selected.name : t('tpl_dialog_title')}
</DialogTitle>
</DialogHeader>
{!selected ? (
<>
<div className="flex items-center gap-2 border-b border-border/60 pb-2">
<Search className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('tpl_search_placeholder')}
className="w-full bg-transparent text-[13px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none"
autoFocus
/>
</div>
<div className="-mx-2 max-h-80 overflow-y-auto px-1">
{templates === null ? (
<div className="flex items-center justify-center gap-2 py-8 text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
</div>
) : filteredTemplates.length === 0 ? (
<p className="px-2.5 py-6 text-center text-[13px] text-muted-foreground">
{t('tpl_empty')}
</p>
) : (
filteredTemplates.map((tpl) => (
<button
key={tpl.id}
type="button"
onClick={() => setSelected(tpl)}
className="flex w-full items-center gap-2.5 rounded-sm px-2.5 py-2.5 text-left transition-colors hover:bg-secondary/60"
>
<span className="min-w-0 flex-1">
<span className="block truncate text-[13px] text-foreground">
{tpl.name}
</span>
<span className="block truncate text-[11px] text-muted-foreground">
{TEMPLATE_CATEGORY_LABELS[tpl.category] ?? tpl.category}
{' · '}
{SCOPE_LABELS[getTemplateScope(tpl)]}
</span>
</span>
<ChevronRight className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground/60" />
</button>
))
)}
</div>
</>
) : (
<div className="space-y-4">
<button
type="button"
onClick={() => setSelected(null)}
className="inline-flex items-center gap-1.5 text-xs text-muted-foreground transition-colors hover:text-foreground"
>
<ArrowLeft className="h-3.5 w-3.5" />
{t('tpl_back')}
</button>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="tpl-date">{t('tpl_date_label')}</Label>
<Input
id="tpl-date"
type="date"
value={entryDate}
onChange={(e) => setEntryDate(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label htmlFor="tpl-amount">{t('tpl_amount_label')}</Label>
<Input
id="tpl-amount"
inputMode="decimal"
placeholder="0,00"
value={amountInput}
onChange={(e) => setAmountInput(e.target.value)}
autoFocus
className="tabular-nums"
/>
</div>
</div>
{/* Live kontering preview */}
<div className="rounded-lg border border-border">
{lines.length === 0 ? (
<p className="px-3 py-4 text-center text-[13px] text-muted-foreground">
{t('tpl_enter_amount')}
</p>
) : (
<>
{lines.map((l, i) => (
<div
key={i}
className="flex items-center gap-3 border-b border-border/60 px-3 py-2 text-[13px] last:border-b-0"
>
<span className="w-12 font-mono text-muted-foreground">
{l.account_number}
</span>
<span className="min-w-0 flex-1 truncate">{l.line_description}</span>
<span className="w-24 text-right tabular-nums">
{l.debit_amount ? formatCurrency(parseFloat(l.debit_amount)) : ''}
</span>
<span className="w-24 text-right tabular-nums text-muted-foreground">
{l.credit_amount ? formatCurrency(parseFloat(l.credit_amount)) : ''}
</span>
</div>
))}
<div
className={cn(
'flex items-center justify-between px-3 py-2 text-[12.5px]',
balanced ? 'text-success' : 'text-destructive',
)}
>
<span className="inline-flex items-center gap-1.5">
{balanced && <Check className="h-3.5 w-3.5" />}
{balanced ? t('tpl_balances') : t('tpl_not_balancing')}
</span>
<span className="tabular-nums">
{formatCurrency(totalDebit)} / {formatCurrency(totalCredit)}
</span>
</div>
</>
)}
</div>
<div className="flex justify-end gap-2">
<Button variant="ghost" onClick={() => onOpenChange(false)} disabled={submitting}>
{t('tpl_cancel')}
</Button>
<Button onClick={() => void handleBook()} disabled={!balanced || submitting}>
{submitting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
{t('tpl_book')}
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
)
}
@@ -1,128 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
computeDropdownPosition,
isSameDropdownPosition,
DROPDOWN_PREFERRED_WIDTH,
DROPDOWN_VIEWPORT_MARGIN,
DROPDOWN_ANCHOR_GAP,
DROPDOWN_MAX_HEIGHT,
} from '../account-combobox-position'
const desktop = { width: 1440, height: 900 }
describe('computeDropdownPosition', () => {
it('opens below the anchor at the preferred width when there is room', () => {
const pos = computeDropdownPosition(
{ top: 200, bottom: 232, left: 300, width: 160 },
desktop,
)
expect(pos.top).toBe(232 + DROPDOWN_ANCHOR_GAP)
expect(pos.bottom).toBeUndefined()
expect(pos.left).toBe(300)
expect(pos.width).toBe(DROPDOWN_PREFERRED_WIDTH)
expect(pos.maxHeight).toBe(DROPDOWN_MAX_HEIGHT)
})
it('keeps the anchor width when the trigger is wider than the preferred width', () => {
const pos = computeDropdownPosition(
{ top: 200, bottom: 232, left: 100, width: 700 },
desktop,
)
expect(pos.width).toBe(700)
})
it('clamps left so the panel never crosses the right viewport edge', () => {
const pos = computeDropdownPosition(
{ top: 200, bottom: 232, left: 1200, width: 160 },
desktop,
)
expect(pos.left + pos.width).toBe(desktop.width - DROPDOWN_VIEWPORT_MARGIN)
})
it('never puts the panel past the left margin', () => {
const pos = computeDropdownPosition(
{ top: 200, bottom: 232, left: 2, width: 160 },
desktop,
)
expect(pos.left).toBe(DROPDOWN_VIEWPORT_MARGIN)
})
it('shrinks to the viewport on a narrow (mobile) screen', () => {
const mobile = { width: 375, height: 700 }
const pos = computeDropdownPosition(
{ top: 100, bottom: 140, left: 16, width: 200 },
mobile,
)
expect(pos.width).toBe(375 - DROPDOWN_VIEWPORT_MARGIN * 2)
expect(pos.left).toBe(DROPDOWN_VIEWPORT_MARGIN)
})
it('caps maxHeight to the space below the anchor', () => {
const pos = computeDropdownPosition(
{ top: 650, bottom: 682, left: 300, width: 160 },
desktop,
)
expect(pos.top).toBe(682 + DROPDOWN_ANCHOR_GAP)
expect(pos.maxHeight).toBe(
desktop.height - 682 - DROPDOWN_ANCHOR_GAP - DROPDOWN_VIEWPORT_MARGIN,
)
})
it('flips above the anchor when the space below is too small', () => {
const pos = computeDropdownPosition(
{ top: 800, bottom: 832, left: 300, width: 160 },
desktop,
)
expect(pos.top).toBeUndefined()
expect(pos.bottom).toBe(desktop.height - 800 + DROPDOWN_ANCHOR_GAP)
expect(pos.maxHeight).toBe(DROPDOWN_MAX_HEIGHT)
})
it('stays below when the space above is even smaller than below', () => {
const shortViewport = { width: 1440, height: 220 }
const pos = computeDropdownPosition(
{ top: 40, bottom: 72, left: 300, width: 160 },
shortViewport,
)
expect(pos.top).toBe(72 + DROPDOWN_ANCHOR_GAP)
// Cramped viewport: the height floor keeps the list usable and scrollable.
expect(pos.maxHeight).toBeGreaterThanOrEqual(96)
})
})
describe('isSameDropdownPosition', () => {
const anchor = { top: 200, bottom: 232, left: 300, width: 160 }
it('is false against null (no previous position)', () => {
expect(isSameDropdownPosition(null, computeDropdownPosition(anchor, desktop))).toBe(false)
})
it('is true for two computations off an unmoved anchor', () => {
const a = computeDropdownPosition(anchor, desktop)
const b = computeDropdownPosition({ ...anchor }, desktop)
expect(isSameDropdownPosition(a, b)).toBe(true)
})
it.each([
['left', { left: 301 }],
['width', { width: 545 }],
['maxHeight', { maxHeight: 299 }],
['top', { top: 237 }],
] as const)('is false when %s differs', (_field, patch) => {
const a = computeDropdownPosition(anchor, desktop)
expect(isSameDropdownPosition(a, { ...a, ...patch })).toBe(false)
})
it('distinguishes open-below from open-above at the same coordinates', () => {
const below = computeDropdownPosition(anchor, desktop)
const above = computeDropdownPosition({ top: 800, bottom: 832, left: 300, width: 160 }, desktop)
expect(below.top).toBeDefined()
expect(above.bottom).toBeDefined()
expect(isSameDropdownPosition(below, above)).toBe(false)
// Flipping sides toggles which of top/bottom is undefined: the guard must
// compare both, not just the defined one.
expect(
isSameDropdownPosition(below, { ...below, top: undefined, bottom: 123 }),
).toBe(false)
})
})
@@ -1,121 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
K2_ACCRUAL_THRESHOLD_SEK,
accrualHintKey,
resolveAccrualAmountSek,
shouldShowK2AccrualHint,
} from '@/components/bookkeeping/accrual-k2-hint'
describe('resolveAccrualAmountSek', () => {
it('returns the amount unchanged for SEK', () => {
expect(resolveAccrualAmountSek({ amount: 4999, currency: 'SEK' })).toBe(4999)
})
it('treats a missing currency as SEK (the editors default to it)', () => {
expect(resolveAccrualAmountSek({ amount: 4999 })).toBe(4999)
expect(resolveAccrualAmountSek({ amount: 4999, currency: null })).toBe(4999)
expect(resolveAccrualAmountSek({ amount: 4999, currency: '' })).toBe(4999)
})
it('converts a foreign amount with the given rate, rounded to ore', () => {
// 500 EUR at 11.5012 = 5750.60 kr, not 5750.5999999999995.
expect(
resolveAccrualAmountSek({ amount: 500, currency: 'EUR', exchangeRate: 11.5012 }),
).toBe(5750.6)
})
it('returns null for a foreign amount with no usable rate', () => {
expect(resolveAccrualAmountSek({ amount: 500, currency: 'EUR' })).toBeNull()
expect(
resolveAccrualAmountSek({ amount: 500, currency: 'EUR', exchangeRate: null }),
).toBeNull()
// An empty rate field parses to NaN; a cleared one to 0.
expect(
resolveAccrualAmountSek({ amount: 500, currency: 'EUR', exchangeRate: NaN }),
).toBeNull()
expect(
resolveAccrualAmountSek({ amount: 500, currency: 'EUR', exchangeRate: 0 }),
).toBeNull()
expect(
resolveAccrualAmountSek({ amount: 500, currency: 'EUR', exchangeRate: -11.5 }),
).toBeNull()
})
it('returns null for a non-finite amount', () => {
expect(resolveAccrualAmountSek({ amount: NaN, currency: 'SEK' })).toBeNull()
})
it('accepts a lowercase or padded currency code', () => {
expect(resolveAccrualAmountSek({ amount: 100, currency: ' sek ' })).toBe(100)
expect(
resolveAccrualAmountSek({ amount: 100, currency: ' eur ', exchangeRate: 11.5 }),
).toBe(1150)
})
})
describe('shouldShowK2AccrualHint', () => {
it('hides the hint for a foreign line that is above 5 000 kr once converted', () => {
// THE BUG: 500 EUR is ~5 750 kr, i.e. ABOVE the K2 threshold, but the raw
// 500 reads as below it and used to surface "under 5 000 kr" wrongly.
expect(
shouldShowK2AccrualHint({ amount: 500, currency: 'EUR', exchangeRate: 11.5 }),
).toBe(false)
})
it('shows the hint for a foreign line that is genuinely below 5 000 kr', () => {
// 400 EUR = 4 600 kr.
expect(
shouldShowK2AccrualHint({ amount: 400, currency: 'EUR', exchangeRate: 11.5 }),
).toBe(true)
})
it('shows the hint for a foreign line the raw amount would have hidden', () => {
// The reverse direction: 6 000 NOK at 0.98 = 5 880 kr... above. At 0.8 it
// is 4 800 kr, below the threshold, while the raw 6 000 reads as above.
expect(
shouldShowK2AccrualHint({ amount: 6000, currency: 'NOK', exchangeRate: 0.8 }),
).toBe(true)
})
it('hides the hint when the SEK value cannot be determined', () => {
// The customer-invoice editor has no exchange_rate field at all: never
// guess a branch, show nothing.
expect(shouldShowK2AccrualHint({ amount: 500, currency: 'EUR' })).toBe(false)
expect(shouldShowK2AccrualHint({ amount: 50000, currency: 'EUR' })).toBe(false)
})
it('leaves SEK behaviour exactly as it was', () => {
expect(shouldShowK2AccrualHint({ amount: 4999.99, currency: 'SEK' })).toBe(true)
expect(shouldShowK2AccrualHint({ amount: 1, currency: 'SEK' })).toBe(true)
expect(shouldShowK2AccrualHint({ amount: K2_ACCRUAL_THRESHOLD_SEK, currency: 'SEK' })).toBe(
false,
)
expect(shouldShowK2AccrualHint({ amount: 5001, currency: 'SEK' })).toBe(false)
expect(shouldShowK2AccrualHint({ amount: 0, currency: 'SEK' })).toBe(false)
// No currency prop at all is the same as SEK.
expect(shouldShowK2AccrualHint({ amount: 4999 })).toBe(true)
expect(shouldShowK2AccrualHint({ amount: 5000 })).toBe(false)
})
it('does not fire on a negative (discount) line', () => {
expect(shouldShowK2AccrualHint({ amount: -100, currency: 'SEK' })).toBe(false)
expect(
shouldShowK2AccrualHint({ amount: -100, currency: 'EUR', exchangeRate: 11.5 }),
).toBe(false)
})
})
describe('accrualHintKey', () => {
it('cites K1 (BFNAR 2006:1) for enskild firma', () => {
expect(accrualHintKey('enskild_firma')).toBe('k1_hint')
})
it('cites K2 for aktiebolag', () => {
expect(accrualHintKey('aktiebolag')).toBe('k2_hint')
})
it('keeps the K2 default when the entity type is unknown', () => {
expect(accrualHintKey(null)).toBe('k2_hint')
expect(accrualHintKey(undefined)).toBe('k2_hint')
})
})
@@ -1,40 +0,0 @@
import { describe, it, expect } from 'vitest'
import {
autoCorrectionDescription,
correctionDescriptionForSubmit,
} from '@/components/bookkeeping/correction-entry-description'
const ORIGINAL = 'Lån från närstående personer, långfristig del'
describe('autoCorrectionDescription', () => {
it('matches the server-side fallback format', () => {
expect(autoCorrectionDescription(ORIGINAL)).toBe(`Rättelse: ${ORIGINAL}`)
})
})
describe('correctionDescriptionForSubmit', () => {
it('sends nothing when the field still equals the auto prefill', () => {
expect(correctionDescriptionForSubmit(`Rättelse: ${ORIGINAL}`, ORIGINAL)).toBeUndefined()
})
it('sends nothing when the prefill only gained surrounding whitespace', () => {
expect(correctionDescriptionForSubmit(` Rättelse: ${ORIGINAL} `, ORIGINAL)).toBeUndefined()
})
it('sends nothing when the field was cleared (server fallback applies)', () => {
expect(correctionDescriptionForSubmit('', ORIGINAL)).toBeUndefined()
expect(correctionDescriptionForSubmit(' ', ORIGINAL)).toBeUndefined()
})
it('sends a user-edited description (the reported bug: relabel after account change)', () => {
expect(
correctionDescriptionForSubmit('Rättelse: Skulder till närstående personer, kortfristig del', ORIGINAL),
).toBe('Rättelse: Skulder till närstående personer, kortfristig del')
})
it('trims a user-edited description before sending', () => {
expect(correctionDescriptionForSubmit(' Omföring till rätt konto ', ORIGINAL)).toBe(
'Omföring till rätt konto',
)
})
})
@@ -1,50 +0,0 @@
import { describe, it, expect } from 'vitest'
import { nextLineDescriptionForAccountChange } from '@/components/bookkeeping/correction-line-description'
const ACCOUNTS = [
{ account_number: '2393', account_name: 'Lån från närstående personer, långfristig del' },
{ account_number: '2893', account_name: 'Skulder till närstående personer, kortfristig del' },
{ account_number: '1930', account_name: 'Företagskonto' },
]
describe('nextLineDescriptionForAccountChange', () => {
it('refreshes the carried-over description when switching 2393 -> 2893 (the reported bug)', () => {
// Original correction line pre-filled from 2393 with 2393's name.
const result = nextLineDescriptionForAccountChange(
'Lån från närstående personer, långfristig del',
'2393',
'2893',
ACCOUNTS,
)
expect(result).toBe('Skulder till närstående personer, kortfristig del')
})
it('fills the description when the line had no description yet', () => {
expect(nextLineDescriptionForAccountChange('', '', '2893', ACCOUNTS)).toBe(
'Skulder till närstående personer, kortfristig del',
)
})
it('preserves a memo the user typed themselves', () => {
expect(
nextLineDescriptionForAccountChange('Återbetalning till Anna', '1930', '2893', ACCOUNTS),
).toBe('Återbetalning till Anna')
})
it('leaves the description untouched when the new account is unknown', () => {
expect(
nextLineDescriptionForAccountChange('Lån från närstående personer, långfristig del', '2393', '9999', ACCOUNTS),
).toBe('Lån från närstående personer, långfristig del')
})
it('returns the current description when the account is cleared', () => {
expect(nextLineDescriptionForAccountChange('Företagskonto', '1930', '', ACCOUNTS)).toBe('Företagskonto')
})
it('treats a description equal to the new account name as already correct', () => {
// Switching to an account whose name already matches: no visible change.
expect(
nextLineDescriptionForAccountChange('Skulder till närstående personer, kortfristig del', '2393', '2893', ACCOUNTS),
).toBe('Skulder till närstående personer, kortfristig del')
})
})
@@ -1,177 +0,0 @@
import { describe, it, expect } from 'vitest'
import { makeJournalEntryLine } from '@/tests/helpers'
import {
buildCorrectionRows,
formatSignedAmount,
} from '@/components/bookkeeping/correction-preview-rows'
describe('buildCorrectionRows', () => {
it('returns no rows when both inputs are empty', () => {
expect(buildCorrectionRows([], [])).toEqual([])
})
it('amount change on same accounts: storno cancels original, correction adds the new value', () => {
const original = [
makeJournalEntryLine({ account_number: '5410', debit_amount: 1000, credit_amount: 0 }),
makeJournalEntryLine({ account_number: '1930', debit_amount: 0, credit_amount: 1000 }),
]
const corrected = [
{ account_number: '5410', debit_amount: 1200, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 1200 },
]
const rows = buildCorrectionRows(original, corrected)
expect(rows).toEqual([
{ account_number: '1930', original: -1000, storno: 1000, correction: -1200, delta: -200, correctionPresent: true },
{ account_number: '5410', original: 1000, storno: -1000, correction: 1200, delta: 200, correctionPresent: true },
])
})
it('account swap: old account zeros out, new account picks up the value', () => {
const original = [
makeJournalEntryLine({ account_number: '5410', debit_amount: 1000, credit_amount: 0 }),
makeJournalEntryLine({ account_number: '1930', debit_amount: 0, credit_amount: 1000 }),
]
const corrected = [
{ account_number: '5420', debit_amount: 1000, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 1000 },
]
const rows = buildCorrectionRows(original, corrected)
// 5410 ends at delta=-1000 (drained back), 5420 ends at delta=+1000 (new),
// 1930 nets to zero: correction matches storno exactly.
expect(rows.find((r) => r.account_number === '5410')).toEqual({
account_number: '5410',
original: 1000,
storno: -1000,
correction: 0,
delta: -1000,
correctionPresent: false,
})
expect(rows.find((r) => r.account_number === '5420')).toEqual({
account_number: '5420',
original: 0,
storno: 0,
correction: 1000,
delta: 1000,
correctionPresent: true,
})
expect(rows.find((r) => r.account_number === '1930')).toEqual({
account_number: '1930',
original: -1000,
storno: 1000,
correction: -1000,
delta: 0,
correctionPresent: true,
})
})
it('identical correction has zero delta on every row', () => {
const original = [
makeJournalEntryLine({ account_number: '5410', debit_amount: 1000, credit_amount: 0 }),
makeJournalEntryLine({ account_number: '1930', debit_amount: 0, credit_amount: 1000 }),
]
const corrected = [
{ account_number: '5410', debit_amount: 1000, credit_amount: 0 },
{ account_number: '1930', debit_amount: 0, credit_amount: 1000 },
]
const rows = buildCorrectionRows(original, corrected)
expect(rows.every((r) => r.delta === 0)).toBe(true)
})
it('accepts string amounts from form inputs', () => {
const original = [
makeJournalEntryLine({ account_number: '5410', debit_amount: 1000, credit_amount: 0 }),
]
const corrected = [
{ account_number: '5410', debit_amount: '1500.50', credit_amount: '' },
]
const rows = buildCorrectionRows(original, corrected)
expect(rows[0]).toEqual({
account_number: '5410',
original: 1000,
storno: -1000,
correction: 1500.5,
delta: 500.5,
correctionPresent: true,
})
})
it('skips corrected lines with partial account numbers (mid-edit)', () => {
const original = [
makeJournalEntryLine({ account_number: '5410', debit_amount: 1000, credit_amount: 0 }),
]
const corrected = [
{ account_number: '54', debit_amount: 1200, credit_amount: 0 },
{ account_number: '193', debit_amount: 0, credit_amount: 1200 },
]
const rows = buildCorrectionRows(original, corrected)
// Only original 5410 shows up; the partial entries are ignored.
expect(rows).toHaveLength(1)
expect(rows[0].account_number).toBe('5410')
expect(rows[0].correction).toBe(0)
})
it('flags a removed account: storno drains it, correctionPresent is false', () => {
// The reported scenario: a sale-shaped verifikat where the user drops the
// revenue line (3001) from the rättelse. The storno still reverses 3001
// (delta = −original), and correctionPresent=false lets the UI label it
// "tas bort" rather than rendering a bare "-".
const original = [
makeJournalEntryLine({ account_number: '1510', debit_amount: 0, credit_amount: 1875 }),
makeJournalEntryLine({ account_number: '2611', debit_amount: 375, credit_amount: 0 }),
makeJournalEntryLine({ account_number: '3001', debit_amount: 1500, credit_amount: 0 }),
]
const corrected = [
{ account_number: '2611', debit_amount: 375, credit_amount: 0 },
{ account_number: '1510', debit_amount: 0, credit_amount: 1875 },
]
const rows = buildCorrectionRows(original, corrected)
expect(rows.find((r) => r.account_number === '3001')).toEqual({
account_number: '3001',
original: 1500,
storno: -1500,
correction: 0,
delta: -1500,
correctionPresent: false,
})
// The kept accounts net to zero and stay flagged as present.
expect(rows.find((r) => r.account_number === '1510')?.delta).toBe(0)
expect(rows.find((r) => r.account_number === '1510')?.correctionPresent).toBe(true)
expect(rows.find((r) => r.account_number === '2611')?.delta).toBe(0)
expect(rows.find((r) => r.account_number === '2611')?.correctionPresent).toBe(true)
})
it('rounds to öre to avoid 0.1+0.2 drift', () => {
const original = [
makeJournalEntryLine({ account_number: '5410', debit_amount: 0.1, credit_amount: 0 }),
makeJournalEntryLine({ account_number: '5410', debit_amount: 0.2, credit_amount: 0 }),
]
const rows = buildCorrectionRows(original, [])
expect(rows[0].original).toBe(0.3)
expect(rows[0].storno).toBe(-0.3)
})
})
describe('formatSignedAmount', () => {
it('formats positive amounts with leading +', () => {
expect(formatSignedAmount(1200)).toBe('+1\u00a0200,00')
})
it('formats negative amounts with unicode minus', () => {
expect(formatSignedAmount(-1000)).toBe('−1\u00a0000,00')
})
it('renders zero as a hyphen', () => {
expect(formatSignedAmount(0)).toBe('-')
})
it('always renders two decimals', () => {
expect(formatSignedAmount(5.5)).toBe('+5,50')
})
})
@@ -1,47 +0,0 @@
import { describe, it, expect } from 'vitest'
import fs from 'node:fs'
import path from 'node:path'
const SRC = fs.readFileSync(
path.resolve(__dirname, '../JournalEntryList.tsx'),
'utf8',
)
/**
* Regression pin for the per-row copy affordance (#1266).
*
* The icon was removed as collateral of the row-language rewrite in #1123: its
* slot was reused for the expand toggle, and the only trace left was an
* orphaned `copy_voucher_tooltip` key in both message files. The repo does not
* render components in tests, so nothing observed the loss; pin the source
* shape instead, the same way NewInvoiceDialog's copy query is pinned.
*/
describe('JournalEntryList row copy affordance', () => {
it('keeps the Copy icon imported from lucide', () => {
const importLine = SRC.split('\n').find(
(l) => l.includes("from 'lucide-react'") && l.startsWith('import'),
)
expect(importLine).toBeDefined()
expect(importLine).toContain('Copy')
})
it('references copy_voucher_tooltip, so the i18n key is not orphaned', () => {
expect(SRC).toContain("t('copy_voucher_tooltip')")
})
it('labels the row icon for screen readers', () => {
expect(SRC).toContain("aria-label={t('copy_voucher_tooltip')}")
})
it('stops propagation before navigating, so copying never toggles the foldout', () => {
// The whole <tr> is the expand toggle, so a copy click that bubbles would
// open the row instead of (or as well as) starting the copy.
const start = SRC.indexOf("aria-label={t('copy_voucher_tooltip')}")
expect(start).toBeGreaterThan(-1)
const push = SRC.indexOf('/bookkeeping?copy_from=${entry.id}', start)
expect(push).toBeGreaterThan(-1)
const handler = SRC.slice(start, push)
expect(handler).toContain('e.stopPropagation()')
})
})
@@ -1,92 +0,0 @@
/**
* Pure positioning for AccountCombobox's portaled (non-flat) dropdown.
*
* The non-flat dropdown renders on document.body (see AccountCombobox) so a
* scrollable DialogContent can never clip it or grow a horizontal scrollbar
* around it. That trades CSS anchoring (absolute + top-full) for explicit
* viewport math, which lives here so it can be unit-tested headlessly.
*
* All numbers are CSS pixels in viewport coordinates (getBoundingClientRect
* space), matching position: fixed.
*/
export interface DropdownAnchorRect {
top: number
bottom: number
left: number
width: number
}
export interface DropdownViewportSize {
width: number
height: number
}
export interface DropdownPosition {
left: number
width: number
maxHeight: number
/** Set when the dropdown opens below the anchor (CSS `top`). */
top?: number
/**
* Set when the dropdown opens above the anchor (CSS `bottom`, measured from
* the viewport bottom). Anchoring by `bottom` lets the panel grow upward
* without knowing its own height.
*/
bottom?: number
}
/** 34rem: wide enough for account number + name + activation marker. */
export const DROPDOWN_PREFERRED_WIDTH = 544
/** Minimum gap kept between the dropdown and every viewport edge. */
export const DROPDOWN_VIEWPORT_MARGIN = 8
/** Gap between the anchor (trigger) and the dropdown. */
export const DROPDOWN_ANCHOR_GAP = 4
/** The dropdown's own scroll ceiling (was max-h-[300px] pre-portal). */
export const DROPDOWN_MAX_HEIGHT = 300
/** Below this much room the dropdown flips above the anchor instead. */
const MIN_USEFUL_HEIGHT = 120
/** Height floor so a cramped viewport still shows a scrollable list. */
const HEIGHT_FLOOR = 96
/**
* Shallow equality over the full position shape. The scroll/resize reposition
* handler uses this to skip setState when the recomputed geometry is
* unchanged (e.g. scroll events that did not move the anchor), so React does
* not re-render the open dropdown on every scroll tick.
*/
export function isSameDropdownPosition(
a: DropdownPosition | null,
b: DropdownPosition,
): boolean {
return (
a !== null &&
a.left === b.left &&
a.width === b.width &&
a.maxHeight === b.maxHeight &&
a.top === b.top &&
a.bottom === b.bottom
)
}
export function computeDropdownPosition(
anchor: DropdownAnchorRect,
viewport: DropdownViewportSize,
): DropdownPosition {
const margin = DROPDOWN_VIEWPORT_MARGIN
const maxWidth = Math.max(viewport.width - margin * 2, 0)
const width = Math.min(Math.max(anchor.width, DROPDOWN_PREFERRED_WIDTH), maxWidth)
const left = Math.max(margin, Math.min(anchor.left, viewport.width - width - margin))
const spaceBelow = viewport.height - anchor.bottom - DROPDOWN_ANCHOR_GAP - margin
const spaceAbove = anchor.top - DROPDOWN_ANCHOR_GAP - margin
const openUp = spaceBelow < MIN_USEFUL_HEIGHT && spaceAbove > spaceBelow
const available = openUp ? spaceAbove : spaceBelow
const maxHeight = Math.min(DROPDOWN_MAX_HEIGHT, Math.max(available, HEIGHT_FLOOR))
if (openUp) {
return { left, width, maxHeight, bottom: viewport.height - anchor.top + DROPDOWN_ANCHOR_GAP }
}
return { left, width, maxHeight, top: anchor.bottom + DROPDOWN_ANCHOR_GAP }
}
-96
View File
@@ -1,96 +0,0 @@
/**
* K2 vasentlighetsgrans for periodisering, extracted as a pure helper so it
* can be unit-tested (this repo's Vitest runs in a node environment and does
* not render components).
*
* K2 (BFNAR 2016:10) lets a smaller company skip accruing individual
* recurring costs below 5 000 kr that do not fluctuate more than 20 % year
* over year; personnel costs must always be accrued. It is a simplification
* the company MAY use, never an obligation, so the UI copy it drives is
* advisory only. That is exactly why it must not fire on an amount we cannot
* express in kronor: an advisory nudge based on the wrong unit is worse than
* no nudge at all.
*
* The invoice editors hold line amounts in the invoice's currency. A 500 EUR
* line is roughly 5 750 kr and therefore ABOVE the threshold, but a naive
* `amount < 5000` reads it as below (and a 400 USD line reads the reverse
* way once the rate moves). Converting needs an FX rate. The supplier-invoice
* form has one (Riksbanken-fetched or hand-typed); the customer-invoice
* editor has none. When no rate is available we return null and the caller
* shows nothing, rather than guessing a branch.
*/
/** BFNAR 2016:10: the K2 accrual simplification ceiling, in SEK. */
import type { EntityType } from '@/types'
import { simplifiedYearEndRegelverk } from '@/lib/company/entity-type'
export const K2_ACCRUAL_THRESHOLD_SEK = 5000
export interface AccrualAmountInput {
/** Net line amount, expressed in `currency`. */
amount: number
/** ISO currency code of `amount`. Missing/empty is treated as SEK. */
currency?: string | null
/** SEK per one unit of `currency`. Required to convert anything non-SEK. */
exchangeRate?: number | null
}
/**
* The line amount in SEK, or null when it cannot be determined.
*
* Deliberately NOT `resolveSekAmount()` from `@/lib/bookkeeping/currency-utils`:
* that helper falls back to returning the foreign amount untouched, which is
* the silent wrong-unit branch this helper exists to avoid.
*/
export function resolveAccrualAmountSek({
amount,
currency,
exchangeRate,
}: AccrualAmountInput): number | null {
if (typeof amount !== 'number' || !Number.isFinite(amount)) return null
const code = (currency ?? '').trim().toUpperCase()
if (code === '' || code === 'SEK') {
return Math.round(amount * 100) / 100
}
if (
typeof exchangeRate !== 'number' ||
!Number.isFinite(exchangeRate) ||
exchangeRate <= 0
) {
return null
}
return Math.round(amount * exchangeRate * 100) / 100
}
/**
* Whether to show the "below 5 000 kr need not be deferred" hint.
*
* False whenever the SEK value is unknown: no hint beats a hint measured in
* the wrong currency.
*/
export function shouldShowK2AccrualHint(input: AccrualAmountInput): boolean {
const amountSek = resolveAccrualAmountSek(input)
if (amountSek === null) return false
return amountSek > 0 && amountSek < K2_ACCRUAL_THRESHOLD_SEK
}
/**
* Which `accruals.*` message key carries the materiality hint for the given
* entity type. An enskild firma normally closes under K1 (BFNAR 2006:1,
* förenklat årsbokslut), which relieves posts below 5 000 kr; citing K2
* (BFNAR 2016:10) at a sole trader names a regelverk that does not apply to
* it. There is no stored förenklat-vs-full-årsbokslut flag, so entity_type
* is a proxy and the copy stays advisory ("behöver normalt inte").
*
* Unknown/missing entity keeps the K2 wording: it is the historical default
* and correct for every aktiebolag.
*/
export function accrualHintKey(
entityType?: EntityType | null,
): 'k1_hint' | 'k2_hint' {
if (!entityType) return 'k2_hint'
return simplifiedYearEndRegelverk(entityType) === 'K1' ? 'k1_hint' : 'k2_hint'
}
@@ -1,496 +0,0 @@
'use client'
import { useMemo, useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Loader2, Plus, X } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { useCompanyOptional } from '@/contexts/CompanyContext'
import { formatCurrency } from '@/lib/utils'
import type { AssetCategory, K3Component } from '@/types'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
interface CreateAssetDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onCreated: () => void
}
/** Editor row state: strings so the user can clear inputs without zeroing
* out the component immediately. Converted to numbers at submit time. */
interface ComponentRow {
id: string
name: string
cost: string
useful_life_months: string
salvage_value: string
}
let componentRowCounter = 0
function newComponentRow(): ComponentRow {
componentRowCounter += 1
return {
id: `cmp-${componentRowCounter}`,
name: '',
cost: '',
useful_life_months: '',
salvage_value: '',
}
}
// Defaults are K2-redovisning (BFNAR 2016:10) schablon, NOT skattemässig
// avskrivning. Building / markanläggning values are conservative: IL 19/20
// kap may allow longer (50 yr) or shorter (10 yr) depending on byggnadstyp.
const CATEGORY_OPTIONS: { value: AssetCategory; label: string; defaultYears: number }[] = [
{ value: 'computer', label: 'Dator / IT-utrustning', defaultYears: 3 },
{ value: 'equipment', label: 'Inventarier', defaultYears: 5 },
{ value: 'machinery', label: 'Maskiner', defaultYears: 10 },
{ value: 'vehicle', label: 'Fordon', defaultYears: 5 },
{ value: 'building', label: 'Byggnad', defaultYears: 25 },
{ value: 'land_improvement', label: 'Markanläggning', defaultYears: 10 },
{ value: 'immaterial', label: 'Immateriell tillgång', defaultYears: 5 },
{ value: 'other_tangible', label: 'Övrig materiell tillgång', defaultYears: 5 },
]
// No account override here on purpose. The server resolves the immaterial
// default per framework (defaultAccountsForCategory in
// lib/bokslut/assets/asset-service.ts): 1090/1099 for K2, 1010/1019 for K3.
// Sending an explicit pair from this dialog would duplicate that rule on a
// second surface, and the edit dialog (which has no account inputs at all)
// could never mirror it. The hint below just tells the user where it lands.
export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAssetDialogProps) {
const { toast } = useToast()
// useCompanyOptional so the dialog still works in tests / storyboards
// that don't wrap it in CompanyProvider. K3 features simply hide.
const companyCtx = useCompanyOptional()
const isK3 = companyCtx?.company?.accounting_framework === 'k3'
const [name, setName] = useState('')
const [category, setCategory] = useState<AssetCategory>('equipment')
const [acquisitionDate, setAcquisitionDate] = useState(
new Date().toISOString().split('T')[0],
)
const [acquisitionCost, setAcquisitionCost] = useState('')
const [usefulLifeYears, setUsefulLifeYears] = useState('5')
// K3 component depreciation. `useComponents` toggles the advanced section;
// null when disabled, an array (possibly empty during editing) when enabled.
const [useComponents, setUseComponents] = useState(false)
const [componentRows, setComponentRows] = useState<ComponentRow[]>([])
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const handleCategoryChange = (next: AssetCategory) => {
setCategory(next)
const option = CATEGORY_OPTIONS.find((o) => o.value === next)
if (option) setUsefulLifeYears(option.defaultYears.toString())
}
const totalComponentCost = useMemo(() => {
return componentRows.reduce((sum, row) => {
const v = parseFloat(row.cost)
return Number.isFinite(v) ? sum + v : sum
}, 0)
}, [componentRows])
const parsedAcquisitionCost = parseFloat(acquisitionCost)
const componentMismatch =
useComponents
&& componentRows.length > 0
&& Number.isFinite(parsedAcquisitionCost)
&& Math.abs(totalComponentCost - parsedAcquisitionCost) > 1
const addComponentRow = () => {
setComponentRows((rows) => [...rows, newComponentRow()])
}
const removeComponentRow = (id: string) => {
setComponentRows((rows) => rows.filter((r) => r.id !== id))
}
const updateComponentRow = (id: string, patch: Partial<ComponentRow>) => {
setComponentRows((rows) => rows.map((r) => (r.id === id ? { ...r, ...patch } : r)))
}
const toggleUseComponents = (next: boolean) => {
setUseComponents(next)
if (next && componentRows.length === 0) {
setComponentRows([newComponentRow()])
}
}
const handleSubmit = async () => {
setError(null)
const cost = parseFloat(acquisitionCost)
const years = parseInt(usefulLifeYears, 10)
if (!name.trim() || !Number.isFinite(cost) || cost <= 0 || !Number.isFinite(years) || years <= 0) {
setError('Fyll i namn, anskaffningsvärde och avskrivningstid.')
return
}
// K3 components: only when both the framework permits (gate at API)
// and the user opted into the section. Empty array is invalid (the
// validator rejects it) so the dialog also flips back to "off" when
// every row is removed.
let componentsPayload: K3Component[] | null = null
if (useComponents && isK3) {
if (componentRows.length === 0) {
setError('Lägg till minst en komponent eller stäng av komponentuppdelningen.')
return
}
const parsed: K3Component[] = []
for (const [index, row] of componentRows.entries()) {
const componentCost = parseFloat(row.cost)
const months = parseInt(row.useful_life_months, 10)
const salvageRaw = row.salvage_value.trim()
const salvage = salvageRaw === '' ? undefined : parseFloat(salvageRaw)
const trimmedName = row.name.trim()
if (!trimmedName) {
setError(`Komponent ${index + 1}: ange ett namn.`)
return
}
if (!Number.isFinite(componentCost) || componentCost <= 0) {
setError(`${trimmedName}: anskaffningsvärdet måste vara större än 0.`)
return
}
if (!Number.isFinite(months) || months <= 0) {
setError(`${trimmedName}: ange ett positivt heltal månader.`)
return
}
if (salvage !== undefined && (!Number.isFinite(salvage) || salvage < 0)) {
setError(`${trimmedName}: restvärdet får inte vara negativt.`)
return
}
if (salvage !== undefined && salvage > componentCost) {
setError(`${trimmedName}: restvärdet får inte överstiga anskaffningsvärdet.`)
return
}
parsed.push({
name: trimmedName,
cost: componentCost,
useful_life_months: months,
...(salvage !== undefined ? { salvage_value: salvage } : {}),
})
}
const sum = parsed.reduce((s, c) => s + c.cost, 0)
if (Math.abs(sum - cost) > 1) {
setError(
`Komponenter summerar till ${formatCurrency(sum)} men anskaffningsvärdet är ${formatCurrency(cost)}.`,
)
return
}
componentsPayload = parsed
}
setSubmitting(true)
try {
const res = await fetch('/api/assets', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: name.trim(),
category,
acquisition_date: acquisitionDate,
acquisition_cost: cost,
useful_life_months: years * 12,
...(componentsPayload !== null ? { k3_components: componentsPayload } : {}),
}),
})
const body = await res.json()
if (!res.ok) {
setError(getUserErrorMessage(body?.error) ?? 'Kunde inte spara tillgången')
return
}
toast({ title: 'Tillgång sparad', description: name.trim() })
// Reset form for next entry
setName('')
setAcquisitionCost('')
setUseComponents(false)
setComponentRows([])
onCreated()
} catch (err) {
setError(err instanceof Error ? getUserErrorMessage(err) : 'Okänt fel')
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className={isK3 ? 'sm:max-w-2xl' : 'sm:max-w-md'}>
<DialogHeader>
<DialogTitle>Ny anläggningstillgång</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="asset-name">Namn</Label>
<Input
id="asset-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="t.ex. MacBook Pro 14"
autoFocus
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="asset-category">Kategori</Label>
<Select value={category} onValueChange={(v) => handleCategoryChange(v as AssetCategory)}>
<SelectTrigger id="asset-category">
<SelectValue />
</SelectTrigger>
<SelectContent>
{CATEGORY_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
{category === 'immaterial' && !isK3 && (
<p className="text-xs text-muted-foreground">
Bokförs som förvärvad immateriell tillgång (konto 1090). Egenupparbetad
utveckling får inte aktiveras enligt K2 (BFNAR 2016:10 punkt 10.4): det kräver K3.
</p>
)}
{category === 'immaterial' && isK3 && (
<p className="text-xs text-muted-foreground">
För aktiebolag medför aktivering av egenupparbetad utveckling (konto 1010) att
motsvarande belopp sätts av till fond för utvecklingsutgifter (konto 2089) enligt
ÅRL 4 kap. 2 §.
</p>
)}
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="asset-date">Anskaffat</Label>
<Input
id="asset-date"
type="date"
value={acquisitionDate}
onChange={(e) => setAcquisitionDate(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="asset-cost">Anskaffningsvärde (kr)</Label>
<Input
id="asset-cost"
type="number"
step="1"
min="0"
value={acquisitionCost}
onChange={(e) => setAcquisitionCost(e.target.value)}
placeholder="t.ex. 25000"
className="tabular-nums"
/>
</div>
</div>
<div className="space-y-1.5">
<Label htmlFor="asset-life">Avskrivningstid (år)</Label>
<Input
id="asset-life"
type="number"
min="1"
max="50"
step="1"
value={usefulLifeYears}
onChange={(e) => setUsefulLifeYears(e.target.value)}
className="tabular-nums"
/>
<p className="text-xs text-muted-foreground">
K2-schablon för redovisning: datorer 3 år, inventarier 5 år, byggnader 25 år.
För skattemässig avskrivning kan annan livslängd gälla (IL 18-20 kap).
</p>
</div>
{isK3 && (
<div className="space-y-3 rounded-lg border border-border bg-muted/20 p-4">
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<Label className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Avancerat: komponentuppdelning
</Label>
<p className="text-xs text-muted-foreground">
K3 (BFNAR 2012:1 17.4): när väsentliga komponenter har olika nyttjandeperiod
skrivs varje komponent av för sig. Typisk för fastigheter (tak, fasad, stomme,
installationer).
</p>
</div>
<Button
type="button"
variant={useComponents ? 'default' : 'outline'}
size="sm"
onClick={() => toggleUseComponents(!useComponents)}
>
{useComponents ? 'Aktiverad' : 'Aktivera'}
</Button>
</div>
{useComponents && (
<div className="space-y-2">
{componentRows.map((row, idx) => (
<div
key={row.id}
className="grid grid-cols-12 items-end gap-2 rounded-lg border border-border bg-background p-2"
>
<div className="col-span-12 sm:col-span-4 space-y-1">
<Label
htmlFor={`cmp-name-${row.id}`}
className="text-xs text-muted-foreground"
>
Komponent
</Label>
<Input
id={`cmp-name-${row.id}`}
value={row.name}
onChange={(e) =>
updateComponentRow(row.id, { name: e.target.value })
}
placeholder={idx === 0 ? 't.ex. Stomme' : 'Namn'}
/>
</div>
<div className="col-span-6 sm:col-span-3 space-y-1">
<Label
htmlFor={`cmp-cost-${row.id}`}
className="text-xs text-muted-foreground"
>
Kostnad (kr)
</Label>
<Input
id={`cmp-cost-${row.id}`}
type="number"
min="0"
step="1"
value={row.cost}
onChange={(e) =>
updateComponentRow(row.id, { cost: e.target.value })
}
className="tabular-nums"
/>
</div>
<div className="col-span-6 sm:col-span-2 space-y-1">
<Label
htmlFor={`cmp-life-${row.id}`}
className="text-xs text-muted-foreground"
>
Liv (mån)
</Label>
<Input
id={`cmp-life-${row.id}`}
type="number"
min="1"
step="1"
value={row.useful_life_months}
onChange={(e) =>
updateComponentRow(row.id, { useful_life_months: e.target.value })
}
className="tabular-nums"
/>
</div>
<div className="col-span-9 sm:col-span-2 space-y-1">
<Label
htmlFor={`cmp-salvage-${row.id}`}
className="text-xs text-muted-foreground"
>
Restvärde
</Label>
<Input
id={`cmp-salvage-${row.id}`}
type="number"
min="0"
step="1"
value={row.salvage_value}
onChange={(e) =>
updateComponentRow(row.id, { salvage_value: e.target.value })
}
placeholder="0"
className="tabular-nums"
/>
</div>
<div className="col-span-3 sm:col-span-1 flex justify-end">
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => removeComponentRow(row.id)}
aria-label="Ta bort komponent"
disabled={componentRows.length === 1}
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
))}
<div className="flex items-center justify-between gap-3">
<Button
type="button"
variant="outline"
size="sm"
onClick={addComponentRow}
>
<Plus className="mr-1 h-4 w-4" /> Lägg till komponent
</Button>
<div className="text-xs tabular-nums text-muted-foreground">
Summa komponenter:{' '}
<span
className={
componentMismatch
? 'text-destructive font-medium'
: 'text-foreground'
}
>
{formatCurrency(totalComponentCost)}
</span>
</div>
</div>
{componentMismatch && (
<p className="text-xs text-destructive">
Komponenter summerar inte till anskaffningsvärdet (
{formatCurrency(parsedAcquisitionCost)}).
</p>
)}
</div>
)}
</div>
)}
<div className="rounded-lg border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
<strong className="text-foreground">Tips:</strong> Anskaffningen måste redan vara
bokförd (debet på 1xxx-kontot mot t.ex. 1930/2440): registret bokför inte
själva köpet. Det här registret styr enbart de planenliga avskrivningarna under
bokslutet.
</div>
{error && (
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
{error}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
Avbryt
</Button>
<Button onClick={handleSubmit} disabled={submitting}>
{submitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Sparar…
</>
) : (
'Spara'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,248 +0,0 @@
'use client'
import { useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Loader2, Lock } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { Asset, AssetCategory } from '@/types'
/** The list route annotates each asset with whether any depreciation has been
* posted against it. When true, the acquisition-basis fields are locked. */
type EditableAsset = Asset & { has_posted_depreciation?: boolean }
interface EditAssetDialogProps {
asset: EditableAsset
open: boolean
onOpenChange: (open: boolean) => void
onSaved: () => void
}
// Same category labels as CreateAssetDialog.
const CATEGORY_OPTIONS: { value: AssetCategory; label: string }[] = [
{ value: 'computer', label: 'Dator / IT-utrustning' },
{ value: 'equipment', label: 'Inventarier' },
{ value: 'machinery', label: 'Maskiner' },
{ value: 'vehicle', label: 'Fordon' },
{ value: 'building', label: 'Byggnad' },
{ value: 'land_improvement', label: 'Markanläggning' },
{ value: 'immaterial', label: 'Immateriell tillgång' },
{ value: 'other_tangible', label: 'Övrig materiell tillgång' },
]
export function EditAssetDialog({ asset, open, onOpenChange, onSaved }: EditAssetDialogProps) {
const { toast } = useToast()
const { canWrite } = useCanWrite()
// Once depreciation has been booked, acquisition date/cost/category are
// locked: a real change has to go through storno. The server enforces the
// same rule (ASSET_CORRECTION_BLOCKED); this just makes it visible up front.
const basisLocked = asset.has_posted_depreciation === true
const [name, setName] = useState(asset.name)
const [category, setCategory] = useState<AssetCategory>(asset.category)
const [acquisitionDate, setAcquisitionDate] = useState(asset.acquisition_date)
const [acquisitionCost, setAcquisitionCost] = useState(String(asset.acquisition_cost))
const [usefulLifeYears, setUsefulLifeYears] = useState(
String(Math.round(asset.useful_life_months / 12)),
)
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const handleSubmit = async () => {
setError(null)
const trimmedName = name.trim()
if (!trimmedName) {
setError('Namnet får inte vara tomt.')
return
}
// Send only what actually changed. This keeps a name-only edit on a
// depreciated asset from tripping the acquisition-basis guard, and avoids
// clobbering a useful_life_months value that isn't a clean multiple of 12.
const patch: Record<string, unknown> = {}
if (trimmedName !== asset.name) patch.name = trimmedName
if (!basisLocked) {
if (category !== asset.category) patch.category = category
if (acquisitionDate !== asset.acquisition_date) patch.acquisition_date = acquisitionDate
const cost = parseFloat(acquisitionCost)
if (!Number.isFinite(cost) || cost <= 0) {
setError('Anskaffningsvärdet måste vara större än 0.')
return
}
if (cost !== Number(asset.acquisition_cost)) patch.acquisition_cost = cost
}
const years = parseInt(usefulLifeYears, 10)
if (!Number.isFinite(years) || years <= 0) {
setError('Ange en avskrivningstid (minst 1 år).')
return
}
const months = years * 12
if (months !== asset.useful_life_months) patch.useful_life_months = months
if (Object.keys(patch).length === 0) {
toast({ title: 'Inga ändringar', description: 'Inget att spara.' })
onOpenChange(false)
return
}
setSubmitting(true)
try {
const res = await fetch(`/api/assets/${asset.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch),
})
const body = await res.json()
if (!res.ok) {
setError(getErrorMessage(body?.error ?? body) || 'Kunde inte spara ändringen.')
return
}
toast({ title: 'Tillgång uppdaterad', description: trimmedName })
onSaved()
} catch (err) {
setError(getErrorMessage(err))
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>Ändra anläggningstillgång</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className="space-y-1.5">
<Label htmlFor="edit-asset-name">Namn</Label>
<Input
id="edit-asset-name"
value={name}
onChange={(e) => setName(e.target.value)}
autoFocus
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="edit-asset-category">Kategori</Label>
<Select
value={category}
onValueChange={(v) => setCategory(v as AssetCategory)}
disabled={basisLocked}
>
<SelectTrigger id="edit-asset-category">
<SelectValue />
</SelectTrigger>
<SelectContent>
{CATEGORY_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-1.5">
<Label htmlFor="edit-asset-date">Anskaffat</Label>
<Input
id="edit-asset-date"
type="date"
value={acquisitionDate}
onChange={(e) => setAcquisitionDate(e.target.value)}
disabled={basisLocked}
className="tabular-nums"
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="edit-asset-cost">Anskaffningsvärde (kr)</Label>
<Input
id="edit-asset-cost"
type="number"
step="1"
min="0"
value={acquisitionCost}
onChange={(e) => setAcquisitionCost(e.target.value)}
disabled={basisLocked}
className="tabular-nums"
/>
</div>
</div>
{basisLocked && (
<div className="flex items-start gap-2 rounded-lg border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
<Lock className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>
Anskaffningsdatum, anskaffningsvärde och kategori är låsta eftersom avskrivningar
redan har bokförts. Återför avskrivningen (storno) eller använd avyttring för att
ändra grunduppgifterna. Namn och avskrivningstid kan fortfarande justeras.
</span>
</div>
)}
<div className="space-y-1.5">
<Label htmlFor="edit-asset-life">Avskrivningstid (år)</Label>
<Input
id="edit-asset-life"
type="number"
min="1"
max="50"
step="1"
value={usefulLifeYears}
onChange={(e) => setUsefulLifeYears(e.target.value)}
className="tabular-nums"
/>
</div>
{error && (
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive">
{error}
</div>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
Avbryt
</Button>
<Button
onClick={handleSubmit}
disabled={!canWrite || submitting}
title={
!canWrite ? 'Endast användare med skrivrättigheter kan ändra tillgångar.' : undefined
}
>
{!canWrite && <Lock className="mr-1 h-4 w-4" />}
{submitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Sparar…
</>
) : (
'Spara'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,34 +0,0 @@
/**
* Entry-level verifikationstext handling for the correction dialog.
*
* The correction header defaults server-side to "Rättelse: <original>"
* (lib/core/bookkeeping/storno-service.ts). If the original entry was
* labelled after the wrong account (e.g. "Lån från närstående personer,
* långfristig del"), that header keeps echoing the wrong label even after
* the account itself is corrected (issue #1031). The dialog therefore
* pre-fills an editable field with the same auto text and only sends a
* description when the user actually changed it: an untouched auto prefill
* is omitted from the request so the server-side fallback stays the single
* source of truth for the default format. Same only-overwrite-auto-filled
* principle as the line-description guard from #1029.
*/
/** The auto text the server would generate for the correction header. */
export function autoCorrectionDescription(originalDescription: string): string {
return `Rättelse: ${originalDescription}`
}
/**
* Decide what to send as the correction's description.
* Returns undefined when the field is blank or still equals the auto prefill:
* in both cases the server-side fallback should apply.
*/
export function correctionDescriptionForSubmit(
currentDescription: string,
originalDescription: string,
): string | undefined {
const trimmed = currentDescription.trim()
if (!trimmed) return undefined
if (trimmed === autoCorrectionDescription(originalDescription).trim()) return undefined
return trimmed
}

Some files were not shown because too many files have changed in this diff Show More