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
File diff suppressed because it is too large Load Diff
@@ -1,401 +0,0 @@
'use client'
import { useState } from 'react'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { cn, formatDate } from '@/lib/utils'
import { ChevronRight, Loader2, MoreHorizontal } from 'lucide-react'
import { getConnectionUiState } from '../lib/connection-state'
import { describeClaimedElsewhere, partitionByClaim } from '../lib/claimed-accounts'
import type { BankConnection } from '@/types'
interface BankConnectionStatusProps {
connection: BankConnection
onSync: (connectionId: string) => void
onDisconnect: (connectionId: string) => void
onReconnect?: (connection: BankConnection, psuType?: 'personal' | 'business') => void
onManageAccounts?: (connectionId: string) => void
isSyncing?: boolean
}
/**
* One bank connection as a flat hairline row (Fönster settings language):
* identity + state on one line, exactly ONE primary action decided by the
* derived UI state, every secondary action behind a "..." menu, and the
* details (accounts, IBAN, balances, initial backfill) behind a collapsed
* disclosure. The page-level attention sentence lives in the panel, not
* here (design convention 6: one .attn per page).
*/
export function BankConnectionStatus({
connection,
onSync,
onDisconnect,
onReconnect,
onManageAccounts,
isSyncing = false,
}: BankConnectionStatusProps) {
const [now] = useState(() => Date.now())
const [detailsOpen, setDetailsOpen] = useState(false)
const uiState = getConnectionUiState(connection, now)
// Parse accounts from connection
const accounts = (connection.accounts_data as Array<{
uid: string
iban?: string
name?: string
currency: string
balance?: number
balance_updated_at?: string
enabled?: boolean
claimed_by_company_id?: string
claimed_by_company_name?: string
}>) || []
// Accounts another of the user's companies books (one SEB consent covers
// every company the signer represents) are not this company's accounts:
// they are left out of the list and the count, and summarised in one line.
const { own: ownAccounts, claimedElsewhere } = partitionByClaim(accounts)
const enabledCount = ownAccounts.filter((a) => a.enabled !== false).length
function formatBalanceAge(updatedAt: string): string {
const hoursAgo = Math.floor((now - new Date(updatedAt).getTime()) / (1000 * 60 * 60))
if (hoursAgo < 1) return 'Nyss uppdaterat'
if (hoursAgo < 24) return `${hoursAgo}h sedan`
const daysAgo = Math.floor(hoursAgo / 24)
return `${daysAgo}d sedan`
}
// In-flight authorization: the row exists but the user is still at the
// bank. Render it as a quiet spinner row instead of hiding it (the connect
// button lock alone made this state invisible).
if (uiState === 'pending') {
return (
<div className="flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1 border-b border-border px-1 py-3">
<span className="text-sm font-medium">{connection.bank_name}</span>
<span className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
Väntar på banken…
</span>
<span className="ml-auto shrink-0">
<Button
variant="ghost"
size="sm"
className="text-muted-foreground hover:text-foreground"
onClick={() => onDisconnect(connection.id)}
>
Avbryt
</Button>
</span>
</div>
)
}
// Status display: muted text for the normal state, Badge only when the row
// deviates (design convention 5).
type StatusEntry =
| { kind: 'text'; label: string }
| { kind: 'badge'; label: string; variant: 'warning' | 'destructive' | 'secondary' }
const statusDisplay: StatusEntry = (() => {
switch (uiState) {
case 'pending_selection':
return { kind: 'badge', label: 'Välj konton', variant: 'warning' }
case 'error':
return { kind: 'badge', label: 'Fel', variant: 'destructive' }
case 'expired':
return { kind: 'badge', label: 'Utgånget samtycke', variant: 'warning' }
case 'expiring':
return { kind: 'badge', label: 'Går ut snart', variant: 'warning' }
default:
return { kind: 'text', label: 'Aktiv' }
}
})()
const isExpired = uiState === 'expired'
const canReconnect = !!onReconnect
const canSync = connection.status === 'active' || connection.status === 'error'
// Exactly ONE primary action per state; everything else goes in the menu.
function renderPrimaryAction() {
switch (uiState) {
case 'pending_selection':
return onManageAccounts ? (
<Button size="sm" onClick={() => onManageAccounts(connection.id)}>
Välj konton
</Button>
) : null
case 'error':
return (
<Button size="sm" onClick={() => onSync(connection.id)} disabled={isSyncing}>
{isSyncing ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
Försök igen
</Button>
)
case 'expired':
case 'expiring':
// No psu override: the server reuses the stored psu_type, so renewal
// is one click. Switching account type lives in the menu.
return canReconnect ? (
<Button size="sm" onClick={() => onReconnect!(connection)}>
Förnya samtycke
</Button>
) : null
case 'stale':
case 'never_synced':
return (
<Button size="sm" onClick={() => onSync(connection.id)} disabled={isSyncing}>
{isSyncing ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
Synka nu
</Button>
)
default:
// Healthy active row: no primary needed; sync stays reachable as a
// quiet ghost button.
return (
<Button
variant="ghost"
size="sm"
className="text-muted-foreground hover:text-foreground"
onClick={() => onSync(connection.id)}
disabled={isSyncing}
>
{isSyncing ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
Synka
</Button>
)
}
}
const primaryIsSync = uiState === 'stale' || uiState === 'never_synced' || uiState === 'active' || uiState === 'error'
const primaryIsReconnect = uiState === 'expired' || uiState === 'expiring'
return (
<div className="border-b border-border px-1 py-3">
{/* Main line: identity + state left, one primary action + menu right */}
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
<span className="text-sm font-medium">{connection.bank_name}</span>
{statusDisplay.kind === 'badge' ? (
<Badge variant={statusDisplay.variant}>{statusDisplay.label}</Badge>
) : (
<span className="text-xs text-muted-foreground">{statusDisplay.label}</span>
)}
{uiState === 'pending_selection' ? (
<span className="text-xs text-muted-foreground">
{ownAccounts.length > 0
? `${ownAccounts.length} konton tillgängliga: inga transaktioner synkas ännu`
: claimedElsewhere.length > 0
? 'Alla konton i kopplingen synkas redan i andra bolag'
: 'Inga konton i kopplingen: inga transaktioner synkas ännu'}
</span>
) : (
<>
{connection.last_synced_at && (
<span className="text-xs text-muted-foreground tabular-nums">
Synkad {formatDate(connection.last_synced_at)}
</span>
)}
{connection.consent_expires && !isExpired && (
<span className="text-xs text-muted-foreground tabular-nums">
Samtycke till {formatDate(connection.consent_expires)}
</span>
)}
</>
)}
<span className="ml-auto flex shrink-0 items-center gap-1">
{renderPrimaryAction()}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
className="text-muted-foreground hover:text-foreground"
aria-label={`Fler åtgärder för ${connection.bank_name}`}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{uiState === 'pending_selection' ? (
<DropdownMenuItem onSelect={() => onDisconnect(connection.id)}>
Avbryt
</DropdownMenuItem>
) : (
<>
{onManageAccounts && (
<DropdownMenuItem onSelect={() => onManageAccounts(connection.id)}>
Välj konton
</DropdownMenuItem>
)}
{canSync && !primaryIsSync && (
<DropdownMenuItem onSelect={() => onSync(connection.id)}>
Synka
</DropdownMenuItem>
)}
{canReconnect && !primaryIsReconnect && (
<DropdownMenuItem onSelect={() => onReconnect!(connection)}>
Förnya samtycke
</DropdownMenuItem>
)}
{canReconnect && (
<>
<DropdownMenuSeparator />
{/* Some banks (notably Handelsbanken) only sign with one
account type: keep the explicit choice reachable even
though the primary renew reuses the stored type. */}
<DropdownMenuLabel className="text-xs font-normal normal-case tracking-normal">
Förnya och logga in som
</DropdownMenuLabel>
<DropdownMenuItem onSelect={() => onReconnect!(connection, 'business')}>
Företagskonto
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => onReconnect!(connection, 'personal')}>
Privatkonto
</DropdownMenuItem>
</>
)}
<DropdownMenuSeparator />
<DropdownMenuItem asChild>
<Link href="/import?mode=bank">Importera bankfil</Link>
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onSelect={() => onDisconnect(connection.id)}
>
Koppla från
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</span>
</div>
{/* Error detail: the page-level .attn owns the ochre sentence; the
row's own message stays quiet. */}
{uiState === 'error' && connection.error_message && (
<p className="mt-1 text-[12.5px] leading-relaxed text-muted-foreground">
{connection.error_message}
</p>
)}
{/* Details behind a collapsed disclosure: accounts, IBAN, balances,
initial backfill. Expired rows never show balances (stale numbers
would read as current). */}
{accounts.length > 0 && uiState !== 'pending_selection' && (
<div className="mt-1">
<button
type="button"
onClick={() => setDetailsOpen((v) => !v)}
aria-expanded={detailsOpen}
className="flex min-h-9 items-center gap-1 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
>
<ChevronRight
className={cn('h-3.5 w-3.5 transition-transform duration-150', detailsOpen && 'rotate-90')}
/>
<span className="tabular-nums">
{enabledCount} av {ownAccounts.length} konton synkas
</span>
</button>
{detailsOpen && (
<div className="ml-3 border-l border-border pl-4">
{/* Initial backfill summary: what the bank actually returned vs
what we asked for. Diagnostics, so it lives in the details. */}
{!isExpired &&
connection.initial_sync_completed_at &&
connection.initial_sync_requested_from &&
(() => {
const requested = connection.initial_sync_requested_from
const min = connection.initial_sync_returned_min_date
const max = connection.initial_sync_returned_max_date
// Truncation = bank returned less history than requested.
// 7-day grace for off-by-one + weekend posting differences.
let truncated = false
if (min && requested) {
const requestedTime = new Date(requested).getTime()
const minTime = new Date(min).getTime()
truncated = minTime - requestedTime > 7 * 24 * 60 * 60 * 1000
}
return (
<div className="flex flex-wrap items-center gap-2 py-2 text-xs text-muted-foreground">
<span>
Initial historik:{' '}
<span className="tabular-nums">
{min ? formatDate(min) : '-'} → {max ? formatDate(max) : '-'}
</span>{' '}
(begärde <span className="tabular-nums">{formatDate(requested)}</span>)
</span>
{truncated && (
<Badge variant="outline">
Bankens API returnerade kortare period än begärt: använd SIE-import för äldre data
</Badge>
)}
</div>
)
})()}
{ownAccounts.map((account) => {
const isDisabled = account.enabled === false
return (
<div
key={account.uid}
className={cn(
'flex flex-wrap items-center gap-x-3 gap-y-1 py-2',
isDisabled && 'opacity-60',
)}
>
<span className="text-sm">
{account.name || account.iban || 'Okänt konto'}
</span>
{isDisabled && (
<Badge variant="outline" className="text-[10px] uppercase tracking-wide text-muted-foreground">
Synkas ej
</Badge>
)}
{account.iban && (
<span className="text-xs text-muted-foreground">
{account.iban.replace(/(.{4})/g, '$1 ').trim()}
</span>
)}
{!isExpired && account.balance !== undefined && (
<span className="ml-auto inline-flex shrink-0 items-baseline gap-2">
{account.balance_updated_at && (
<span className="text-[10px] text-muted-foreground">
{formatBalanceAge(account.balance_updated_at)}
</span>
)}
<span className="text-sm tabular-nums">
{new Intl.NumberFormat('sv-SE', {
style: 'currency',
currency: account.currency,
}).format(account.balance)}
</span>
</span>
)}
</div>
)
})}
{/* Sibling companies' accounts carried by this consent: one
muted line, never rows. Moving one here is done in the
account picker ("Hantera konton"), where it is a deliberate
tick inside a disclosure. */}
{claimedElsewhere.length > 0 && (
<div className="py-2 text-xs text-muted-foreground tabular-nums" data-ph-mask="">
{describeClaimedElsewhere(claimedElsewhere)}
</div>
)}
</div>
)}
</div>
)}
</div>
)
}
@@ -1,307 +0,0 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import { ChevronRight, Landmark, Loader2, Search } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { cn } from '@/lib/utils'
import { matchBankByName } from '../lib/bank-match'
export interface Bank {
name: string
country: string
logo?: string
bic?: string
}
const POPULAR_SWEDISH_BANKS = [
'Swedbank',
'SEB',
'Nordea',
'Handelsbanken',
'Danske Bank',
]
interface BankSelectorProps {
onConnect: (bank: Bank) => void
onPsuTypeDetected?: (psuType: 'personal' | 'business') => void
isConnecting?: boolean
connectingBankName?: string | null
className?: string
}
/**
* Eyebrow above a list section: same micro-label and same px-1 inset as the
* SettingsGroup eyebrow, so the two sit on one left edge.
*/
function SectionLabel({ children }: { children: React.ReactNode }) {
return (
<h3 className="px-1 pb-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
{children}
</h3>
)
}
/**
* 32px leading mark for a row. Real bank logos are drawn for a white
* background, so they sit on a white chip (same treatment as LogoMark in
* components/onboarding/NewUserChecklist.tsx); the no-logo fallback uses the
* neutral surface instead, which keeps the icon readable in dark mode.
* While connecting, the mark is replaced by a bare spinner: quiet inline
* state, no tint, no box.
*/
function BankMark({ bank, connecting }: { bank: Bank; connecting: boolean }) {
if (connecting) {
return (
<span className="flex h-8 w-8 shrink-0 items-center justify-center">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden="true" />
</span>
)
}
if (bank.logo) {
return (
<span className="flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-md border border-border bg-white">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={bank.logo} alt="" className="h-6 w-6 object-contain" />
</span>
)
}
return (
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-secondary">
<Landmark className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
</span>
)
}
function BankRow({ bank, isConnecting, connectingBankName, onConnect }: {
bank: Bank
isConnecting: boolean
connectingBankName: string | null
onConnect: (bank: Bank) => void
}) {
const connecting = isConnecting && connectingBankName === bank.name
return (
<button
type="button"
disabled={isConnecting}
onClick={() => onConnect(bank)}
className={cn(
// 32px mark + py-2 keeps the row at 48px: comfortably past the 44px
// touch target without turning back into a card.
'flex w-full items-center gap-3 px-1 py-2 text-left transition-colors duration-150',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',
!isConnecting && 'hover:bg-secondary/60',
isConnecting && 'cursor-not-allowed',
isConnecting && !connecting && 'opacity-50',
)}
>
<BankMark bank={bank} connecting={connecting} />
<span
className={cn(
'min-w-0 flex-1 truncate text-sm',
connecting ? 'text-muted-foreground' : 'text-foreground',
)}
>
{bank.name}
</span>
{/* No per-row "Ansluter..." text: the spinner mark carries the row's
share of the state, the wording lives once in the line below the
list. */}
{!connecting && (
<ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
)}
</button>
)
}
export function BankSelector({
onConnect,
onPsuTypeDetected,
isConnecting = false,
connectingBankName = null,
className,
}: BankSelectorProps) {
const [banks, setBanks] = useState<Bank[]>([])
const [isSandbox, setIsSandbox] = useState(true)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [searchQuery, setSearchQuery] = useState('')
const searchRef = useRef<HTMLInputElement>(null)
const autoStartHandled = useRef(false)
// Deep-link preselect (?bank=<name>, set by the MCP connect card when the
// user already named their bank in chat): auto-start that bank's consent
// the way clicking its row would, so the flow feels like Skatteverket's
// one-click authorize. The param is stripped immediately so an abort at
// the bank followed by back-navigation does not silently re-launch; an
// unknown or ambiguous name just prefills the search instead of guessing.
// Guards further down (duplicate pending, renew-instead-409) stay fully
// interactive because this runs through the same onConnect handler.
useEffect(() => {
if (autoStartHandled.current || isLoading || banks.length === 0 || isConnecting) return
const params = new URLSearchParams(window.location.search)
const requested = params.get('bank')
if (!requested) {
autoStartHandled.current = true
return
}
autoStartHandled.current = true
params.delete('bank')
const query = params.toString()
window.history.replaceState(
null,
'',
`${window.location.pathname}${query ? `?${query}` : ''}${window.location.hash}`
)
const match = matchBankByName(banks, requested)
if (match) {
onConnect(match)
} else {
setSearchQuery(requested)
searchRef.current?.focus()
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- one-shot after the bank list arrives
}, [isLoading, banks, isConnecting])
useEffect(() => {
async function fetchBanks() {
try {
const res = await fetch('/api/extensions/ext/enable-banking/banks')
if (!res.ok) {
// A non-OK response (500, or the 403 capability gate) has no `banks`
// array; without this guard it falls through to the "no banks
// available" empty state, which misreads as a successful-but-empty
// load rather than a failure.
setError('Kunde inte ladda banker')
return
}
const data = await res.json()
if (data.banks) {
setBanks(data.banks as Bank[])
}
if (data.sandbox !== undefined) {
setIsSandbox(data.sandbox)
}
if (data.psu_type && onPsuTypeDetected) {
onPsuTypeDetected(data.psu_type)
}
} catch {
setError('Kunde inte ladda banker')
} finally {
setIsLoading(false)
}
}
fetchBanks()
// eslint-disable-next-line react-hooks/exhaustive-deps -- onPsuTypeDetected is a stable setter, only run on mount
}, [onPsuTypeDetected])
const filteredBanks = banks.filter((bank) =>
bank.name.toLowerCase().includes(searchQuery.toLowerCase())
)
const showPopular = !isSandbox && !searchQuery
const popularBanks = showPopular
? filteredBanks.filter((bank) => POPULAR_SWEDISH_BANKS.includes(bank.name))
: []
const otherBanks = showPopular
? filteredBanks.filter((bank) => !POPULAR_SWEDISH_BANKS.includes(bank.name))
: filteredBanks
return (
<div className={cn('space-y-4', className)}>
{/* Search input */}
<div className="relative">
<Search
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
aria-hidden="true"
/>
<Input
ref={searchRef}
type="text"
placeholder="Sök efter din bank..."
aria-label="Sök efter din bank"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
{/* Loading state. The spinner is decorative, so the state needs a text
equivalent: without it a screen-reader user gets silence between
submitting and the list appearing. */}
{isLoading && (
<div role="status" className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" aria-hidden="true" />
<span className="sr-only">Laddar banker...</span>
</div>
)}
{/* Error state: one quiet line, not a tinted panel. role="alert" so the
failure is announced rather than only redrawn. */}
{error && (
<p role="alert" className="px-1 text-[12.5px] leading-relaxed text-destructive">{error}</p>
)}
{/* Bank list */}
{!isLoading && !error && (
<>
{filteredBanks.length === 0 ? (
<div className="px-1 py-8 text-center">
<p className="text-sm text-muted-foreground">
{searchQuery
? `Inga banker matchar "${searchQuery}"`
: 'Inga banker tillgängliga'}
</p>
{searchQuery && (
<p className="mt-1 text-xs text-muted-foreground/70">
Försök med ett annat sökord
</p>
)}
</div>
) : (
// -mx-1 cancels the px-1 the settings panel wraps this in, so the
// hairlines and the hover band run the full width of the settings
// content, level with the SettingsRow hairlines above; the rows'
// own px-1 then puts the bank mark on the same left edge as the
// settings labels.
// max-h-96 is exactly eight 48px rows: a scroll box with a reason.
<div className="-mx-1 max-h-96 space-y-6 overflow-y-auto overscroll-contain">
{popularBanks.length > 0 && (
<section>
<SectionLabel>Populära banker</SectionLabel>
<div className="divide-y divide-border border-t border-border">
{popularBanks.map((bank) => (
<BankRow key={bank.name} bank={bank} isConnecting={isConnecting} connectingBankName={connectingBankName} onConnect={onConnect} />
))}
</div>
</section>
)}
{otherBanks.length > 0 && (
<section>
{popularBanks.length > 0 && <SectionLabel>Alla banker</SectionLabel>}
<div className="divide-y divide-border border-t border-border">
{otherBanks.map((bank) => (
<BankRow key={bank.name} bank={bank} isConnecting={isConnecting} connectingBankName={connectingBankName} onConnect={onConnect} />
))}
</div>
</section>
)}
</div>
)}
</>
)}
{/* The single worded home of the connecting state: one muted line rather
than a tinted bordered panel, and it names the bank so the state is
still readable when the chosen row has scrolled out of view. */}
{isConnecting && connectingBankName && (
<p role="status" className="flex items-center gap-2 px-1 text-[12.5px] leading-relaxed text-muted-foreground">
<Loader2 className="h-4 w-4 shrink-0 animate-spin" aria-hidden="true" />
Ansluter till {connectingBankName}...
</p>
)}
</div>
)
}
@@ -1,290 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Loader2, CheckCircle2, AlertTriangle } from 'lucide-react'
import { daysBetween } from '@/lib/company/fiscal-year'
import type { StoredAccount } from '../types'
export interface SyncProgressSummary {
imported: number
duplicates: number
/**
* Rows the post-backfill reconciliation sweep linked to existing verifikat
* (renewal over an already-bookkept period). Optional: responses from before
* the sweep existed omit it.
*/
auto_matched?: number
requested_from: string
returned_min_date: string | null
returned_max_date: string | null
}
export interface SyncProgressError {
message: string
}
export type SyncProgressState =
| { kind: 'syncing' }
| { kind: 'done'; summary: SyncProgressSummary }
| { kind: 'failed'; error: SyncProgressError }
interface BankSyncProgressDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
bankName: string
accounts: StoredAccount[]
state: SyncProgressState
}
// Past this point the sync has run longer than the promised "up to a minute".
// We stop hard-locking the modal so the user isn't trapped: the request keeps
// running server-side (idempotent) and completion still resolves the state.
const GRACE_SEC = 75
function formatElapsed(sec: number): string {
if (sec < 60) return `${sec}s`
return `${Math.floor(sec / 60)}m ${String(sec % 60).padStart(2, '0')}s`
}
export function BankSyncProgressDialog({
open,
onOpenChange,
bankName,
accounts,
state,
}: BankSyncProgressDialogProps) {
const enabledAccounts = accounts.filter((a) => a.enabled !== false)
// Tick a visible elapsed counter while syncing so a slow bank doesn't look
// frozen, and so we know when to release the close-lock (GRACE_SEC). State is
// only ever set from the timer callbacks (never synchronously in the effect
// body), and elapsed is never computed from Date.now() during render, so this
// stays clear of the react-hooks purity rules.
const [elapsedSec, setElapsedSec] = useState(0)
useEffect(() => {
if (!open || state.kind !== 'syncing') return
const started = Date.now()
const tick = () => setElapsedSec(Math.max(0, Math.floor((Date.now() - started) / 1000)))
// Reset to ~0 on the next tick (async, so not a synchronous effect setState).
const reset = setTimeout(tick, 0)
const id = setInterval(tick, 1000)
return () => {
clearTimeout(reset)
clearInterval(id)
}
}, [open, state.kind])
const overGrace = state.kind === 'syncing' && elapsedSec >= GRACE_SEC
// Only hard-block the close affordances during the expected window; after the
// grace period the user may background the (still-running) sync.
const blockClose = state.kind === 'syncing' && !overGrace
// The payoff: once the first sync lands, name the work now waiting so the
// moment points onward instead of stranding the user on the settings panel.
// Same authenticated endpoint the dashboard pane refetches; best-effort.
const [workCounts, setWorkCounts] = useState<{ book: number; matches: number } | null>(null)
useEffect(() => {
if (!open || state.kind !== 'done' || state.summary.imported === 0) {
// A later sync must not inherit the previous run's numbers.
setWorkCounts(null)
return
}
let cancelled = false
fetch('/api/worklist/counts')
.then((res) => (res.ok ? res.json() : null))
.then((json: { data?: { counts?: Record<string, number> } } | null) => {
if (cancelled || !json?.data?.counts) return
setWorkCounts({
book: json.data.counts.book_transaction ?? 0,
matches: json.data.counts.suggested_match ?? 0,
})
})
.catch(() => {
// The CTA degrades to a plain link; the numbers are a nicety.
})
return () => {
cancelled = true
}
}, [open, state])
return (
<Dialog
open={open}
onOpenChange={(next) => {
if (!next && blockClose) return
onOpenChange(next)
}}
>
<DialogContent
className="max-w-md"
onPointerDownOutside={(e) => {
if (blockClose) e.preventDefault()
}}
onEscapeKeyDown={(e) => {
if (blockClose) e.preventDefault()
}}
>
<DialogHeader>
{/* data-ph-mask: the bank name reveals which bank the user uses */}
<DialogTitle data-ph-mask="">
{state.kind === 'syncing' && `Hämtar transaktioner från ${bankName}`}
{state.kind === 'done' && 'Klart'}
{state.kind === 'failed' && 'Synkningen misslyckades'}
</DialogTitle>
<DialogDescription>
{state.kind === 'syncing' && (
overGrace ? (
<>
Det tar längre tid än vanligt. Vi fortsätter i bakgrunden: du kan
stänga rutan och komma tillbaka senare.
</>
) : (
<>
Vi hämtar transaktioner från {enabledAccounts.length}{' '}
{enabledAccounts.length === 1 ? 'konto' : 'konton'}. Detta kan ta upp till en minut. Stäng inte fönstret.
</>
)
)}
{state.kind === 'done' && (
<>
Vi hämtade {state.summary.imported}{' '}
{state.summary.imported === 1 ? 'transaktion' : 'transaktioner'}.
</>
)}
{state.kind === 'failed' && (
<>Vi försöker igen automatiskt i bakgrunden. Du kan stänga den här rutan.</>
)}
</DialogDescription>
</DialogHeader>
{state.kind === 'syncing' && (
<div className="space-y-3 py-2">
<div className="flex flex-col items-center justify-center gap-2 py-6">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
<span className="text-xs text-muted-foreground tabular-nums" aria-live="polite">
{formatElapsed(elapsedSec)}
</span>
</div>
<ul className="rounded-lg border border-border divide-y divide-border text-sm">
{enabledAccounts.map((a) => (
<li key={a.uid} className="flex items-center justify-between gap-3 px-3 py-2">
<span className="truncate">{a.name || a.iban || a.uid}</span>
<span className="text-xs text-muted-foreground">{a.currency}</span>
</li>
))}
</ul>
</div>
)}
{state.kind === 'done' && (
<DoneBody summary={state.summary} workCounts={workCounts} />
)}
{state.kind === 'failed' && (
<div className="rounded-lg border border-border bg-muted/30 p-3 text-sm text-muted-foreground">
{state.error.message}
</div>
)}
<DialogFooter>
{state.kind === 'done' && state.summary.imported > 0 ? (
<>
<Button
type="button"
variant="ghost"
onClick={() => onOpenChange(false)}
>
Stäng
</Button>
<Button asChild>
<Link href="/transactions">
{workCounts && workCounts.book > 0
? `Visa ${workCounts.book} att bokföra`
: 'Öppna transaktionerna'}
</Link>
</Button>
</>
) : (
<Button
type="button"
onClick={() => onOpenChange(false)}
disabled={blockClose}
>
{state.kind === 'syncing'
? (overGrace ? 'Fortsätt i bakgrunden' : 'Hämtar…')
: 'Klar'}
</Button>
)}
</DialogFooter>
</DialogContent>
</Dialog>
)
}
function DoneBody({
summary,
workCounts,
}: {
summary: SyncProgressSummary
workCounts: { book: number; matches: number } | null
}) {
const requestedDays = daysBetween(summary.requested_from)
const returnedDays =
summary.returned_min_date && summary.returned_max_date
? daysBetween(summary.returned_min_date, new Date(summary.returned_max_date))
: 0
const wasTruncated = requestedDays - returnedDays > 7
return (
<div className="space-y-3 py-2">
<div className="flex items-center gap-3 rounded-lg border border-border bg-muted/30 p-4">
<CheckCircle2 className="h-6 w-6 shrink-0 text-foreground" />
<div className="text-sm">
<p>
<span className="tabular-nums font-medium">{summary.imported}</span> nya transaktioner
importerade.
</p>
{summary.returned_min_date && summary.returned_max_date && (
<p className="text-xs text-muted-foreground">
Datum: {summary.returned_min_date} → {summary.returned_max_date}
</p>
)}
{(summary.auto_matched ?? 0) > 0 && (
<p className="text-xs text-muted-foreground tabular-nums">
{summary.auto_matched} kopplades automatiskt till redan bokförda verifikat.
</p>
)}
{workCounts && workCounts.book > 0 && (
<p className="mt-1 text-xs text-muted-foreground tabular-nums">
{workCounts.book} att bokföra
{workCounts.matches > 0 && <> · {workCounts.matches} matchar fakturor</>}
</p>
)}
</div>
</div>
{wasTruncated && (
<div className="flex items-start gap-2 rounded-lg border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
<span>
Banken returnerade kortare historik än begärt. För äldre data, använd{' '}
<Link href="/import?mode=sie" className="text-foreground underline underline-offset-2">
SIE- eller bankfil-import
</Link>
.
</span>
</div>
)}
</div>
)
}
File diff suppressed because it is too large Load Diff