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:
File diff suppressed because it is too large
Load Diff
@@ -1,387 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import type { ReconciliationAccount, ReconciliationItem } from '@/lib/reconciliation/schemas'
|
||||
import type { ReconciliationWindow } from './AccountOverview'
|
||||
import type { ResidualKind } from '@/lib/reconciliation/residual'
|
||||
|
||||
/**
|
||||
* "Matcha manuellt": the two-pane worksheet from the approved design. Left:
|
||||
* outside rows with no verifikat (bank transactions or skattekonto rows),
|
||||
* multi-select. Right: verifikat on the account with no outside row. The
|
||||
* right pane follows the left: with exactly ONE bank row picked it is
|
||||
* multi-select (one row settling several verifikat, the 1:N split of #1553);
|
||||
* with several rows picked it is single-select (N rows settling one
|
||||
* verifikat). The footer sums both sides; Koppla is enabled only when the
|
||||
* selection nets to zero, because the engine links N rows to ONE verifikat,
|
||||
* ONE row to N verifikat with slices summing to the row, and (for the
|
||||
* skattekonto) refuses a group whose sum the verifikat does not settle. A
|
||||
* non-zero difference is shown, not hidden: for the N:1 shape the residual
|
||||
* can be booked in the same gesture; a split must close exactly.
|
||||
*/
|
||||
|
||||
interface ManualMatchModeProps {
|
||||
account: ReconciliationAccount
|
||||
window: ReconciliationWindow
|
||||
onChanged: () => void
|
||||
}
|
||||
|
||||
const LIMIT = 200
|
||||
|
||||
export function ManualMatchMode({ account, window, onChanged }: ManualMatchModeProps) {
|
||||
const t = useTranslations('reconciliation')
|
||||
const { toast } = useToast()
|
||||
const [external, setExternal] = useState<ReconciliationItem[] | null>(null)
|
||||
const [ledger, setLedger] = useState<ReconciliationItem[] | null>(null)
|
||||
const [loadError, setLoadError] = useState(false)
|
||||
const [pickedExternal, setPickedExternal] = useState<Set<string>>(new Set())
|
||||
const [pickedEntries, setPickedEntries] = useState<Set<string>>(new Set())
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [residualKind, setResidualKind] = useState<ResidualKind | ''>('')
|
||||
|
||||
const base = `/api/reconciliation/accounts/${encodeURIComponent(account.account_key)}`
|
||||
const isSkv = account.kind === 'skattekonto'
|
||||
const currency = account.currency
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const qs = new URLSearchParams({ date_from: window.from, date_to: window.to, limit: String(LIMIT) })
|
||||
const [extRes, ledRes] = await Promise.all([
|
||||
fetch(`${base}/items?bucket=unmatched_external&${qs.toString()}`),
|
||||
fetch(`${base}/items?bucket=unmatched_ledger&${qs.toString()}`),
|
||||
])
|
||||
setLoadError(false)
|
||||
if (!extRes.ok || !ledRes.ok) {
|
||||
setLoadError(true)
|
||||
return
|
||||
}
|
||||
const ext = (await extRes.json()).data as { items: ReconciliationItem[] }
|
||||
const led = (await ledRes.json()).data as { items: ReconciliationItem[] }
|
||||
setExternal(ext.items)
|
||||
setLedger(led.items)
|
||||
} catch {
|
||||
setLoadError(true)
|
||||
}
|
||||
}, [base, window.from, window.to])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const externalSum = useMemo(
|
||||
() => roundOre((external ?? []).filter((i) => pickedExternal.has(i.item_id)).reduce((s, i) => s + i.amount, 0)),
|
||||
[external, pickedExternal],
|
||||
)
|
||||
const entries = useMemo(
|
||||
() => (ledger ?? []).filter((i) => pickedEntries.has(i.item_id)),
|
||||
[ledger, pickedEntries],
|
||||
)
|
||||
const entry = entries.length === 1 ? entries[0] : null
|
||||
const ledgerSum = roundOre(entries.reduce((s, i) => s + i.amount, 0))
|
||||
const difference = roundOre(externalSum - ledgerSum)
|
||||
// One bank row may settle several verifikat; several rows settle one.
|
||||
// N:M has no engine shape and the right pane never lets it be built.
|
||||
const splitMode = !isSkv && pickedExternal.size === 1
|
||||
const isSplit = entries.length > 1
|
||||
const canLink =
|
||||
pickedExternal.size > 0 &&
|
||||
entries.length > 0 &&
|
||||
!(pickedExternal.size > 1 && isSplit) &&
|
||||
Math.abs(difference) < 0.005 &&
|
||||
!busy
|
||||
|
||||
function toggleExternal(id: string) {
|
||||
setPickedExternal((prev) => {
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
// Leaving the one-row shape with several verifikat picked would build
|
||||
// an N:M selection: drop the verifikat side, the user re-picks one.
|
||||
if (next.size !== 1) {
|
||||
setPickedEntries((picked) => (picked.size > 1 ? new Set() : picked))
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
function toggleEntry(id: string) {
|
||||
setPickedEntries((prev) => {
|
||||
if (!splitMode) return prev.has(id) ? new Set() : new Set([id])
|
||||
const next = new Set(prev)
|
||||
if (next.has(id)) next.delete(id)
|
||||
else next.add(id)
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
async function link() {
|
||||
if (entries.length === 0 || pickedExternal.size === 0) return
|
||||
setBusy(true)
|
||||
try {
|
||||
// The split sends no allocations: each slice defaults to the voucher's
|
||||
// bank line and the engine refuses the set unless the slices sum to
|
||||
// the row, which is exactly the difference-is-zero gate above.
|
||||
const res = await fetch(`${base}/links`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
pairs: [{ external_ids: [...pickedExternal], journal_entry_ids: entries.map((e) => e.item_id) }],
|
||||
}),
|
||||
})
|
||||
const json = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
toast({ title: t('toast_failed'), description: getUserErrorMessage(json, { statusCode: res.status }), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
const applied = (json.data?.applied as unknown[] | undefined)?.length ?? 0
|
||||
const skipped = (json.data?.skipped as Array<{ message: string }> | undefined) ?? []
|
||||
if (applied === 0 && skipped.length > 0) {
|
||||
toast({ title: t('toast_failed'), description: skipped[0].message, variant: 'destructive' })
|
||||
} else if (isSplit) {
|
||||
toast({ title: t('toast_split_matched', { count: applied }) })
|
||||
} else {
|
||||
toast({
|
||||
title: skipped.length > 0 ? t('toast_matched_skipped', { applied, skipped: skipped.length }) : t('toast_matched', { applied }),
|
||||
})
|
||||
}
|
||||
setPickedExternal(new Set())
|
||||
setPickedEntries(new Set())
|
||||
await load()
|
||||
onChanged()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function bookResidual() {
|
||||
if (!entry || pickedExternal.size === 0 || !residualKind) return
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await fetch(`${base}/residual`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ external_ids: [...pickedExternal], journal_entry_id: entry.item_id, kind: residualKind }),
|
||||
})
|
||||
const json = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
toast({ title: t('toast_failed'), description: getUserErrorMessage(json, { statusCode: res.status }), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
toast({ title: t('toast_residual_booked', { amount: formatCurrency(Math.abs(Number(json.data?.residual_amount ?? 0)), currency) }) })
|
||||
setPickedExternal(new Set())
|
||||
setPickedEntries(new Set())
|
||||
setResidualKind('')
|
||||
await load()
|
||||
onChanged()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<AttnLine action={{ label: t('older_show'), onClick: () => void load() }}>{t('load_failed')}</AttnLine>
|
||||
)
|
||||
}
|
||||
if (!external || !ledger) {
|
||||
return (
|
||||
<div className="grid gap-6 lg:grid-cols-2" aria-busy>
|
||||
<Skeleton className="h-64 w-full" />
|
||||
<Skeleton className="h-64 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid gap-6 lg:grid-cols-2">
|
||||
{/* Left: outside rows, multi-select. */}
|
||||
<section aria-label={t(isSkv ? 'bucket_unmatched_external_skv' : 'bucket_unmatched_external_bank')}>
|
||||
<h2 className="mb-2 text-[11px] font-semibold uppercase tracking-[0.06em] text-muted-foreground">
|
||||
{t(isSkv ? 'bucket_unmatched_external_skv' : 'bucket_unmatched_external_bank')}
|
||||
<span className="ml-1.5 font-normal tabular-nums text-muted-foreground/70">{external.length}</span>
|
||||
</h2>
|
||||
{external.length === 0 ? (
|
||||
<p className="text-[13px] text-muted-foreground">{t('match_empty_left')}</p>
|
||||
) : (
|
||||
<table className="w-full text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={cn(TH_CLASS, 'w-8 px-2')} />
|
||||
<th className={cn(TH_CLASS, 'w-[96px]')}>{t('col_date')}</th>
|
||||
<th className={TH_CLASS}>{t('col_event')}</th>
|
||||
<th className={cn(TH_CLASS, 'w-[120px] text-right')}>{t('col_amount')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="stagger-enter">
|
||||
{external.map((item) => {
|
||||
const picked = pickedExternal.has(item.item_id)
|
||||
return (
|
||||
<tr
|
||||
key={item.item_id}
|
||||
onClick={() => toggleExternal(item.item_id)}
|
||||
className={cn('cursor-pointer', picked ? 'bg-secondary/60' : 'hover:bg-muted/40')}
|
||||
>
|
||||
<td className={cn(TD_CLASS, 'px-2')}>
|
||||
<Checkbox
|
||||
checked={picked}
|
||||
onCheckedChange={() => toggleExternal(item.item_id)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
aria-label={item.description}
|
||||
/>
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums text-muted-foreground')}>{formatDate(item.date)}</td>
|
||||
<td className={cn(TD_CLASS, 'max-w-0')}>
|
||||
<span className="block truncate" data-ph-mask title={item.description}>{item.description}</span>
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')} data-ph-mask>
|
||||
{formatCurrency(item.amount, currency)}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Right: verifikat without an outside row. Single-select for N:1,
|
||||
multi-select while exactly one bank row is picked (1:N). */}
|
||||
<section aria-label={t(isSkv ? 'bucket_unmatched_ledger_skv' : 'bucket_unmatched_ledger_bank')}>
|
||||
<h2 className="mb-2 text-[11px] font-semibold uppercase tracking-[0.06em] text-muted-foreground">
|
||||
{t(isSkv ? 'bucket_unmatched_ledger_skv' : 'bucket_unmatched_ledger_bank')}
|
||||
<span className="ml-1.5 font-normal tabular-nums text-muted-foreground/70">{ledger.length}</span>
|
||||
</h2>
|
||||
{splitMode && ledger.length > 0 && (
|
||||
<p className="mb-2 text-[12.5px] text-muted-foreground">{t('match_pick_vouchers')}</p>
|
||||
)}
|
||||
{ledger.length === 0 ? (
|
||||
<p className="text-[13px] text-muted-foreground">{t('match_empty_right')}</p>
|
||||
) : (
|
||||
<table className="w-full text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={cn(TH_CLASS, 'w-8 px-2')} />
|
||||
<th className={cn(TH_CLASS, 'w-[96px]')}>{t('col_date')}</th>
|
||||
<th className={cn(TH_CLASS, 'w-[90px]')}>{t('col_voucher')}</th>
|
||||
<th className={TH_CLASS}>{t('col_event')}</th>
|
||||
<th className={cn(TH_CLASS, 'w-[120px] text-right')}>{t('col_amount')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="stagger-enter">
|
||||
{ledger.map((item) => {
|
||||
const picked = pickedEntries.has(item.item_id)
|
||||
return (
|
||||
<tr
|
||||
key={item.item_id}
|
||||
onClick={() => toggleEntry(item.item_id)}
|
||||
className={cn('cursor-pointer', picked ? 'bg-secondary/60' : 'hover:bg-muted/40')}
|
||||
>
|
||||
<td className={cn(TD_CLASS, 'px-2')}>
|
||||
{splitMode ? (
|
||||
<Checkbox
|
||||
checked={picked}
|
||||
onCheckedChange={() => toggleEntry(item.item_id)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
aria-label={item.description}
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type="radio"
|
||||
name="manual-match-entry"
|
||||
checked={picked}
|
||||
onChange={() => toggleEntry(item.item_id)}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
aria-label={item.description}
|
||||
className="h-3.5 w-3.5 accent-foreground"
|
||||
/>
|
||||
)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums text-muted-foreground')}>{formatDate(item.date)}</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums')} data-ph-mask>
|
||||
{item.voucher_number != null
|
||||
? formatVoucher({ voucher_series: item.voucher_series, voucher_number: item.voucher_number })
|
||||
: item.item_id.slice(0, 8)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'max-w-0')}>
|
||||
<span className="block truncate" data-ph-mask title={item.description}>{item.description}</span>
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')} data-ph-mask>
|
||||
{formatCurrency(item.amount, currency)}
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{/* Footer: the arithmetic of the selection, and the one button. */}
|
||||
<div className="sticky bottom-0 flex flex-wrap items-center gap-x-6 gap-y-2 border-t border-border bg-background py-3 text-[13px]">
|
||||
<span className="tabular-nums" data-ph-mask>
|
||||
{t('match_selected_external', { count: pickedExternal.size, amount: formatCurrency(externalSum, currency) })}
|
||||
</span>
|
||||
<span className="tabular-nums" data-ph-mask>
|
||||
{isSplit
|
||||
? t('match_selected_entries', { count: entries.length, amount: formatCurrency(ledgerSum, currency) })
|
||||
: entry
|
||||
? t('match_selected_entry', { amount: formatCurrency(ledgerSum, currency) })
|
||||
: t('match_no_entry')}
|
||||
</span>
|
||||
<span
|
||||
className={cn('tabular-nums', Math.abs(difference) >= 0.005 && pickedExternal.size > 0 && entries.length > 0 ? 'text-warning' : 'text-muted-foreground')}
|
||||
data-ph-mask
|
||||
>
|
||||
{t('match_difference', { amount: formatCurrency(difference, currency) })}
|
||||
</span>
|
||||
{/* A split has no residual: the slices must sum to the row exactly
|
||||
(the engine refuses anything else), so the footer says so instead
|
||||
of offering a fee/interest booking against several verifikat. */}
|
||||
{Math.abs(difference) >= 0.005 && pickedExternal.size > 0 && isSplit && (
|
||||
<span className="text-[12.5px] text-muted-foreground">{t('match_hint_split')}</span>
|
||||
)}
|
||||
{Math.abs(difference) >= 0.005 && pickedExternal.size > 0 && entry && (
|
||||
isSkv ? (
|
||||
<span className="text-[12.5px] text-muted-foreground">{t('match_hint_residual_skv')}</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-2 text-[12.5px]">
|
||||
<label htmlFor="residual-kind" className="text-muted-foreground">{t('match_residual_label')}</label>
|
||||
<select
|
||||
id="residual-kind"
|
||||
value={residualKind}
|
||||
onChange={(e) => setResidualKind(e.target.value as ResidualKind | '')}
|
||||
className="h-8 rounded-lg border border-border bg-background px-2 text-[12.5px]"
|
||||
>
|
||||
<option value="">{t('match_residual_pick')}</option>
|
||||
{(difference < 0 ? ['bank_fee', 'interest_expense', 'rounding'] : ['interest_income', 'rounding']).map((k) => (
|
||||
<option key={k} value={k}>{t(`residual_${k}`)}</option>
|
||||
))}
|
||||
</select>
|
||||
<Button size="sm" variant="outline" onClick={() => void bookResidual()} disabled={!residualKind || busy} aria-busy={busy}>
|
||||
{t('match_residual_apply', { amount: formatCurrency(Math.abs(difference), currency) })}
|
||||
</Button>
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
<span className="ml-auto">
|
||||
<Button size="sm" onClick={() => void link()} disabled={!canLink} aria-busy={busy}>
|
||||
{isSplit ? t('match_apply_split', { count: entries.length }) : t('match_apply', { count: pickedExternal.size })}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,277 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useMemo, useRef } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Search, X } from 'lucide-react'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
|
||||
/**
|
||||
* Map the endpoint's 0-1 match confidence (attached only when candidates are
|
||||
* ranked for a specific transaction) to a strength label, so the user can tell
|
||||
* an exact-amount hit from a fuzzy guess before vouching for an immutable
|
||||
* verifikat. Returns null when no confidence was attached.
|
||||
*
|
||||
* Chips mark exceptions (convention 5): a strong hit is the normal,
|
||||
* auto-selected case and renders as muted text; only the fuzzy guesses that
|
||||
* deserve a second look get a chip.
|
||||
*/
|
||||
function confidenceMark(
|
||||
confidence: number | undefined,
|
||||
): { label: string; variant: 'secondary' | 'outline' | null } | null {
|
||||
if (confidence == null) return null
|
||||
if (confidence >= 0.85) return { label: 'Stark träff', variant: null }
|
||||
if (confidence >= 0.6) return { label: 'Trolig träff', variant: 'secondary' }
|
||||
return { label: 'Svag träff', variant: 'outline' }
|
||||
}
|
||||
|
||||
/**
|
||||
* A posted journal entry line on a cash account (e.g. 1930) not yet linked to
|
||||
* any bank transaction: a candidate for manual reconciliation. Mirrors the
|
||||
* `UnlinkedGLLine` returned by GET /api/reconciliation/bank/unmatched-entries.
|
||||
*
|
||||
* Defined here (not imported from lib/reconciliation/bank-reconciliation) so the
|
||||
* client bundle never pulls in that module's server-only dependencies (event
|
||||
* bus, match-log). The optional `confidence` is attached when the endpoint
|
||||
* ranks candidates for a specific transaction.
|
||||
*/
|
||||
export interface UnlinkedGLLine {
|
||||
line_id: string
|
||||
journal_entry_id: string
|
||||
debit_amount: number
|
||||
credit_amount: number
|
||||
line_description: string | null
|
||||
entry_date: string
|
||||
voucher_number: number
|
||||
voucher_series: string
|
||||
entry_description: string
|
||||
source_type: string
|
||||
confidence?: number
|
||||
/** How many bank transactions already settle this entry on the account being
|
||||
* matched (links on OTHER cash accounts, e.g. a transfer's outgoing leg,
|
||||
* don't count). > 0 means the voucher is already matched on this account:
|
||||
* surfaced (behind the "visa matchade" opt-in) so a second/third
|
||||
* transaction can be attached to it (N:1). */
|
||||
linked_transaction_count?: number
|
||||
}
|
||||
|
||||
interface MatchPickerProps {
|
||||
glLines: UnlinkedGLLine[]
|
||||
value: string
|
||||
onChange: (journalEntryId: string) => void
|
||||
disabled?: boolean
|
||||
placeholder?: string
|
||||
/**
|
||||
* Render the candidate list in normal document flow (always visible below the
|
||||
* search box) instead of as an absolutely-positioned overlay. Use inside a
|
||||
* Dialog or any `overflow-y-auto` container: an absolute dropdown is clipped at
|
||||
* the container's edge (the "klipper i dialogerna" bug: the list got cut off
|
||||
* and the dialog couldn't scroll to it). The reconciliation view keeps the
|
||||
* compact overlay (one picker per transaction row); the modal uses inline.
|
||||
*/
|
||||
inline?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Inline combobox for choosing a journal entry to match a bank transaction
|
||||
* against. The native <select> couldn't be searched, and the unmatched-GL list
|
||||
* routinely runs to hundreds of rows (historical SIE imports), so the old UX
|
||||
* forced users to scroll a giant unsorted dropdown. This picker filters by
|
||||
* voucher number, date, amount or description as the user types, and renders
|
||||
* the selected verifikation as a removable chip.
|
||||
*
|
||||
* Extracted from BankReconciliationView so the Transactions-page
|
||||
* MatchVoucherDialog can reuse the exact same picker.
|
||||
*/
|
||||
export function MatchVerifikationPicker({
|
||||
glLines,
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
placeholder = 'Sök ver.nr, datum, belopp eller beskrivning…',
|
||||
inline = false,
|
||||
}: MatchPickerProps) {
|
||||
// `open` controls the overlay dropdown only. In inline mode the list is always
|
||||
// rendered, so the setOpen() writes in the handlers below are harmless no-ops
|
||||
// there (the inline branch never reads `open`).
|
||||
const [open, setOpen] = useState(false)
|
||||
const [search, setSearch] = useState('')
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Inline mode shows the list permanently, so there's nothing to close on an
|
||||
// outside click: the overlay-only dismissal handler would be dead weight.
|
||||
if (inline || !open) return
|
||||
function onDocMouseDown(e: MouseEvent) {
|
||||
if (!containerRef.current?.contains(e.target as Node)) setOpen(false)
|
||||
}
|
||||
document.addEventListener('mousedown', onDocMouseDown)
|
||||
return () => document.removeEventListener('mousedown', onDocMouseDown)
|
||||
}, [open, inline])
|
||||
|
||||
const selected = glLines.find((l) => l.journal_entry_id === value) || null
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const q = search.trim().toLowerCase()
|
||||
const base = q.length === 0
|
||||
? glLines
|
||||
: glLines.filter((line) => {
|
||||
const amt = (line.debit_amount > 0 ? line.debit_amount : line.credit_amount).toString()
|
||||
return (
|
||||
formatVoucher(line).toLowerCase().includes(q) ||
|
||||
line.entry_date.toLowerCase().includes(q) ||
|
||||
amt.includes(q) ||
|
||||
(line.entry_description || '').toLowerCase().includes(q) ||
|
||||
(line.line_description || '').toLowerCase().includes(q)
|
||||
)
|
||||
})
|
||||
return base.slice(0, 25)
|
||||
}, [search, glLines])
|
||||
|
||||
if (selected) {
|
||||
const amount = selected.debit_amount > 0 ? selected.debit_amount : -selected.credit_amount
|
||||
// Suppress the match-strength badge on an already-matched verifikat so a
|
||||
// green "Stark träff" can't visually encourage an accidental double-match:
|
||||
// "Redan matchad" is the signal that matters there (N:1 stays opt-in).
|
||||
const strength =
|
||||
(selected.linked_transaction_count ?? 0) > 0 ? null : confidenceMark(selected.confidence)
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-border bg-secondary/40 px-3 py-2 text-sm">
|
||||
<span className="font-mono text-xs shrink-0">{formatVoucher(selected)}</span>
|
||||
<span className="text-muted-foreground shrink-0 tabular-nums">{formatDate(selected.entry_date)}</span>
|
||||
<span className="tabular-nums shrink-0">{formatCurrency(amount)}</span>
|
||||
<span className="truncate text-muted-foreground flex-1 min-w-0">{selected.entry_description}</span>
|
||||
{strength && (
|
||||
strength.variant ? (
|
||||
<Badge variant={strength.variant} className="shrink-0 text-[10px]">
|
||||
{strength.label}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="shrink-0 text-[11px] text-muted-foreground">{strength.label}</span>
|
||||
)
|
||||
)}
|
||||
{(selected.linked_transaction_count ?? 0) > 0 && (
|
||||
<Badge variant="secondary" className="shrink-0 text-[10px]">
|
||||
Redan matchad
|
||||
</Badge>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
size="icon"
|
||||
variant="ghost"
|
||||
className="h-6 w-6 shrink-0"
|
||||
onClick={() => onChange('')}
|
||||
disabled={disabled}
|
||||
aria-label="Avmarkera verifikation"
|
||||
>
|
||||
<X className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// The candidate list: shared by the inline and overlay layouts below.
|
||||
const listContent =
|
||||
filtered.length === 0 ? (
|
||||
<div className="px-3 py-4 text-sm text-muted-foreground text-center">
|
||||
Inga verifikationer matchar "{search}"
|
||||
</div>
|
||||
) : (
|
||||
<div className="max-h-72 overflow-y-auto">
|
||||
{filtered.map((line) => {
|
||||
const amount = line.debit_amount > 0 ? line.debit_amount : -line.credit_amount
|
||||
const strength =
|
||||
(line.linked_transaction_count ?? 0) > 0 ? null : confidenceMark(line.confidence)
|
||||
return (
|
||||
<button
|
||||
key={line.line_id}
|
||||
type="button"
|
||||
className="flex w-full items-center gap-3 px-3 py-2 text-left text-sm transition-colors hover:bg-secondary/60 focus:bg-secondary/60 focus:outline-none"
|
||||
onMouseDown={(e) => {
|
||||
// mousedown beats blur: without this the popover closes
|
||||
// before the click registers when the user has tabbed
|
||||
// through and uses keyboard.
|
||||
e.preventDefault()
|
||||
}}
|
||||
onClick={() => {
|
||||
onChange(line.journal_entry_id)
|
||||
setSearch('')
|
||||
setOpen(false)
|
||||
}}
|
||||
>
|
||||
<span className="font-mono text-xs shrink-0 w-12">{formatVoucher(line)}</span>
|
||||
<span className="text-muted-foreground shrink-0 tabular-nums w-24">{formatDate(line.entry_date)}</span>
|
||||
<span className="tabular-nums shrink-0 w-24 text-right">{formatCurrency(amount)}</span>
|
||||
<span className="truncate text-muted-foreground flex-1">
|
||||
{line.line_description || line.entry_description}
|
||||
</span>
|
||||
{strength && (
|
||||
strength.variant ? (
|
||||
<Badge variant={strength.variant} className="shrink-0 text-[10px]">
|
||||
{strength.label}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="shrink-0 text-[11px] text-muted-foreground">{strength.label}</span>
|
||||
)
|
||||
)}
|
||||
{(line.linked_transaction_count ?? 0) > 0 && (
|
||||
<Badge variant="secondary" className="shrink-0 text-[10px]">
|
||||
Matchad
|
||||
</Badge>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{glLines.length > filtered.length && (
|
||||
<div className="px-3 py-2 text-[11px] text-muted-foreground border-t border-border bg-secondary/30">
|
||||
Visar {filtered.length} av {glLines.length}: sök för att filtrera fler.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
const searchBox = (
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value)
|
||||
setOpen(true)
|
||||
}}
|
||||
onFocus={() => setOpen(true)}
|
||||
placeholder={placeholder}
|
||||
disabled={disabled}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
// Inline: list lives in normal flow so it can never be clipped by a scroll
|
||||
// container (Dialog). The enclosing modal scrolls if the whole thing is tall.
|
||||
if (inline) {
|
||||
return (
|
||||
<div ref={containerRef} className="space-y-2">
|
||||
{searchBox}
|
||||
<div className="overflow-hidden rounded-lg border border-border bg-popover">
|
||||
{listContent}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Overlay: compact, opens on focus, dismisses on outside click. Right for the
|
||||
// reconciliation view's one-picker-per-row layout.
|
||||
return (
|
||||
<div ref={containerRef} className="relative">
|
||||
{searchBox}
|
||||
{open && (
|
||||
<div className="absolute z-20 mt-1 w-full overflow-hidden rounded-lg border border-border bg-popover shadow-[var(--shadow-md)]">
|
||||
{listContent}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { TH_CLASS, TD_CLASS, QUIET_LINK_CLASS } from '@/components/ui/dry-table'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
|
||||
|
||||
/**
|
||||
* The automatic matcher's dry-run preview, inline on the Avstämning page:
|
||||
* candidate transaction↔verifikat pairs with confidence, applied per row or
|
||||
* all strong ones at once. Same endpoint and same server-side intersection
|
||||
* guard as the old bank view; this is only the surface. Pairs at or above
|
||||
* STRONG_CONFIDENCE mirror the old view's preselect floor.
|
||||
*/
|
||||
|
||||
export const STRONG_CONFIDENCE = 0.85
|
||||
|
||||
export interface MatcherMatch {
|
||||
transaction_id: string
|
||||
transaction_date: string
|
||||
transaction_description: string
|
||||
transaction_amount: number
|
||||
journal_entry_id: string
|
||||
voucher_number: number
|
||||
voucher_series: string
|
||||
entry_date: string
|
||||
entry_description: string
|
||||
method: string
|
||||
confidence: number
|
||||
}
|
||||
|
||||
interface MatcherPreviewProps {
|
||||
matches: MatcherMatch[]
|
||||
currency: string
|
||||
busy: boolean
|
||||
onApply: (pairs: MatcherMatch[], strongOnly: boolean) => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
export function MatcherPreview({ matches, currency, busy, onApply, onClose }: MatcherPreviewProps) {
|
||||
const t = useTranslations('reconciliation')
|
||||
const strong = matches.filter((m) => m.confidence >= STRONG_CONFIDENCE)
|
||||
|
||||
if (matches.length === 0) {
|
||||
return (
|
||||
<p className="text-[13px] text-muted-foreground">
|
||||
{t('matcher_none')}{' '}
|
||||
<button type="button" onClick={onClose} className={QUIET_LINK_CLASS}>
|
||||
{t('matcher_close')}
|
||||
</button>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<p className="text-[13px]">
|
||||
{t('matcher_title', { count: matches.length })}
|
||||
</p>
|
||||
{strong.length > 0 && (
|
||||
<Button size="sm" onClick={() => onApply(strong, true)} disabled={busy}>
|
||||
{t('matcher_apply_strong', { count: strong.length })}
|
||||
</Button>
|
||||
)}
|
||||
<button type="button" onClick={onClose} disabled={busy} className={cn(QUIET_LINK_CLASS, 'ml-auto')}>
|
||||
{t('matcher_close')}
|
||||
</button>
|
||||
</div>
|
||||
<div className="-mx-4 overflow-x-auto sm:mx-0">
|
||||
<table className="w-full text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={cn(TH_CLASS, 'w-[110px]')}>{t('col_date')}</th>
|
||||
<th className={TH_CLASS}>{t('col_event')}</th>
|
||||
<th className={cn(TH_CLASS, 'w-[140px] text-right')}>{t('col_amount')}</th>
|
||||
<th className={cn(TH_CLASS, 'w-[34%]')}>{t('col_proposal')}</th>
|
||||
<th className={cn(TH_CLASS, 'w-[120px]')} />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="stagger-enter">
|
||||
{matches.map((m) => (
|
||||
<tr key={`${m.transaction_id}:${m.journal_entry_id}`} className="group">
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums text-muted-foreground')}>
|
||||
{formatDate(m.transaction_date)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'max-w-0')}>
|
||||
<span className="block truncate" data-ph-mask title={m.transaction_description}>
|
||||
{m.transaction_description}
|
||||
</span>
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap text-right tabular-nums')} data-ph-mask>
|
||||
{formatCurrency(m.transaction_amount, currency)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'max-w-0')}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="tabular-nums" data-ph-mask>
|
||||
{formatVoucher({ voucher_series: m.voucher_series, voucher_number: m.voucher_number })}
|
||||
</span>
|
||||
<span className="text-[11.5px] tabular-nums text-muted-foreground">{formatDate(m.entry_date)}</span>
|
||||
<span
|
||||
className={cn(
|
||||
'whitespace-nowrap rounded-full px-1.5 py-px text-[10.5px]',
|
||||
m.confidence >= STRONG_CONFIDENCE
|
||||
? 'bg-success/10 text-success'
|
||||
: 'bg-muted text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{m.confidence >= STRONG_CONFIDENCE
|
||||
? t('matcher_strong')
|
||||
: t('confidence', { percent: Math.round(m.confidence * 100) })}
|
||||
</span>
|
||||
</span>
|
||||
<span className="block truncate text-[12px] text-muted-foreground" data-ph-mask>
|
||||
{m.entry_description}
|
||||
</span>
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'text-right')}>
|
||||
<Button size="sm" variant="outline" onClick={() => onApply([m], false)} disabled={busy}>
|
||||
{t('row_match')}
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,215 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { Fragment, useState } from 'react'
|
||||
import Image from 'next/image'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { ChevronDown, ChevronRight } from 'lucide-react'
|
||||
import { cn, formatDate } from '@/lib/utils'
|
||||
import type { ReconciliationAccount } from '@/lib/reconciliation/schemas'
|
||||
|
||||
/**
|
||||
* The account rail of the Avstämning page: one row per account with an
|
||||
* outside truth (bank accounts, the skattekonto), logo or monogram, the
|
||||
* account number, when its outside side was last fetched, and a status dot.
|
||||
* The rest of the balance sheet follows under its own label: those accounts
|
||||
* have no feed, so their row says whether they are signed off instead.
|
||||
* Selection is URL-owned (?account=) by the workspace; the rail only reports.
|
||||
*/
|
||||
|
||||
const DOT_CLASS: Record<NonNullable<ReconciliationAccount['status']>['state'] | 'unknown', string> = {
|
||||
reconciled: 'bg-success',
|
||||
open: 'bg-warning',
|
||||
stale: 'bg-warning',
|
||||
not_configured: 'bg-muted-foreground/40',
|
||||
unknown: 'bg-muted-foreground/40',
|
||||
}
|
||||
|
||||
function monogram(name: string): string {
|
||||
const words = name.trim().split(/\s+/).filter(Boolean)
|
||||
if (words.length === 0) return '?'
|
||||
if (words.length === 1) return words[0].slice(0, 2).toUpperCase()
|
||||
return (words[0][0] + words[1][0]).toUpperCase()
|
||||
}
|
||||
|
||||
export function AccountLogo({ account, className }: { account: ReconciliationAccount; className?: string }) {
|
||||
if (account.logo_url) {
|
||||
return (
|
||||
<Image
|
||||
src={account.logo_url}
|
||||
alt=""
|
||||
width={20}
|
||||
height={20}
|
||||
className={cn('h-5 w-5 shrink-0 rounded-sm object-contain', className)}
|
||||
unoptimized
|
||||
/>
|
||||
)
|
||||
}
|
||||
const label = account.kind === 'manual' ? account.account_number.slice(0, 2) : monogram(account.name)
|
||||
return (
|
||||
<span
|
||||
aria-hidden
|
||||
className={cn(
|
||||
'flex h-5 w-5 shrink-0 items-center justify-center rounded-sm bg-secondary text-[9px] font-semibold tracking-tight text-secondary-foreground tabular-nums',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
interface ReconciliationRailProps {
|
||||
accounts: ReconciliationAccount[]
|
||||
selectedKey: string | null
|
||||
onSelect: (accountKey: string) => void
|
||||
/** Rendered under the list: the way to the pärm the accounts feed. */
|
||||
footer?: React.ReactNode
|
||||
}
|
||||
|
||||
const MANUAL_OPEN_STORAGE_KEY = 'Accounted:recon-rail-manual-open'
|
||||
|
||||
export function ReconciliationRail({ accounts, selectedKey, onSelect, footer }: ReconciliationRailProps) {
|
||||
const t = useTranslations('reconciliation')
|
||||
const fed = accounts.filter((a) => a.kind !== 'manual')
|
||||
const manual = accounts.filter((a) => a.kind === 'manual')
|
||||
const selectedIsManual = selectedKey?.startsWith('manual:') ?? false
|
||||
|
||||
// The manual group folds: a migrated company has twenty-odd balance
|
||||
// accounts, and the bank rows must stay in view. It opens when a manual
|
||||
// account is selected and otherwise remembers the last choice per browser.
|
||||
const [manualOpen, setManualOpen] = useState<boolean>(() => {
|
||||
if (selectedIsManual) return true
|
||||
try {
|
||||
return window.localStorage.getItem(MANUAL_OPEN_STORAGE_KEY) === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
})
|
||||
// Derived, not synced: the selected row must stay visible.
|
||||
const showManual = manualOpen || selectedIsManual
|
||||
const toggleManual = () => {
|
||||
setManualOpen((open) => {
|
||||
try {
|
||||
window.localStorage.setItem(MANUAL_OPEN_STORAGE_KEY, open ? '0' : '1')
|
||||
} catch {
|
||||
// Per-browser convenience only.
|
||||
}
|
||||
return !open
|
||||
})
|
||||
}
|
||||
const manualUnsigned = manual.filter((a) => a.status?.state !== 'reconciled').length
|
||||
|
||||
const stateLabel = (account: ReconciliationAccount): string => {
|
||||
const state = account.status?.state ?? 'unknown'
|
||||
if (account.kind === 'manual' && state === 'open') return t('state_unsigned')
|
||||
return t(`state_${state === 'unknown' ? 'not_configured' : state}`)
|
||||
}
|
||||
|
||||
const subLine = (account: ReconciliationAccount): string => {
|
||||
if (account.signed_off_through) return t('rail_signed_off', { date: formatDate(account.signed_off_through) })
|
||||
if (account.kind === 'manual') return t('rail_never_signed')
|
||||
const synced = account.source.synced_at
|
||||
return synced ? t('rail_synced', { date: formatDate(synced) }) : t('rail_never_synced')
|
||||
}
|
||||
|
||||
// A manual account with nothing to compare against is not a problem, just
|
||||
// not attested yet: neutral until it is signed or a specification differs.
|
||||
const dotState = (account: ReconciliationAccount): keyof typeof DOT_CLASS => {
|
||||
const state = account.status?.state ?? 'unknown'
|
||||
if (account.kind === 'manual' && state === 'open' && account.status?.unexplained_difference == null) return 'unknown'
|
||||
return state
|
||||
}
|
||||
|
||||
const renderRow = (account: ReconciliationAccount) => {
|
||||
const selected = account.account_key === selectedKey
|
||||
const state = dotState(account)
|
||||
const open = account.status
|
||||
? account.status.open_counts.proposed +
|
||||
account.status.open_counts.unmatched_external +
|
||||
account.status.open_counts.unmatched_ledger
|
||||
: 0
|
||||
return (
|
||||
<li key={account.account_key}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(account.account_key)}
|
||||
aria-current={selected ? 'page' : undefined}
|
||||
className={cn(
|
||||
'group flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left transition-colors duration-150',
|
||||
selected ? 'bg-secondary' : 'hover:bg-muted/60',
|
||||
account.superseded_by && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
<AccountLogo account={account} />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="truncate text-[13px] font-medium text-foreground" data-ph-mask>
|
||||
{account.name}
|
||||
</span>
|
||||
{account.superseded_by && (
|
||||
<span className="rounded-full bg-muted px-1.5 py-px text-[10px] text-muted-foreground">
|
||||
{t('rail_superseded')}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="block truncate text-[11.5px] text-muted-foreground tabular-nums">
|
||||
<span data-ph-mask>{account.account_number}</span>
|
||||
{' · '}
|
||||
{subLine(account)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="flex shrink-0 items-center gap-1.5">
|
||||
{open > 0 && (
|
||||
<span className="text-[11px] tabular-nums text-muted-foreground" data-ph-mask>
|
||||
{open}
|
||||
</span>
|
||||
)}
|
||||
<span
|
||||
aria-label={stateLabel(account)}
|
||||
title={stateLabel(account)}
|
||||
className={cn('h-2 w-2 rounded-full', DOT_CLASS[state])}
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<nav aria-label={t('rail_heading')} className="stagger-enter">
|
||||
<ul className="flex flex-col gap-0.5">
|
||||
{fed.map(renderRow)}
|
||||
{manual.length > 0 && (
|
||||
<Fragment>
|
||||
<li className={cn(fed.length > 0 && 'mt-3')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleManual}
|
||||
aria-expanded={showManual}
|
||||
aria-controls="recon-rail-manual"
|
||||
className="flex w-full items-center gap-1.5 rounded-lg px-3 py-1.5 text-left text-[10.5px] font-semibold uppercase tracking-[0.08em] text-muted-foreground hover:bg-muted/60"
|
||||
>
|
||||
{showManual ? (
|
||||
<ChevronDown className="h-3 w-3 shrink-0" aria-hidden="true" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3 shrink-0" aria-hidden="true" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">{t('rail_group_manual')}</span>
|
||||
<span className="shrink-0 normal-case tracking-normal tabular-nums" data-ph-mask>
|
||||
{manualUnsigned > 0 ? t('rail_group_manual_unsigned', { count: manualUnsigned, total: manual.length }) : String(manual.length)}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
{showManual && (
|
||||
<Fragment>
|
||||
<li id="recon-rail-manual" className="sr-only" aria-hidden />
|
||||
{manual.map(renderRow)}
|
||||
</Fragment>
|
||||
)}
|
||||
</Fragment>
|
||||
)}
|
||||
</ul>
|
||||
{footer}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -1,179 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Paperclip } from 'lucide-react'
|
||||
import { QUIET_LINK_CLASS, HOVER_REVEAL_CLASS } from '@/components/ui/dry-table'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { cn, formatDate } from '@/lib/utils'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { exceedsHostedUploadLimit, isShrinkableImage, tooLargeMessage } from '@/lib/documents/upload-size'
|
||||
import { shrinkImageForUpload } from '@/lib/documents/shrink-image'
|
||||
import type { ReconciliationAttachment } from '@/lib/reconciliation/schemas'
|
||||
|
||||
/**
|
||||
* The underlag of one account's balansdag: the files it was reconciled
|
||||
* against (kontoutdrag, engagemangsbesked, reskontralista, inventering).
|
||||
* Lists what is attached for the date, attaches more, and lets a member
|
||||
* withdraw a wrong file (a stamp, the file stays). Reads and writes the
|
||||
* attachments routes under /api/reconciliation/accounts/{key}/attachments.
|
||||
*/
|
||||
|
||||
interface ReconciliationUnderlagProps {
|
||||
accountKey: string
|
||||
/** The balansdag the files document: the sign-off date in play. */
|
||||
throughDate: string
|
||||
canWrite?: boolean
|
||||
}
|
||||
|
||||
const ACCEPT = 'application/pdf,image/jpeg,image/png,image/webp'
|
||||
|
||||
function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} kB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
export function ReconciliationUnderlag({ accountKey, throughDate, canWrite = true }: ReconciliationUnderlagProps) {
|
||||
const t = useTranslations('reconciliation_underlag')
|
||||
const { toast } = useToast()
|
||||
const [attachments, setAttachments] = useState<ReconciliationAttachment[] | null>(null)
|
||||
const [busy, setBusy] = useState<string | null>(null)
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const base = `/api/reconciliation/accounts/${encodeURIComponent(accountKey)}/attachments`
|
||||
|
||||
const load = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch(`${base}?through_date=${throughDate}`)
|
||||
if (!res.ok) {
|
||||
setAttachments([])
|
||||
return
|
||||
}
|
||||
const json = await res.json()
|
||||
setAttachments((json.data?.attachments ?? []) as ReconciliationAttachment[])
|
||||
} catch {
|
||||
setAttachments([])
|
||||
}
|
||||
}, [base, throughDate])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
async function upload(files: FileList | null) {
|
||||
if (!files || files.length === 0) return
|
||||
setBusy('upload')
|
||||
try {
|
||||
for (const original of Array.from(files)) {
|
||||
// Hosted functions refuse bodies over 4.5 MB before the route runs
|
||||
// (no logs, no message); shrink images, refuse the rest with a reason.
|
||||
let file = original
|
||||
if (exceedsHostedUploadLimit(file.size) && isShrinkableImage(file.type)) {
|
||||
file = await shrinkImageForUpload(file)
|
||||
}
|
||||
if (exceedsHostedUploadLimit(file.size)) {
|
||||
toast({ title: t('too_large_title'), description: tooLargeMessage(file.size), variant: 'destructive' })
|
||||
continue
|
||||
}
|
||||
const form = new FormData()
|
||||
form.set('file', file)
|
||||
form.set('through_date', throughDate)
|
||||
const res = await fetch(base, { method: 'POST', body: form })
|
||||
const json = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
toast({ title: t('upload_failed'), description: getUserErrorMessage(json, { statusCode: res.status }), variant: 'destructive' })
|
||||
continue
|
||||
}
|
||||
toast({ title: t('attached', { name: file.name }) })
|
||||
}
|
||||
await load()
|
||||
} finally {
|
||||
setBusy(null)
|
||||
if (inputRef.current) inputRef.current.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(attachment: ReconciliationAttachment) {
|
||||
setBusy(attachment.id)
|
||||
try {
|
||||
const res = await fetch(`${base}/${attachment.id}`, { method: 'DELETE' })
|
||||
const json = await res.json().catch(() => ({}))
|
||||
if (!res.ok) {
|
||||
toast({ title: t('remove_failed'), description: getUserErrorMessage(json, { statusCode: res.status }), variant: 'destructive' })
|
||||
return
|
||||
}
|
||||
toast({ title: t('removed', { name: attachment.file_name }) })
|
||||
await load()
|
||||
} finally {
|
||||
setBusy(null)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-label={t('heading')} className="space-y-1.5">
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
|
||||
<h3 className="text-[11px] font-medium uppercase tracking-[0.07em] text-muted-foreground">
|
||||
{t('heading_dated', { date: formatDate(throughDate) })}
|
||||
</h3>
|
||||
{attachments !== null && attachments.length === 0 && (
|
||||
<span className="text-[12.5px] text-muted-foreground" title={t('empty')}>
|
||||
{t('empty_short')}
|
||||
</span>
|
||||
)}
|
||||
{canWrite && (
|
||||
<>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={ACCEPT}
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => void upload(e.target.files)}
|
||||
aria-label={t('attach')}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => inputRef.current?.click()}
|
||||
disabled={busy !== null}
|
||||
aria-busy={busy === 'upload'}
|
||||
className={cn(QUIET_LINK_CLASS, 'inline-flex items-center gap-1')}
|
||||
>
|
||||
<Paperclip className="h-3 w-3" aria-hidden="true" />
|
||||
{t('attach')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{attachments === null || attachments.length === 0 ? null : (
|
||||
<ul className="max-w-[560px] divide-y divide-border/60 text-[13px]">
|
||||
{attachments.map((a) => (
|
||||
<li key={a.id} className="group flex items-center gap-3 py-1.5">
|
||||
<a
|
||||
href={`${base}/${a.id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={cn(QUIET_LINK_CLASS, 'min-w-0 flex-1 truncate')}
|
||||
data-ph-mask
|
||||
>
|
||||
{a.file_name}
|
||||
</a>
|
||||
<span className="shrink-0 text-[11.5px] tabular-nums text-muted-foreground">
|
||||
{formatSize(a.size_bytes)} · {formatDate(a.uploaded_at)}
|
||||
</span>
|
||||
{canWrite && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void remove(a)}
|
||||
disabled={busy !== null}
|
||||
className={cn(QUIET_LINK_CLASS, HOVER_REVEAL_CLASS, 'shrink-0')}
|
||||
>
|
||||
{t('remove')}
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Scale } from 'lucide-react'
|
||||
import { QUIET_LINK_CLASS } from '@/components/ui/dry-table'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { HelpPopover } from '@/components/ui/help-popover'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { FyPicker } from '@/components/common/FyPicker'
|
||||
import { ReportDateRange, type DateRangeValue } from '@/components/common/ReportDateRange'
|
||||
import { SegmentedControl } from '@/components/ui/segmented-control'
|
||||
import type { ReconciliationAccount } from '@/lib/reconciliation/schemas'
|
||||
import type { FiscalPeriod } from '@/types'
|
||||
import { ReconciliationRail } from './ReconciliationRail'
|
||||
import { AccountOverview, type ReconciliationWindow } from './AccountOverview'
|
||||
import { ManualMatchMode } from './ManualMatchMode'
|
||||
|
||||
/**
|
||||
* /reconciliation: one page for every account with an outside truth. The
|
||||
* rail on the left lists the accounts (bank accounts, the skattekonto) with
|
||||
* their status; the body shows the selected account's bridge and the rows
|
||||
* behind it. Selection lives in the URL (?account=) so a link lands on the
|
||||
* right account and a reload keeps it.
|
||||
*
|
||||
* The period (räkenskapsår + range within it) scopes the bank bridge and the
|
||||
* item windows and sets the default sign-off date. It keeps its own preset
|
||||
* memory, separate from the reports: reconciling is a monthly ritual, so it
|
||||
* opens on this month rather than on whatever range a report left behind.
|
||||
*/
|
||||
|
||||
const FY_STORAGE_KEY_PREFIX = 'Accounted:recon-fy:'
|
||||
const RANGE_STORAGE_KEY_PREFIX = 'Accounted:recon-page-range-preset:'
|
||||
|
||||
interface ReconciliationWorkspaceProps {
|
||||
initialPeriods: FiscalPeriod[]
|
||||
initialCompanyId: string | null
|
||||
}
|
||||
|
||||
export function ReconciliationWorkspace({ initialPeriods, initialCompanyId }: ReconciliationWorkspaceProps) {
|
||||
const t = useTranslations('reconciliation')
|
||||
const tParm = useTranslations('bokslutsbilagor')
|
||||
const router = useRouter()
|
||||
const pathname = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
const [accounts, setAccounts] = useState<ReconciliationAccount[] | null>(null)
|
||||
const [loadError, setLoadError] = useState(false)
|
||||
const [periodId, setPeriodId] = useState<string | null>(null)
|
||||
const [periodBounds, setPeriodBounds] = useState<{ start: string; end: string } | null>(null)
|
||||
const [dateRange, setDateRange] = useState<DateRangeValue>({})
|
||||
|
||||
// The effective window: the range within the period, defaulting to the
|
||||
// period bounds. Null until the period picker has resolved.
|
||||
const window = useMemo<ReconciliationWindow | null>(() => {
|
||||
if (!periodBounds) return null
|
||||
return {
|
||||
from: dateRange.fromDate ?? periodBounds.start,
|
||||
to: dateRange.toDate ?? periodBounds.end,
|
||||
}
|
||||
}, [periodBounds, dateRange])
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!window) return
|
||||
try {
|
||||
const qs = new URLSearchParams({ date_from: window.from, date_to: window.to })
|
||||
const res = await fetch(`/api/reconciliation/accounts?${qs.toString()}`)
|
||||
setLoadError(false)
|
||||
if (!res.ok) {
|
||||
setLoadError(true)
|
||||
return
|
||||
}
|
||||
const json = await res.json()
|
||||
setAccounts((json.data?.accounts ?? []) as ReconciliationAccount[])
|
||||
} catch {
|
||||
setLoadError(true)
|
||||
}
|
||||
}, [window])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const requestedKey = searchParams.get('account')
|
||||
const mode: 'overview' | 'match' = searchParams.get('mode') === 'match' ? 'match' : 'overview'
|
||||
const setMode = useCallback(
|
||||
(next: 'overview' | 'match') => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
if (next === 'match') params.set('mode', 'match')
|
||||
else params.delete('mode')
|
||||
router.replace(`${pathname}?${params.toString()}`, { scroll: false })
|
||||
},
|
||||
[pathname, router, searchParams],
|
||||
)
|
||||
const selected = useMemo(() => {
|
||||
if (!accounts || accounts.length === 0) return null
|
||||
return (
|
||||
accounts.find((a) => a.account_key === requestedKey) ??
|
||||
accounts.find((a) => !a.superseded_by) ??
|
||||
accounts[0]
|
||||
)
|
||||
}, [accounts, requestedKey])
|
||||
|
||||
const select = useCallback(
|
||||
(accountKey: string) => {
|
||||
const params = new URLSearchParams(searchParams.toString())
|
||||
params.set('account', accountKey)
|
||||
router.replace(`${pathname}?${params.toString()}`, { scroll: false })
|
||||
},
|
||||
[pathname, router, searchParams],
|
||||
)
|
||||
|
||||
const header = (
|
||||
<PageHeader
|
||||
title={t('title')}
|
||||
help={
|
||||
<HelpPopover>
|
||||
<p>{t('help_text')}</p>
|
||||
</HelpPopover>
|
||||
}
|
||||
action={
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
<FyPicker
|
||||
value={periodId}
|
||||
onChange={(id, period) => {
|
||||
setPeriodId(id)
|
||||
setPeriodBounds(period ? { start: period.period_start, end: period.period_end } : null)
|
||||
setDateRange({})
|
||||
}}
|
||||
includeAllOption={false}
|
||||
hideFuturePeriods
|
||||
initialPeriods={initialPeriods}
|
||||
initialCompanyId={initialCompanyId}
|
||||
storageKeyPrefix={FY_STORAGE_KEY_PREFIX}
|
||||
/>
|
||||
{periodBounds && (
|
||||
<ReportDateRange
|
||||
periodStart={periodBounds.start}
|
||||
periodEnd={periodBounds.end}
|
||||
value={dateRange}
|
||||
onChange={setDateRange}
|
||||
defaultPreset="this_month"
|
||||
storageKeyPrefix={RANGE_STORAGE_KEY_PREFIX}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)
|
||||
|
||||
if (loadError) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{header}
|
||||
<AttnLine action={{ label: t('older_show'), onClick: () => void load() }}>{t('load_failed')}</AttnLine>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (accounts === null || !window) {
|
||||
return (
|
||||
<div className="space-y-6" aria-busy>
|
||||
{header}
|
||||
<div className="grid gap-8 lg:grid-cols-[220px_1fr]">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-9 w-full" />
|
||||
<Skeleton className="h-9 w-full" />
|
||||
</div>
|
||||
<Skeleton className="h-48 w-full" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (accounts.length === 0) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{header}
|
||||
<EmptyState
|
||||
icon={Scale}
|
||||
title={t('empty_title')}
|
||||
description={t('empty_body')}
|
||||
actionLabel={t('empty_connect_bank')}
|
||||
actionHref="/settings/banking"
|
||||
secondaryActionLabel={t('empty_connect_skv')}
|
||||
secondaryActionHref="/settings/skatteverket"
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const railFooter = (
|
||||
<Link href="/reports/bokslutsbilagor" className={cn(QUIET_LINK_CLASS, 'block px-3 pt-4 text-[12.5px]')}>
|
||||
{tParm('open_parm')}
|
||||
</Link>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{header}
|
||||
{/* How the selected account is worked: a view of the body, so it sits with the body, not with the page scope. */}
|
||||
<SegmentedControl
|
||||
value={mode}
|
||||
onChange={setMode}
|
||||
aria-label={t('title')}
|
||||
options={[
|
||||
{ value: 'overview', label: t('mode_overview') },
|
||||
{ value: 'match', label: t('mode_match') },
|
||||
]}
|
||||
/>
|
||||
{selected && mode === 'match' && (
|
||||
<div className="grid gap-8 lg:grid-cols-[220px_1fr]">
|
||||
<ReconciliationRail accounts={accounts} selectedKey={selected.account_key} onSelect={select} footer={railFooter} />
|
||||
<div className="min-w-0">
|
||||
<ManualMatchMode key={selected.account_key} account={selected} window={window} onChanged={() => void load()} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{selected && mode === 'overview' && (
|
||||
<AccountOverview
|
||||
key={selected.account_key}
|
||||
account={selected}
|
||||
rail={<ReconciliationRail accounts={accounts} selectedKey={selected.account_key} onSelect={select} footer={railFooter} />}
|
||||
otherBankAccounts={accounts.filter((a) => a.kind === 'bank' && a.account_key !== selected.account_key && !a.superseded_by)}
|
||||
window={window}
|
||||
onChanged={() => void load()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,260 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { roundOre } from '@/lib/money'
|
||||
|
||||
/**
|
||||
* "Markera som avstämd": date, optional note, and (only when the engine
|
||||
* reports an unexplained difference) the explicit "sign anyway" choice that
|
||||
* makes the note mandatory. A manual account without a system specification
|
||||
* also asks for the balance per the signer's underlag; the difference against
|
||||
* the booked balance is then what needs explaining. The policy lives in
|
||||
* lib/reconciliation/signoff.ts; this dialog only collects the input and
|
||||
* shows the server's refusal verbatim.
|
||||
*
|
||||
* Whether the override is needed comes from the server, not from the page
|
||||
* tile: on open and on every date change the dialog previews the exact
|
||||
* sign-off (dry run), because the server judges its own window (fiscal
|
||||
* period start to the date) while the tile is scoped to whatever period or
|
||||
* range the page has picked. Judging from the tile let the signer press
|
||||
* Signera on a sign-off the server then refused.
|
||||
*/
|
||||
export interface SignoffSubmitInput {
|
||||
through_date: string
|
||||
note: string | null
|
||||
force: boolean
|
||||
external_balance?: number | null
|
||||
}
|
||||
|
||||
export type SignoffPreviewResult =
|
||||
/** The server would sign as-is; `unexplained` is what it would record. */
|
||||
| { kind: 'ok'; unexplained: number | null }
|
||||
/** The server refuses without the override: an unexplained difference (null = the outside balance is unknown). */
|
||||
| { kind: 'needs_force'; unexplained: number | null }
|
||||
/** Refused for a reason the override does not lift (already signed through a later date, date in the future, ...). */
|
||||
| { kind: 'blocked'; message: string }
|
||||
|
||||
interface SignoffDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
accountName: string
|
||||
/** Default through-date (the window end, clamped to today). */
|
||||
defaultDate: string
|
||||
/** Latest possible date (today, or the skattekonto snapshot date). */
|
||||
maxDate: string
|
||||
/** The page tile's number: the starting point until the preview answers. */
|
||||
unexplained: number | null
|
||||
currency: string
|
||||
/** Ask for the balance per underlag (manual accounts without a system specification). */
|
||||
askExternalBalance?: boolean
|
||||
/** The booked balance the stated one is compared with. */
|
||||
ledgerBalance?: number | null
|
||||
/** Dry-run the sign-off for a date; the verdict decides whether the override is asked for. */
|
||||
onPreview?: (input: SignoffSubmitInput) => Promise<SignoffPreviewResult>
|
||||
/** Returns an error message to show inline, or null on success. */
|
||||
onSubmit: (input: SignoffSubmitInput) => Promise<string | null>
|
||||
}
|
||||
|
||||
function parseAmount(raw: string): number | null {
|
||||
const normalized = raw.replace(/\s/g, '').replace(',', '.')
|
||||
if (normalized === '' || normalized === '-') return null
|
||||
const n = Number(normalized)
|
||||
return Number.isFinite(n) ? roundOre(n) : null
|
||||
}
|
||||
|
||||
export function SignoffDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
accountName,
|
||||
defaultDate,
|
||||
maxDate,
|
||||
unexplained,
|
||||
currency,
|
||||
askExternalBalance = false,
|
||||
ledgerBalance = null,
|
||||
onPreview,
|
||||
onSubmit,
|
||||
}: SignoffDialogProps) {
|
||||
const t = useTranslations('reconciliation')
|
||||
const [date, setDate] = useState(defaultDate)
|
||||
const [note, setNote] = useState('')
|
||||
const [force, setForce] = useState(false)
|
||||
const [external, setExternal] = useState('')
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [preview, setPreview] = useState<SignoffPreviewResult | null>(null)
|
||||
const [previewing, setPreviewing] = useState(false)
|
||||
// Only the latest preview may land: a quick date edit fires two requests
|
||||
// and the slower one must not overwrite the newer verdict.
|
||||
const previewSeq = useRef(0)
|
||||
// The parent passes a fresh function each render; reading it through a ref
|
||||
// keeps the preview effect keyed on the date alone.
|
||||
const onPreviewRef = useRef(onPreview)
|
||||
onPreviewRef.current = onPreview
|
||||
|
||||
// Reset per opening so a second sign-off does not inherit the last one's
|
||||
// note or override choice.
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setDate(defaultDate)
|
||||
setNote('')
|
||||
setForce(false)
|
||||
setExternal('')
|
||||
setError(null)
|
||||
setPreview(null)
|
||||
}
|
||||
}, [open, defaultDate])
|
||||
|
||||
// Ask the server what it would do with this exact date. A manual account
|
||||
// that takes a stated balance is judged locally against the booked balance
|
||||
// below, so it is not previewed (the preview would only say "unknown").
|
||||
useEffect(() => {
|
||||
const previewFn = onPreviewRef.current
|
||||
if (!open || !previewFn || askExternalBalance || date.length !== 10) return
|
||||
const seq = ++previewSeq.current
|
||||
setPreviewing(true)
|
||||
previewFn({ through_date: date, note: null, force: false })
|
||||
.then((result) => {
|
||||
if (seq === previewSeq.current) setPreview(result)
|
||||
})
|
||||
.catch(() => {
|
||||
// Network failure: fall back to the tile's number rather than block.
|
||||
if (seq === previewSeq.current) setPreview(null)
|
||||
})
|
||||
.finally(() => {
|
||||
if (seq === previewSeq.current) setPreviewing(false)
|
||||
})
|
||||
}, [open, date, askExternalBalance])
|
||||
|
||||
// With a stated balance the difference is against the booked balance;
|
||||
// otherwise the server's preview decides, and until it has answered the
|
||||
// engine's number from the page tile (or "unknown") stands in.
|
||||
const stated = askExternalBalance ? parseAmount(external) : null
|
||||
const blocked = preview?.kind === 'blocked' ? preview.message : null
|
||||
const previewUnexplained = preview && preview.kind !== 'blocked' ? preview.unexplained : unexplained
|
||||
const effectiveUnexplained =
|
||||
stated != null && ledgerBalance != null ? roundOre(ledgerBalance - stated) : previewUnexplained
|
||||
const needsForce =
|
||||
preview?.kind === 'ok' && stated == null
|
||||
? false
|
||||
: effectiveUnexplained == null || Math.abs(effectiveUnexplained) >= 0.005
|
||||
|
||||
const canSubmit =
|
||||
!busy &&
|
||||
!previewing &&
|
||||
blocked === null &&
|
||||
date.length === 10 &&
|
||||
(!needsForce || (force && note.trim().length > 0))
|
||||
|
||||
async function submit() {
|
||||
setBusy(true)
|
||||
setError(null)
|
||||
try {
|
||||
const message = await onSubmit({
|
||||
through_date: date,
|
||||
note: note.trim() || null,
|
||||
force: needsForce && force,
|
||||
...(askExternalBalance ? { external_balance: stated } : {}),
|
||||
})
|
||||
if (message) setError(message)
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-[440px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('signoff_title')}</DialogTitle>
|
||||
<DialogDescription>{t('signoff_body', { account: accountName })}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="signoff-date">{t('signoff_date')}</Label>
|
||||
<Input
|
||||
id="signoff-date"
|
||||
type="date"
|
||||
value={date}
|
||||
max={maxDate}
|
||||
onChange={(e) => setDate(e.target.value)}
|
||||
className="tabular-nums"
|
||||
/>
|
||||
{previewing && <p className="text-[12px] text-muted-foreground">{t('signoff_preview_pending')}</p>}
|
||||
</div>
|
||||
{askExternalBalance && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="signoff-external">{t('signoff_external_balance')}</Label>
|
||||
<Input
|
||||
id="signoff-external"
|
||||
inputMode="decimal"
|
||||
value={external}
|
||||
onChange={(e) => setExternal(e.target.value)}
|
||||
placeholder="0,00"
|
||||
className="tabular-nums"
|
||||
/>
|
||||
<p className="text-[12px] text-muted-foreground">
|
||||
{ledgerBalance != null
|
||||
? t('signoff_external_balance_help', { amount: formatCurrency(ledgerBalance, currency) })
|
||||
: t('signoff_external_balance_optional')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{blocked === null && needsForce && (
|
||||
<div className="space-y-2 rounded-lg bg-warning/10 px-3 py-2.5 text-[13px] text-foreground">
|
||||
<p>
|
||||
{effectiveUnexplained == null
|
||||
? askExternalBalance
|
||||
? t('signoff_external_balance_optional')
|
||||
: t('tile_unknown')
|
||||
: t('signoff_unexplained_warning', { amount: formatCurrency(effectiveUnexplained, currency) })}
|
||||
</p>
|
||||
<label className="flex items-center gap-2 text-[13px]">
|
||||
<Checkbox checked={force} onCheckedChange={(v) => setForce(v === true)} />
|
||||
{t('signoff_force')}
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="signoff-note">{t('signoff_note')}</Label>
|
||||
<Textarea
|
||||
id="signoff-note"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
placeholder={t('signoff_note_placeholder')}
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
{(error ?? blocked) && (
|
||||
<p role="alert" className="text-[13px] text-destructive">
|
||||
{error ?? blocked}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>
|
||||
{t('signoff_cancel')}
|
||||
</Button>
|
||||
<Button onClick={() => void submit()} disabled={!canSubmit} aria-busy={busy}>
|
||||
{t('signoff_confirm')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user