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
@@ -1,230 +0,0 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import { Sparkles, AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { VatTreatment } from '@/types'
/**
* The auto-booking proposal, inline in the quick-review dialog.
*
* Fetches POST /api/agent/categorize (Tier 1 deterministic candidates → Tier 2
* model selector, provider-agnostic) and shows the model's pick with a
* confidence pill, a short "Varför", and the candidate alternatives. It
* pre-fills the dialog's account + VAT when it lands on a real account, and
* clicking an alternative re-applies. Nothing books here — the dialog's own
* "Bokför" commits through the existing categorize route.
*
* i18n: strings are inline Swedish for now (this is the Swedish-answering
* assistant surface); lift to messages/{sv,en}.json before final merge.
*/
interface CandidateDto {
account: string
label: string
vatTreatment: VatTreatment | null
source: string
confidence: number
}
interface ProposalDto {
account: string | null
category: string | null
vatTreatment: VatTreatment | null
reverseCharge: boolean
confidence: number
agreement: number
modelConfidence: 'high' | 'medium' | 'low'
fromCandidate: boolean
reasoning: string
choice: { kind: 'candidate' | 'category' | 'needs_review' }
candidates: CandidateDto[]
}
/** What the dialog needs to log a calibration sample when the user books. */
export interface AiProposalMeta {
account: string
confidence: number
agreement: number
modelConfidence: 'high' | 'medium' | 'low'
source: string
}
type State =
| { status: 'loading' }
| { status: 'error' }
| { status: 'unconfigured' }
| { status: 'ready'; proposal: ProposalDto }
interface Props {
transactionId: string
/** Fetch when the dialog is open. */
open: boolean
/** Apply an account + VAT to the dialog fields. */
onApply: (account: string, vat: VatTreatment | 'none') => void
/** Surface the proposal metadata so the dialog can log a calibration sample on book. */
onProposal?: (meta: AiProposalMeta) => void
}
type Band = 'sure' | 'likely' | 'review'
function bandOf(p: ProposalDto): Band {
if (p.choice.kind === 'needs_review' || !p.account) return 'review'
if (p.confidence >= 0.8) return 'sure'
if (p.confidence >= 0.5) return 'likely'
return 'review'
}
const BAND_LABEL: Record<Band, string> = { sure: 'Säker', likely: 'Trolig', review: 'Välj konto' }
export default function AiCategorizeProposal({ transactionId, open, onApply, onProposal }: Props) {
const [state, setState] = useState<State>({ status: 'loading' })
// Apply the pick to the dialog exactly once per fetch, so the user's later
// manual edits are never clobbered by a re-render.
const appliedRef = useRef<string | null>(null)
useEffect(() => {
if (!open) return
let alive = true
appliedRef.current = null
// Initial state is already 'loading'; the dialog mounts this fresh per
// transaction (keyed on tx.id), so no in-effect reset is needed.
;(async () => {
try {
const res = await fetch('/api/agent/categorize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ transaction_id: transactionId }),
})
if (!alive) return
if (res.status === 503) return setState({ status: 'unconfigured' })
if (!res.ok) return setState({ status: 'error' })
const body = (await res.json()) as { data?: ProposalDto }
if (!alive) return
if (!body.data) return setState({ status: 'error' })
setState({ status: 'ready', proposal: body.data })
} catch {
if (alive) setState({ status: 'error' })
}
})()
return () => {
alive = false
}
}, [open, transactionId])
const reportedRef = useRef(false)
// When a proposal with a real account arrives: surface its metadata to the
// dialog (for calibration logging on book) and pre-fill the fields.
useEffect(() => {
if (state.status !== 'ready') return
const p = state.proposal
if (!p.account) return
if (!reportedRef.current) {
reportedRef.current = true
const source = p.fromCandidate
? (p.candidates.find((c) => c.account === p.account)?.source ?? 'candidate')
: 'category'
onProposal?.({
account: p.account,
confidence: p.confidence,
agreement: p.agreement,
modelConfidence: p.modelConfidence,
source,
})
}
// Pre-fill only when it's not the low "review" band, and only once.
if (appliedRef.current === p.account || bandOf(p) === 'review') return
appliedRef.current = p.account
onApply(p.account, p.vatTreatment ?? 'none')
}, [state, onApply, onProposal])
if (state.status === 'loading') {
return (
<div className="flex items-center gap-2 rounded-lg border border-border bg-secondary/30 px-3 py-2.5 text-sm text-muted-foreground">
<Sparkles className="h-3.5 w-3.5 animate-pulse" />
Assistenten föreslår kontering…
</div>
)
}
if (state.status === 'error') return null // fall back silently to the deterministic default
if (state.status === 'unconfigured') {
return (
<div className="flex items-start gap-2 rounded-lg border border-border bg-secondary/30 px-3 py-2.5 text-xs text-muted-foreground">
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-warning" />
Assistenten är inte konfigurerad. Välj konto nedan som vanligt.
</div>
)
}
const p = state.proposal
const band = bandOf(p)
const alternatives = p.candidates.filter((c) => c.account !== p.account).slice(0, 3)
return (
<div className="rounded-lg border border-border bg-card">
<div className="flex items-start justify-between gap-3 px-3 pt-3">
<div className="flex items-center gap-2 text-xs font-medium text-muted-foreground">
<Sparkles className="h-3.5 w-3.5" />
Assistentens förslag
</div>
<span
className={cn(
'inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-medium',
band === 'sure' && 'bg-success/15 text-success',
band === 'likely' && 'bg-warning/15 text-warning',
band === 'review' && 'bg-secondary text-muted-foreground',
)}
>
<span
className={cn(
'h-1.5 w-1.5 rounded-full',
band === 'sure' && 'bg-success',
band === 'likely' && 'bg-warning',
band === 'review' && 'bg-muted-foreground',
)}
/>
{BAND_LABEL[band]}
</span>
</div>
<div className="px-3 pb-3 pt-2">
{band === 'review' ? (
<p className="text-sm text-foreground">
{p.reasoning || 'För lite underlag för att avgöra konto. Välj konto nedan.'}
</p>
) : (
<>
{p.reasoning && (
<p className="text-[13px] leading-snug text-muted-foreground">{p.reasoning}</p>
)}
{alternatives.length > 0 && (
<div className="mt-2.5">
<p className="mb-1.5 text-[11px] text-muted-foreground">Byt konto:</p>
<div className="flex flex-wrap gap-1.5">
{alternatives.map((c) => (
<button
key={c.account}
type="button"
onClick={() => {
appliedRef.current = c.account
onApply(c.account, c.vatTreatment ?? 'none')
}}
className="inline-flex items-center gap-1.5 rounded-full border border-border bg-card px-2.5 py-1 text-xs transition-colors hover:bg-secondary"
>
<span className="font-mono">{c.account}</span>
<span className="text-muted-foreground">{c.label}</span>
</button>
))}
</div>
</div>
)}
</>
)}
</div>
</div>
)
}
@@ -1,331 +0,0 @@
'use client'
import { useEffect, useSyncExternalStore } from 'react'
import { useRouter } from 'next/navigation'
import { useTranslations } from 'next-intl'
import { Loader2, RefreshCw } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { ToastAction } from '@/components/ui/toast'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { createClient } from '@/lib/supabase/client'
import { notifyBankSyncUpdated } from '@/lib/transactions/bank-sync-signal'
import { invalidateReferenceData } from '@/lib/reference-data/invalidate'
import {
claimConnectionsLoad,
clearBusyConnection,
getBankSyncSnapshot,
markConnectionStatus,
publishConnections,
releaseConnectionsLoad,
setBusyConnection,
setSyncingAll,
subscribeBankSync,
type BankConn,
} from '@/lib/transactions/bank-sync-store'
import { useCompany, useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { isSelfHosted } from '@/lib/env/public-flags'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
export type { BankConn }
/**
* Shared on-demand bank sync state + actions. Powers the footer "Synka nu"
* button below and the "Synka bank nu" row in the Importera split-button menu
* (TransactionStatusBar). Reuses the per-connection sync endpoint that
* BankingSettingsPanel already calls.
*
* Also handles dead PSD2 sessions: a connection whose consent has closed or
* expired re-authorizes in place via `reconnect` (no disconnect needed), and a
* sync that fails with a session expiry surfaces the same reconnect action
* right in the error toast.
*/
export function useBankSync() {
const t = useTranslations('transactions')
const { toast } = useToast()
const router = useRouter()
const { company } = useCompany()
const hasBankSync = useCapability(CAPABILITY.bank_sync)
// Busy state and the connection list live in a module-level store so every
// useBankSync() instance (header split button, footer button) sees the same
// sync in flight and cannot start a concurrent one (#1162).
const store = useSyncExternalStore(subscribeBankSync, getBankSyncSnapshot, getBankSyncSnapshot)
// Never present another company's cached list while a switch is loading.
const connections = store.companyId === company?.id ? store.connections : null
useEffect(() => {
if (!company?.id) return
// First instance to mount claims the fetch; the rest read the store. The
// store outlives components, so the result publishes even if this
// instance unmounts mid-flight.
if (!claimConnectionsLoad(company.id)) return
const companyId = company.id
const supabase = createClient()
supabase
.from('bank_connections')
.select('id, bank_name, status, provider, last_synced_at')
// Include expired/error so the reconnect entry point survives a reload:
// not just active connections that can sync.
.in('status', ['active', 'expired', 'error'])
.eq('company_id', companyId)
.then(({ data, error }) => {
if (error) {
releaseConnectionsLoad(companyId)
return
}
publishConnections(companyId, (data as BankConn[]) ?? [])
})
}, [company?.id])
// Re-authorize an existing connection in place: posts the connection_id so
// the server reuses the same row, then hands off to the bank's consent screen.
async function reconnect(conn: BankConn) {
setBusyConnection(conn.id)
try {
const country = conn.provider?.split('-').pop()?.toUpperCase() || 'SE'
const res = await fetch('/api/extensions/ext/enable-banking/connect', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
connection_id: conn.id,
aspsp_name: conn.bank_name,
aspsp_country: country,
}),
})
const data = await res.json()
if (!res.ok) throw new Error(data.error || 'Reconnect failed')
window.location.href = data.authorization_url
} catch (error) {
toast({
title: t('bank_reconnect'),
description: error instanceof Error ? getUserErrorMessage(error) : 'Reconnect failed',
variant: 'destructive',
})
setBusyConnection(null)
}
}
async function syncConnection(conn: BankConn) {
setBusyConnection(conn.id)
try {
const res = await fetch('/api/extensions/ext/enable-banking/sync', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ connection_id: conn.id }),
})
const data = await res.json()
if (!res.ok) {
// A dead PSD2 session can't be fixed by retrying: surface a one-click
// reconnect in the toast instead of a dead-end error.
if (data?.reauth_required) {
toast({
title: t('bank_sync_session_expired'),
description: t('bank_sync_session_expired_desc'),
variant: 'destructive',
action: (
<ToastAction altText={t('bank_reconnect')} onClick={() => reconnect(conn)}>
{t('bank_reconnect')}
</ToastAction>
),
})
// Reflect the now-expired status so the button flips to reconnect
// on every surface at once.
markConnectionStatus(conn.id, 'expired')
return
}
throw new Error(data.error || 'Sync failed')
}
toast({
title: t('bank_sync_button_now'),
// Surface skipped duplicates too: a renewal that dedupes correctly
// imports 0 rows, which without this line reads as a broken sync.
// Joined with '. ' so the two sentences do not run together (the
// imported-count strings are shared with the BankSyncSinceLastVisit
// chip and deliberately carry no trailing period).
description: [
data.imported === 1
? t('bank_sync_new_since_last_visit_one')
: t('bank_sync_new_since_last_visit_many', { count: data.imported ?? 0 }),
typeof data.duplicates === 'number' && data.duplicates > 0
? data.duplicates === 1
? t('bank_sync_duplicates_skipped_one')
: t('bank_sync_duplicates_skipped_many', { count: data.duplicates })
: null,
]
.filter(Boolean)
.join('. '),
})
// Tell the neighbouring status chip to refetch so it doesn't keep showing
// the pre-sync "synced Nd ago" until a hard reload.
notifyBankSyncUpdated()
// The account chooser reads cash accounts from the session cache
// (lib/reference-data); a sync can change balances, so refetch them.
void invalidateReferenceData('ref:cash-accounts')
router.refresh()
} catch (error) {
toast({
title: t('bank_sync_button_now'),
description: error instanceof Error ? getUserErrorMessage(error) : 'Sync failed',
variant: 'destructive',
})
} finally {
clearBusyConnection(conn.id)
}
}
// Active connections sync; expired/error connections reconnect. Reads the
// live snapshot, not the render closure, so a click racing a sync started
// from the other surface is a no-op instead of a concurrent PSD2 call.
function runFor(conn: BankConn) {
const { busyId, syncingAll } = getBankSyncSnapshot()
if (busyId !== null || syncingAll) return
if (conn.status === 'active') return syncConnection(conn)
return reconnect(conn)
}
// One-shot "sync everything" for the split-button menu row: syncs every
// active connection in turn; with only dead connections it jumps straight
// to re-authorizing the first one (a retry can't revive a closed session).
async function syncAll() {
const { busyId, syncingAll } = getBankSyncSnapshot()
if (busyId !== null || syncingAll) return
setSyncingAll(true)
try {
const conns = connections ?? []
const active = conns.filter((c) => c.status === 'active')
if (active.length === 0) {
if (conns[0]) await reconnect(conns[0])
return
}
for (const conn of active) {
await syncConnection(conn)
}
} finally {
setSyncingAll(false)
}
}
const lastSyncedAt =
(connections ?? [])
.map((c) => c.last_synced_at)
.filter((s): s is string => Boolean(s))
.sort()
.pop() ?? null
return {
connections,
busyId: store.busyId,
isBusy: store.busyId !== null || store.syncingAll,
hasBankSync,
reconnect,
syncConnection,
runFor,
syncAll,
lastSyncedAt,
}
}
/**
* On-demand "Sync now" button beside BankSyncStatusChip. If the user has
* multiple connections, a dropdown lets them pick which one to sync/reconnect.
*/
export default function BankSyncNowButton() {
const t = useTranslations('transactions')
const { connections, isBusy, hasBankSync, runFor } = useBankSync()
if (!connections || connections.length === 0) return null
const syncLabel = isBusy ? t('bank_sync_button_syncing') : t('bank_sync_button_now')
// Bank sync (and reconnect) is a paid external PSD2 call. Without the
// capability we keep the button VISIBLE as the conversion surface but inert,
// and surface an Uppgradera link. CSV/SIE import stays free (separate UI).
// Self-host: the remedy is a connector key (or own EB credentials), never
// the hosted Stripe billing page; same branch as UpgradeNote.
const selfHosted = isSelfHosted()
const gateTitle = !hasBankSync
? selfHosted
? t('bank_sync_requires_connector_key')
: t('bank_sync_requires_subscription')
: undefined
const upsellNote = !hasBankSync ? (
selfHosted ? (
<span className="text-xs text-muted-foreground">{t('bank_sync_upsell_connector_key')}</span>
) : (
<span className="text-xs text-muted-foreground">
{t('bank_sync_upsell_subscription')}{' '}
<a href="/settings/billing" className="underline underline-offset-2">
{t('bank_sync_upsell_upgrade')}
</a>
</span>
)
) : null
if (connections.length === 1) {
const conn = connections[0]
const needsReconnect = conn.status !== 'active'
return (
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
className="h-7 gap-1.5 px-2.5 text-xs"
disabled={isBusy || !hasBankSync}
title={gateTitle}
onClick={() => runFor(conn)}
>
{isBusy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="h-3.5 w-3.5" />
)}
<span>{needsReconnect ? t('bank_reconnect') : syncLabel}</span>
</Button>
{upsellNote}
</div>
)
}
return (
<div className="flex items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="outline"
size="sm"
className="h-7 gap-1.5 px-2.5 text-xs"
disabled={isBusy || !hasBankSync}
title={gateTitle}
>
{isBusy ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="h-3.5 w-3.5" />
)}
<span>{syncLabel}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
{connections.map((conn) => (
<DropdownMenuItem
key={conn.id}
disabled={isBusy}
onSelect={() => runFor(conn)}
>
{conn.status === 'active'
? conn.bank_name
: `${conn.bank_name} · ${t('bank_reconnect')}`}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{upsellNote}
</div>
)
}
@@ -1,94 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { X } from 'lucide-react'
import { createClient } from '@/lib/supabase/client'
import { useCompany } from '@/contexts/CompanyContext'
/**
* One-time pill telling the user how many new PSD2-synced transactions
* have arrived since they last visited /transactions. Helps make the
* nightly cron visible without polling or pushing notifications.
*
* State lives in localStorage keyed per company. On mount:
* - If no previous visit recorded: store now, render nothing.
* - Else: count rows added since lastVisit. If > 0, show the pill.
* - On dismiss: write `now` to localStorage and hide.
*/
export default function BankSyncSinceLastVisit() {
const t = useTranslations('transactions')
const { company } = useCompany()
const [count, setCount] = useState<number | null>(null)
const [dismissed, setDismissed] = useState(false)
useEffect(() => {
if (!company?.id) return
if (typeof window === 'undefined') return
const storageKey = `gnubok.lastTransactionsVisit.${company.id}`
const lastVisitRaw = window.localStorage.getItem(storageKey)
const now = new Date().toISOString()
if (!lastVisitRaw) {
window.localStorage.setItem(storageKey, now)
return
}
let cancelled = false
const supabase = createClient()
supabase
.from('transactions')
.select('id', { count: 'exact', head: true })
.eq('company_id', company.id)
.eq('import_source', 'enable_banking')
.gt('created_at', lastVisitRaw)
.then(({ count: rowCount, error }) => {
if (cancelled) return
// A failed query must not advance the marker: that would silently
// swallow the notification for rows that DID arrive in the window.
if (error) return
if (rowCount && rowCount > 0) {
setCount(rowCount)
} else {
// Nothing new: refresh the timestamp so we don't keep checking
// the same window forever.
window.localStorage.setItem(storageKey, now)
}
})
return () => {
cancelled = true
}
}, [company?.id])
if (dismissed || !count || count <= 0) return null
function handleDismiss() {
if (typeof window === 'undefined') return
if (company?.id) {
window.localStorage.setItem(
`gnubok.lastTransactionsVisit.${company.id}`,
new Date().toISOString(),
)
}
setDismissed(true)
}
return (
<div className="inline-flex items-center gap-2 rounded-full border border-border bg-secondary px-2.5 py-1 text-xs text-foreground">
<span>
{count === 1
? t('bank_sync_new_since_last_visit_one')
: t('bank_sync_new_since_last_visit_many', { count })}
</span>
<button
type="button"
onClick={handleDismiss}
aria-label={t('bank_sync_new_since_last_visit_dismiss')}
className="ml-1 rounded-sm p-0.5 opacity-70 transition-opacity hover:opacity-100"
>
<X className="h-3 w-3" />
</button>
</div>
)
}
@@ -1,171 +0,0 @@
'use client'
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useTranslations } from 'next-intl'
import { AlertTriangle, RefreshCw } from 'lucide-react'
import { createClient } from '@/lib/supabase/client'
import { onBankSyncUpdated } from '@/lib/transactions/bank-sync-signal'
import { useCompany, useCapability } from '@/contexts/CompanyContext'
import { CAPABILITY } from '@/lib/entitlements/keys'
import { isSelfHosted } from '@/lib/env/public-flags'
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/info-tooltip'
import {
getChipState,
type ConnectionRow,
} from '@/lib/transactions/bank-sync-chip-state'
export function useAgeFormatter() {
const t = useTranslations('transactions')
return (iso: string): string => {
const ms = Date.now() - new Date(iso).getTime()
const min = Math.floor(ms / 60000)
if (min < 1) return t('bank_sync_age_just_now')
if (min < 60) return t('bank_sync_age_minutes', { count: min })
const h = Math.floor(min / 60)
if (h < 24) return t('bank_sync_age_hours', { count: h })
const d = Math.floor(h / 24)
return t('bank_sync_age_days', { count: d })
}
}
export default function BankSyncStatusChip() {
const t = useTranslations('transactions')
const formatAge = useAgeFormatter()
const { company } = useCompany()
const hasBankSync = useCapability(CAPABILITY.bank_sync)
const [rows, setRows] = useState<ConnectionRow[] | null>(null)
useEffect(() => {
if (!company?.id) return
const companyId = company.id
let cancelled = false
const supabase = createClient()
const load = () => {
supabase
.from('bank_connections')
.select('id, status, last_synced_at, consent_expires')
.eq('company_id', companyId)
.then(({ data, error }) => {
if (cancelled) return
// On error keep the chip hidden (empty rows) rather than rendering a
// false "healthy" state from stale data.
setRows(error ? [] : (data ?? []))
})
}
load()
// Refetch when a manual "Sync now" / reconnect elsewhere on the page
// changes the connections, so the chip doesn't keep showing "synced 2d ago".
const unsubscribe = onBankSyncUpdated(load)
return () => {
cancelled = true
unsubscribe()
}
}, [company?.id])
if (!rows) return null
const state = getChipState(rows, { hasBankSync })
if (state.kind === 'none') return null
if (state.kind === 'paused') {
// Same remedy split as BankSyncNowButton: hosted points at billing,
// self-host at the connector key (never the Stripe page).
const selfHosted = isSelfHosted()
return (
<Link
href={selfHosted ? '/settings/banking' : '/settings/billing'}
className="inline-flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-attn transition-colors hover:bg-muted/50"
>
<AlertTriangle className="h-3.5 w-3.5" />
<span>
{selfHosted
? t('bank_sync_paused_connector_key')
: t('bank_sync_paused_subscription')}
</span>
</Link>
)
}
if (state.kind === 'attention') {
return (
<Link
href="/settings/banking"
className="inline-flex items-center gap-1.5 rounded-full border border-destructive/40 bg-destructive/5 px-2.5 py-1 text-xs text-destructive transition-colors hover:bg-destructive/10"
>
<AlertTriangle className="h-3.5 w-3.5" />
<span>
{state.count === 1
? t('bank_sync_attention_one')
: t('bank_sync_attention_many', { count: state.count })}
</span>
</Link>
)
}
if (state.kind === 'expiring') {
// The consent is still alive, so the connection syncs today; the ochre
// text says "act before it dies" without the terracotta of a dead one.
return (
<Link
href="/settings/banking"
className="inline-flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-attn transition-colors hover:bg-muted/50"
>
<AlertTriangle className="h-3.5 w-3.5" />
<span>
{state.count === 1
? t('bank_sync_expiring_one', { days: state.daysLeft })
: t('bank_sync_expiring_many', { count: state.count, days: state.daysLeft })}
</span>
</Link>
)
}
if (state.kind === 'stale') {
// Same neutral shape as the healthy chip: the ochre text is the signal,
// never an amber box (convention 12: status colors are data, not chrome).
return (
<Link
href="/settings/banking"
className="inline-flex items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-attn transition-colors hover:bg-muted/50"
>
<AlertTriangle className="h-3.5 w-3.5" />
<span>
{t('bank_sync_stale_warning')}
<span className="ml-1 tabular-nums opacity-70">({formatAge(state.mostRecent)})</span>
</span>
</Link>
)
}
// healthy
return (
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex cursor-help items-center gap-1.5 rounded-full border border-border bg-muted/30 px-2.5 py-1 text-xs text-muted-foreground">
<RefreshCw className="h-3.5 w-3.5" />
<span>
{t('bank_sync_auto_nightly')}
{state.mostRecent && (
<>
{t('bank_sync_last_separator')}
<span className="tabular-nums">{formatAge(state.mostRecent)}</span>
</>
)}
</span>
</span>
</TooltipTrigger>
<TooltipContent side="bottom" className="max-w-[320px]">
<div className="text-sm leading-relaxed">{t('bank_sync_latency_hint')}</div>
</TooltipContent>
</Tooltip>
)
}
@@ -1,191 +0,0 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { createClient } from '@/lib/supabase/client'
// `createClient()` returns a fresh object on every call, so we keep the
// instance creation inside the effect: listing it as a dep would re-fire
// the fetch on every render and create an infinite loop.
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { useCompany } from '@/contexts/CompanyContext'
import { formatCurrency, formatDate } from '@/lib/utils'
import { Loader2, Search, ArrowDownRight } from 'lucide-react'
interface BankTransaction {
id: string
date: string
description: string
amount: number
currency: string
}
interface BankTransactionPickerProps {
open: boolean
onOpenChange: (open: boolean) => void
/** Invoice total in invoice currency. Used to rank transactions by amount proximity. */
targetAmount: number
/** Invoice currency. Used to filter the candidate list when set. */
targetCurrency: string
onPick: (transactionId: string) => void
}
/**
* Lightweight picker for unmatched outgoing bank transactions. Used by
* `/supplier-invoices/new` when the user wants to register an invoice and
* mark it paid against a specific bank transaction in one go.
*
* Filters: negative amount, no journal entry, no supplier_invoice link.
* Ranks by absolute amount-difference vs `targetAmount`.
*/
export default function BankTransactionPicker({
open,
onOpenChange,
targetAmount,
targetCurrency,
onPick,
}: BankTransactionPickerProps) {
const { company } = useCompany()
const [transactions, setTransactions] = useState<BankTransaction[]>([])
const [isLoading, setIsLoading] = useState(false)
const [searchTerm, setSearchTerm] = useState('')
useEffect(() => {
if (!open || !company) return
let cancelled = false
const supabase = createClient()
;(async () => {
setIsLoading(true)
// No strict currency filter: the bank transaction that pays a
// foreign-currency invoice is almost always in the company's domestic
// currency (e.g. SEK bank account paying a USD invoice). The user
// would see "no matches" if we filtered to the invoice currency.
// Cross-currency amount diff is hidden in the row below so the user
// isn't shown a misleading "Diff X kr" against a USD target.
const { data, error } = await supabase
.from('transactions')
.select('id, date, description, amount, currency')
.eq('company_id', company.id)
.lt('amount', 0)
.is('journal_entry_id', null)
.is('supplier_invoice_id', null)
.is('invoice_id', null)
.order('date', { ascending: false })
.limit(200)
if (!cancelled) {
if (!error) setTransactions(data || [])
setIsLoading(false)
}
})()
return () => {
cancelled = true
}
}, [open, company])
const filtered = useMemo(() => {
const term = searchTerm.trim().toLowerCase()
const matches = transactions.filter((t) =>
term === '' ? true : (t.description || '').toLowerCase().includes(term),
)
// Rank by amount proximity only when currencies match: comparing a USD
// target to a SEK transaction numerically would produce a meaningless
// ranking. Cross-currency rows fall back to date-desc order.
return matches.sort((a, b) => {
const aSame = a.currency === targetCurrency
const bSame = b.currency === targetCurrency
if (aSame !== bSame) return aSame ? -1 : 1
if (!aSame) return 0
const da = Math.abs(Math.abs(a.amount) - targetAmount)
const db = Math.abs(Math.abs(b.amount) - targetAmount)
return da - db
})
}, [transactions, searchTerm, targetAmount, targetCurrency])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl max-h-[90vh] flex flex-col">
<DialogHeader>
<DialogTitle>Välj banktransaktion</DialogTitle>
<DialogDescription>
Välj den utgående banktransaktion som motsvarar denna faktura. Fakturan registreras och markeras som betald i ett steg.
</DialogDescription>
</DialogHeader>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
autoFocus
placeholder="Sök på beskrivning..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
<div className="flex-1 overflow-y-auto space-y-2 -mx-1 px-1">
{isLoading ? (
<div className="flex items-center justify-center py-12 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin mr-2" />
Laddar transaktioner…
</div>
) : filtered.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-sm text-muted-foreground">
<ArrowDownRight className="h-8 w-8 mb-2" />
{transactions.length === 0
? 'Inga okategoriserade utgifts­transaktioner hittades.'
: `Inga transaktioner matchar "${searchTerm}".`}
</div>
) : (
filtered.map((tx) => {
const sameCurrency = tx.currency === targetCurrency
const absAmount = Math.abs(tx.amount)
const diff = sameCurrency ? Math.abs(absAmount - targetAmount) : null
const isExact = diff != null && diff < 0.01
return (
<button
key={tx.id}
type="button"
onClick={() => onPick(tx.id)}
className="w-full text-left rounded-lg border p-3 hover:border-primary/50 hover:bg-muted/30 transition-colors"
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<p className="font-medium truncate">{tx.description}</p>
<p className="text-xs text-muted-foreground">{formatDate(tx.date)}</p>
</div>
<div className="text-right shrink-0">
<p className="font-mono font-medium tabular-nums text-destructive">
{formatCurrency(tx.amount, tx.currency)}
</p>
{isExact ? (
<p className="text-xs text-success">Belopp matchar</p>
) : diff != null && targetAmount > 0 ? (
<p className="text-xs text-muted-foreground">
Diff {formatCurrency(diff, tx.currency)}
</p>
) : !sameCurrency ? (
<p className="text-xs text-muted-foreground">
Annan valuta
</p>
) : null}
</div>
</div>
</button>
)
})
)}
</div>
<div className="flex justify-end pt-2">
<Button variant="outline" onClick={() => onOpenChange(false)}>
Avbryt
</Button>
</div>
</DialogContent>
</Dialog>
)
}
@@ -1,128 +0,0 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { Progress } from '@/components/ui/progress'
import { Paperclip } from 'lucide-react'
import VatTreatmentSelect from './VatTreatmentSelect'
import { EXPENSE_CATEGORIES, INCOME_CATEGORIES } from './transaction-types'
import type { TransactionCategory, VatTreatment } from '@/types'
const expenseCategories = EXPENSE_CATEGORIES
const incomeCategories = INCOME_CATEGORIES
interface BatchCategorySelectorProps {
open: boolean
onOpenChange: (open: boolean) => void
selectedCount: number
onSelectCategory: (category: TransactionCategory, vatTreatment?: VatTreatment) => void
progress: { done: number; total: number } | null
}
export default function BatchCategorySelector({
open,
onOpenChange,
selectedCount,
onSelectCategory,
progress,
}: BatchCategorySelectorProps) {
const t = useTranslations('tx_batch_selector')
const tCat = useTranslations('tx_categories')
// 'auto' sends no explicit treatment: the server derives the correct default
// per category (exempt for bank/card fees, 12% representation, else 25%).
// A hardcoded 'standard_25' initial value used to override that derivation
// and claim 25% moms on VAT-exempt bank fees.
const [vatTreatment, setVatTreatment] = useState<VatTreatment | 'none' | 'auto'>('auto')
const isProcessing = progress !== null
const handleSelectCategory = (category: TransactionCategory) => {
// 'auto' omits the treatment so the server derives it per category. An
// explicit 'Ingen moms' goes over the wire as 'exempt' (books no VAT
// line): the old collapse to undefined made an explicit no-VAT choice
// book the DERIVED default, i.e. 25% moms on most expense categories.
const resolvedVat =
vatTreatment === 'auto' ? undefined : vatTreatment === 'none' ? 'exempt' : vatTreatment
onSelectCategory(category, resolvedVat)
}
return (
<Dialog open={open} onOpenChange={isProcessing ? undefined : onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
{isProcessing
? t('title_processing', { done: progress.done, total: progress.total })
: t('title_default', { count: selectedCount })}
</DialogTitle>
<DialogDescription>
{isProcessing
? t('description_processing')
: t('description_default')}
</DialogDescription>
</DialogHeader>
{isProcessing ? (
<div className="py-4">
<Progress value={(progress.done / progress.total) * 100} />
<p className="text-sm text-muted-foreground mt-2 text-center">
{t('progress_label', { done: progress.done, total: progress.total })}
</p>
</div>
) : (
<div className="space-y-4 py-2">
{/* Underlag reminder */}
<div className="flex items-start gap-2 rounded-lg bg-muted/30 border border-border p-3">
<Paperclip className="h-4 w-4 text-attn mt-0.5 shrink-0" />
<p className="text-xs text-attn">
{t('underlag_reminder')}
</p>
</div>
<div>
<h4 className="text-sm font-medium text-muted-foreground mb-2">{t('vat_label')}</h4>
<VatTreatmentSelect
value={vatTreatment}
onValueChange={setVatTreatment}
allowAuto
/>
</div>
<div>
<h4 className="text-sm font-medium text-muted-foreground mb-2">{t('expenses_label')}</h4>
<div className="grid grid-cols-2 gap-1.5">
{expenseCategories.map((cat) => (
<Button
key={cat.value}
variant="outline"
size="sm"
className="justify-start text-xs"
onClick={() => handleSelectCategory(cat.value)}
>
{tCat(cat.labelKey)}
</Button>
))}
</div>
</div>
<div>
<h4 className="text-sm font-medium text-muted-foreground mb-2">{t('income_label')}</h4>
<div className="grid grid-cols-2 gap-1.5">
{incomeCategories.map((cat) => (
<Button
key={cat.value}
variant="outline"
size="sm"
className="justify-start text-xs"
onClick={() => handleSelectCategory(cat.value)}
>
{tCat(cat.labelKey)}
</Button>
))}
</div>
</div>
</div>
)}
</DialogContent>
</Dialog>
)
}
File diff suppressed because it is too large Load Diff
@@ -1,323 +0,0 @@
'use client'
import { useState } from 'react'
import { useCashAccounts } from '@/lib/reference-data/hooks'
import { useTranslations, useLocale } from 'next-intl'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { AlertTriangle, Loader2 } from 'lucide-react'
import { formatCurrency, formatDate } from '@/lib/utils'
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
import { resolveAccount } from '@/lib/cash-accounts/resolve-account'
import type { BookedDuplicateCandidate } from '@/lib/transactions/booking-duplicate-detection'
/** The bank transaction being booked, as much as the caller knows about it.
* Enables the "Matcha mot verifikatet" action for ledger-only candidates. */
export interface DuplicateMatchTransaction {
id: string
cash_account_id?: string | null
currency?: string | null
}
/**
* Soft warning shown when the booking-time duplicate guard fires
* (TRANSACTION_BOOK_POSSIBLE_DUPLICATE): another already-booked transaction
* shares this one's date + amount + bank account. Never a hard block:
* genuinely repeated same-day payments (e.g. several identical Swish transfers)
* are legitimate, so the user can review the existing verifikat or book anyway.
*
* Shared by the /transactions list (runCategorize) and the manual booking
* dialog (JournalEntryForm → /api/transactions/[id]/book). The caller owns the
* retry: "Bokför ändå" must re-issue the request with force=true bound to
* `candidate.journal_entry_id` via `expected_duplicate_journal_entry_id`: it
* is present on both candidate kinds (a sibling-transaction candidate and a
* ledger-only voucher candidate, which has no transaction_id), and the server
* re-detects it so a stale id can't wave the guard away.
*
* Ledger-only candidates (candidate.transaction_id === null: the voucher exists
* but no bank transaction is linked to it, e.g. a verifikat from an SIE import
* or an invoice marked paid) get "Matcha mot verifikatet" as the PRIMARY action
* when the caller supplies `matchTransaction` + `onMatched`: it links the bank
* line to the existing voucher via /api/reconciliation/bank/link (the same path
* MatchVoucherDialog uses) instead of double-booking the affärshändelse.
* "Bokför ändå" stays available but demoted.
*
* Sibling-transaction candidates (candidate.transaction_id set: the verifikat
* is already linked to ANOTHER bank transaction) get the match action too:
* manualLink (lib/reconciliation/bank-reconciliation.ts) explicitly allows a
* second transaction on one voucher (split settlements), so hiding the action
* dead-ended the user in "Bokför ändå". Their body copy asks "vill du matcha i
* stället?" and, because that shape is very often a duplicate IMPORT of one
* real movement (where matching would double-count the bank side), they
* additionally get "Ignorera transaktionen" via /api/transactions/[id]/ignore
* when the caller supplies `onIgnored`.
*/
export default function DuplicateBookingDialog({
candidate,
processing = false,
onBookAnyway,
onCancel,
matchTransaction,
onMatched,
onIgnored,
}: {
/** The already-booked sibling, or null to keep the dialog closed. */
candidate: BookedDuplicateCandidate | null
processing?: boolean
onBookAnyway: () => void
onCancel: () => void
/** The transaction being booked; required for the match action. */
matchTransaction?: DuplicateMatchTransaction | null
/** Called after /api/reconciliation/bank/link succeeds. Mirrors
* MatchVoucherDialog's onLinked signature: everything the refresh needs is
* passed in, so a mid-request dialog close can't strand the update. The
* caller owns the success toast and state refresh (and closes the dialog by
* clearing `candidate`). */
onMatched?: (transactionId: string, journalEntryId: string, voucherLabel: string) => void
/** Called after POST /api/transactions/[id]/ignore succeeds for a
* sibling-transaction candidate (the row is likely a duplicate import).
* The caller owns the refresh and closes the dialog by clearing
* `candidate`. Omit to hide the ignore action. */
onIgnored?: (transactionId: string) => void
}) {
const t = useTranslations('transactions')
const locale = useLocale() as ErrorLocale
const { toast } = useToast()
const [matching, setMatching] = useState(false)
const [ignoring, setIgnoring] = useState(false)
// A sibling-transaction candidate: the twin bank row is already booked, so
// the target is either a duplicate import (ignore), the second leg of an
// N:1 settlement (match), or a genuinely separate identical event (book).
const isSiblingCandidate = candidate !== null && candidate.transaction_id !== null
// Matching links THIS bank line to the existing voucher instead of minting a
// second verifikat (one affärshändelse, one verifikat). Offered for both
// candidate kinds: for ledger-only vouchers it is the right default, and for
// sibling candidates manualLink explicitly permits N:1 links.
const canMatch = candidate !== null && !!matchTransaction && !!onMatched
const canIgnore = isSiblingCandidate && !!matchTransaction && !!onIgnored
// Session-cached (lib/reference-data); an empty list resolves to 1930 and
// the link route re-validates the account either way.
const { cashAccounts } = useCashAccounts()
async function handleMatch() {
if (!candidate || !matchTransaction || !onMatched || matching) return
setMatching(true)
try {
// Link on the exact 19xx account the candidate voucher was booked to
// when the guard reported it: a legacy transaction without a
// cash_account_id would otherwise resolve by currency and can pick a
// different 19xx than the voucher's leg, dead-ending the link. Fall back
// to resolving from the company's cash accounts, same as
// MatchVoucherDialog: the link route validates the voucher has a leg on
// this account and that the transaction belongs to it.
let account = candidate.account_number ?? '1930'
if (!candidate.account_number) {
account = resolveAccount(
cashAccounts,
matchTransaction.cash_account_id ?? null,
matchTransaction.currency ?? 'SEK',
).account
}
const res = await fetch('/api/reconciliation/bank/link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
transaction_id: matchTransaction.id,
journal_entry_id: candidate.journal_entry_id,
account_number: account,
}),
})
const result = await res.json()
if (!res.ok || result.error) {
toast({
title: t('dialog_duplicate_match_failed'),
description: getErrorMessage(result, { context: 'transaction', statusCode: res.status, locale }),
variant: 'destructive',
})
return
}
onMatched(matchTransaction.id, candidate.journal_entry_id, candidate.voucher_label)
} catch {
toast({
title: t('dialog_duplicate_match_failed'),
description: getErrorMessage(null, { context: 'transaction', locale }),
variant: 'destructive',
})
} finally {
setMatching(false)
}
}
async function handleIgnore() {
if (!candidate || !matchTransaction || !onIgnored || ignoring) return
setIgnoring(true)
try {
const res = await fetch(`/api/transactions/${matchTransaction.id}/ignore`, {
method: 'POST',
})
const result = await res.json().catch(() => null)
if (!res.ok || result?.error) {
toast({
title: t('dialog_duplicate_ignore_failed'),
description: getErrorMessage(result, { context: 'transaction', statusCode: res.status, locale }),
variant: 'destructive',
})
return
}
onIgnored(matchTransaction.id)
} catch {
toast({
title: t('dialog_duplicate_ignore_failed'),
description: getErrorMessage(null, { context: 'transaction', locale }),
variant: 'destructive',
})
} finally {
setIgnoring(false)
}
}
const busy = processing || matching || ignoring
return (
<Dialog
open={candidate !== null}
onOpenChange={(open) => {
if (!open) onCancel()
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>{t('dialog_duplicate_title')}</DialogTitle>
</DialogHeader>
<div className="space-y-4">
{/* Sibling candidates get the "vill du matcha i stället?" copy: the
generic body's "en annan transaktion eller en befintlig
verifikation" hedge reads as noise once the twin is known. The
ignore hint renders only when the action itself does (callers
without onIgnored, e.g. the manual booking form and the bulk
dialog, must not have copy pointing at a button that is not
there). */}
<p className="text-sm text-muted-foreground">
{isSiblingCandidate ? t('dialog_duplicate_body_sibling') : t('dialog_duplicate_body')}
{canIgnore && <> {t('dialog_duplicate_ignore_hint')}</>}
</p>
{candidate && (
<div className="space-y-1 rounded-lg border bg-muted/30 p-3">
<div className="flex items-center justify-between gap-3 text-sm">
<span className="font-medium">
{candidate.voucher_label
? t('dialog_duplicate_voucher_label', { label: candidate.voucher_label })
: t('dialog_duplicate_voucher_generic')}
</span>
{/* candidate.amount is ALWAYS SEK or null, never a foreign
number (booking-duplicate-detection.ts): the explicit 'SEK'
states that contract at the call site. When the sibling is
foreign and carries no stored rate, amount is null and the
honest figure is the sibling's own amount in its own
currency, explicitly labelled. */}
<span className="tabular-nums">
{candidate.amount != null
? formatCurrency(candidate.amount, 'SEK')
: candidate.currency && candidate.amount_in_currency != null
? formatCurrency(candidate.amount_in_currency, candidate.currency)
: t('dialog_duplicate_amount_unknown')}
</span>
</div>
{/* Verified FX sibling: the kr figure above is the sibling's own
booked SEK value; show the foreign original beneath it so the
user can recognise their EUR/USD line at a glance. */}
{candidate.amount != null &&
candidate.currency &&
candidate.amount_in_currency != null && (
<div className="text-right text-xs text-muted-foreground tabular-nums">
{formatCurrency(candidate.amount_in_currency, candidate.currency)}
</div>
)}
<div className="text-xs text-muted-foreground tabular-nums">
{formatDate(candidate.entry_date)}
</div>
{candidate.description && (
<div className="truncate text-xs text-muted-foreground">{candidate.description}</div>
)}
{/* Rateless foreign sibling: the amounts matched exactly in the
shared currency, but no SEK value exists for it, so say that
instead of printing an authoritative-looking kr figure.
Gated on candidate.currency: the sentence names the currency,
and interpolating an empty string renders broken Swedish
("samma belopp i , men..."). A null-currency candidate with a
null amount already shows dialog_duplicate_amount_unknown. */}
{candidate.amount == null && candidate.currency && (
<div className="flex items-start gap-2 pt-1">
<AlertTriangle className="h-3.5 w-3.5 text-attn flex-shrink-0 mt-0.5" />
<p className="text-xs text-attn leading-snug">
{t('dialog_duplicate_sek_unavailable', { currency: candidate.currency })}
</p>
</div>
)}
{/* Ledger-only candidate found for a bank line that has no SEK
value: the kr figure above is the voucher leg's real amount,
but it could not be compared against the transaction, so the
match rests on date + account + direction alone. */}
{candidate.amount != null && !candidate.amount_verified && (
<div className="flex items-start gap-2 pt-1">
<AlertTriangle className="h-3.5 w-3.5 text-attn flex-shrink-0 mt-0.5" />
<p className="text-xs text-attn leading-snug">
{t('dialog_duplicate_amount_unverified')}
</p>
</div>
)}
</div>
)}
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between">
{candidate && (
<Button asChild variant="ghost" size="sm" className="text-muted-foreground sm:mr-auto">
<a
href={`/bookkeeping/${candidate.journal_entry_id}`}
target="_blank"
rel="noopener noreferrer"
>
{t('dialog_duplicate_view_voucher')}
</a>
</Button>
)}
<div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<Button variant="outline" onClick={onCancel} disabled={busy}>
{t('dialog_duplicate_cancel')}
</Button>
{canMatch ? (
<>
<Button variant="outline" onClick={onBookAnyway} disabled={busy}>
{t('dialog_duplicate_book_anyway')}
</Button>
{/* Sibling candidates only: when the row is a duplicate
import of the already-booked twin, ignoring it is the
correct resolution (matching would double-count the bank
side, booking would double-count the ledger side). */}
{canIgnore && (
<Button variant="outline" onClick={handleIgnore} disabled={busy}>
{ignoring && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t('dialog_duplicate_ignore')}
</Button>
)}
<Button onClick={handleMatch} disabled={busy}>
{matching && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{t('dialog_duplicate_match')}
</Button>
</>
) : (
<Button onClick={onBookAnyway} disabled={busy}>
{t('dialog_duplicate_book_anyway')}
</Button>
)}
</div>
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -1,131 +0,0 @@
'use client'
import { useEffect, 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 { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Loader2 } from 'lucide-react'
interface EditTransactionTitleDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** Current (possibly edited) title shown in the input. */
currentTitle: string
/** Bank's original title; when it differs from the current title a restore
* affordance is offered. */
originalTitle: string | null
/** Persist a new title. Resolves true on success (dialog closes), false to
* keep the dialog open (e.g. the request failed). */
onSave: (description: string) => Promise<boolean>
}
/**
* Edit a bank transaction's working title. Carries the product-required warning
* ("Är du säker…") in the dialog body and offers a one-click restore back to
* the bank's original name. Gating (only unbooked/unmatched rows) is enforced
* server-side; callers only open this for editable rows.
*/
export default function EditTransactionTitleDialog({
open,
onOpenChange,
currentTitle,
originalTitle,
onSave,
}: EditTransactionTitleDialogProps) {
const t = useTranslations('tx_inbox_card')
const [value, setValue] = useState(currentTitle)
const [isSaving, setIsSaving] = useState(false)
// Re-seed the field each time the dialog opens for a (possibly different) row.
useEffect(() => {
if (open) setValue(currentTitle)
}, [open, currentTitle])
const trimmed = value.trim()
const canRestore = originalTitle != null && originalTitle !== currentTitle
const isUnchanged = trimmed === currentTitle.trim()
async function persist(next: string) {
setIsSaving(true)
try {
const ok = await onSave(next)
if (ok) onOpenChange(false)
} finally {
setIsSaving(false)
}
}
return (
<Dialog
open={open}
onOpenChange={(v) => {
if (isSaving) return
onOpenChange(v)
}}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t('edit_title_dialog_title')}</DialogTitle>
<DialogDescription>{t('edit_title_warning')}</DialogDescription>
</DialogHeader>
<div className="space-y-2">
<Label htmlFor="tx-title-input">{t('edit_title_label')}</Label>
<Input
id="tx-title-input"
value={value}
onChange={(e) => setValue(e.target.value)}
maxLength={500}
autoFocus
disabled={isSaving}
onKeyDown={(e) => {
if (e.key === 'Enter' && trimmed && !isUnchanged && !isSaving) {
e.preventDefault()
void persist(trimmed)
}
}}
/>
{canRestore && (
<p className="text-xs text-muted-foreground">
{t('edit_title_original_hint', { name: originalTitle as string })}{' '}
<button
type="button"
onClick={() => void persist(originalTitle as string)}
disabled={isSaving}
className="underline underline-offset-2 hover:text-foreground transition-colors disabled:opacity-50"
>
{t('edit_title_restore')}
</button>
</p>
)}
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isSaving}
className="min-h-11 w-full sm:w-auto"
>
{t('edit_title_cancel')}
</Button>
<Button
onClick={() => void persist(trimmed)}
disabled={isSaving || !trimmed || isUnchanged}
className="min-h-11 w-full sm:w-auto"
>
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
{t('edit_title_save')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,230 +0,0 @@
'use client'
import { useEffect, useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
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 } from '@/lib/errors/get-error-message'
import { formatCurrency, formatDate } from '@/lib/utils'
import { roundOre } from '@/lib/money'
import { expenseClaimantKey, groupExpenseClaimsByPerson } from '@/lib/expenses/expense-payout-candidates'
import type { ExpensePayoutDue } from '@/lib/worklist/types'
import type { TransactionWithInvoice } from './transaction-types'
interface ClaimRow {
id: string
employee_id: string | null
claimant_name: string
liability_account: string
amount_sek: number | string
expense_date: string
description: string
}
interface Props {
open: boolean
onOpenChange: (open: boolean) => void
transaction: TransactionWithInvoice | null
onMatched: (transactionId: string, journalEntryId: string, personKey: string) => void
}
/**
* Manual "Matcha mot utlägg": for an outflow that the exact-amount suggestion
* did not pair (two receipts of three were paid, or the amount covers a
* subset), the user picks the person and the receipts the transfer covers.
* The sum must equal the transfer to the öre: the same RPC as the one-click
* path books it, so a partial receipt can never be marked paid.
*/
export default function ExpenseClaimPickerDialog({ open, onOpenChange, transaction, onMatched }: Props) {
const t = useTranslations('tx_expense_claim_picker')
const { toast } = useToast()
const [claims, setClaims] = useState<ClaimRow[]>([])
const [loading, setLoading] = useState(false)
const [personKey, setPersonKey] = useState<string>('')
const [selected, setSelected] = useState<Set<string>>(new Set())
const [submitting, setSubmitting] = useState(false)
const transferOre = transaction ? Math.round(Math.abs(transaction.amount) * 100) : 0
useEffect(() => {
if (!open) return
let cancelled = false
setLoading(true)
setSelected(new Set())
fetch('/api/expense-claims?status=registered')
.then((res) => (res.ok ? res.json() : { data: [] }))
.then((json) => {
if (cancelled) return
const rows = ((json?.data ?? []) as ClaimRow[]).filter((r) => r.liability_account !== '2018')
setClaims(rows)
const people = groupExpenseClaimsByPerson(rows)
// Preselect the person (and all their receipts) when one person's
// total equals the transfer; otherwise the first person, nothing ticked.
const exact = people.find((p) => Math.round(p.total_sek * 100) === transferOre)
const first = exact ?? people[0]
setPersonKey(first?.key ?? '')
setSelected(new Set(exact ? exact.claim_ids : []))
})
.catch(() => {
if (!cancelled) setClaims([])
})
.finally(() => {
if (!cancelled) setLoading(false)
})
return () => {
cancelled = true
}
}, [open, transferOre])
const people: ExpensePayoutDue[] = useMemo(() => groupExpenseClaimsByPerson(claims), [claims])
const personClaims = useMemo(
() =>
claims
.filter((c) => expenseClaimantKey(c) === personKey)
.sort((a, b) => a.expense_date.localeCompare(b.expense_date)),
[claims, personKey],
)
const selectedOre = personClaims
.filter((c) => selected.has(c.id))
.reduce((sum, c) => sum + Math.round((Number(c.amount_sek) || 0) * 100), 0)
const diff = roundOre((selectedOre - transferOre) / 100)
const canConfirm = !submitting && !loading && selected.size > 0 && selectedOre === transferOre
const toggle = (id: string, checked: boolean) => {
setSelected((prev) => {
const next = new Set(prev)
if (checked) next.add(id)
else next.delete(id)
return next
})
}
const handleConfirm = async () => {
if (!transaction || !canConfirm) return
setSubmitting(true)
try {
const res = await fetch(`/api/transactions/${transaction.id}/match-expense-payout`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ claim_ids: [...selected] }),
})
const result = await res.json().catch(() => ({}))
if (!res.ok) {
toast({
title: t('failed_title'),
description: getErrorMessage(result, { context: 'transaction', statusCode: res.status }),
variant: 'destructive',
})
return
}
onMatched(transaction.id, result.journal_entry_id, personKey)
} catch (error) {
toast({
title: t('failed_title'),
description: getErrorMessage(error, { context: 'transaction' }),
variant: 'destructive',
})
} finally {
setSubmitting(false)
}
}
return (
<Dialog open={open} onOpenChange={(next) => !submitting && onOpenChange(next)}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
<DialogDescription>{t('description')}</DialogDescription>
</DialogHeader>
{loading ? (
<div className="flex items-center justify-center py-8 text-sm text-muted-foreground">
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
</div>
) : people.length === 0 ? (
<p className="py-6 text-center text-sm text-muted-foreground">{t('no_claims')}</p>
) : (
<div className="space-y-4">
{people.length > 1 && (
<div className="space-y-1.5">
<Label>{t('person_label')}</Label>
<Select
value={personKey}
onValueChange={(next) => {
setPersonKey(next)
setSelected(new Set())
}}
>
<SelectTrigger className="h-9 text-[13px]">
<SelectValue />
</SelectTrigger>
<SelectContent>
{people.map((p) => (
<SelectItem key={p.key} value={p.key}>
{p.claimant_name} · {formatCurrency(p.total_sek)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
<div className="rounded-lg border border-border">
{personClaims.map((c) => (
<label
key={c.id}
className="flex cursor-pointer items-center gap-3 border-b border-border px-3 py-2.5 text-[13px] last:border-b-0 hover:bg-secondary/30"
>
<Checkbox
checked={selected.has(c.id)}
onCheckedChange={(checked) => toggle(c.id, checked === true)}
disabled={submitting}
/>
<span className="w-[86px] shrink-0 tabular-nums text-muted-foreground">{formatDate(c.expense_date)}</span>
<span className="min-w-0 flex-1 truncate">{c.description}</span>
<span className="shrink-0 tabular-nums">{formatCurrency(Number(c.amount_sek))}</span>
</label>
))}
</div>
<div className="flex items-baseline justify-between text-xs text-muted-foreground tabular-nums">
<span>{t('selected_sum', { amount: formatCurrency(selectedOre / 100) })}</span>
<span>{t('transfer_sum', { amount: formatCurrency(transferOre / 100) })}</span>
</div>
{selected.size > 0 && diff !== 0 && (
<p className="text-xs text-attn tabular-nums">{t('diff', { amount: formatCurrency(diff) })}</p>
)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
{t('cancel')}
</Button>
<Button onClick={handleConfirm} disabled={!canConfirm}>
{submitting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
{t('confirm')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,90 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { formatCurrency, formatDate } from '@/lib/utils'
import { Loader2 } from 'lucide-react'
import type { TransactionWithInvoice } from './transaction-types'
interface ExpensePayoutMatchDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** Row carrying `potential_expense_payout`; the dialog renders nothing without it. */
transaction: TransactionWithInvoice | null
isConfirming: boolean
onConfirm: () => void
}
/**
* Confirm dialog for booking an outgoing bank row as the repayment of one
* person's registered utlägg: the person's liability account is debited,
* the row's cash account credited, the claims flip to paid and the row is
* linked to the voucher, all in one RPC call. Two legs, amount from the bank
* row, so everything to approve is known up front (convention 10).
*/
export default function ExpensePayoutMatchDialog({
open,
onOpenChange,
transaction,
isConfirming,
onConfirm,
}: ExpensePayoutMatchDialogProps) {
const t = useTranslations('tx_expense_payout_match')
const match = transaction?.potential_expense_payout ?? null
const currency = transaction?.currency || 'SEK'
const amount = transaction ? Math.abs(transaction.amount) : 0
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
<DialogDescription>{t('description')}</DialogDescription>
</DialogHeader>
{transaction && match && (
<div className="space-y-4">
<div className="rounded-lg border border-border p-4 space-y-1">
<p className="font-medium">{transaction.description}</p>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground tabular-nums">{formatDate(transaction.date)}</span>
<span className="font-medium tabular-nums">{formatCurrency(-amount, currency)}</span>
</div>
</div>
<div className="rounded-lg border border-border p-4 space-y-1 text-sm">
<p className="font-medium">{match.claimant_name}</p>
<p className="text-muted-foreground">
{match.claim_count === 1
? t('claims_one', { date: formatDate(match.oldest_expense_date) })
: t('claims_other', { count: match.claim_count, date: formatDate(match.oldest_expense_date) })}
</p>
<p className="text-xs text-muted-foreground tabular-nums pt-2 border-t border-border">
{match.liability_account} D {formatCurrency(amount, 'SEK')} · 19xx K {formatCurrency(amount, 'SEK')}
</p>
<p className="text-xs text-muted-foreground">{t('outcome')}</p>
</div>
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isConfirming}>
{t('cancel')}
</Button>
<Button onClick={onConfirm} disabled={isConfirming || !match}>
{isConfirming && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
{t('confirm')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,53 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { EmptyState } from '@/components/ui/empty-state'
import { StartCard } from '@/components/dashboard/StartCard'
import { Check, Upload, Plus } from 'lucide-react'
import Link from 'next/link'
interface InboxZeroStateProps {
hasTransactions: boolean
onCreateTransaction: () => void
}
export default function InboxZeroState({ hasTransactions, onCreateTransaction }: InboxZeroStateProps) {
const t = useTranslations('tx_inbox_zero')
const tStart = useTranslations('start_cards')
if (!hasTransactions) {
// No transactions at all: the start card leads with the bank connection
// (the import page's own "Rekommenderat" path) and keeps the bank-file
// import as the alternative. Manual creation stays reachable from the
// header split button.
return (
<div className="animate-fade-in">
<StartCard
card="sthlm"
layout="bleed-left"
title={tStart('transactions_title')}
body={tStart('transactions_body')}
primary={{ label: tStart('transactions_primary'), href: '/import?mode=psd2' }}
secondary={{ label: tStart('transactions_secondary'), href: '/import?mode=bank' }}
/>
</div>
)
}
// All transactions categorized: inbox zero!
return (
<EmptyState icon={Check} title={t('done_title')} description={t('done_description')}>
<Button asChild variant="outline">
<Link href="/import">
<Upload className="mr-2 h-4 w-4" />
{t('import_more_btn')}
</Link>
</Button>
<Button variant="outline" onClick={onCreateTransaction}>
<Plus className="mr-2 h-4 w-4" />
{t('new_btn')}
</Button>
</EmptyState>
)
}
File diff suppressed because it is too large Load Diff
-401
View File
@@ -1,401 +0,0 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { useTranslations } from 'next-intl'
import { createClient } from '@/lib/supabase/client'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { formatCurrency, formatDate, cn } from '@/lib/utils'
import { roundOre } from '@/lib/money'
import { Search, FileText, Loader2, Landmark } from 'lucide-react'
import { useCompany } from '@/contexts/CompanyContext'
import type { Invoice, Customer } from '@/types'
import type { PotentialRotRutPayoutRequest, TransactionWithInvoice } from './transaction-types'
import {
DOMESTIC_CURRENCY,
normalizeCurrency,
rankInvoicesByAmountProximity,
} from './invoice-candidate-ranking'
import {
expectedRotRutPayoutAmount,
OPEN_ROT_RUT_PAYOUT_STATUSES,
} from '@/lib/invoices/rot-rut-payout-matching'
type OpenInvoice = Invoice & { customer?: Customer }
interface InvoicePickerProps {
transaction: TransactionWithInvoice
onSelect: (invoice: OpenInvoice) => void
/** Pick one or several open ROT/RUT begäran instead of an invoice
* (Skatteverkets utbetalning). A row click hands over that begäran alone;
* the checkboxes build a bundle for a transfer that paid several beslut,
* which the automatic set matcher refuses when two begäran carry the same
* amount (#2425). The section only renders when the company has one. */
onSelectRotRutPayout?: (requests: PotentialRotRutPayoutRequest[]) => void
}
type RotRutRequestRow = {
id: string
name: string
deduction_type: 'rot' | 'rut'
status: string
requested_total: number | string
decided_total: number | string | null
settlement_journal_entry_id: string | null
items?: Array<{
requested_amount: number | string
invoice?: { invoice_number: string | null } | { invoice_number: string | null }[] | null
}> | null
}
export default function InvoicePicker({ transaction, onSelect, onSelectRotRutPayout }: InvoicePickerProps) {
const t = useTranslations('tx_invoice_picker')
const { company } = useCompany()
const supabase = useMemo(() => createClient(), [])
const [invoices, setInvoices] = useState<OpenInvoice[]>([])
const [rotRutRequests, setRotRutRequests] = useState<PotentialRotRutPayoutRequest[]>([])
const [isLoading, setIsLoading] = useState(true)
const [search, setSearch] = useState('')
// Begäran ticked for a bundled handoff; empty until the user ticks one.
const [pickedRequestIds, setPickedRequestIds] = useState<ReadonlySet<string>>(() => new Set())
// Boolean, not the callback: a fresh function identity per parent render
// must not refetch the list.
const wantRotRutRequests = !!onSelectRotRutPayout
useEffect(() => {
if (!company) return
// Capture the company id once so the async closure below never
// dereferences a `company` that has flipped to null between renders.
// The earlier non-null assertions allowed a stale render to query
// against an undefined company_id; pinning the value avoids that.
const companyId = company.id
let cancelled = false
async function load() {
setIsLoading(true)
// Filter out fully-settled invoices defensively: match-invoice should
// flip status to 'paid' on full settlement, but a stale 'sent'/'overdue'
// row with remaining_amount=0 would otherwise be selectable here and
// could be matched a second time, double-booking the income.
// Also exclude proformas (PF- series): proforma is not a faktura per
// ML 17 kap 24§, has no VAT obligation, and must never be matched
// against a bank receipt or trigger a verifikation.
const { data } = await supabase
.from('invoices')
.select('*, customer:customers(*)')
.eq('company_id', companyId)
.eq('document_type', 'invoice')
.is('credited_invoice_id', null)
.in('status', ['sent', 'overdue', 'partially_paid'])
.gt('remaining_amount', 0)
.order('invoice_date', { ascending: false })
.limit(200)
if (cancelled) return
const all = (data as OpenInvoice[]) || []
// Status-leak guard: if an invoice still says 'sent'/'overdue' but
// already has a payment voucher attached (manual or system), hide it.
// Partially-paid invoices intentionally pass through: they may take
// more payments. Mirrors the server-side filter in findMatchingInvoices.
const fullIds = all
.filter((inv) => inv.status === 'sent' || inv.status === 'overdue')
.map((inv) => inv.id)
let visible = all
if (fullIds.length > 0) {
const { data: paid } = await supabase
.from('invoice_payments')
.select('invoice_id')
.eq('company_id', companyId)
.in('invoice_id', fullIds)
.not('journal_entry_id', 'is', null)
if (cancelled) return
const paidSet = new Set<string>(
((paid as { invoice_id: string }[] | null) ?? []).map((r) => r.invoice_id),
)
visible = all.filter((inv) => !paidSet.has(inv.id))
}
// Open ROT/RUT begäran: the manual fallback when the SKV payout got no
// auto-hint (amount differs from the request, or the row predates the
// hint). Non-fatal: the invoice list renders either way.
if (wantRotRutRequests) {
const { data: requests } = await supabase
.from('rot_rut_payout_requests')
.select(
'id, name, deduction_type, status, requested_total, decided_total, settlement_journal_entry_id, items:rot_rut_payout_request_items(requested_amount, invoice:invoices(invoice_number))',
)
.eq('company_id', companyId)
.in('status', [...OPEN_ROT_RUT_PAYOUT_STATUSES])
.is('settlement_journal_entry_id', null)
.order('created_at', { ascending: false })
if (cancelled) return
setRotRutRequests(
((requests as RotRutRequestRow[] | null) ?? []).map((req) => ({
id: req.id,
name: req.name,
deduction_type: req.deduction_type,
status: req.status,
requested_total: req.requested_total,
decided_total: req.decided_total,
settlement_journal_entry_id: req.settlement_journal_entry_id,
invoices: (req.items ?? []).map((item) => {
const inv = Array.isArray(item.invoice) ? item.invoice[0] : item.invoice
return { invoice_number: inv?.invoice_number ?? null, requested_amount: item.requested_amount }
}),
})),
)
}
setInvoices(visible)
setIsLoading(false)
}
load()
return () => {
cancelled = true
}
}, [company, supabase, wantRotRutRequests])
const sorted = useMemo(() => {
const filtered = !search
? invoices
: invoices.filter((inv) => {
const q = search.toLowerCase()
return (
(inv.invoice_number ?? '').toLowerCase().includes(q) ||
(inv.customer?.name ?? '').toLowerCase().includes(q)
)
})
// Amount proximity is only meaningful between comparable amounts: ranking
// a 1 000 EUR invoice as a perfect hit for a 1 000 SEK deposit put the
// wrong row first. Foreign invoices stay in the list either way; see
// ./invoice-candidate-ranking.
return rankInvoicesByAmountProximity(filtered, {
amount: transaction.amount,
currency: transaction.currency,
amountSek: transaction.amount_sek,
})
}, [invoices, search, transaction.amount, transaction.currency, transaction.amount_sek])
if (isLoading) {
return (
<div className="flex items-center justify-center py-8 text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin mr-2" />
{t('loading')}
</div>
)
}
const txAmount = roundOre(transaction.amount)
// Skatteverket pays out in kronor only; the match route refuses other
// currencies, so a foreign-currency row must not be offered a begäran.
const txIsSek = (transaction.currency || 'SEK').toUpperCase() === 'SEK'
const pickedRequests = rotRutRequests.filter((request) => pickedRequestIds.has(request.id))
const pickedTotal = roundOre(
pickedRequests.reduce((sum, request) => sum + expectedRotRutPayoutAmount(request), 0),
)
const pickedDiff = roundOre(Math.abs(pickedTotal - txAmount))
const pickedExact = pickedRequests.length > 0 && pickedDiff < 0.005
const togglePicked = (id: string, checked: boolean) => {
setPickedRequestIds((prev) => {
const next = new Set(prev)
if (checked) next.add(id)
else next.delete(id)
return next
})
}
// The settle service books a bundle largest first (the matcher's order):
// hand the manual pick over in the same order so the voucher reads alike.
const handOverPicked = () => {
if (!onSelectRotRutPayout || pickedRequests.length === 0) return
onSelectRotRutPayout(
[...pickedRequests].sort(
(a, b) => expectedRotRutPayoutAmount(b) - expectedRotRutPayoutAmount(a),
),
)
}
const rotRutSection =
onSelectRotRutPayout && txIsSek && rotRutRequests.length > 0 ? (
<div className="space-y-1.5">
<p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
{t('rot_rut_section_title')}
</p>
{rotRutRequests.map((request) => {
const expected = expectedRotRutPayoutAmount(request)
const exact = Math.abs(expected - txAmount) < 0.005
const picked = pickedRequestIds.has(request.id)
return (
<div
key={request.id}
className={cn(
'flex items-stretch rounded-lg border transition-colors',
exact && 'border-success/50 bg-success/5',
picked && 'border-primary/40 bg-secondary/40',
)}
>
<label className="flex cursor-pointer items-center pl-3 pr-1">
<Checkbox
checked={picked}
onCheckedChange={(checked) => togglePicked(request.id, checked === true)}
aria-label={t('rot_rut_pick_aria', { name: request.name })}
/>
</label>
<button
type="button"
onClick={() => onSelectRotRutPayout([request])}
className={cn(
'min-w-0 flex-1 rounded-r-lg py-2.5 pl-2 pr-3 text-left transition-colors',
'hover:bg-muted/50 focus:outline-none focus:ring-2 focus:ring-ring',
)}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<Landmark className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
<span className="font-medium text-sm">{request.name}</span>
</div>
<p className="text-xs text-muted-foreground mt-0.5 truncate">
{t('rot_rut_request_meta', {
type: request.deduction_type === 'rut' ? 'RUT' : 'ROT',
count: request.invoices.length,
})}
</p>
</div>
<div className="text-right flex-shrink-0">
<p className={cn('text-sm font-medium tabular-nums', exact && 'text-success')}>
{formatCurrency(expected, DOMESTIC_CURRENCY)}
</p>
{exact && <p className="text-[10px] text-success">{t('exact_match')}</p>}
</div>
</div>
</button>
</div>
)
})}
{pickedRequests.length > 0 && (
<div className="flex items-center justify-between gap-3 pt-1">
<div className="min-w-0 text-xs">
<p className={cn('tabular-nums', pickedExact ? 'text-success' : 'text-muted-foreground')}>
{t('rot_rut_picked_sum', {
count: pickedRequests.length,
amount: formatCurrency(pickedTotal, DOMESTIC_CURRENCY),
})}
</p>
{!pickedExact && (
<p className="text-attn tabular-nums">
{t('rot_rut_picked_diff', { amount: formatCurrency(pickedDiff, DOMESTIC_CURRENCY) })}
</p>
)}
</div>
<Button type="button" size="sm" onClick={handOverPicked}>
{t('rot_rut_match_picked', { count: pickedRequests.length })}
</Button>
</div>
)}
</div>
) : null
if (invoices.length === 0) {
return (
<div className="space-y-3">
{rotRutSection}
<div className="text-center py-8 text-muted-foreground">
<p className="text-sm">{t('empty')}</p>
</div>
</div>
)
}
return (
<div className="space-y-3">
{rotRutSection}
<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={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-9"
autoFocus
/>
</div>
<div className="space-y-1.5 max-h-[55vh] overflow-y-auto pr-1">
{sorted.map(({ invoice, proximity }) => {
const remaining = invoice.remaining_amount ?? invoice.total
const { exact, close, candidateSek } = proximity
const invoiceCurrency = normalizeCurrency(invoice.currency)
// The currency earns a marker only when it deviates from the bank
// row's: the same marker on every row would say nothing (design.md,
// "chips mark exceptions"). It is what explains why a row is or is
// not ranked as close.
const foreignCurrency = proximity.basis !== 'same_currency'
return (
<button
key={invoice.id}
type="button"
onClick={() => onSelect(invoice)}
className={cn(
'w-full text-left rounded-lg border px-3 py-2.5 transition-colors',
'hover:bg-muted/50 focus:outline-none focus:ring-2 focus:ring-ring',
exact && 'border-success/50 bg-success/5',
close && 'border-primary/30'
)}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<FileText className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
<span className="font-medium text-sm">
{invoice.invoice_number ?? t('no_number')}
</span>
{invoice.status === 'overdue' && (
<span className="text-[10px] uppercase tracking-wide text-destructive">
{t('status_overdue')}
</span>
)}
{invoice.status === 'partially_paid' && (
<span className="text-[10px] uppercase tracking-wide text-attn">
{t('status_partially_paid')}
</span>
)}
{foreignCurrency && (
<span className="text-[10px] uppercase tracking-wide text-muted-foreground">
{invoiceCurrency}
</span>
)}
</div>
<p className="text-xs text-muted-foreground mt-0.5 truncate">
{invoice.customer?.name || t('unknown_customer')} · {t('due_short', { date: formatDate(invoice.due_date) })}
</p>
</div>
<div className="text-right flex-shrink-0">
<p
className={cn(
'text-sm font-medium tabular-nums',
exact && 'text-success'
)}
>
{formatCurrency(remaining, invoiceCurrency)}
</p>
{exact && <p className="text-[10px] text-success">{t('exact_match')}</p>}
{candidateSek != null && (
<p className="text-[10px] text-muted-foreground tabular-nums">
≈ {formatCurrency(candidateSek, DOMESTIC_CURRENCY)}
</p>
)}
</div>
</div>
</button>
)
})}
{sorted.length === 0 && (
<p className="text-center text-sm text-muted-foreground py-4">
{t('no_search_results', { term: search })}
</p>
)}
</div>
</div>
)
}
@@ -1,69 +0,0 @@
'use client'
import { useMemo } from 'react'
import { formatCurrency } from '@/lib/utils'
import { formatAccountWithName } from '@/lib/bookkeeping/client-account-names'
import { computeProposalLines } from '@/lib/bookkeeping/proposal-lines'
import type { ProposalLinesInput } from '@/lib/bookkeeping/proposal-lines'
export type JournalEntryPreviewProps = ProposalLinesInput
export default function JournalEntryPreview(props: JournalEntryPreviewProps) {
const {
amount,
amountSek,
category,
vatTreatment,
accountOverride,
entityType,
templateDebitAccount,
templateCreditAccount,
templateVatRate,
templateVatTreatment,
templateSupplierType,
counterpartyLegacy,
linePattern,
settlementAccount,
} = props
// Line computation lives in lib/bookkeeping/proposal-lines.ts, shared with
// the "Andra rader" prefill so preview and editable lines never drift.
const lines = useMemo(
() => computeProposalLines({
amount,
amountSek,
category,
vatTreatment,
accountOverride,
entityType,
templateDebitAccount,
templateCreditAccount,
templateVatRate,
templateVatTreatment,
templateSupplierType,
counterpartyLegacy,
linePattern,
settlementAccount,
}),
[amount, amountSek, category, vatTreatment, accountOverride, entityType, templateDebitAccount, templateCreditAccount, templateVatRate, templateVatTreatment, templateSupplierType, counterpartyLegacy, linePattern, settlementAccount]
)
if (lines.length === 0) return null
return (
<div className="rounded-lg border bg-muted/30 px-3 py-2.5 overflow-hidden">
<p className="text-xs font-medium text-muted-foreground mb-1.5">Verifikation</p>
<div className="space-y-0.5 font-mono text-xs min-w-0">
{lines.map((line, i) => (
<div key={i} className="flex items-baseline gap-2 min-w-0">
<span className={`w-12 text-right flex-shrink-0 ${line.side === 'debet' ? 'text-foreground' : 'text-muted-foreground'}`}>
{line.side === 'debet' ? 'Debet' : 'Kredit'}
</span>
<span className="flex-1 truncate">{formatAccountWithName(line.account)}</span>
<span className="flex-shrink-0 tabular-nums">{formatCurrency(line.amount, 'SEK')}</span>
</div>
))}
</div>
</div>
)
}
File diff suppressed because it is too large Load Diff
@@ -1,302 +0,0 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useCashAccounts } from '@/lib/reference-data/hooks'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { HelpPopover } from '@/components/ui/help-popover'
import {
MatchVerifikationPicker,
type UnlinkedGLLine,
} from '@/components/reconciliation/MatchVerifikationPicker'
import { formatCurrency, formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { useToast } from '@/components/ui/use-toast'
import { ArrowUpRight, ArrowDownRight, Loader2 } from 'lucide-react'
import type { TransactionWithInvoice } from './transaction-types'
import { resolveAccount } from '@/lib/cash-accounts/resolve-account'
interface MatchVoucherDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
transaction: TransactionWithInvoice | null
/** Called after a successful link. voucherLabel is the picked verifikat's label (e.g. "A-42"). */
onLinked: (transactionId: string, journalEntryId: string, voucherLabel: string) => void
}
// ±30 days around the transaction date: wide enough to catch a salary or
// supplier voucher booked a few days off the bank value date, narrow enough to
// keep the candidate list short. "Visa alla" drops the window entirely.
const WINDOW_DAYS = 30
function shiftDate(isoDate: string, deltaDays: number): string {
const d = new Date(isoDate)
if (Number.isNaN(d.getTime())) return isoDate
d.setDate(d.getDate() + deltaDays)
return d.toISOString().slice(0, 10)
}
export function MatchVoucherDialog({
open,
onOpenChange,
transaction,
onLinked,
}: MatchVoucherDialogProps) {
const { toast } = useToast()
const [glLines, setGlLines] = useState<UnlinkedGLLine[]>([])
const [selected, setSelected] = useState('')
const [accountNumber, setAccountNumber] = useState('1930')
const [accountFallback, setAccountFallback] = useState(false)
const [loading, setLoading] = useState(false)
const [submitting, setSubmitting] = useState(false)
const [wideRange, setWideRange] = useState(false)
// Opt-in: also surface vouchers already matched to another bank transaction,
// so several transactions can settle one verifikat (N:1: a salary run paid in
// multiple transfers, an invoice paid in instalments).
const [includeMatched, setIncludeMatched] = useState(false)
// Session-cached (lib/reference-data): resolving the settlement account no
// longer costs a /api/cash-accounts round trip per candidate load.
const { cashAccounts } = useCashAccounts()
const loadCandidates = useCallback(
async (tx: TransactionWithInvoice, wide: boolean, matched: boolean, signal: { cancelled: boolean }) => {
setLoading(true)
try {
// Resolve the settlement account from the company's cash accounts
// (an empty list resolves to 1930 with the fallback note shown).
const resolved = resolveAccount(cashAccounts, tx.cash_account_id ?? null, tx.currency ?? 'SEK')
const account = resolved.account
const fallback = resolved.fallback
if (!signal.cancelled) {
setAccountNumber(account)
setAccountFallback(fallback)
}
const params = new URLSearchParams()
params.set('account_number', account)
params.set('transaction_id', tx.id)
if (matched) params.set('include_matched', 'true')
if (!wide) {
params.set('date_from', shiftDate(tx.date, -WINDOW_DAYS))
params.set('date_to', shiftDate(tx.date, WINDOW_DAYS))
}
const res = await fetch(`/api/reconciliation/bank/unmatched-entries?${params}`)
const json = await res.json()
if (signal.cancelled) return
const lines = (json.data ?? []) as UnlinkedGLLine[]
setGlLines(lines)
// Pre-select a strong auto-match (exact/reference/date-range) so the
// common case is one click. Fuzzy (<0.85) is left for the user to confirm.
// Auto-select a strong match only when nothing is chosen yet. Toggling
// "Visa alla datum" reloads with a wider set: it must NOT discard a
// voucher the user already picked. (selected resets to '' on close.)
// Never auto-select an already-matched voucher: N:1 must be a
// deliberate choice, not the default when "visa matchade" is on.
const top = lines[0]
setSelected((prev) =>
prev
? prev
: top && (top.confidence ?? 0) >= 0.85 && !(top.linked_transaction_count ?? 0)
? top.journal_entry_id
: '',
)
} finally {
if (!signal.cancelled) setLoading(false)
}
},
[cashAccounts],
)
// (Re)load whenever the dialog opens for a transaction, the range widens, or
// the user toggles already-matched vouchers in/out.
useEffect(() => {
if (!open || !transaction) return
const signal = { cancelled: false }
void loadCandidates(transaction, wideRange, includeMatched, signal)
return () => { signal.cancelled = true }
}, [open, transaction, wideRange, includeMatched, loadCandidates])
// Reset transient state when the dialog closes so the next open starts clean.
useEffect(() => {
if (open) return
setGlLines([])
setSelected('')
setWideRange(false)
setIncludeMatched(false)
setAccountFallback(false)
}, [open])
if (!transaction) return null
const isIncome = transaction.amount > 0
const selectedLine = glLines.find((l) => l.journal_entry_id === selected) ?? null
async function handleConfirm() {
if (!transaction || !selected) return
setSubmitting(true)
try {
const res = await fetch('/api/reconciliation/bank/link', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
transaction_id: transaction.id,
journal_entry_id: selected,
account_number: accountNumber,
}),
})
const result = await res.json()
if (!res.ok || result.error) {
toast({
title: 'Kunde inte matcha',
description: getErrorMessage(result, { context: 'transaction', statusCode: res.status }),
variant: 'destructive',
})
return
}
const label = selectedLine ? formatVoucher(selectedLine) : ''
onLinked(transaction.id, selected, label)
} catch {
toast({
title: 'Kunde inte koppla',
description: 'Ett fel uppstod. Försök igen.',
variant: 'destructive',
})
} finally {
setSubmitting(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>Matcha mot befintlig verifikation</DialogTitle>
<HelpPopover>
<p>
Kopplar bankhändelsen till en verifikation som redan är bokförd,
t.ex. en lön eller en post importerad från Fortnox. Ingen ny
bokföring skapas.
</p>
<p className="mt-2">
Med &quot;Visa även matchade&quot; kan flera bankhändelser kopplas
till samma verifikation, t.ex. en lön utbetald i flera
överföringar.
</p>
</HelpPopover>
</div>
</DialogHeader>
{/* Transaction summary */}
<div className="flex items-center gap-3 rounded-lg border border-border bg-secondary/30 px-3 py-2.5 text-sm">
<span
className={isIncome ? 'text-success' : 'text-foreground/60'}
aria-hidden
>
{isIncome ? <ArrowUpRight className="h-4 w-4" /> : <ArrowDownRight className="h-4 w-4" />}
</span>
<div className="min-w-0 flex-1">
<p className="truncate font-medium">{transaction.description}</p>
<p className="text-xs text-muted-foreground tabular-nums">{formatDate(transaction.date)}</p>
</div>
<span className={`font-medium tabular-nums ${isIncome ? 'text-success' : ''}`}>
{isIncome ? '+' : ''}
{formatCurrency(transaction.amount, transaction.currency)}
</span>
</div>
{accountFallback && (
<p className="text-xs text-muted-foreground">
Avstämning mot 1930. Hör transaktionen till ett annat bankkonto? Stäm av
det under Rapporter → Bankavstämning.
</p>
)}
{/* Candidate picker */}
<div className="space-y-2">
{loading ? (
<div className="flex items-center justify-center gap-2 rounded-lg border border-border py-6 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
Söker verifikationer…
</div>
) : glLines.length === 0 ? (
<div className="rounded-lg border border-border px-3 py-6 text-center text-sm text-muted-foreground">
<p>
{includeMatched
? `Inga verifikationer på ${accountNumber} i perioden.`
: `Inga omatchade verifikationer på ${accountNumber} i perioden.`}
</p>
</div>
) : (
<>
<MatchVerifikationPicker glLines={glLines} value={selected} onChange={setSelected} inline />
{(selectedLine?.linked_transaction_count ?? 0) > 0 && (
<p className="text-xs text-muted-foreground">
Redan matchad mot {selectedLine?.linked_transaction_count}{' '}
transaktion{(selectedLine?.linked_transaction_count ?? 0) === 1 ? '' : 'er'};
den här läggs till.
</p>
)}
</>
)}
{/* One verifikat per dialog, by design: the 1:N split (one bank
row over several verifikat) needs the sum arithmetic of the
worksheet, so this stays a single pick and points there. */}
<p className="text-xs text-muted-foreground">
Ska händelsen delas på flera verifikat? Använd Bankavstämning → Matcha manuellt.
</p>
{/* Discovery affordances: widen the date window, and surface vouchers
already matched so another transaction can be attached (N:1).
Quiet links, not switches: these are list filters, and the switch
idiom belongs to settings (convention 15). */}
<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2 pt-1">
<button
type="button"
className="text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground"
onClick={() => setIncludeMatched((v) => !v)}
>
{includeMatched ? 'Dölj matchade' : 'Visa även matchade'}
</button>
{!wideRange && (
<button
type="button"
className="text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground"
onClick={() => setWideRange(true)}
>
Visa alla datum
</button>
)}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={submitting}>
Avbryt
</Button>
<Button onClick={handleConfirm} disabled={!selected || submitting}>
{submitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Matchar…
</>
) : (
'Matcha'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,150 +0,0 @@
'use client'
import { useEffect, 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 { Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { CashAccount } from '@/types'
interface MoveTransactionCashAccountDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** Enabled cash accounts to offer (the page's /api/cash-accounts?enabled_only=true list). */
cashAccounts: CashAccount[]
/** cash_accounts.id the transaction is currently bound to (null = unassigned). */
currentCashAccountId: string | null
/** Transaction currency: accounts in another currency cannot be picked
* (the server hard-rejects a cross-currency move). */
currency: string
/** Persist the move (PATCH). Resolves true on success (dialog closes),
* false to keep the dialog open (e.g. the request failed). */
onMove: (accountNumber: string) => Promise<boolean>
}
/**
* Move an unbooked bank transaction to another of the company's cash accounts.
* Radio list of the enabled accounts (name + ledger account); the current
* account is preselected and disabled so the user picks where the row should
* go. Gating (only unbooked/unmatched rows) is enforced server-side; callers
* only open this for movable rows.
*/
export default function MoveTransactionCashAccountDialog({
open,
onOpenChange,
cashAccounts,
currentCashAccountId,
currency,
onMove,
}: MoveTransactionCashAccountDialogProps) {
const t = useTranslations('tx_inbox_card')
const currentLedger =
cashAccounts.find((a) => a.id === currentCashAccountId)?.ledger_account ?? null
const [selected, setSelected] = useState<string | null>(currentLedger)
const [isSaving, setIsSaving] = useState(false)
// Re-seed the selection each time the dialog opens for a (possibly different) row.
useEffect(() => {
if (open) setSelected(currentLedger)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, currentCashAccountId])
const canSave = selected !== null && selected !== currentLedger && !isSaving
async function persist() {
if (!canSave || selected === null) return
setIsSaving(true)
try {
const ok = await onMove(selected)
if (ok) onOpenChange(false)
} finally {
setIsSaving(false)
}
}
return (
<Dialog
open={open}
onOpenChange={(v) => {
if (isSaving) return
onOpenChange(v)
}}
>
<DialogContent className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{t('move_account_dialog_title')}</DialogTitle>
<DialogDescription>{t('move_account_dialog_description')}</DialogDescription>
</DialogHeader>
<div role="radiogroup" aria-label={t('move_account_dialog_title')} className="space-y-2">
{cashAccounts.map((account) => {
const isCurrent = account.id === currentCashAccountId
const currencyMismatch = account.currency.toUpperCase() !== currency.toUpperCase()
const disabled = isCurrent || currencyMismatch || isSaving
return (
<label
key={account.id}
className={cn(
'flex min-h-11 items-center gap-3 rounded-lg border border-border px-3 py-2 text-sm transition-colors duration-150',
disabled ? 'opacity-60' : 'cursor-pointer hover:bg-secondary/35',
selected === account.ledger_account && !disabled && 'bg-secondary/40',
)}
>
<input
type="radio"
name="move-cash-account"
value={account.ledger_account}
checked={selected === account.ledger_account}
onChange={() => setSelected(account.ledger_account)}
disabled={disabled}
className="h-4 w-4 shrink-0 accent-foreground"
/>
<span className="min-w-0 flex-1 truncate">
{account.name || `Bankkonto ${account.currency}`}
</span>
{isCurrent && (
<span className="shrink-0 text-xs text-muted-foreground">
{t('move_account_current')}
</span>
)}
{!isCurrent && currencyMismatch && (
<span className="shrink-0 text-xs text-muted-foreground">
{t('move_account_currency_mismatch', { currency: account.currency })}
</span>
)}
<span className="shrink-0 font-mono text-xs tabular-nums text-muted-foreground">
{account.ledger_account}
</span>
</label>
)
})}
</div>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isSaving}
className="min-h-11 w-full sm:w-auto"
>
{t('move_account_cancel')}
</Button>
<Button
onClick={() => void persist()}
disabled={!canSave}
className="min-h-11 w-full sm:w-auto"
>
{isSaving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : null}
{t('move_account_save')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
File diff suppressed because it is too large Load Diff
@@ -1,270 +0,0 @@
'use client'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { formatCurrency, formatDate } from '@/lib/utils'
import { roundOre } from '@/lib/money'
import {
expectedRotRutPayoutAmount,
getRotRutPayoutMatchTargetState,
} from '@/lib/invoices/rot-rut-payout-matching'
import { CheckCircle2, AlertTriangle } from 'lucide-react'
import type { TransactionWithInvoice } from './transaction-types'
interface RotRutPayoutMatchDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
/** Row carrying `potential_rot_rut_payout`; the dialog renders nothing without it. */
transaction: TransactionWithInvoice | null
isConfirming: boolean
onConfirm: () => void
}
/**
* Confirm dialog for matching an income bank row to one or several open
* ROT/RUT begäran: Skatteverkets utbetalning clears the 1513 receivable
* (debit the row's cash account, one 1513 credit per begäran) and the row is
* linked to that voucher.
*
* Kept separate from InvoiceMatchDialog on purpose: no FX, no preview fetch,
* no editable lines. The legs are known up front, so everything the user
* needs to approve is on screen. A bundle (several begäran paid in one
* transfer) is booked at exactly the decided sums: partial and over
* variants exist only for a single begäran.
*/
export default function RotRutPayoutMatchDialog({
open,
onOpenChange,
transaction,
isConfirming,
onConfirm,
}: RotRutPayoutMatchDialogProps) {
const t = useTranslations('tx_rot_rut_match')
const requests = transaction?.potential_rot_rut_payout?.requests ?? []
const isSet = requests.length > 1
const single = requests.length === 1 ? requests[0] : null
// Every begäran must still be open and unsettled; the first blocked one
// explains the refusal.
const blockedState =
requests.map((request) => getRotRutPayoutMatchTargetState(request)).find((s) => s !== 'matchable') ??
null
const targetBlocked = requests.length === 0 || blockedState !== null
const txAmount = transaction ? roundOre(transaction.amount) : 0
const expected = roundOre(
requests.reduce((sum, request) => sum + expectedRotRutPayoutAmount(request), 0),
)
const requestedTotal = roundOre(
requests.reduce((sum, request) => sum + roundOre(Number(request.requested_total)), 0),
)
const diff = roundOre(Math.abs(txAmount - expected))
const amountsMatch = diff < 0.01
// The settle service refuses a payout below requested_total unless the
// beslut (decided_total) is recorded: say so here instead of letting the
// button fail.
const isPartial = single ? txAmount < requestedTotal - 0.005 : false
const partialBlocked = isPartial && single?.decided_total == null
// The service refuses more than Skatteverket can owe on this begäran: a
// larger row would drive 1513 negative. Block here too, with the reason.
const overBlocked = single ? txAmount > expected + 0.005 : false
// A bundle only ever books the exact sum of its begäran.
const setBlocked = isSet && !amountsMatch
// Skatteverket pays out in SEK only; the route refuses anything else.
const currencyBlocked = (transaction?.currency || 'SEK').toUpperCase() !== 'SEK'
const currency = transaction?.currency || 'SEK'
const typeLabel = (deductionType: 'rot' | 'rut') => (deductionType === 'rut' ? 'RUT' : 'ROT')
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
<DialogDescription>
{targetBlocked ? t('description_blocked') : t('description')}
</DialogDescription>
</DialogHeader>
{transaction && requests.length > 0 && (
<div className="space-y-4">
<div className="rounded-lg border p-4 space-y-2">
<p className="text-sm font-medium text-muted-foreground">{t('transaction_label')}</p>
<p className="font-medium">{transaction.description}</p>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">{formatDate(transaction.date)}</span>
<span className="font-medium text-success">
+{formatCurrency(transaction.amount, currency)}
</span>
</div>
</div>
<div className="rounded-lg border p-4 space-y-3">
<p className="text-sm font-medium text-muted-foreground">
{isSet ? t('requests_label', { count: requests.length }) : t('request_label')}
</p>
{requests.map((request) => (
<div key={request.id} className="space-y-2">
<p className="font-medium">
{t('request_name', { type: typeLabel(request.deduction_type), name: request.name })}
</p>
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">
{t('requested_total', {
amount: formatCurrency(roundOre(Number(request.requested_total)), 'SEK'),
})}
</span>
{request.decided_total != null && (
<span className="text-muted-foreground">
{t('decided_total', {
amount: formatCurrency(Number(request.decided_total), 'SEK'),
})}
</span>
)}
</div>
{request.invoices.length > 0 && (
<div className="pt-2 border-t space-y-1">
<p className="text-xs font-medium text-muted-foreground">{t('invoices_title')}</p>
<ul className="text-sm space-y-0.5">
{request.invoices.map((inv, i) => (
<li key={`${inv.invoice_number ?? 'x'}-${i}`} className="flex justify-between">
<span>{t('invoice_row', { number: inv.invoice_number ?? '' })}</span>
<span className="tabular-nums text-muted-foreground">
{formatCurrency(Number(inv.requested_amount), 'SEK')}
</span>
</li>
))}
</ul>
</div>
)}
</div>
))}
{isSet && (
<div className="flex justify-between border-t pt-2 text-sm font-medium">
<span>{t('requests_total_label')}</span>
<span className="tabular-nums">{formatCurrency(expected, 'SEK')}</span>
</div>
)}
</div>
{targetBlocked ? (
<div className="flex items-start gap-2 p-3 rounded-lg bg-muted/30 text-attn">
<AlertTriangle className="h-4 w-4 flex-shrink-0 mt-0.5" />
<div className="text-sm">
<p className="font-medium">
{t(blockedState === 'settled' ? 'target_settled_title' : 'target_not_open_title')}
</p>
<p>
{t(
blockedState === 'settled'
? 'target_settled_description'
: 'target_not_open_description',
)}
</p>
</div>
</div>
) : amountsMatch ? (
<div className="flex items-center gap-2 p-3 rounded-lg bg-success/10 text-success">
<CheckCircle2 className="h-4 w-4 flex-shrink-0" />
<p className="text-sm font-medium">
{isSet ? t('amounts_match_set') : t('amounts_match')}
</p>
</div>
) : (
<div className="flex items-start gap-2 p-3 rounded-lg bg-muted/30 text-attn">
<AlertTriangle className="h-4 w-4 flex-shrink-0 mt-0.5" />
<div className="text-sm">
<p className="font-medium">{isSet ? t('amounts_differ_set') : t('amounts_differ')}</p>
<p>{t('amount_diff', { amount: formatCurrency(diff, currency) })}</p>
{setBlocked && <p className="mt-1">{t('set_exact_required')}</p>}
{overBlocked && <p className="mt-1">{t('over_payout_blocked')}</p>}
{partialBlocked && <p className="mt-1">{t('partial_requires_beslut')}</p>}
{isPartial && !partialBlocked && (
<p className="mt-1">{t('partial_with_beslut_note')}</p>
)}
</div>
</div>
)}
{!targetBlocked && (
<div className="rounded-lg border p-4 space-y-2">
<p className="text-sm font-medium">{t('booking_title')}</p>
<div className="text-sm space-y-1">
<div className="flex justify-between">
<span>
<span className="text-muted-foreground">{t('booking_debit')}</span>{' '}
{t('booking_bank_line')}
</span>
<span className="tabular-nums">{formatCurrency(txAmount, currency)}</span>
</div>
{isSet ? (
requests.map((request) => (
<div key={request.id} className="flex justify-between">
<span>
<span className="text-muted-foreground">{t('booking_credit')}</span>{' '}
{t('booking_receivable_line_named', { name: request.name })}
</span>
<span className="tabular-nums">
{formatCurrency(expectedRotRutPayoutAmount(request), currency)}
</span>
</div>
))
) : (
<div className="flex justify-between">
<span>
<span className="text-muted-foreground">{t('booking_credit')}</span>{' '}
{t('booking_receivable_line')}
</span>
<span className="tabular-nums">{formatCurrency(txAmount, currency)}</span>
</div>
)}
</div>
</div>
)}
{!targetBlocked && (
<div className="rounded-lg bg-muted/50 p-4 space-y-2">
<p className="text-sm font-medium">{t('on_confirm_title')}</p>
<ul className="text-sm text-muted-foreground space-y-1">
<li>• {t('on_confirm_link')}</li>
<li>
• {isSet ? t('on_confirm_requests', { count: requests.length }) : t('on_confirm_request')}
</li>
<li>• {t('on_confirm_voucher')}</li>
</ul>
</div>
)}
</div>
)}
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={isConfirming}>
{t('cancel')}
</Button>
<Button
onClick={onConfirm}
disabled={
isConfirming ||
requests.length === 0 ||
targetBlocked ||
partialBlocked ||
overBlocked ||
setBlocked ||
currencyBlocked
}
>
{isConfirming ? t('confirming') : t('confirm')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -1,206 +0,0 @@
'use client'
import { useRef } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { TD_CLASS, QUIET_LINK_CLASS, CHECKBOX_REVEAL_CLASS } from '@/components/ui/dry-table'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { AlertCircle, Landmark, Link2, Loader2 } from 'lucide-react'
import type {
SkattekontoBookingSuggestion,
SkattekontoMatchSuggestion,
StoredSkattekontoTransaction,
} from '@/types/skatteverket'
/**
* Skattekonto-rad in the /transactions inbox, rendered as a dry-table row
* (concept scene 10). The Skatteverket chip is the cue that this row is
* fundamentally different from a bank tx: different counter-account (1630 vs
* 1930), different categorization rules. No foldout: both actions fit inline.
*/
export default function SkattekontoInboxCard({
row,
matchSuggestion,
bookingSuggestion,
isExiting = false,
processing,
selectable,
isSelected,
onToggleSelect,
onBokfor,
onMatch,
onIgnore,
}: {
row: StoredSkattekontoTransaction
matchSuggestion?: SkattekontoMatchSuggestion | null
bookingSuggestion?: SkattekontoBookingSuggestion | null
/** The row was just booked and is animating out during the page's 350ms
* removal window (.row-exit collapse; instant under reduced motion). */
isExiting?: boolean
processing: boolean
selectable?: boolean
isSelected?: boolean
onToggleSelect?: (id: string, extend?: boolean) => void
onBokfor: (row: StoredSkattekontoTransaction) => void
onMatch: (row: StoredSkattekontoTransaction) => void
/** Optional "Ignorera" affordance: hides the row from the work list without
* booking it (skattekonto rows are never deleted). The parent owns the
* confirm dialog and the PATCH. */
onIgnore?: (row: StoredSkattekontoTransaction) => void
}) {
const t = useTranslations('tx_skattekonto_card')
// See TransactionInboxCard: onCheckedChange has no event, so shift is
// captured from the preceding click.
const shiftHeld = useRef(false)
const amount = Number(row.belopp_skatteverket)
const isIncome = amount > 0
const duplicateLabel =
matchSuggestion?.voucher_series && matchSuggestion?.voucher_number
? t('duplicate_title_with_voucher', {
label: formatVoucher({
voucher_series: matchSuggestion.voucher_series,
voucher_number: matchSuggestion.voucher_number,
}),
})
: t('duplicate_title_draft')
return (
<tr
className={cn(
'group transition-colors duration-150 hover:bg-secondary/35',
isSelected && 'bg-secondary/40',
isExiting && 'row-exit',
)}
// .row-exit only blocks pointer input; `inert` also drops keyboard
// focus and activation (booking/matching controls) during the 350ms
// removal window.
inert={isExiting || undefined}
>
{/* Always-visible selection checkbox (concept .cb) */}
{/* Zero-width cell: the checkbox hangs in the left page margin so
the date column can sit flush with the page edge. */}
<td className={cn(TD_CLASS, 'relative w-0 !p-0 select-none')}>
{selectable && (
<Checkbox
checked={isSelected}
onClick={(e) => {
shiftHeld.current = e.shiftKey
}}
onCheckedChange={() => onToggleSelect?.(row.id, shiftHeld.current)}
aria-label={t('select_row')}
className={cn(
'absolute -left-5 top-1/2 -translate-y-1/2 border-foreground duration-150 md:-left-6',
isSelected ? 'opacity-100' : CHECKBOX_REVEAL_CLASS,
)}
/>
)}
</td>
<td className={cn(TD_CLASS, '!pl-0 whitespace-nowrap tabular-nums text-muted-foreground')}>
{formatDate(row.transaktionsdatum)}
</td>
{/* overflow-hidden: the shrink-0 chips below don't truncate, so on a
viewport too narrow for them the cell must clip instead of painting
over the Belopp column. Same guard #2003 put on TransactionInboxCard;
this row and the ones below never got it. */}
<td className={cn(TD_CLASS, 'max-w-0 w-full overflow-hidden')}>
<span className="row-collapsible flex min-w-0 items-center gap-2">
<span className="truncate">{row.transaktionstext}</span>
<Badge variant="outline" className="h-4 shrink-0 gap-1 px-1.5 py-0 text-[10px] font-normal">
<Landmark className="h-3 w-3" />
{t('skv_badge')}
</Badge>
{matchSuggestion && (
<Badge variant="warning" className="h-4 shrink-0 gap-1 px-1.5 py-0 text-[10px]">
<AlertCircle className="h-3 w-3" />
{duplicateLabel}
</Badge>
)}
{/* What "Bokför" will do: the deterministic rule match, muted so it
reads as information, not state. Suppressed on likely duplicates
where linking (not booking) is the recommended action. */}
{bookingSuggestion && !matchSuggestion && (
<span className="hidden shrink-0 whitespace-nowrap text-xs text-muted-foreground md:inline">
{t('suggestion_line', {
account: bookingSuggestion.account_name
? `${bookingSuggestion.account} ${bookingSuggestion.account_name}`
: bookingSuggestion.account,
})}
</span>
)}
</span>
</td>
<td
className={cn(
TD_CLASS,
'whitespace-nowrap text-right tabular-nums rr-mask',
isIncome && 'text-success',
)}
>
{isIncome ? '+' : ''}
{formatCurrency(amount)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right !pr-0 py-[9px]')}>
<span className="row-collapsible inline-flex items-center justify-end gap-3">
{matchSuggestion ? (
<>
{/* Likely duplicate: linking beats re-booking, so it leads. */}
<Button
size="sm"
variant="outline"
className="h-7 px-3.5 text-xs"
onClick={() => onMatch(row)}
disabled={processing}
>
<Link2 className="mr-1 h-3 w-3" />
{t('link_to_voucher')}
</Button>
<button
type="button"
className={QUIET_LINK_CLASS}
onClick={() => onBokfor(row)}
disabled={processing}
>
{t('book_anyway')}
</button>
</>
) : (
<>
<Button
size="sm"
variant="outline"
className="h-7 px-3.5 text-xs"
onClick={() => onBokfor(row)}
disabled={processing}
>
{processing && <Loader2 className="mr-1 h-3 w-3 animate-spin" />}
{t('book')}
</Button>
<button
type="button"
className={QUIET_LINK_CLASS}
onClick={() => onMatch(row)}
disabled={processing}
>
{t('match_to_voucher')}
</button>
</>
)}
{onIgnore && (
<button
type="button"
className={QUIET_LINK_CLASS}
onClick={() => onIgnore(row)}
disabled={processing}
>
{t('ignore')}
</button>
)}
</span>
</td>
</tr>
)
}
@@ -1,182 +0,0 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import { MoreHorizontal, Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { EmptyState } from '@/components/ui/empty-state'
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
import { formatCurrency, formatDate, cn } from '@/lib/utils'
import type { TransactionWithInvoice } from './transaction-types'
/**
* "Granska migrerad historik": the review surface for journal-entry match
* suggestions the reconciliation sweep persisted (the 0.75-0.89 band). Each
* row shows the bank transaction beside its suggested verifikat; confirming
* goes through the server-side revalidating bulk endpoint, so a stale pair
* degrades to a reported skip, never a wrong link. Per-row fallbacks: open the
* match dialog to pick another verifikat, or reject the suggestion (the row
* returns to the ordinary "Att bokföra" flow as backstop).
*/
interface SuggestionReviewListProps {
items: TransactionWithInvoice[]
/** Bulk/single confirm: resolves when the API call and list refresh are done. */
onConfirm: (transactionIds: string[]) => Promise<void>
onReject: (transactionIds: string[]) => Promise<void>
onOpenMatchVoucher: (tx: TransactionWithInvoice) => void
onRerunMatching: () => Promise<void>
rerunning: boolean
}
export function SuggestionReviewList({
items,
onConfirm,
onReject,
onOpenMatchVoucher,
onRerunMatching,
rerunning,
}: SuggestionReviewListProps) {
const t = useTranslations('tx_review')
const [busyIds, setBusyIds] = useState<Set<string>>(new Set())
const [bulkBusy, setBulkBusy] = useState(false)
const runRows = async (ids: string[], action: (ids: string[]) => Promise<void>) => {
setBusyIds((prev) => new Set([...prev, ...ids]))
try {
await action(ids)
} finally {
setBusyIds((prev) => {
const next = new Set(prev)
for (const id of ids) next.delete(id)
return next
})
}
}
const confirmAll = async () => {
setBulkBusy(true)
try {
await runRows(items.map((i) => i.id), onConfirm)
} finally {
setBulkBusy(false)
}
}
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<p className="text-[12.5px] text-muted-foreground">
{t('intro', { count: items.length })}
</p>
<div className="flex items-center gap-2">
<Button
size="sm"
variant="outline"
disabled={rerunning || bulkBusy}
onClick={() => void onRerunMatching()}
>
{rerunning && <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />}
{t('rerun')}
</Button>
<Button size="sm" disabled={bulkBusy || items.length === 0} onClick={() => void confirmAll()}>
{bulkBusy && <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />}
{t('confirm_all', { count: items.length })}
</Button>
</div>
</div>
{items.length === 0 ? (
<EmptyState title={t('empty_title')} description={t('empty_description')} />
) : (
<div className="overflow-x-auto">
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={TH_CLASS}>{t('th_date')}</th>
<th className={TH_CLASS}>{t('th_description')}</th>
<th className={cn(TH_CLASS, 'text-right')}>{t('th_amount')}</th>
<th className={TH_CLASS}>{t('th_suggestion')}</th>
<th className={TH_CLASS} aria-label={t('th_actions')} />
</tr>
</thead>
<tbody className="stagger-enter">
{items.map((tx) => {
const busy = busyIds.has(tx.id)
const voucher = tx.potential_voucher
return (
<tr key={tx.id} className="group transition-colors duration-150 hover:bg-secondary/35">
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums text-muted-foreground')}>
{formatDate(tx.date)}
</td>
<td className={cn(TD_CLASS, 'max-w-[280px]')}>
<span className="block truncate">{tx.description}</span>
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')}>
{formatCurrency(tx.amount, tx.currency)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap')}>
{voucher ? (
<span className="tabular-nums">
{voucher.voucher_series}-{voucher.voucher_number}
<span className="text-muted-foreground">
{' · '}
{formatDate(voucher.entry_date)}
{typeof tx.potential_match_confidence === 'number' && (
<> {' · '}{Math.round(tx.potential_match_confidence * 100)} %</>
)}
</span>
</span>
) : (
<span className="text-muted-foreground">{t('suggestion_gone')}</span>
)}
</td>
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right')}>
<div className="flex items-center justify-end gap-1">
<Button
size="sm"
variant="outline"
className="h-7 px-3.5 text-xs"
disabled={busy || bulkBusy || !voucher}
onClick={() => void runRows([tx.id], onConfirm)}
>
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : t('confirm')}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="ghost"
className="h-7 w-7"
disabled={busy || bulkBusy}
aria-label={t('row_menu')}
>
<MoreHorizontal className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => onOpenMatchVoucher(tx)}>
{t('open_match_dialog')}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => void runRows([tx.id], onReject)}>
{t('reject')}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
</div>
)
}
@@ -1,219 +0,0 @@
'use client'
import { useState, useEffect, useMemo } from 'react'
import { createClient } from '@/lib/supabase/client'
import { Input } from '@/components/ui/input'
import { formatCurrency, formatDate, cn } from '@/lib/utils'
import { Search, FileText, Loader2 } from 'lucide-react'
import { useCompany } from '@/contexts/CompanyContext'
import type { SupplierInvoice, Supplier } from '@/types'
import type { TransactionWithInvoice } from './transaction-types'
import {
DOMESTIC_CURRENCY,
normalizeCurrency,
rankInvoicesByAmountProximity,
} from './invoice-candidate-ranking'
type OpenSupplierInvoice = SupplierInvoice & { supplier?: Supplier }
interface SupplierInvoicePickerProps {
transaction: TransactionWithInvoice
onSelect: (invoice: OpenSupplierInvoice) => void
}
export default function SupplierInvoicePicker({
transaction,
onSelect,
}: SupplierInvoicePickerProps) {
const { company } = useCompany()
const supabase = useMemo(() => createClient(), [])
const [invoices, setInvoices] = useState<OpenSupplierInvoice[]>([])
const [isLoading, setIsLoading] = useState(true)
const [search, setSearch] = useState('')
useEffect(() => {
if (!company) return
const companyId = company.id
let cancelled = false
async function load() {
setIsLoading(true)
// Status filter mirrors match-supplier-invoice route expectations: only
// approved/overdue/partially_paid invoices can take a payment. Registered
// invoices haven't passed the approval gate yet; paid/credited/reversed
// are terminal.
const { data } = await supabase
.from('supplier_invoices')
.select('*, supplier:suppliers(*)')
.eq('company_id', companyId)
.in('status', ['approved', 'overdue', 'partially_paid'])
.gt('remaining_amount', 0)
.order('invoice_date', { ascending: false })
.limit(200)
if (cancelled) return
const all = ((data as OpenSupplierInvoice[]) || [])
// Status-leak guard: if a supplier invoice still says 'approved'/'overdue'
// but already has a payment voucher attached, hide it. Partially-paid
// invoices intentionally pass through: they may take more payments.
// Mirrors the customer-side guard in InvoicePicker.
const fullIds = all
.filter((inv) => inv.status === 'approved' || inv.status === 'overdue')
.map((inv) => inv.id)
let visible = all
if (fullIds.length > 0) {
const { data: paid } = await supabase
.from('supplier_invoice_payments')
.select('supplier_invoice_id')
.eq('company_id', companyId)
.in('supplier_invoice_id', fullIds)
.not('journal_entry_id', 'is', null)
if (cancelled) return
const paidSet = new Set<string>(
((paid as { supplier_invoice_id: string }[] | null) ?? []).map(
(r) => r.supplier_invoice_id,
),
)
visible = all.filter((inv) => !paidSet.has(inv.id))
}
setInvoices(visible)
setIsLoading(false)
}
load()
return () => {
cancelled = true
}
}, [company, supabase])
const sorted = useMemo(() => {
const filtered = !search
? invoices
: invoices.filter((inv) => {
const q = search.toLowerCase()
return (
(inv.supplier_invoice_number ?? '').toLowerCase().includes(q) ||
(inv.supplier?.name ?? '').toLowerCase().includes(q)
)
})
// Amount proximity is only meaningful between comparable amounts: ranking
// a 1 000 EUR invoice as a perfect hit for a 1 000 SEK payment put the
// wrong row first. Foreign invoices stay in the list either way; see
// ./invoice-candidate-ranking.
return rankInvoicesByAmountProximity(filtered, {
amount: transaction.amount,
currency: transaction.currency,
amountSek: transaction.amount_sek,
})
}, [invoices, search, transaction.amount, transaction.currency, transaction.amount_sek])
if (isLoading) {
return (
<div className="flex items-center justify-center py-8 text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin mr-2" />
Laddar leverantörsfakturor...
</div>
)
}
if (invoices.length === 0) {
return (
<div className="text-center py-8 text-muted-foreground">
<p className="text-sm">Inga öppna leverantörsfakturor att matcha mot.</p>
</div>
)
}
return (
<div className="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="Sök fakturanummer eller leverantör..."
value={search}
onChange={(e) => setSearch(e.target.value)}
className="pl-9"
autoFocus
/>
</div>
<div className="space-y-1.5 max-h-[55vh] overflow-y-auto pr-1">
{sorted.map(({ invoice, proximity }) => {
const remaining = invoice.remaining_amount ?? invoice.total
const { exact, close, candidateSek } = proximity
const invoiceCurrency = normalizeCurrency(invoice.currency)
// The currency earns a marker only when it deviates from the bank
// row's: the same marker on every row would say nothing (design.md,
// "chips mark exceptions"). It is what explains why a row is or is
// not ranked as close.
const foreignCurrency = proximity.basis !== 'same_currency'
return (
<button
key={invoice.id}
type="button"
onClick={() => onSelect(invoice)}
className={cn(
'w-full text-left rounded-lg border px-3 py-2.5 transition-colors',
'hover:bg-muted/50 focus:outline-none focus:ring-2 focus:ring-ring',
exact && 'border-success/50 bg-success/5',
close && 'border-primary/30'
)}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<FileText className="h-3.5 w-3.5 text-muted-foreground flex-shrink-0" />
<span className="font-medium text-sm">
{invoice.supplier_invoice_number ?? '(utan nummer)'}
</span>
{invoice.status === 'overdue' && (
<span className="text-[10px] uppercase tracking-wide text-destructive">
Förfallen
</span>
)}
{invoice.status === 'partially_paid' && (
<span className="text-[10px] uppercase tracking-wide text-attn">
Delbetald
</span>
)}
{foreignCurrency && (
<span className="text-[10px] uppercase tracking-wide text-muted-foreground">
{invoiceCurrency}
</span>
)}
</div>
<p className="text-xs text-muted-foreground mt-0.5 truncate">
{invoice.supplier?.name || 'Okänd leverantör'} · Förfaller{' '}
{formatDate(invoice.due_date)}
</p>
</div>
<div className="text-right flex-shrink-0">
<p
className={cn(
'text-sm font-medium tabular-nums',
exact && 'text-success'
)}
>
{formatCurrency(remaining, invoiceCurrency)}
</p>
{exact && <p className="text-[10px] text-success">Exakt match</p>}
{candidateSek != null && (
<p className="text-[10px] text-muted-foreground tabular-nums">
≈ {formatCurrency(candidateSek, DOMESTIC_CURRENCY)}
</p>
)}
</div>
</div>
</button>
)
})}
{sorted.length === 0 && (
<p className="text-center text-sm text-muted-foreground py-4">
Ingen faktura matchar &quot;{search}&quot;
</p>
)}
</div>
</div>
)
}
File diff suppressed because it is too large Load Diff
@@ -1,245 +0,0 @@
'use client'
import { 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 { useToast } from '@/components/ui/use-toast'
import { formatCurrency, formatDate } from '@/lib/utils'
import { ArrowUpRight, ArrowDownRight, FileText, Inbox, Loader2, X } from 'lucide-react'
import DocumentUploadZone from '@/components/bookkeeping/DocumentUploadZone'
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
import InboxDocumentPicker from '@/components/bookkeeping/InboxDocumentPicker'
import type { AvailableInboxDoc } from '@/components/bookkeeping/InboxDocumentPicker'
import type { TransactionWithInvoice } from './transaction-types'
interface TransactionAttachDocumentDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
transaction: TransactionWithInvoice | null
onAttached: (transactionId: string, documentId: string) => void
/** Detach the current pin (#2132). The page owns confirm + DELETE; the
* dialog only offers the entry point next to the already-attached hint. */
onDetach?: (transaction: TransactionWithInvoice) => void
}
/**
* Standalone "Matcha mot underlag" dialog for the /transactions view: the
* mirror of the Documents view's TransactionMatchPicker (doc → tx direction).
* Pick an unconsumed inbox document or upload a new file, then pin it to the
* transaction via POST /api/transactions/[id]/attach-document. The pin is
* single-valued (transactions.document_id); for booked rows the route
* propagates the link onto the verifikation immediately.
*/
export default function TransactionAttachDocumentDialog({
open,
onOpenChange,
transaction,
onAttached,
onDetach,
}: TransactionAttachDocumentDialogProps) {
const t = useTranslations('tx_attach_dialog')
const tDetach = useTranslations('tx_detach')
const { toast } = useToast()
const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])
const [pickedDoc, setPickedDoc] = useState<AvailableInboxDoc | null>(null)
const [inboxPickerOpen, setInboxPickerOpen] = useState(false)
const [isAttaching, setIsAttaching] = useState(false)
if (!transaction) return null
const isIncome = transaction.amount > 0
// Single selection: transactions.document_id pins exactly one doc, so an
// inbox pick replaces any upload and vice versa.
const selectedDocumentId =
pickedDoc?.document_id ??
uploadedFiles.find((f) => f.status === 'uploaded' && f.id)?.id ??
null
const reset = () => {
setUploadedFiles([])
setPickedDoc(null)
setInboxPickerOpen(false)
}
const handleAttach = async () => {
if (!selectedDocumentId || isAttaching) return
setIsAttaching(true)
try {
const res = await fetch(`/api/transactions/${transaction.id}/attach-document`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ document_id: selectedDocumentId }),
})
if (!res.ok) {
const json = (await res.json().catch(() => ({}))) as { error?: unknown }
// The route returns Swedish domain messages (immutability, locked
// period) as a plain string: surface them verbatim.
toast({
title: t('error_toast'),
description: typeof json.error === 'string' ? json.error : undefined,
variant: 'destructive',
})
return
}
toast({ title: t('success_toast') })
// Same event AgentChat and the booking dialog dispatch: flips the inbox
// card's indicator optimistically without a refetch.
window.dispatchEvent(
new CustomEvent('Accounted:transaction-document-linked', {
detail: { transaction_id: transaction.id, document_id: selectedDocumentId },
}),
)
onAttached(transaction.id, selectedDocumentId)
reset()
onOpenChange(false)
} catch {
// Network-level failure: fetch rejected before a response existed.
toast({ title: t('error_toast'), variant: 'destructive' })
} finally {
setIsAttaching(false)
}
}
return (
<Dialog
open={open}
onOpenChange={(o) => {
if (!o) reset()
onOpenChange(o)
}}
>
<DialogContent className="sm:max-w-lg">
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
<DialogDescription>{t('description')}</DialogDescription>
</DialogHeader>
{/* Transaction summary: same block as TransactionBookingDialog */}
<div className="flex items-center gap-3 rounded-lg border p-3">
<div
className={`h-9 w-9 rounded-full flex items-center justify-center flex-shrink-0 ${
isIncome
? 'text-success'
: 'text-destructive'
}`}
>
{isIncome ? (
<ArrowUpRight className="h-4 w-4" />
) : (
<ArrowDownRight className="h-4 w-4" />
)}
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-sm truncate">{transaction.description}</p>
<p className="text-xs text-muted-foreground">{formatDate(transaction.date)}</p>
</div>
<p className={`font-medium text-sm flex-shrink-0 ${isIncome ? 'text-success' : ''}`}>
{isIncome ? '+' : ''}
{formatCurrency(transaction.amount, transaction.currency)}
</p>
</div>
{transaction.document_id && (
<p className="text-xs text-muted-foreground">
{t('already_attached_hint')}
{onDetach && !transaction.journal_entry_id && (
<>
{' '}
<Button
type="button"
variant="link"
size="sm"
className="h-auto p-0 text-xs"
disabled={isAttaching}
onClick={() => onDetach(transaction)}
>
{tDetach('menu_item')}
</Button>
</>
)}
</p>
)}
<div className="space-y-2">
<DocumentUploadZone
files={uploadedFiles}
onFilesChange={(files) => {
setUploadedFiles(files)
if (files.length > 0) setPickedDoc(null)
}}
maxFiles={1}
compact
disabled={isAttaching}
/>
{pickedDoc && (
<div className="flex items-center gap-2 text-sm py-1.5 px-2 rounded-sm bg-muted/50">
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="truncate flex-1">
{pickedDoc.supplier_name ?? pickedDoc.file_name}
</span>
{pickedDoc.amount != null && (
<span className="text-xs text-muted-foreground tabular-nums shrink-0">
{formatCurrency(pickedDoc.amount, pickedDoc.currency ?? 'SEK')}
</span>
)}
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0"
aria-label={t('selected_remove')}
onClick={() => setPickedDoc(null)}
>
<X className="h-3 w-3" />
</Button>
</div>
)}
<Button
type="button"
variant="outline"
size="sm"
className="w-full"
disabled={isAttaching}
onClick={() => setInboxPickerOpen(true)}
>
<Inbox className="h-4 w-4 mr-2" />
{t('pick_existing')}
</Button>
</div>
<DialogFooter>
<Button variant="outline" disabled={isAttaching} onClick={() => onOpenChange(false)}>
{t('cancel')}
</Button>
<Button disabled={!selectedDocumentId || isAttaching} onClick={handleAttach}>
{isAttaching ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('attaching')}
</>
) : (
t('confirm')
)}
</Button>
</DialogFooter>
<InboxDocumentPicker
open={inboxPickerOpen}
onClose={() => setInboxPickerOpen(false)}
onSelect={(doc) => {
setPickedDoc(doc)
setUploadedFiles([])
}}
/>
</DialogContent>
</Dialog>
)
}
@@ -1,153 +0,0 @@
'use client'
import { useState } from 'react'
import { useTranslations } from 'next-intl'
import Link from 'next/link'
import { Paperclip, Loader2 } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { cn } from '@/lib/utils'
import { useToast } from '@/components/ui/use-toast'
import { openDeferredTab } from '@/lib/browser/deferred-tab'
import { useBranding } from '@/lib/branding/brand-context'
interface Props {
documentId: string | null | undefined
/** The booked tx's journal entry: link target when the underlag lives only
* at verifikat level (multi-doc entries, booking-dialog uploads). */
journalEntryId?: string | null
/** Underlag exists on the journal entry even though no doc is pinned to the
* transaction row (computeJeUnderlagStatus === 'has'). */
hasJeDoc?: boolean
/** Booked, requires underlag, has none (computeJeUnderlagStatus === 'missing'). */
missing?: boolean
/** Opens the attach dialog from the negative state. Omit for viewers:
* the badge then renders non-interactive. */
onAttach?: () => void
className?: string
}
const badgeClass = 'h-4 gap-1 px-1.5 py-0 text-[10px] font-normal'
// Enlarges the hit area beyond the 16px badge without shifting layout.
const hitAreaClass = 'shrink-0 p-1 -m-1'
/**
* Per-row underlag status for the /transactions lists.
*
* - Pinned doc (transactions.document_id): clickable badge that fetches a
* signed URL and opens the document in a new tab.
* - Verifikat-level doc only: same badge, links to the verifikat page (which
* lists all attachments: handles multi-doc without a per-row fetch).
* - Missing on a booked row: discreet outline badge that doubles as the
* attach affordance when onAttach is provided.
*/
export function TransactionAttachmentIndicator({
documentId,
journalEntryId,
hasJeDoc,
missing,
onAttach,
className,
}: Props) {
const t = useTranslations('tx_underlag')
const tCommon = useTranslations('common')
const { appName } = useBranding()
const { toast } = useToast()
const [isLoading, setIsLoading] = useState(false)
const handleOpen = async (e: React.MouseEvent) => {
e.stopPropagation()
e.preventDefault()
if (isLoading || !documentId) return
setIsLoading(true)
// 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/${documentId}`)
if (!res.ok) {
tab.close()
toast({ title: t('open_failed'), variant: 'destructive' })
return
}
const { data } = await res.json()
if (!data?.download_url || !tab.navigate(data.download_url)) {
tab.close()
toast({
title: t('open_failed'),
description: tab.blocked ? tCommon('popup_blocked_description', { appName }) : undefined,
variant: 'destructive',
})
}
} catch {
tab.close()
toast({ title: t('open_failed'), variant: 'destructive' })
} finally {
setIsLoading(false)
}
}
if (documentId) {
return (
<button
type="button"
onClick={handleOpen}
title={t('attached_title')}
aria-label={t('attached_aria')}
className={cn(hitAreaClass, className)}
>
<Badge variant="secondary" className={badgeClass}>
{isLoading ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<Paperclip className="h-3 w-3" />
)}
{t('attached_label')}
</Badge>
</button>
)
}
if (hasJeDoc && journalEntryId) {
return (
<Link
href={`/bookkeeping/${journalEntryId}`}
title={t('attached_title')}
aria-label={t('attached_aria')}
onClick={(e) => e.stopPropagation()}
className={cn(hitAreaClass, className)}
>
<Badge variant="secondary" className={badgeClass}>
<Paperclip className="h-3 w-3" />
{t('attached_label')}
</Badge>
</Link>
)
}
if (missing) {
const badge = (
<Badge variant="outline" className={cn(badgeClass, 'text-muted-foreground')}>
<Paperclip className="h-3 w-3" />
{t('missing_label')}
</Badge>
)
if (!onAttach) return <span className={cn('shrink-0', className)}>{badge}</span>
return (
<button
type="button"
onClick={(e) => {
e.stopPropagation()
e.preventDefault()
onAttach()
}}
title={t('missing_title')}
aria-label={t('missing_title')}
className={cn(hitAreaClass, className)}
>
{badge}
</button>
)
}
return null
}
@@ -1,464 +0,0 @@
'use client'
import { useMemo, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogVeil, useDashShellInert } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { formatCurrency, formatDate } from '@/lib/utils'
import { ArrowUpRight, ArrowDownRight, FileText, Inbox, X } from 'lucide-react'
import JournalEntryForm from '@/components/bookkeeping/JournalEntryForm'
import DocumentViewerPane from '@/components/bookkeeping/DocumentViewerPane'
import DocumentUploadZone from '@/components/bookkeeping/DocumentUploadZone'
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
import InboxDocumentPicker from '@/components/bookkeeping/InboxDocumentPicker'
import type { AvailableInboxDoc } from '@/components/bookkeeping/InboxDocumentPicker'
import type { FormLine } from '@/components/bookkeeping/JournalEntryForm'
import { resolveSekAmount, buildCurrencyMetadata } from '@/lib/bookkeeping/currency-utils'
import { applyTemplate } from '@/lib/bookkeeping/template-library'
import { proposalLinesToFormLines } from '@/lib/bookkeeping/proposal-lines'
import type { ProposalLine } from '@/lib/bookkeeping/proposal-lines'
import type { BookingTemplateLibrary } from '@/types'
import type { TransactionWithInvoice } from './transaction-types'
import { resolveAccount } from '@/lib/cash-accounts/resolve-account'
import { useCashAccounts } from '@/lib/reference-data/hooks'
interface TransactionBookingDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
transaction: TransactionWithInvoice | null
onBooked: (
transactionId: string,
journalEntryId: string,
attachedDocumentId?: string | null,
/** True when the transaction was LINKED to an existing voucher via the
* duplicate guard's match action: no new verifikat was created. */
matched?: boolean,
) => void
preselectedTemplate?: BookingTemplateLibrary | null
/**
* "Andra rader" hand-off from a proposal view (QuickReviewDialog): the
* COMPUTED lines the user was shown, prefilled for per-line editing. Takes
* precedence over preselectedTemplate. The settlement leg's account is
* swapped for the transaction's resolved cash account, same as the
* library-template path.
*/
proposalLines?: ProposalLine[] | null
/** Account number (string, e.g. '5460') to prefill on the counter line:
* set when the user picked an account from the template picker's "Konton"
* search results. Ignored when a preselectedTemplate is present. */
preselectedAccount?: string | null
}
function buildInitialLines(
transaction: TransactionWithInvoice,
bankLineDescription: string,
bankAccount: string = '1930',
counterAccount?: string | null,
): FormLine[] {
const sekAmount = Math.round(Math.abs(resolveSekAmount(
transaction.amount,
transaction.amount_sek,
transaction.currency,
transaction.exchange_rate
)) * 100) / 100
const amountStr = sekAmount.toFixed(2)
const isExpense = transaction.amount < 0
const isForeign = !!transaction.currency && transaction.currency !== 'SEK'
const currencyMeta = isForeign
? buildCurrencyMetadata(
transaction.currency,
Math.abs(transaction.amount),
transaction.exchange_rate
)
: {}
const bankLine: FormLine = {
account_number: bankAccount,
debit_amount: isExpense ? '' : amountStr,
credit_amount: isExpense ? amountStr : '',
line_description: bankLineDescription,
...currencyMeta,
}
const counterLine: FormLine = {
account_number: counterAccount ?? '',
debit_amount: isExpense ? amountStr : '',
credit_amount: isExpense ? '' : amountStr,
line_description: '',
}
return isExpense ? [bankLine, counterLine] : [bankLine, counterLine]
}
function buildInitialLinesFromTemplate(
transaction: TransactionWithInvoice,
template: BookingTemplateLibrary,
bankAccount: string = '1930',
): FormLine[] {
const sekAmount = Math.round(Math.abs(resolveSekAmount(
transaction.amount,
transaction.amount_sek,
transaction.currency,
transaction.exchange_rate
)) * 100) / 100
const lines = applyTemplate(template.lines, sekAmount)
const isForeign = !!transaction.currency && transaction.currency !== 'SEK'
const currencyMeta = isForeign
? buildCurrencyMetadata(
transaction.currency,
Math.abs(transaction.amount),
transaction.exchange_rate
)
: {}
return lines.map((line, i) => {
const raw = template.lines[i]
if (raw?.type === 'settlement') {
return { ...line, ...(isForeign ? currencyMeta : {}), account_number: bankAccount }
}
return line
})
}
export default function TransactionBookingDialog({
open,
onOpenChange,
transaction,
onBooked,
preselectedTemplate,
proposalLines,
preselectedAccount,
}: TransactionBookingDialogProps) {
const t = useTranslations('tx_booking_dialog')
const { toast } = useToast()
const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])
const [pickedInboxDocs, setPickedInboxDocs] = useState<AvailableInboxDoc[]>([])
const [inboxPickerOpen, setInboxPickerOpen] = useState(false)
// Settlement account for the bank line: resolved from the session-cached
// cash accounts (seeded by the dashboard layout), so the form below mounts
// on the first paint instead of after a /api/cash-accounts round trip on
// every open. null only while the list is genuinely still loading.
const { cashAccounts, isLoading: cashAccountsLoading } = useCashAccounts()
const { bankAccount, bankAccountName } = useMemo(() => {
if (!transaction || cashAccountsLoading) {
return { bankAccount: null as string | null, bankAccountName: null as string | null }
}
const { account } = resolveAccount(
cashAccounts,
transaction.cash_account_id ?? null,
transaction.currency ?? 'SEK',
)
// Use the matched account's own name instead of a generic label.
const matched =
cashAccounts.find((a) => a.id === transaction.cash_account_id) ??
cashAccounts.find((a) => a.ledger_account === account)
return { bankAccount: account, bankAccountName: matched?.name ?? null }
}, [transaction, cashAccounts, cashAccountsLoading])
// Non-modal dialog (see below): page modality is restored by hand so the
// agent sheet stays live. See useDashShellInert in components/ui/dialog.tsx.
useDashShellInert(open)
if (!transaction) return null
const isIncome = transaction.amount > 0
const handleBooked = async (transactionId: string, journalEntryId: string, matched = false) => {
// Link any attached documents to the new journal entry: freshly uploaded
// files, and existing inbox documents picked via InboxDocumentPicker. For
// picked docs, inbox_item_id stamps the inbox item as consumed so it drops
// out of the active inbox: see app/api/documents/[id]/link/route.ts.
// transaction_id additionally pins the doc to the transaction row so the
// /transactions list shows the underlag indicator (first linked doc wins).
const filesToLink = uploadedFiles.filter((f) => f.status === 'uploaded' && f.id)
let linkFailCount = 0
let firstLinkedDocId: string | null = null
for (const file of filesToLink) {
try {
const res = await fetch(`/api/documents/${file.id}/link`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
journal_entry_id: journalEntryId,
transaction_id: transactionId,
}),
})
if (!res.ok) linkFailCount++
else firstLinkedDocId ??= file.id ?? null
} catch {
linkFailCount++
}
}
for (const doc of pickedInboxDocs) {
try {
const res = await fetch(`/api/documents/${doc.document_id}/link`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
journal_entry_id: journalEntryId,
inbox_item_id: doc.inbox_item_id,
transaction_id: transactionId,
}),
})
if (!res.ok) linkFailCount++
else firstLinkedDocId ??= doc.document_id
} catch {
linkFailCount++
}
}
if (linkFailCount > 0) {
toast({
title: t('doc_link_failed_title'),
description: t('doc_link_failed_description', { count: linkFailCount }),
variant: 'destructive',
})
}
// The server pins only when the tx has no document_id yet (first linked
// doc wins): mirror that here so the optimistic state never claims a
// pin the server refused to swap.
const pinnedDocId = transaction.document_id ? null : firstLinkedDocId
if (pinnedDocId) {
// Same event AgentChat dispatches after uploads: flips the inbox card's
// paperclip optimistically without a refetch.
window.dispatchEvent(
new CustomEvent('Accounted:transaction-document-linked', {
detail: { transaction_id: transactionId, document_id: pinnedDocId },
}),
)
}
setUploadedFiles([])
setPickedInboxDocs([])
onBooked(transactionId, journalEntryId, pinnedDocId, matched)
}
// The receipt to show beside the form. A transaction may arrive with a
// pre-linked document; otherwise the user attaches one in-dialog (upload or
// inbox pick) and it appears here as soon as it's available.
const uploadedDoc = uploadedFiles.find((f) => f.status === 'uploaded' && f.id)
const pickedDoc = pickedInboxDocs[0]
const preexistingDocId = transaction.document_id ?? null
const inDialogDocId = uploadedDoc?.id ?? pickedDoc?.document_id ?? null
const currentDocId = preexistingDocId ?? inDialogDocId
const currentDocMime = preexistingDocId ? null : uploadedDoc?.file.type ?? null
const currentDocName = preexistingDocId
? null
: uploadedDoc?.fileName ?? pickedDoc?.file_name ?? null
return (
<Dialog open={open} onOpenChange={(o) => {
if (!o) {
setUploadedFiles([])
setPickedInboxDocs([])
setInboxPickerOpen(false)
}
onOpenChange(o)
}} modal={false}>
<DialogVeil />
<DialogContent
// Width caps at the space left of a docked agent sheet so the form's
// right edge, and the Granska button, never end up unreachable under
// the sheet (z-60 over z-50). --agent-sheet-w is docked-only, so with
// the sheet closed this is exactly the old max-w-6xl.
className="max-w-[min(72rem,calc(100vw-var(--agent-sheet-w,0px)))] max-h-[90vh] overflow-y-auto"
// Non-modal so the agent sheet (fixed z-[60], portaled outside this
// dialog) stays interactive beside a booking in progress; a click in
// its text field must not count as outside-dismissal. A half-booked
// transaction must also survive a stray Escape or backdrop click.
// Closing is explicit: the header X. Same convention as
// NewInvoiceDialog (which pairs non-modality with the inert effect
// above).
onEscapeKeyDown={(e) => e.preventDefault()}
onPointerDownOutside={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
>
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
<DialogDescription className="sr-only">
{t('description')}
</DialogDescription>
</DialogHeader>
{/* Transaction summary */}
<div className="flex items-center gap-3 rounded-lg border p-3">
<div
className={`h-9 w-9 rounded-full flex items-center justify-center flex-shrink-0 ${
isIncome
? 'text-success'
: 'text-destructive'
}`}
>
{isIncome ? (
<ArrowUpRight className="h-4 w-4" />
) : (
<ArrowDownRight className="h-4 w-4" />
)}
</div>
<div className="flex-1 min-w-0">
<p className="font-medium text-sm truncate">{transaction.description}</p>
<p className="text-xs text-muted-foreground">{formatDate(transaction.date)}</p>
</div>
<p className={`font-medium text-sm flex-shrink-0 ${isIncome ? 'text-success' : ''}`}>
{isIncome ? '+' : ''}
{formatCurrency(transaction.amount, transaction.currency)}
</p>
</div>
<div className="grid grid-cols-1 gap-6 lg:grid-cols-[minmax(0,2fr)_minmax(0,3fr)]">
{/* Underlag column: one coherent surface. Empty state sizes to its
content (dropzone + attached inbox-picker row) and top-aligns;
once a document exists the column takes the fixed viewer height
and stays sticky on desktop while the form scrolls. Stacks above
the form on smaller screens. */}
<div
className={
currentDocId
? 'flex h-[45vh] flex-col gap-3 lg:sticky lg:top-0 lg:h-[72vh] lg:self-start'
: 'flex flex-col gap-2 lg:sticky lg:top-0 lg:self-start'
}
>
{currentDocId ? (
<DocumentViewerPane
documentId={currentDocId}
mime={currentDocMime}
fileName={currentDocName}
className="min-h-0 flex-1"
/>
) : (
<DocumentUploadZone
files={uploadedFiles}
onFilesChange={setUploadedFiles}
/>
)}
{/* Attach controls: only when the transaction has no pre-linked
document (a pre-linked one is already the verifikat's underlag). */}
{!preexistingDocId && (
currentDocId ? (
<div className="shrink-0 space-y-2">
{pickedInboxDocs.length > 0 && (
<div className="space-y-1">
{pickedInboxDocs.map((doc) => (
<div
key={doc.document_id}
className="flex items-center gap-2 text-sm py-1.5 px-2 rounded-sm bg-muted/50"
>
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="truncate flex-1">
{doc.supplier_name ?? doc.file_name}
</span>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0"
aria-label={t('doc_picked_remove')}
onClick={() =>
setPickedInboxDocs((prev) =>
prev.filter((d) => d.document_id !== doc.document_id),
)
}
>
<X className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setInboxPickerOpen(true)}
>
<Inbox className="h-4 w-4 mr-2" />
{t('doc_pick_existing')}
</Button>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => {
setUploadedFiles([])
setPickedInboxDocs([])
}}
>
<X className="h-3.5 w-3.5 mr-1.5" />
{t('doc_clear')}
</Button>
</div>
</div>
) : (
/* Secondary intake path, rendered as the dropzone's footer so
"drop a file" and "pick from the inbox" read as one surface. */
<button
type="button"
onClick={() => setInboxPickerOpen(true)}
className="flex w-full items-center justify-center gap-2 rounded-lg border border-dashed border-muted-foreground/25 px-3 py-2 text-[13px] text-muted-foreground transition-colors duration-150 hover:border-primary/50 hover:text-foreground"
>
<Inbox className="h-4 w-4" />
<span>{t('doc_pick_existing_inline')}</span>
</button>
)
)}
</div>
{/* Booking form */}
<div className="space-y-4">
{bankAccount !== null && (
<JournalEntryForm
key={`${transaction.id}-${proposalLines && proposalLines.length > 0 ? 'proposal' : preselectedTemplate?.id ?? 'default'}-${preselectedAccount ?? 'none'}-${bankAccount}`}
embedded
initialLines={
proposalLines && proposalLines.length > 0
? proposalLinesToFormLines(proposalLines, {
settlementAccount: bankAccount,
currency: transaction.currency,
foreignAmount: Math.abs(transaction.amount),
exchangeRate: transaction.exchange_rate,
})
: preselectedTemplate
? buildInitialLinesFromTemplate(transaction, preselectedTemplate, bankAccount)
: buildInitialLines(transaction, bankAccountName ?? t('bank_line_description'), bankAccount, preselectedAccount)
}
initialDate={transaction.date}
initialDescription={transaction.description}
submitUrl={`/api/transactions/${transaction.id}/book`}
sourceType="bank_transaction"
sourceId={transaction.id}
// Series picker seeded from the bank account's own series
// (Inställningar → Bokföring → Verifikationsserie per bankkonto).
seriesPicker
cashAccountId={transaction.cash_account_id ?? null}
onEntryCreated={(entryId) => handleBooked(transaction.id, entryId)}
duplicateMatchTransaction={{
id: transaction.id,
cash_account_id: transaction.cash_account_id ?? null,
currency: transaction.currency ?? 'SEK',
}}
// Duplicate guard match: the bank line was linked to an existing
// voucher (no new entry). Reuse the booked flow so attached
// documents land on that verifikat and the row leaves the list.
onDuplicateMatched={(journalEntryId) => handleBooked(transaction.id, journalEntryId, true)}
/>
)}
</div>
</div>
<InboxDocumentPicker
open={inboxPickerOpen}
onClose={() => setInboxPickerOpen(false)}
onSelect={(doc) =>
setPickedInboxDocs((prev) =>
prev.some((d) => d.document_id === doc.document_id) ? prev : [...prev, doc],
)
}
/>
</DialogContent>
</Dialog>
)
}
-161
View File
@@ -1,161 +0,0 @@
'use client'
import { useEffect, useMemo } from 'react'
import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { format } from 'date-fns'
import { isSaneDateString } from '@/lib/utils'
import { useTranslations } from 'next-intl'
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 } from 'lucide-react'
import type { CreateTransactionInput, Currency } from '@/types'
interface TransactionFormProps {
onSubmit: (data: CreateTransactionInput) => Promise<void>
isLoading: boolean
}
const currencies: Currency[] = ['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']
export default function TransactionForm({ onSubmit, isLoading }: TransactionFormProps) {
const t = useTranslations('tx_form')
const schema = useMemo(
() =>
z.object({
date: z
.string()
.min(1, t('date_required'))
// Single source of truth for the date rule, shared with the server
// CreateTransactionSchema: rejects the 6-digit-year corruption a
// native date input can emit ('202403-02-05') plus impossible /
// out-of-range dates.
.refine((s) => !s || isSaneDateString(s), t('date_invalid')),
description: z.string().min(1, t('description_required')),
amount: z.number().refine((n) => n !== 0, t('amount_required')),
currency: z.enum(['SEK', 'EUR', 'USD', 'GBP', 'NOK', 'DKK']),
notes: z.string().optional(),
}),
[t]
)
type FormData = z.infer<typeof schema>
const {
register,
handleSubmit,
control,
setValue,
formState: { errors },
} = useForm<FormData>({
resolver: zodResolver(schema),
defaultValues: {
date: '',
description: '',
amount: 0,
currency: 'SEK',
notes: '',
},
})
// Set date default on client only to avoid hydration mismatch
useEffect(() => {
setValue('date', format(new Date(), 'yyyy-MM-dd'))
}, [])
const onFormSubmit = (data: FormData) => {
onSubmit({
date: data.date,
description: data.description,
amount: data.amount,
currency: data.currency,
notes: data.notes,
})
}
return (
<form onSubmit={handleSubmit(onFormSubmit)} className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="date">{t('date_label')}</Label>
<Input id="date" type="date" min="1900-01-01" max="2100-12-31" {...register('date')} />
{errors.date && (
<p className="text-sm text-destructive">{errors.date.message}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="currency">{t('currency_label')}</Label>
<Controller
name="currency"
control={control}
render={({ field }) => (
<Select value={field.value} onValueChange={field.onChange}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
{currencies.map((currency) => (
<SelectItem key={currency} value={currency}>
{currency}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="description">{t('description_label')}</Label>
<Input
id="description"
placeholder={t('description_placeholder')}
{...register('description')}
/>
{errors.description && (
<p className="text-sm text-destructive">{errors.description.message}</p>
)}
</div>
<div className="space-y-2">
<Label htmlFor="amount">{t('amount_label')}</Label>
<Input
id="amount"
type="number"
step="0.01"
placeholder={t('amount_placeholder')}
{...register('amount', { valueAsNumber: true })}
/>
{errors.amount && (
<p className="text-sm text-destructive">{errors.amount.message}</p>
)}
<p className="text-xs text-muted-foreground">
{t('amount_help')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="notes">{t('notes_label')}</Label>
<Textarea
id="notes"
placeholder={t('notes_placeholder')}
{...register('notes')}
/>
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('saving')}
</>
) : (
t('save')
)}
</Button>
</form>
)
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

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