fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,315 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState, useCallback } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Trash2, AlertTriangle, Loader2, RefreshCw } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { ArticleType } from '@/types'
|
||||
import type { AnnotatedArticleRow } from '@/lib/import/articles/types'
|
||||
|
||||
let idCounter = 0
|
||||
const newId = () => `art_row_${++idCounter}_${Date.now()}`
|
||||
|
||||
interface EditableArticleRow extends AnnotatedArticleRow {
|
||||
id: string
|
||||
}
|
||||
|
||||
interface ArticlesEditStepProps {
|
||||
rows: AnnotatedArticleRow[]
|
||||
onExecute: (rows: AnnotatedArticleRow[], updateDuplicates: boolean) => void
|
||||
onBack: () => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
}
|
||||
|
||||
const TYPE_LABELS: Record<ArticleType, string> = {
|
||||
vara: 'Vara',
|
||||
tjanst: 'Tjänst',
|
||||
}
|
||||
|
||||
const VAT_RATES = [25, 12, 6, 0] as const
|
||||
|
||||
export default function ArticlesEditStep({
|
||||
rows: initialRows,
|
||||
onExecute,
|
||||
onBack,
|
||||
isLoading,
|
||||
error,
|
||||
}: ArticlesEditStepProps) {
|
||||
const [rows, setRows] = useState<EditableArticleRow[]>(() =>
|
||||
initialRows.map((r) => ({ ...r, id: newId() })),
|
||||
)
|
||||
const [updateDuplicates, setUpdateDuplicates] = useState(false)
|
||||
|
||||
const liveDuplicateCount = useMemo(
|
||||
() => rows.filter((r) => r.duplicate_match !== null).length,
|
||||
[rows],
|
||||
)
|
||||
|
||||
const newCount = rows.length - liveDuplicateCount
|
||||
|
||||
const hasErrors = useMemo(() => rows.some((r) => !r.is_valid), [rows])
|
||||
|
||||
const adjustedVatCount = useMemo(
|
||||
() => rows.filter((r) => r.vat_rate_adjusted).length,
|
||||
[rows],
|
||||
)
|
||||
|
||||
const canContinue = rows.length > 0 && !hasErrors && !isLoading
|
||||
|
||||
const updateRow = useCallback((id: string, updates: Partial<EditableArticleRow>) => {
|
||||
setRows((prev) => prev.map((r) => (r.id === id ? { ...r, ...updates } : r)))
|
||||
}, [])
|
||||
|
||||
const deleteRow = useCallback((id: string) => {
|
||||
setRows((prev) => prev.filter((r) => r.id !== id))
|
||||
}, [])
|
||||
|
||||
const handlePriceChange = useCallback((id: string, raw: string) => {
|
||||
const n = parseFloat(raw.replace(',', '.'))
|
||||
const price = Number.isFinite(n) ? n : 0
|
||||
updateRow(id, {
|
||||
price_excl_vat: price,
|
||||
is_valid: price >= 0,
|
||||
validation_errors: price < 0 ? ['Priset kan inte vara negativt'] : [],
|
||||
})
|
||||
}, [updateRow])
|
||||
|
||||
const handleExecute = () => {
|
||||
if (!canContinue) return
|
||||
const stripped: AnnotatedArticleRow[] = rows.map(({ id: _id, ...rest }) => rest)
|
||||
onExecute(stripped, updateDuplicates)
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Granska artiklar</CardTitle>
|
||||
<CardDescription>
|
||||
Kontrollera att uppgifterna stämmer. Du kan justera benämning, typ, pris och moms
|
||||
inline, eller ta bort rader. {newCount} ny{newCount === 1 ? '' : 'a'} artik{newCount === 1 ? 'el' : 'lar'} skapas
|
||||
{liveDuplicateCount > 0 ? ` och ${liveDuplicateCount} matchar befintliga.` : '.'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Duplicate handling banner */}
|
||||
{liveDuplicateCount > 0 && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<RefreshCw className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{liveDuplicateCount} rader</span> matchar befintliga
|
||||
artiklar (på artikelnummer eller benämning).
|
||||
</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
id="update-duplicates"
|
||||
checked={updateDuplicates}
|
||||
onCheckedChange={setUpdateDuplicates}
|
||||
/>
|
||||
<Label htmlFor="update-duplicates" className="text-sm cursor-pointer">
|
||||
{updateDuplicates
|
||||
? 'Uppdatera befintliga artiklar med ny information'
|
||||
: 'Hoppa över befintliga artiklar'}
|
||||
</Label>
|
||||
</div>
|
||||
{updateDuplicates && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Endast fält med värden i filen skrivs över. Typ, enhet och moms lämnas orörda.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* VAT-adjustment notice: rows whose rate was snapped/defaulted */}
|
||||
{adjustedVatCount > 0 && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{adjustedVatCount} rad{adjustedVatCount === 1 ? '' : 'er'}</span> fick
|
||||
momssatsen omtolkad (avrundad till närmaste giltiga, eller satt till 25 %).
|
||||
Kontrollera de markerade raderna innan du importerar: fel momssats ger fel moms på fakturan.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Table */}
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b">
|
||||
<th className="px-3 py-2 text-left w-28">Art.nr</th>
|
||||
<th className="px-3 py-2 text-left">Benämning</th>
|
||||
<th className="px-3 py-2 text-left w-28">Typ</th>
|
||||
<th className="px-3 py-2 text-right w-28">Pris exkl moms</th>
|
||||
<th className="px-3 py-2 text-left w-24">Moms</th>
|
||||
<th className="px-3 py-2 text-left w-28">Status</th>
|
||||
<th className="px-3 py-2 w-10" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={cn('border-b last:border-0', !row.is_valid && 'bg-destructive/5')}
|
||||
>
|
||||
<td className="px-3 py-1.5 text-muted-foreground tabular-nums">
|
||||
{row.article_number || 'Auto'}
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Input
|
||||
value={row.name}
|
||||
onChange={(e) => updateRow(row.id, { name: e.target.value })}
|
||||
className="h-8"
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Select
|
||||
value={row.type}
|
||||
onValueChange={(v) => updateRow(row.id, { type: v as ArticleType })}
|
||||
>
|
||||
<SelectTrigger className="h-8">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(Object.keys(TYPE_LABELS) as ArticleType[]).map((t) => (
|
||||
<SelectItem key={t} value={t}>
|
||||
{TYPE_LABELS[t]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Input
|
||||
value={String(row.price_excl_vat)}
|
||||
inputMode="decimal"
|
||||
onChange={(e) => handlePriceChange(row.id, e.target.value)}
|
||||
className="h-8 text-right tabular-nums"
|
||||
/>
|
||||
{/* Exception chip: only non-SEK rows carry a marker. */}
|
||||
{row.currency && row.currency !== 'SEK' && (
|
||||
<span className="shrink-0 text-xs text-muted-foreground">{row.currency}</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Select
|
||||
value={String(row.vat_rate)}
|
||||
onValueChange={(v) =>
|
||||
updateRow(row.id, { vat_rate: Number(v), vat_rate_adjusted: false })
|
||||
}
|
||||
>
|
||||
<SelectTrigger
|
||||
className={cn('h-8', row.vat_rate_adjusted && 'border-border text-warning')}
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{VAT_RATES.map((r) => (
|
||||
<SelectItem key={r} value={String(r)}>
|
||||
{r} %
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{row.vat_rate_adjusted && (
|
||||
<span
|
||||
className="text-warning shrink-0"
|
||||
title="Momssatsen tolkades om från filen: kontrollera att den stämmer."
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{!row.is_valid && (
|
||||
<span
|
||||
className="text-destructive shrink-0"
|
||||
title={row.validation_errors.join(', ')}
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
)}
|
||||
{row.duplicate_match ? (
|
||||
<span
|
||||
className={cn(
|
||||
'text-[11px] font-medium px-1.5 py-0.5 rounded-full',
|
||||
updateDuplicates
|
||||
? 'bg-muted text-warning'
|
||||
: 'bg-muted text-muted-foreground',
|
||||
)}
|
||||
title={`Matchar ${row.duplicate_match.existing_name} (${row.duplicate_match.matched_by})`}
|
||||
>
|
||||
{updateDuplicates ? 'Uppdateras' : 'Hoppas över'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[11px] font-medium px-1.5 py-0.5 rounded-full bg-success/15 text-success">
|
||||
Ny
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
aria-label="Ta bort rad"
|
||||
onClick={() => deleteRow(row.id)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{hasErrors && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-warning">
|
||||
Vissa rader har valideringsfel (markerade i rött). Åtgärda eller ta bort dem
|
||||
innan du fortsätter.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-destructive mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between pt-2">
|
||||
<Button variant="ghost" onClick={onBack} disabled={isLoading}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={handleExecute} disabled={!canContinue}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
Importerar...
|
||||
</>
|
||||
) : (
|
||||
`Importera ${rows.length} rad${rows.length === 1 ? '' : 'er'}`
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,441 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import { ArrowLeft, ArrowRight, Columns3 } from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { getCSVPreview, normalizeMinusSign, suggestColumnMapping } from '@/lib/import/bank-file/formats/generic-csv'
|
||||
import type { GenericCSVColumnMapping } from '@/lib/import/bank-file/types'
|
||||
|
||||
const HEADER_KEYWORDS = [
|
||||
'datum',
|
||||
'bokföringsdag',
|
||||
'bokforingsdag',
|
||||
'transaktionsdatum',
|
||||
'reskontradatum',
|
||||
'beskrivning',
|
||||
'belopp',
|
||||
'transaktion',
|
||||
'text',
|
||||
'mottagare',
|
||||
'saldo',
|
||||
'valuta',
|
||||
'amount',
|
||||
'description',
|
||||
'date',
|
||||
'title',
|
||||
'balance',
|
||||
]
|
||||
|
||||
interface BankFileColumnMappingStepProps {
|
||||
rawFileContent: string
|
||||
onConfirm: (mapping: GenericCSVColumnMapping) => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export default function BankFileColumnMappingStep({
|
||||
rawFileContent,
|
||||
onConfirm,
|
||||
onBack,
|
||||
}: BankFileColumnMappingStepProps) {
|
||||
const [dateCol, setDateCol] = useState<number>(-1)
|
||||
const [descCol, setDescCol] = useState<number>(-1)
|
||||
const [amountCol, setAmountCol] = useState<number>(-1)
|
||||
const [referenceCol, setReferenceCol] = useState<number>(-1)
|
||||
const [counterpartyCol, setCounterpartyCol] = useState<number>(-1)
|
||||
const [balanceCol, setBalanceCol] = useState<number>(-1)
|
||||
// Auto-detect the most likely delimiter by counting field splits on the first line.
|
||||
// Runs once per file. Users can still override via the dropdown.
|
||||
const detectedDelimiter = useMemo(() => {
|
||||
const firstLine = rawFileContent.split(/\r?\n/).find((l) => l.trim() !== '') ?? ''
|
||||
const candidates: Array<{ d: string; count: number }> = [
|
||||
{ d: ',', count: getCSVPreview(firstLine, ',', 1)[0]?.length ?? 0 },
|
||||
{ d: ';', count: getCSVPreview(firstLine, ';', 1)[0]?.length ?? 0 },
|
||||
{ d: '\t', count: getCSVPreview(firstLine, '\t', 1)[0]?.length ?? 0 },
|
||||
]
|
||||
const best = candidates.reduce((a, b) => (b.count > a.count ? b : a))
|
||||
return best.count > 1 ? best.d : ','
|
||||
}, [rawFileContent])
|
||||
|
||||
const [delimiter, setDelimiter] = useState<string>(detectedDelimiter)
|
||||
const [decimalSep, setDecimalSep] = useState<',' | '.'>(',')
|
||||
const [dateFormat, setDateFormat] = useState<string>('YYYY-MM-DD')
|
||||
|
||||
// Re-parse headers and preview whenever delimiter or file content changes.
|
||||
// Pull a generous slice (30 rows) so we can scan past metadata preambles like
|
||||
// Northmill's 5-line Kontonummer/Saldo/Kontohavare/Org.Nr/Period header.
|
||||
const parsedRows = useMemo(
|
||||
() => getCSVPreview(rawFileContent, delimiter, 30),
|
||||
[rawFileContent, delimiter]
|
||||
)
|
||||
|
||||
// Auto-detect the header row index by scanning for a row whose cells
|
||||
// contain known column-name keywords (bokföringsdag, beskrivning, belopp, …).
|
||||
// A row needs ≥ 2 keyword hits to qualify, which excludes metadata rows where
|
||||
// only the label cell happens to match (e.g. "Saldo,251495,41,SEK").
|
||||
// Falls back to row 0 if nothing qualifies: preserves prior behavior for
|
||||
// simple files where the header truly is the first row.
|
||||
const DATE_PATTERNS = [/^\d{4}-\d{2}-\d{2}$/, /^\d{2}[./]\d{2}[./]\d{4}$/, /^\d{8}$/]
|
||||
const detectedHeaderRow = useMemo(() => {
|
||||
let best: { idx: number; score: number; cells: number } | null = null
|
||||
for (let i = 0; i < Math.min(parsedRows.length, 20); i++) {
|
||||
const row = parsedRows[i]
|
||||
if (!row || row.length < 2) continue
|
||||
const hits = row.filter((cell) => {
|
||||
const c = cell.trim().toLowerCase()
|
||||
return c.length > 0 && HEADER_KEYWORDS.some((kw) => c === kw || c.includes(kw))
|
||||
}).length
|
||||
if (hits < 2) continue
|
||||
if (!best || hits > best.score || (hits === best.score && row.length > best.cells)) {
|
||||
best = { idx: i, score: hits, cells: row.length }
|
||||
}
|
||||
}
|
||||
return best?.idx ?? 0
|
||||
}, [parsedRows])
|
||||
|
||||
// Detect whether the file actually has a header row at all: if the auto-detect
|
||||
// landed on row 0 but row 0 already looks like data (any cell is a date), assume
|
||||
// no header. Otherwise trust the detection.
|
||||
const detectedHasHeader = useMemo(() => {
|
||||
const headerRow = parsedRows[detectedHeaderRow]
|
||||
if (!headerRow) return true
|
||||
const looksLikeData = headerRow.some((cell) =>
|
||||
DATE_PATTERNS.some((re) => re.test(cell.trim()))
|
||||
)
|
||||
return !looksLikeData
|
||||
}, [parsedRows, detectedHeaderRow])
|
||||
|
||||
const [hasHeaderOverride, setHasHeaderOverride] = useState<boolean | null>(null)
|
||||
const hasHeader = hasHeaderOverride ?? detectedHasHeader
|
||||
|
||||
// skip_rows = number of rows to skip before transaction data starts.
|
||||
// When hasHeader: skip past the header row (detectedHeaderRow + 1).
|
||||
// When no header: skip nothing: data starts at row 0.
|
||||
const skipRows = hasHeader ? detectedHeaderRow + 1 : 0
|
||||
|
||||
const columnHeaders = useMemo(() => {
|
||||
if (hasHeader && parsedRows[detectedHeaderRow]) return parsedRows[detectedHeaderRow]
|
||||
const count = parsedRows[0]?.length ?? 0
|
||||
return Array.from({ length: count }, (_, i) => `Kolumn ${i + 1}`)
|
||||
}, [parsedRows, hasHeader, detectedHeaderRow])
|
||||
|
||||
const dataRows = hasHeader ? parsedRows.slice(detectedHeaderRow + 1) : parsedRows
|
||||
|
||||
// Auto-guess date/description/amount/balance columns. Matches header labels
|
||||
// first (so the trailing Saldo column is never picked as the amount), then
|
||||
// falls back to value heuristics. Initial defaults only: user can override.
|
||||
useEffect(() => {
|
||||
if (dateCol !== -1 || descCol !== -1 || amountCol !== -1) return
|
||||
if (dataRows.length === 0) return
|
||||
|
||||
const suggestion = suggestColumnMapping(hasHeader ? columnHeaders : null, dataRows)
|
||||
if (suggestion.date >= 0) setDateCol(suggestion.date)
|
||||
if (suggestion.description >= 0) setDescCol(suggestion.description)
|
||||
if (suggestion.amount >= 0) setAmountCol(suggestion.amount)
|
||||
if (suggestion.balance >= 0) setBalanceCol(suggestion.balance)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [dataRows, hasHeader, columnHeaders])
|
||||
|
||||
const isValid = dateCol >= 0 && descCol >= 0 && amountCol >= 0
|
||||
|
||||
const handleConfirm = () => {
|
||||
const mapping: GenericCSVColumnMapping = {
|
||||
date: dateCol,
|
||||
description: descCol,
|
||||
amount: amountCol,
|
||||
...(referenceCol >= 0 && { reference: referenceCol }),
|
||||
...(counterpartyCol >= 0 && { counterparty: counterpartyCol }),
|
||||
...(balanceCol >= 0 && { balance: balanceCol }),
|
||||
delimiter,
|
||||
decimal_separator: decimalSep,
|
||||
skip_rows: skipRows,
|
||||
date_format: dateFormat,
|
||||
}
|
||||
onConfirm(mapping)
|
||||
}
|
||||
|
||||
const columnOptions = columnHeaders.map((h, i) => ({ label: `${i + 1}: ${h}`, value: i }))
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Columns3 className="h-5 w-5" />
|
||||
Kolumnmappning
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Vi kunde inte identifiera bankformatet automatiskt. Mappa kolumnerna manuellt.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Header row toggle */}
|
||||
<div className="flex items-center justify-between rounded-lg border p-4">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="has-header">Har filen rubrikrad?</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{hasHeader && detectedHeaderRow > 0
|
||||
? `Hoppar över ${detectedHeaderRow} metadatarader. Rubrikraden upptäcktes på rad ${detectedHeaderRow + 1}.`
|
||||
: 'Slå av om filen saknar rubrikrad och första raden redan innehåller transaktionsdata.'}
|
||||
</p>
|
||||
</div>
|
||||
<Switch id="has-header" checked={hasHeader} onCheckedChange={setHasHeaderOverride} />
|
||||
</div>
|
||||
|
||||
{/* Delimiter, decimal, and date format settings */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Avgränsare</Label>
|
||||
<Select value={delimiter} onValueChange={(v) => { if (v) setDelimiter(v) }}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value=",">Komma (,)</SelectItem>
|
||||
<SelectItem value=";">Semikolon (;)</SelectItem>
|
||||
<SelectItem value="\t">Tab</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Decimalavgränsare</Label>
|
||||
<Select value={decimalSep} onValueChange={(v) => { if (v) setDecimalSep(v as ',' | '.') }}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value=",">Komma (1 234,56)</SelectItem>
|
||||
<SelectItem value=".">Punkt (1234.56)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Datumformat</Label>
|
||||
<Select value={dateFormat} onValueChange={(v) => { if (v) setDateFormat(v) }}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="YYYY-MM-DD">YYYY-MM-DD</SelectItem>
|
||||
<SelectItem value="DD.MM.YYYY">DD.MM.YYYY</SelectItem>
|
||||
<SelectItem value="DD/MM/YYYY">DD/MM/YYYY</SelectItem>
|
||||
<SelectItem value="YYYYMMDD">YYYYMMDD</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Required column mappings */}
|
||||
<div>
|
||||
<h3 className="text-sm mb-3">Obligatoriska kolumner</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Datum *</Label>
|
||||
<Select
|
||||
value={dateCol >= 0 ? dateCol.toString() : ''}
|
||||
onValueChange={(v) => setDateCol(parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Beskrivning *</Label>
|
||||
<Select
|
||||
value={descCol >= 0 ? descCol.toString() : ''}
|
||||
onValueChange={(v) => setDescCol(parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Belopp *</Label>
|
||||
<Select
|
||||
value={amountCol >= 0 ? amountCol.toString() : ''}
|
||||
onValueChange={(v) => setAmountCol(parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Optional column mappings */}
|
||||
<div>
|
||||
<h3 className="text-sm mb-3">Valfria kolumner</h3>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Referens/OCR</Label>
|
||||
<Select
|
||||
value={referenceCol >= 0 ? referenceCol.toString() : 'none'}
|
||||
onValueChange={(v) => setReferenceCol(v === 'none' ? -1 : parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Ingen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">Ingen</SelectItem>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Motpart</Label>
|
||||
<Select
|
||||
value={counterpartyCol >= 0 ? counterpartyCol.toString() : 'none'}
|
||||
onValueChange={(v) => setCounterpartyCol(v === 'none' ? -1 : parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Ingen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">Ingen</SelectItem>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Saldo</Label>
|
||||
<Select
|
||||
value={balanceCol >= 0 ? balanceCol.toString() : 'none'}
|
||||
onValueChange={(v) => setBalanceCol(v === 'none' ? -1 : parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Ingen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">Ingen</SelectItem>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Live preview */}
|
||||
{isValid && dataRows.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Förhandsgranskning</CardTitle>
|
||||
<CardDescription>
|
||||
Så tolkas dina data med den valda mappningen
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-lg border max-h-64 overflow-x-auto overflow-y-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Datum</TableHead>
|
||||
<TableHead>Beskrivning</TableHead>
|
||||
<TableHead className="text-right">Belopp</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{dataRows.slice(0, 5).map((row, i) => {
|
||||
const amountStr = row[amountCol] || '0'
|
||||
const normalizedAmountStr = normalizeMinusSign(amountStr)
|
||||
const amount = decimalSep === ','
|
||||
? parseFloat(normalizedAmountStr.replace(/\s/g, '').replace(',', '.'))
|
||||
: parseFloat(normalizedAmountStr.replace(/\s/g, ''))
|
||||
|
||||
return (
|
||||
<TableRow key={i}>
|
||||
<TableCell className="font-mono text-sm">{row[dateCol] || '-'}</TableCell>
|
||||
<TableCell className="text-sm">{row[descCol] || '-'}</TableCell>
|
||||
<TableCell
|
||||
className={`text-right font-mono text-sm ${
|
||||
!isNaN(amount) && amount >= 0 ? 'text-success' : 'text-destructive'
|
||||
}`}
|
||||
>
|
||||
{/* SEK is safe here ONLY because generic-csv hardcodes
|
||||
currency: 'SEK' (formats/generic-csv.ts). If the
|
||||
mapper ever gains a currency column, pass it. */}
|
||||
{!isNaN(amount) ? formatCurrency(amount) : amountStr}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-between">
|
||||
<Button variant="outline" className="min-h-11" onClick={onBack}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button className="min-h-11" onClick={handleConfirm} disabled={!isValid}>
|
||||
Fortsätt
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useMemo, useRef } from 'react'
|
||||
import { useAccounts } from '@/lib/reference-data/hooks'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Loader2,
|
||||
Play,
|
||||
FileText,
|
||||
Link2,
|
||||
Calendar,
|
||||
Landmark,
|
||||
AlertTriangle,
|
||||
} from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { summarizeByCurrency } from '@/lib/import/bank-file/currency-summary'
|
||||
import type { BankFileParseResult, BankFileDuplicateInfo } from '@/lib/import/bank-file/types'
|
||||
|
||||
interface BankAccount {
|
||||
account_number: string
|
||||
account_name: string
|
||||
}
|
||||
|
||||
interface BankFileConfirmStepProps {
|
||||
parseResult: BankFileParseResult
|
||||
duplicateInfo?: BankFileDuplicateInfo | null
|
||||
onExecute: (options: { skip_duplicates: boolean; auto_categorize: boolean; settlement_account?: string }) => void
|
||||
onBack: () => void
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
export default function BankFileConfirmStep({
|
||||
parseResult,
|
||||
duplicateInfo,
|
||||
onExecute,
|
||||
onBack,
|
||||
isLoading,
|
||||
}: BankFileConfirmStepProps) {
|
||||
const t = useTranslations('transactions')
|
||||
const { transactions, stats, date_from, date_to, issues } = parseResult
|
||||
const refsCount = transactions.filter((tx) => tx.reference).length
|
||||
const warnings = issues.filter((i) => i.severity === 'warning')
|
||||
// Same per-currency grouping as the preview step: parser-level totals sum
|
||||
// across currencies, which misleads on Wise/camt.053 multi-currency files.
|
||||
const currencyTotals = summarizeByCurrency(transactions)
|
||||
// Advisory: clamp so a stale preview can never produce a negative CTA
|
||||
// count. Execute stays authoritative; the copy says rows are skipped
|
||||
// automatically rather than promising an exact final number.
|
||||
const duplicateCount = Math.min(Math.max(duplicateInfo?.duplicate_count ?? 0, 0), stats.parsed_rows)
|
||||
|
||||
const [selectedAccount, setSelectedAccount] = useState('1930')
|
||||
// Active 19xx accounts from the session-cached chart (lib/reference-data):
|
||||
// the account select is populated on the first paint.
|
||||
const { accounts } = useAccounts()
|
||||
const bankAccounts = useMemo<BankAccount[]>(
|
||||
() =>
|
||||
accounts
|
||||
.filter((a) => a.account_number >= '1900' && a.account_number <= '1999')
|
||||
.sort((a, b) => a.account_number.localeCompare(b.account_number))
|
||||
.map((a) => ({ account_number: a.account_number, account_name: a.account_name })),
|
||||
[accounts],
|
||||
)
|
||||
// Default to 1930 if available, otherwise the first account (once).
|
||||
const defaultedRef = useRef(false)
|
||||
useEffect(() => {
|
||||
if (defaultedRef.current || bankAccounts.length === 0) return
|
||||
defaultedRef.current = true
|
||||
const has1930 = bankAccounts.some((a) => a.account_number === '1930')
|
||||
if (!has1930) setSelectedAccount(bankAccounts[0].account_number)
|
||||
}, [bankAccounts])
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-24 space-y-6">
|
||||
<div className="relative">
|
||||
<Loader2 className="h-12 w-12 animate-spin text-primary" />
|
||||
</div>
|
||||
<div className="text-center space-y-2">
|
||||
<p className="text-lg font-medium">Importerar transaktioner...</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{stats.parsed_rows} transaktioner bearbetas
|
||||
</p>
|
||||
</div>
|
||||
<div className="w-48 h-1 bg-muted rounded-full overflow-hidden">
|
||||
<div className="h-full bg-primary rounded-full animate-pulse" style={{ width: '60%' }} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Summary */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Bekräfta import</CardTitle>
|
||||
<CardDescription>
|
||||
Granska sammanfattningen och importera transaktionerna.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Stats grid */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="p-4 bg-muted/50 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span className="text-xs">Transaktioner</span>
|
||||
</div>
|
||||
<p className="text-xl font-display tabular-nums">{stats.parsed_rows}</p>
|
||||
{stats.skipped_rows > 0 && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{stats.skipped_rows} rader hoppades över
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-muted/50 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Calendar className="h-4 w-4" />
|
||||
<span className="text-xs">Period</span>
|
||||
</div>
|
||||
<p className="text-sm font-medium">
|
||||
{date_from}: {date_to}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-muted/50 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<span className="text-xs">Inkomster</span>
|
||||
</div>
|
||||
{(currencyTotals.length ? currencyTotals : [{ currency: 'SEK', total_income: 0, total_expenses: 0 }]).map((row) => (
|
||||
<p key={row.currency} className="text-xl font-display tabular-nums">
|
||||
{formatCurrency(row.total_income, row.currency)}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-muted/50 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<span className="text-xs">Utgifter</span>
|
||||
</div>
|
||||
{(currencyTotals.length ? currencyTotals : [{ currency: 'SEK', total_income: 0, total_expenses: 0 }]).map((row) => (
|
||||
<p key={row.currency} className="text-xl font-display tabular-nums">
|
||||
{formatCurrency(row.total_expenses, row.currency)}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Bank account selector */}
|
||||
{bankAccounts.length > 1 && (
|
||||
<div className="space-y-2">
|
||||
<Label className="flex items-center gap-2">
|
||||
<Landmark className="h-4 w-4 text-muted-foreground" />
|
||||
Bankkonto
|
||||
</Label>
|
||||
<Select value={selectedAccount} onValueChange={setSelectedAccount}>
|
||||
<SelectTrigger className="w-full sm:w-72">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{bankAccounts.map((account) => (
|
||||
<SelectItem key={account.account_number} value={account.account_number}>
|
||||
<span className="font-mono">{account.account_number}</span>
|
||||
{' '}
|
||||
{account.account_name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Välj vilket bankkonto transaktionerna ska bokföras mot.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Additional info */}
|
||||
{refsCount > 0 && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Link2 className="h-3 w-3" />
|
||||
{refsCount} med OCR/referens
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Duplicate rows: repeated here because the generic_csv path skips the
|
||||
preview step where the same card is shown. Advisory: ingest skips
|
||||
them automatically at execute. */}
|
||||
{duplicateCount > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-sm flex items-center gap-2 text-warning">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{t('import_duplicate_rows_title', { count: duplicateCount })}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('import_duplicate_rows_body')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Skipped rows: surfaced here because the manual-mapping path skips the
|
||||
preview step where these warnings would otherwise be shown. */}
|
||||
{warnings.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-sm flex items-center gap-2">
|
||||
<AlertTriangle className="h-4 w-4 text-warning" />
|
||||
{warnings.length} {warnings.length === 1 ? 'rad' : 'rader'} hoppades över
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Dessa rader kunde inte läsas och importeras inte. Kontrollera att inga transaktioner saknas.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="space-y-1 max-h-32 overflow-y-auto">
|
||||
{warnings.slice(0, 10).map((issue, i) => (
|
||||
<p key={i} className="text-xs text-muted-foreground">
|
||||
Rad {issue.row}: {issue.message}
|
||||
</p>
|
||||
))}
|
||||
{warnings.length > 10 && (
|
||||
<p className="text-xs text-muted-foreground font-medium">
|
||||
…och {warnings.length - 10} till
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-between">
|
||||
<Button variant="outline" className="min-h-11" onClick={onBack} disabled={isLoading}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button
|
||||
className="min-h-11"
|
||||
onClick={() => onExecute({
|
||||
skip_duplicates: true,
|
||||
auto_categorize: false,
|
||||
settlement_account: selectedAccount !== '1930' ? selectedAccount : undefined,
|
||||
})}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Importerar...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="mr-2 h-4 w-4" />
|
||||
Importera {stats.parsed_rows - duplicateCount} transaktioner
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Undo2 } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { DestructiveConfirmDialog } from '@/components/ui/destructive-confirm-dialog'
|
||||
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { getFormat } from '@/lib/import/bank-file/formats'
|
||||
import type { BankFileFormatId } from '@/lib/import/bank-file/types'
|
||||
import { cn, formatDate } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* Subset of the bank_file_imports row (GET /api/import/bank-file) actually
|
||||
* rendered here. `status` stays a plain string: unknown values fall back to
|
||||
* raw muted text instead of crashing on a missing translation key (same
|
||||
* defensive shape as SIEImportHistory).
|
||||
*/
|
||||
interface BankFileImportListRow {
|
||||
id: string
|
||||
filename: string
|
||||
file_format: string
|
||||
imported_count: number
|
||||
status: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
const STATUS_LABEL_KEY: Record<string, string> = {
|
||||
completed: 'bankfile_history_status_completed',
|
||||
undone: 'bankfile_history_status_undone',
|
||||
failed: 'bankfile_history_status_failed',
|
||||
pending: 'bankfile_history_status_pending',
|
||||
processing: 'bankfile_history_status_processing',
|
||||
}
|
||||
|
||||
/**
|
||||
* Chips mark exceptions (design.md convention 5): the normal 'completed'
|
||||
* state renders as muted text; only deviating states get a Badge.
|
||||
*/
|
||||
const STATUS_BADGE_VARIANT: Record<string, 'secondary' | 'warning' | 'destructive'> = {
|
||||
undone: 'secondary',
|
||||
failed: 'destructive',
|
||||
pending: 'warning',
|
||||
processing: 'warning',
|
||||
}
|
||||
|
||||
/**
|
||||
* The undo report returned by DELETE /api/import/bank-file/[id]/undo:
|
||||
* deleted rows plus what was deliberately left alone (booked rows are
|
||||
* räkenskapsinformation; rows with payment_match_log history keep their
|
||||
* append-only log).
|
||||
*/
|
||||
interface UndoReport {
|
||||
deletedTransactions?: number
|
||||
skippedBooked?: number
|
||||
skippedMatchHistory?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* History of past bank file imports with per-row undo for completed ones.
|
||||
* Rendered fold-open from the 'Tidigare bankfilsimporter' row on the import
|
||||
* tab; mirrors SIEImportHistory. The undo itself is owner/admin-only,
|
||||
* enforced server-side by the undo_bank_file_import RPC's actor gate.
|
||||
*/
|
||||
export default function BankFileImportHistory() {
|
||||
const t = useTranslations('import')
|
||||
const { toast } = useToast()
|
||||
const [rows, setRows] = useState<BankFileImportListRow[] | null>(null)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [pendingUndo, setPendingUndo] = useState<BankFileImportListRow | null>(null)
|
||||
|
||||
const fetchImports = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/import/bank-file?limit=20')
|
||||
if (!res.ok) {
|
||||
setLoadFailed(true)
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
setRows(Array.isArray(data.data) ? data.data : [])
|
||||
setLoadFailed(false)
|
||||
} catch {
|
||||
setLoadFailed(true)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void fetchImports()
|
||||
}, [fetchImports])
|
||||
|
||||
// Deliberately no client-side timeout: undoing a large import can take
|
||||
// minutes (the route runs with maxDuration 300) and the confirm dialog
|
||||
// stays open with its spinner until this resolves.
|
||||
const handleUndoConfirm = useCallback(async () => {
|
||||
if (!pendingUndo) return
|
||||
try {
|
||||
const res = await fetch(`/api/import/bank-file/${pendingUndo.id}/undo`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: t('bankfile_history_undo_failed'),
|
||||
description: getErrorMessage(data),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// The full report, clearly: X removed, and any rows the undo refused
|
||||
// to touch (booked / match history) so nothing disappears silently.
|
||||
const report = data as UndoReport
|
||||
const skippedBooked = report.skippedBooked ?? 0
|
||||
const skippedMatchHistory = report.skippedMatchHistory ?? 0
|
||||
const parts = [
|
||||
t('bankfile_history_undo_success_deleted', {
|
||||
count: report.deletedTransactions ?? 0,
|
||||
}),
|
||||
]
|
||||
if (skippedBooked > 0) {
|
||||
parts.push(t('bankfile_history_undo_skipped_booked', { count: skippedBooked }))
|
||||
}
|
||||
if (skippedMatchHistory > 0) {
|
||||
parts.push(
|
||||
t('bankfile_history_undo_skipped_match_history', { count: skippedMatchHistory }),
|
||||
)
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('bankfile_history_undo_success_title'),
|
||||
description: parts.join(' '),
|
||||
})
|
||||
await fetchImports()
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('bankfile_history_undo_failed'),
|
||||
description: getErrorMessage(err),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}, [pendingUndo, fetchImports, t, toast])
|
||||
|
||||
// 'swedbank' → 'Swedbank' via the format registry; unknown ids (a format
|
||||
// removed from the registry) fall back to the raw stored code.
|
||||
const formatLabel = (row: BankFileImportListRow): string =>
|
||||
getFormat(row.file_format as BankFileFormatId)?.name ?? row.file_format
|
||||
|
||||
const statusCell = (status: string) => {
|
||||
const labelKey = STATUS_LABEL_KEY[status]
|
||||
const label = labelKey ? t(labelKey) : status
|
||||
const variant = STATUS_BADGE_VARIANT[status]
|
||||
if (!variant) {
|
||||
return <span className="text-xs text-muted-foreground">{label}</span>
|
||||
}
|
||||
return (
|
||||
<Badge variant={variant} className="font-normal">
|
||||
{label}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
if (loadFailed) {
|
||||
return (
|
||||
<p className="px-1 text-xs leading-5 text-muted-foreground">
|
||||
{t('bankfile_history_load_error')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
if (rows === null) {
|
||||
return (
|
||||
<div className="space-y-2" role="status">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
return (
|
||||
<p className="px-1 text-xs leading-5 text-muted-foreground">
|
||||
{t('bankfile_history_empty')}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={TH_CLASS}>{t('bankfile_history_col_file')}</th>
|
||||
<th className={TH_CLASS}>{t('bankfile_history_col_date')}</th>
|
||||
<th className={TH_CLASS}>{t('bankfile_history_col_format')}</th>
|
||||
<th className={cn(TH_CLASS, 'text-right')}>
|
||||
{t('bankfile_history_col_transactions')}
|
||||
</th>
|
||||
<th className={TH_CLASS}>{t('bankfile_history_col_status')}</th>
|
||||
<th className={TH_CLASS}>
|
||||
<span className="sr-only">{t('bankfile_history_undo_button')}</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="stagger-enter">
|
||||
{rows.map((row) => (
|
||||
<tr key={row.id} className="transition-colors duration-150 hover:bg-secondary/35">
|
||||
<td className={TD_CLASS}>{row.filename}</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums')}>
|
||||
{formatDate(row.created_at)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap')}>{formatLabel(row)}</td>
|
||||
<td className={cn(TD_CLASS, 'text-right tabular-nums')}>{row.imported_count}</td>
|
||||
<td className={TD_CLASS}>{statusCell(row.status)}</td>
|
||||
<td className={cn(TD_CLASS, 'text-right')}>
|
||||
{row.status === 'completed' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => setPendingUndo(row)}
|
||||
>
|
||||
<Undo2 className="mr-2 h-4 w-4" />
|
||||
{t('bankfile_history_undo_button')}
|
||||
</Button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<DestructiveConfirmDialog
|
||||
open={pendingUndo !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPendingUndo(null)
|
||||
}}
|
||||
title={t('bankfile_history_undo_confirm_title')}
|
||||
description={t('bankfile_history_undo_confirm_description')}
|
||||
confirmLabel={t('bankfile_history_undo_confirm_label')}
|
||||
onConfirm={handleUndoConfirm}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
AlertTriangle,
|
||||
Calendar,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
FileText,
|
||||
} from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import { summarizeByCurrency } from '@/lib/import/bank-file/currency-summary'
|
||||
import type { BankFileParseResult, BankFileDuplicateInfo } from '@/lib/import/bank-file/types'
|
||||
|
||||
interface BankFilePreviewStepProps {
|
||||
parseResult: BankFileParseResult
|
||||
duplicateInfo?: BankFileDuplicateInfo | null
|
||||
onContinue: () => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export default function BankFilePreviewStep({
|
||||
parseResult,
|
||||
duplicateInfo,
|
||||
onContinue,
|
||||
onBack,
|
||||
}: BankFilePreviewStepProps) {
|
||||
const t = useTranslations('transactions')
|
||||
const { transactions, stats, issues, date_from, date_to } = parseResult
|
||||
const errors = issues.filter((i) => i.severity === 'error')
|
||||
const hasIssues = errors.length > 0
|
||||
const warnings = issues.filter((i) => i.severity === 'warning')
|
||||
// Wise/camt.053 files can mix currencies per row: the parser-level totals
|
||||
// sum across currencies, so income/expenses are grouped per currency here.
|
||||
const currencyTotals = summarizeByCurrency(transactions)
|
||||
const duplicateCount = duplicateInfo?.duplicate_count ?? 0
|
||||
// Table rows render transactions.slice(0, 50), so the slice index IS the
|
||||
// original array index the server flagged.
|
||||
const duplicateRowSet = new Set(duplicateInfo?.duplicate_row_indexes ?? [])
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Summary cards */}
|
||||
<div className="grid grid-cols-2 gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span className="text-sm">Transaktioner</span>
|
||||
</div>
|
||||
<p className="text-2xl font-display tabular-nums">{stats.parsed_rows}</p>
|
||||
{stats.skipped_rows > 0 && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{stats.skipped_rows} rader hoppades över
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Calendar className="h-4 w-4" />
|
||||
<span className="text-sm">Period</span>
|
||||
</div>
|
||||
<p className="text-sm font-medium">
|
||||
{date_from || '-'} till {date_to || '-'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
<span className="text-sm">Inkomster</span>
|
||||
</div>
|
||||
{(currencyTotals.length ? currencyTotals : [{ currency: 'SEK', total_income: 0, total_expenses: 0 }]).map((row) => (
|
||||
<p key={row.currency} className="text-lg font-display tabular-nums">
|
||||
{formatCurrency(row.total_income, row.currency)}
|
||||
</p>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<TrendingDown className="h-4 w-4" />
|
||||
<span className="text-sm">Utgifter</span>
|
||||
</div>
|
||||
{(currencyTotals.length ? currencyTotals : [{ currency: 'SEK', total_income: 0, total_expenses: 0 }]).map((row) => (
|
||||
<p key={row.currency} className="text-lg font-display tabular-nums">
|
||||
{formatCurrency(row.total_expenses, row.currency)}
|
||||
</p>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Duplicate rows already in bookkeeping: advisory, ingest skips them */}
|
||||
{duplicateCount > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-sm flex items-center gap-2 text-warning">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{t('import_duplicate_rows_title', { count: duplicateCount })}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('import_duplicate_rows_body')}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Warnings */}
|
||||
{warnings.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-sm flex items-center gap-2 text-warning">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{warnings.length} varning{warnings.length !== 1 ? 'ar' : ''}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="space-y-1 max-h-32 overflow-y-auto">
|
||||
{warnings.slice(0, 10).map((issue, i) => (
|
||||
<p key={i} className="text-xs text-muted-foreground">
|
||||
Rad {issue.row}: {issue.message}
|
||||
</p>
|
||||
))}
|
||||
{warnings.length > 10 && (
|
||||
<p className="text-xs text-muted-foreground font-medium">
|
||||
...och {warnings.length - 10} till
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Transaction preview table */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Transaktioner</CardTitle>
|
||||
<CardDescription>
|
||||
Förhandsgranskning av de {Math.min(transactions.length, 50)} första transaktionerna
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-lg border max-h-96 overflow-x-auto overflow-y-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-28">Datum</TableHead>
|
||||
<TableHead>Beskrivning</TableHead>
|
||||
<TableHead className="text-right w-32">Belopp</TableHead>
|
||||
{transactions.some((t) => t.balance != null) && (
|
||||
<TableHead className="text-right w-32">Saldo</TableHead>
|
||||
)}
|
||||
{transactions.some((t) => t.reference) && (
|
||||
<TableHead className="w-32">Referens</TableHead>
|
||||
)}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{transactions.slice(0, 50).map((tx, i) => (
|
||||
<TableRow key={i}>
|
||||
<TableCell className="font-mono text-sm">{tx.date}</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
{tx.description}
|
||||
{duplicateRowSet.has(i) && (
|
||||
<Badge variant="secondary" className="ml-2">
|
||||
{t('import_duplicate_row_badge')}
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell
|
||||
className="text-right font-mono text-sm"
|
||||
>
|
||||
{formatCurrency(tx.amount, tx.currency || 'SEK')}
|
||||
</TableCell>
|
||||
{transactions.some((t) => t.balance != null) && (
|
||||
<TableCell className="text-right font-mono text-sm text-muted-foreground">
|
||||
{tx.balance != null ? formatCurrency(tx.balance, tx.currency || 'SEK') : '-'}
|
||||
</TableCell>
|
||||
)}
|
||||
{transactions.some((t) => t.reference) && (
|
||||
<TableCell className="font-mono text-sm text-muted-foreground">
|
||||
{tx.reference ? tx.reference : '-'}
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
{transactions.length > 50 && (
|
||||
<p className="text-sm text-muted-foreground mt-2 text-center">
|
||||
Visar 50 av {transactions.length} transaktioner
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Error blocking continuation */}
|
||||
{hasIssues && (
|
||||
<Card className="border-destructive">
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex gap-3">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div className="min-w-0 space-y-2">
|
||||
<p className="font-medium text-destructive">Filen innehåller fel som förhindrar import</p>
|
||||
<div className="max-h-32 space-y-1 overflow-y-auto">
|
||||
{errors.map((issue, i) => (
|
||||
<p key={i} className="text-xs text-muted-foreground">
|
||||
Rad {issue.row}: {issue.message}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-between">
|
||||
<Button variant="outline" className="min-h-11" onClick={onBack}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button className="min-h-11" onClick={onContinue} disabled={hasIssues || transactions.length === 0}>
|
||||
Fortsätt
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
ArrowRight,
|
||||
RotateCcw,
|
||||
} from 'lucide-react'
|
||||
import type { IngestResult } from '@/types'
|
||||
|
||||
interface BankFileResultStepProps {
|
||||
result: IngestResult
|
||||
onNewImport: () => void
|
||||
}
|
||||
|
||||
export default function BankFileResultStep({
|
||||
result,
|
||||
onNewImport,
|
||||
}: BankFileResultStepProps) {
|
||||
const t = useTranslations('transactions')
|
||||
const isSuccess = result.imported > 0 || result.duplicates > 0
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Status header */}
|
||||
<Card className={isSuccess ? 'border-border' : 'border-destructive/50'}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
{isSuccess ? (
|
||||
<>
|
||||
<CheckCircle className="h-6 w-6 text-success" />
|
||||
Import genomförd
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<XCircle className="h-6 w-6 text-destructive" />
|
||||
Import misslyckades
|
||||
</>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{isSuccess
|
||||
? `${result.imported} transaktioner importerades framgångsrikt.`
|
||||
: `${result.errors} fel uppstod under importen.`}
|
||||
</CardDescription>
|
||||
{/* Close the silent-dedup loop: without this line, skipped rows just
|
||||
look like they vanished (fewer imported than parsed, no
|
||||
explanation). */}
|
||||
{result.duplicates > 0 && (
|
||||
<CardDescription>
|
||||
{t('import_duplicate_result', { count: result.duplicates })}
|
||||
</CardDescription>
|
||||
)}
|
||||
</CardHeader>
|
||||
{!isSuccess && result.first_error && (
|
||||
<CardContent>
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-3 text-sm">
|
||||
<p className="font-medium text-destructive">Databasfel</p>
|
||||
<p className="mt-1 font-mono text-xs text-muted-foreground break-all">
|
||||
{result.first_error.message}
|
||||
{result.first_error.details ? `: ${result.first_error.details}` : ''}
|
||||
{result.first_error.code ? ` (${result.first_error.code})` : ''}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* Next steps */}
|
||||
{isSuccess && (
|
||||
<Card className="bg-muted/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Nästa steg</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-sm font-medium flex-shrink-0">
|
||||
1
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Granska obokförda transaktioner</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{result.imported - result.auto_categorized > 0
|
||||
? `${result.imported - result.auto_categorized} transaktioner behöver bokföras manuellt.`
|
||||
: 'Alla transaktioner bokfördes automatiskt.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-sm font-medium flex-shrink-0">
|
||||
2
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Bekräfta fakturamatchningar</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{result.auto_matched_invoices > 0
|
||||
? `${result.auto_matched_invoices} transaktioner matchades mot fakturor. Bekräfta dessa på transaktionssidan.`
|
||||
: 'Inga automatiska fakturamatchningar hittades.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-sm font-medium flex-shrink-0">
|
||||
3
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Importera fler kontoutdrag</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Importera löpande kontoutdrag för att hålla bokföringen uppdaterad.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-between">
|
||||
<Button variant="outline" className="min-h-11" onClick={onNewImport}>
|
||||
<RotateCcw className="mr-2 h-4 w-4" />
|
||||
Ny import
|
||||
</Button>
|
||||
{isSuccess && (
|
||||
<Button className="min-h-11" asChild>
|
||||
<Link href="/transactions">
|
||||
Visa transaktioner
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Upload,
|
||||
FileText,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
HelpCircle,
|
||||
Landmark,
|
||||
} from 'lucide-react'
|
||||
import type { BankFileFormatId } from '@/lib/import/bank-file/types'
|
||||
|
||||
const FORMAT_NAMES: Record<string, string> = {
|
||||
nordea: 'Nordea',
|
||||
nordea_business: 'Nordea Företag',
|
||||
seb: 'SEB',
|
||||
swedbank: 'Swedbank',
|
||||
handelsbanken: 'Handelsbanken',
|
||||
lansforsakringar: 'Länsförsäkringar',
|
||||
ica_banken: 'ICA Banken',
|
||||
skandia: 'Skandia',
|
||||
lunar: 'Lunar',
|
||||
northmill: 'Northmill',
|
||||
wise: 'Wise',
|
||||
generic_csv: 'CSV (manuell mappning)',
|
||||
camt053: 'ISO 20022 camt.053',
|
||||
}
|
||||
|
||||
interface BankFileUploadStepProps {
|
||||
onFileSelect: (file: File, formatOverride?: BankFileFormatId) => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
errorTitle?: string | null
|
||||
detectedFormat?: string | null
|
||||
detectedFormatName?: string | null
|
||||
/** The uploaded file was recognized as a Skatteverket skattekontoutdrag. */
|
||||
skattekontoDetected?: boolean
|
||||
}
|
||||
|
||||
export default function BankFileUploadStep({
|
||||
onFileSelect,
|
||||
isLoading,
|
||||
error,
|
||||
errorTitle,
|
||||
detectedFormat,
|
||||
detectedFormatName,
|
||||
skattekontoDetected,
|
||||
}: BankFileUploadStepProps) {
|
||||
const t = useTranslations('import')
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [formatOverride, setFormatOverride] = useState<BankFileFormatId | undefined>(undefined)
|
||||
|
||||
const acceptedExtensions = '.csv,.txt,.xml'
|
||||
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}, [])
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
}, [])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
|
||||
const files = e.dataTransfer.files
|
||||
if (files.length > 0) {
|
||||
const file = files[0]
|
||||
const ext = file.name.toLowerCase()
|
||||
if (ext.endsWith('.csv') || ext.endsWith('.txt') || ext.endsWith('.xml')) {
|
||||
setSelectedFile(file)
|
||||
onFileSelect(file, formatOverride)
|
||||
}
|
||||
}
|
||||
}, [onFileSelect, formatOverride])
|
||||
|
||||
const handleFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files
|
||||
if (files && files.length > 0) {
|
||||
setSelectedFile(files[0])
|
||||
onFileSelect(files[0], formatOverride)
|
||||
}
|
||||
}, [onFileSelect, formatOverride])
|
||||
|
||||
const handleFormatChange = (value: string) => {
|
||||
const format = value === 'auto' ? undefined : value as BankFileFormatId
|
||||
setFormatOverride(format)
|
||||
if (selectedFile) {
|
||||
onFileSelect(selectedFile, format)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Ladda upp kontoutdrag
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Exportera transaktioner som CSV eller XML från din internetbank och ladda upp filen.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Format override */}
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
|
||||
<label className="text-sm font-medium whitespace-nowrap">Bank/format:</label>
|
||||
<Select
|
||||
value={formatOverride || 'auto'}
|
||||
onValueChange={handleFormatChange}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-64">
|
||||
<SelectValue placeholder="Automatisk identifiering" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="auto">Automatisk identifiering</SelectItem>
|
||||
<SelectItem value="nordea">Nordea</SelectItem>
|
||||
<SelectItem value="nordea_business">Nordea Företag</SelectItem>
|
||||
<SelectItem value="seb">SEB</SelectItem>
|
||||
<SelectItem value="swedbank">Swedbank</SelectItem>
|
||||
<SelectItem value="handelsbanken">Handelsbanken</SelectItem>
|
||||
<SelectItem value="lansforsakringar">Länsförsäkringar</SelectItem>
|
||||
<SelectItem value="ica_banken">ICA Banken</SelectItem>
|
||||
<SelectItem value="skandia">Skandia</SelectItem>
|
||||
<SelectItem value="lunar">Lunar</SelectItem>
|
||||
<SelectItem value="northmill">Northmill</SelectItem>
|
||||
<SelectItem value="wise">Wise</SelectItem>
|
||||
<SelectItem value="wise_statement">{t('bank_format_wise_statement')}</SelectItem>
|
||||
<SelectItem value="camt053">ISO 20022 camt.053 (XML)</SelectItem>
|
||||
<SelectItem value="generic_csv">Annan CSV (manuell mappning)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Drop zone */}
|
||||
<div
|
||||
className={`
|
||||
relative border-2 border-dashed rounded-lg p-8 text-center transition-colors
|
||||
${isDragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25'}
|
||||
${error ? 'border-destructive bg-destructive/5' : ''}
|
||||
${isLoading ? 'pointer-events-none opacity-50' : 'cursor-pointer hover:border-primary/50'}
|
||||
`}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
onClick={() => document.getElementById('bank-file-input')?.click()}
|
||||
>
|
||||
<input
|
||||
id="bank-file-input"
|
||||
type="file"
|
||||
accept={acceptedExtensions}
|
||||
className="hidden"
|
||||
onChange={handleFileInput}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
<FileText className="mx-auto h-12 w-12 text-muted-foreground animate-pulse" />
|
||||
<p className="text-muted-foreground">Analyserar fil...</p>
|
||||
<Progress value={33} className="w-48 mx-auto" />
|
||||
</div>
|
||||
) : selectedFile && detectedFormat ? (
|
||||
<div className="space-y-4">
|
||||
<CheckCircle className="mx-auto h-12 w-12 text-success" />
|
||||
<div>
|
||||
<p className="font-medium">{selectedFile.name}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{(selectedFile.size / 1024).toFixed(1)} KB
|
||||
</p>
|
||||
<Badge variant="secondary" className="mt-2">
|
||||
<Landmark className="mr-1 h-3 w-3" />
|
||||
{detectedFormat === 'wise_statement'
|
||||
? t('bank_format_wise_statement')
|
||||
: detectedFormatName || FORMAT_NAMES[detectedFormat] || detectedFormat}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<Upload className="mx-auto h-12 w-12 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="font-medium hidden sm:block">Dra och släpp bankfil här</p>
|
||||
<p className="font-medium sm:hidden">Tryck för att välja bankfil</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
CSV, TXT eller XML (max 10 MB)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Skattekonto redirect: not an error, a pointer to the right flow */}
|
||||
{skattekontoDetected && (
|
||||
<div className="p-4 bg-muted/30 border border-border rounded-lg flex gap-3">
|
||||
<AlertCircle className="h-5 w-5 text-warning flex-shrink-0 mt-0.5" />
|
||||
<div className="text-sm">
|
||||
<p className="font-medium">{t('skattekonto_detected_title')}</p>
|
||||
<p className="mt-1 text-muted-foreground">
|
||||
{t('skattekonto_detected_body')}{' '}
|
||||
<Link href="/import?mode=skattekonto" className="underline underline-offset-2">
|
||||
{t('skattekonto_detected_link')}
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error display */}
|
||||
{error && (
|
||||
<div className="p-4 bg-destructive/10 border border-destructive/20 rounded-lg flex gap-3">
|
||||
<AlertCircle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-destructive">{errorTitle || 'Kunde inte läsa filen'}</p>
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Bank export instructions */}
|
||||
<Card className="bg-muted/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<HelpCircle className="h-4 w-4" />
|
||||
Så exporterar du från din bank
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm space-y-3">
|
||||
<div>
|
||||
<p className="font-medium">Nordea</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Välj konto → Transaktioner → Exportera (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">SEB</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Transaktioner → Exportera (CSV), eller Kontoutdrag → Hämta som fil (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Swedbank</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Transaktioner → Exportera kontoutdrag (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Handelsbanken</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Transaktioner → Ladda ner (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Länsförsäkringar</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Kontoutdrag → Exportera (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">ICA Banken</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Transaktioner → Exportera till fil (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Skandia</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Transaktioner → Exportera (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Lunar</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konto → Transaktioner → Exportera (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Northmill</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konto → Kontoutdrag → Ladda ner (CSV)
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState, useCallback } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Trash2, AlertTriangle, Loader2, RefreshCw } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { CustomerType } from '@/types'
|
||||
import type { AnnotatedCustomerRow } from '@/lib/import/customers/types'
|
||||
|
||||
let idCounter = 0
|
||||
const newId = () => `cust_row_${++idCounter}_${Date.now()}`
|
||||
|
||||
interface EditableCustomerRow extends AnnotatedCustomerRow {
|
||||
id: string
|
||||
}
|
||||
|
||||
interface CustomersEditStepProps {
|
||||
rows: AnnotatedCustomerRow[]
|
||||
onExecute: (rows: AnnotatedCustomerRow[], updateDuplicates: boolean) => void
|
||||
onBack: () => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
}
|
||||
|
||||
const TYPE_LABELS: Record<CustomerType, string> = {
|
||||
individual: 'Privatperson',
|
||||
swedish_business: 'Svenskt företag eller organisation',
|
||||
eu_business: 'EU-företag',
|
||||
non_eu_business: 'Utomeuropeiskt företag',
|
||||
}
|
||||
|
||||
export default function CustomersEditStep({
|
||||
rows: initialRows,
|
||||
onExecute,
|
||||
onBack,
|
||||
isLoading,
|
||||
error,
|
||||
}: CustomersEditStepProps) {
|
||||
const [rows, setRows] = useState<EditableCustomerRow[]>(() =>
|
||||
initialRows.map((r) => ({ ...r, id: newId() })),
|
||||
)
|
||||
const [updateDuplicates, setUpdateDuplicates] = useState(false)
|
||||
|
||||
const liveDuplicateCount = useMemo(
|
||||
() => rows.filter((r) => r.duplicate_match !== null).length,
|
||||
[rows],
|
||||
)
|
||||
|
||||
const newCount = rows.length - liveDuplicateCount
|
||||
|
||||
const hasErrors = useMemo(
|
||||
() => rows.some((r) => !r.is_valid),
|
||||
[rows],
|
||||
)
|
||||
|
||||
const canContinue = rows.length > 0 && !hasErrors && !isLoading
|
||||
|
||||
const updateRow = useCallback((id: string, updates: Partial<EditableCustomerRow>) => {
|
||||
setRows((prev) =>
|
||||
prev.map((r) => (r.id === id ? { ...r, ...updates } : r)),
|
||||
)
|
||||
}, [])
|
||||
|
||||
const deleteRow = useCallback((id: string) => {
|
||||
setRows((prev) => prev.filter((r) => r.id !== id))
|
||||
}, [])
|
||||
|
||||
const handleExecute = () => {
|
||||
if (!canContinue) return
|
||||
const stripped: AnnotatedCustomerRow[] = rows.map(({ id: _id, ...rest }) => rest)
|
||||
onExecute(stripped, updateDuplicates)
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Granska kunder</CardTitle>
|
||||
<CardDescription>
|
||||
Kontrollera att uppgifterna stämmer. Du kan justera namn och kundtyp inline,
|
||||
eller ta bort rader. {newCount} ny{newCount === 1 ? '' : 'a'} kund{newCount === 1 ? '' : 'er'} skapas
|
||||
{liveDuplicateCount > 0 ? ` och ${liveDuplicateCount} matchar befintliga.` : '.'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Duplicate handling banner */}
|
||||
{liveDuplicateCount > 0 && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<RefreshCw className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{liveDuplicateCount} rader</span> matchar befintliga
|
||||
kunder (på orgnummer eller e-post).
|
||||
</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
id="update-duplicates"
|
||||
checked={updateDuplicates}
|
||||
onCheckedChange={setUpdateDuplicates}
|
||||
/>
|
||||
<Label htmlFor="update-duplicates" className="text-sm cursor-pointer">
|
||||
{updateDuplicates
|
||||
? 'Uppdatera befintliga kunder med ny information'
|
||||
: 'Hoppa över befintliga kunder'}
|
||||
</Label>
|
||||
</div>
|
||||
{updateDuplicates && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Endast fält med värden i filen skrivs över. Tomma fält i filen lämnar
|
||||
befintliga värden orörda.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Table */}
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b">
|
||||
<th className="px-3 py-2 text-left">Namn</th>
|
||||
<th className="px-3 py-2 text-left w-44">Kundtyp</th>
|
||||
<th className="px-3 py-2 text-left w-36">Orgnr</th>
|
||||
<th className="px-3 py-2 text-left">E-post</th>
|
||||
<th className="px-3 py-2 text-left w-32">Status</th>
|
||||
<th className="px-3 py-2 w-10" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={cn(
|
||||
'border-b last:border-0',
|
||||
!row.is_valid && 'bg-destructive/5',
|
||||
)}
|
||||
>
|
||||
<td className="px-3 py-1.5">
|
||||
<Input
|
||||
value={row.name}
|
||||
onChange={(e) => updateRow(row.id, { name: e.target.value })}
|
||||
className="h-8"
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Select
|
||||
value={row.customer_type}
|
||||
onValueChange={(v) => updateRow(row.id, { customer_type: v as CustomerType })}
|
||||
>
|
||||
<SelectTrigger className="h-8">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(Object.keys(TYPE_LABELS) as CustomerType[]).map((t) => (
|
||||
<SelectItem key={t} value={t}>
|
||||
{TYPE_LABELS[t]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</td>
|
||||
<td className="px-3 py-1.5 text-muted-foreground tabular-nums">
|
||||
{row.org_number || '-'}
|
||||
</td>
|
||||
<td className="px-3 py-1.5 text-muted-foreground truncate max-w-xs">
|
||||
{row.email || '-'}
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{!row.is_valid && (
|
||||
<span
|
||||
className="text-destructive shrink-0"
|
||||
title={row.validation_errors.join(', ')}
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
)}
|
||||
{row.duplicate_match ? (
|
||||
<span
|
||||
className={cn(
|
||||
'text-[11px] font-medium px-1.5 py-0.5 rounded-full',
|
||||
updateDuplicates
|
||||
? 'bg-muted text-warning'
|
||||
: 'bg-muted text-muted-foreground',
|
||||
)}
|
||||
title={`Matchar ${row.duplicate_match.existing_name} (${row.duplicate_match.matched_by})`}
|
||||
>
|
||||
{updateDuplicates ? 'Uppdateras' : 'Hoppas över'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[11px] font-medium px-1.5 py-0.5 rounded-full bg-success/15 text-success">
|
||||
Ny
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() => deleteRow(row.id)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{hasErrors && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-warning">
|
||||
Vissa rader har valideringsfel (markerade i rött). Åtgärda eller ta bort dem
|
||||
innan du fortsätter.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-destructive mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between pt-2">
|
||||
<Button variant="ghost" onClick={onBack} disabled={isLoading}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={handleExecute} disabled={!canContinue}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
Importerar...
|
||||
</>
|
||||
) : (
|
||||
`Importera ${rows.length} rad${rows.length === 1 ? '' : 'er'}`
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo } from 'react'
|
||||
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { AlertCircle } from 'lucide-react'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { QUIET_LINK_CLASS } from '@/components/ui/dry-table'
|
||||
import { findFiscalYearGaps, type FiscalYearGap, type PeriodLike } from '@/lib/bookkeeping/fiscal-year-gaps'
|
||||
|
||||
/**
|
||||
* After a SIE import: the years the company now has, with any hole between
|
||||
* them called out. Fortnox and friends export one räkenskapsår per file, so
|
||||
* "import the next file" is the fix and this is the moment to say it.
|
||||
* Renders nothing while loading, on failure, or when the chain is whole.
|
||||
*/
|
||||
export function FiscalYearGapNotice() {
|
||||
const t = useTranslations('fiscal_year_gaps')
|
||||
// Session-cached period list (lib/reference-data): refreshed by the import
|
||||
// flow's invalidation, so the notice reflects the years just imported.
|
||||
const { periods } = useFiscalPeriods()
|
||||
const gaps = useMemo<FiscalYearGap[]>(() => findFiscalYearGaps(periods as PeriodLike[]), [periods])
|
||||
|
||||
if (gaps.length === 0) return null
|
||||
|
||||
return (
|
||||
<Card className="border-attn/50">
|
||||
<CardContent className="flex items-start gap-3 pt-6">
|
||||
<AlertCircle className="mt-0.5 h-5 w-5 shrink-0 text-attn" aria-hidden="true" />
|
||||
<div className="space-y-1 text-[13px] leading-5">
|
||||
<p className="font-medium">{t('title', { count: gaps.length })}</p>
|
||||
{gaps.map((gap) => (
|
||||
<p key={`${gap.missing_from}-${gap.missing_to}`} className="text-muted-foreground tabular-nums">
|
||||
{t('gap', { from: gap.missing_from, to: gap.missing_to, after: gap.after.name, before: gap.before.name })}
|
||||
</p>
|
||||
))}
|
||||
<p className="text-muted-foreground">
|
||||
{t('hint')}{' '}
|
||||
<Link href="/settings/bookkeeping" className={QUIET_LINK_CLASS}>
|
||||
{t('manage')}
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { SegmentedControl } from '@/components/ui/segmented-control'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { useFormat } from '@/lib/hooks/use-format'
|
||||
import { getErrorMessage, type ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import { FiscalYearSelector } from '@/components/common/FiscalYearSelector'
|
||||
import type { ApiResponse, ArchiveEstimate } from '@/types'
|
||||
import { Download, Loader2 } from 'lucide-react'
|
||||
|
||||
type Scope = 'all' | 'period'
|
||||
type ArchiveMode = 'active-company' | 'migration-reset-source'
|
||||
|
||||
const LAST_DOWNLOAD_STORAGE_KEY = 'Accounted:last-backup-download'
|
||||
|
||||
/**
|
||||
* Direct download of the complete company archive (SIE + reports + all
|
||||
* supporting documents) as a ZIP. The normal mode uses the owner/admin-only
|
||||
* full-archive route; migration-reset mode uses its owner-only retained-source
|
||||
* route without making that archived company active.
|
||||
*/
|
||||
export function FullArchiveDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
mode = 'active-company',
|
||||
companyId: explicitCompanyId,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
mode?: ArchiveMode
|
||||
companyId?: string
|
||||
}) {
|
||||
const t = useTranslations('import')
|
||||
const tCompany = useTranslations('settings_company')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const { company } = useCompany()
|
||||
const { formatDateLong } = useFormat()
|
||||
|
||||
const [scope, setScope] = useState<Scope>('all')
|
||||
const [periodId, setPeriodId] = useState<string | null>(null)
|
||||
const [includeDocuments, setIncludeDocuments] = useState(true)
|
||||
const [estimate, setEstimate] = useState<ArchiveEstimate | null>(null)
|
||||
const [isLoadingEstimate, setIsLoadingEstimate] = useState(false)
|
||||
const [isDownloading, setIsDownloading] = useState(false)
|
||||
const [lastDownloadedAt, setLastDownloadedAt] = useState<string | null>(null)
|
||||
const isMigrationResetSource = mode === 'migration-reset-source'
|
||||
const archiveCompanyId = isMigrationResetSource
|
||||
? explicitCompanyId ?? company?.id
|
||||
: company?.id
|
||||
|
||||
const storageKey = useMemo(
|
||||
() => archiveCompanyId
|
||||
? isMigrationResetSource
|
||||
? `${LAST_DOWNLOAD_STORAGE_KEY}:migration-reset:${archiveCompanyId}`
|
||||
: `${LAST_DOWNLOAD_STORAGE_KEY}:${archiveCompanyId}`
|
||||
: null,
|
||||
[archiveCompanyId, isMigrationResetSource]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (!storageKey || !open) return
|
||||
setLastDownloadedAt(window.localStorage.getItem(storageKey))
|
||||
}, [storageKey, open])
|
||||
|
||||
const archiveUrl = useMemo(() => {
|
||||
if (isMigrationResetSource) {
|
||||
if (!archiveCompanyId) return ''
|
||||
const params = new URLSearchParams()
|
||||
if (!includeDocuments) params.set('include_documents', 'false')
|
||||
const query = params.toString()
|
||||
return `/api/company/${archiveCompanyId}/migration-reset/archive${query ? `?${query}` : ''}`
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({ scope })
|
||||
if (scope === 'period' && periodId) params.set('period_id', periodId)
|
||||
if (!includeDocuments) params.set('include_documents', 'false')
|
||||
return `/api/reports/full-archive?${params.toString()}`
|
||||
}, [archiveCompanyId, includeDocuments, isMigrationResetSource, periodId, scope])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !archiveUrl || (!isMigrationResetSource && scope === 'period' && !periodId)) {
|
||||
setEstimate(null)
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
setIsLoadingEstimate(true)
|
||||
setEstimate(null)
|
||||
;(async () => {
|
||||
try {
|
||||
const separator = archiveUrl.includes('?') ? '&' : '?'
|
||||
const res = await fetch(`${archiveUrl}${separator}estimate=1`)
|
||||
if (!res.ok) return
|
||||
const { data } = (await res.json()) as ApiResponse<ArchiveEstimate>
|
||||
if (!cancelled && data) setEstimate(data)
|
||||
} catch {
|
||||
// leave estimate null; the user can still attempt the download
|
||||
} finally {
|
||||
if (!cancelled) setIsLoadingEstimate(false)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, archiveUrl, isMigrationResetSource, scope, periodId])
|
||||
|
||||
const handleDownload = useCallback(async () => {
|
||||
if (!archiveUrl || (!isMigrationResetSource && scope === 'period' && !periodId)) return
|
||||
|
||||
setIsDownloading(true)
|
||||
try {
|
||||
const res = await fetch(archiveUrl)
|
||||
if (!res.ok) {
|
||||
if (res.status === 413) {
|
||||
const body = await res.json().catch(() => ({}))
|
||||
const sizeMb = body.size_bytes ? Math.round(body.size_bytes / (1024 * 1024)) : null
|
||||
toast({
|
||||
title: t('archive_toast_too_large_title'),
|
||||
description: isMigrationResetSource
|
||||
? sizeMb
|
||||
? tCompany('reset_archive_too_large_with_size', { size: sizeMb })
|
||||
: tCompany('reset_archive_too_large')
|
||||
: sizeMb
|
||||
? t('archive_toast_too_large_with_size', { size: sizeMb })
|
||||
: t('archive_toast_too_large_generic'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
const body = await res.json().catch(() => ({}))
|
||||
throw new Error(readArchiveError(body, t('archive_toast_failed')))
|
||||
}
|
||||
|
||||
const blob = await res.blob()
|
||||
const contentDisposition = res.headers.get('Content-Disposition') || ''
|
||||
const match = contentDisposition.match(/filename="?([^";]+)"?/)
|
||||
const filename = match?.[1] || (isMigrationResetSource
|
||||
? 'migration_reset_archive.zip'
|
||||
: 'arkiv.zip')
|
||||
|
||||
const url = window.URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = filename
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
window.URL.revokeObjectURL(url)
|
||||
|
||||
const now = new Date().toISOString()
|
||||
if (storageKey) {
|
||||
window.localStorage.setItem(storageKey, now)
|
||||
setLastDownloadedAt(now)
|
||||
}
|
||||
|
||||
toast({ title: t('archive_toast_created'), description: filename })
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('archive_toast_failed'),
|
||||
description:
|
||||
err instanceof Error
|
||||
? getErrorMessage(err, { locale: errorLocale })
|
||||
: t('archive_error_fallback'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsDownloading(false)
|
||||
}
|
||||
}, [
|
||||
archiveUrl,
|
||||
errorLocale,
|
||||
isMigrationResetSource,
|
||||
periodId,
|
||||
scope,
|
||||
storageKey,
|
||||
t,
|
||||
tCompany,
|
||||
toast,
|
||||
])
|
||||
|
||||
const plannedSizeBytes = estimate
|
||||
? includeDocuments
|
||||
? estimate.total_bytes
|
||||
: Math.max(0, estimate.total_bytes - estimate.document_bytes)
|
||||
: 0
|
||||
const isOverLimit = !!estimate && plannedSizeBytes > estimate.size_limit_bytes
|
||||
const canDownload = !isDownloading
|
||||
&& !isOverLimit
|
||||
&& (isMigrationResetSource || scope === 'all' || !!periodId)
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="font-display text-lg tracking-tight">
|
||||
{isMigrationResetSource
|
||||
? tCompany('reset_archive_download_title')
|
||||
: t('export_archive_title')}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="text-[13px] leading-relaxed">
|
||||
{isMigrationResetSource
|
||||
? tCompany('reset_archive_download_description')
|
||||
: t('archive_dialog_description')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
{!isMigrationResetSource ? (
|
||||
<div className="space-y-2">
|
||||
<SegmentedControl
|
||||
value={scope}
|
||||
onChange={setScope}
|
||||
aria-label={t('archive_scope_label')}
|
||||
options={[
|
||||
{ value: 'all', label: t('archive_scope_all') },
|
||||
{ value: 'period', label: t('archive_scope_period') },
|
||||
]}
|
||||
/>
|
||||
{/* The two scopes count different document sets (all documents vs
|
||||
only those linked to posted vouchers in the year), so a company
|
||||
with unlinked inbox receipts sees very different counts. Say so,
|
||||
or the gap reads as a pagination bug. */}
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
{scope === 'all' ? t('archive_scope_all_note') : t('archive_scope_period_note')}
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!isMigrationResetSource && scope === 'period' && (
|
||||
<FiscalYearSelector
|
||||
value={periodId}
|
||||
onChange={setPeriodId}
|
||||
includeAllOption={false}
|
||||
hideFuturePeriods
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="archive-include-documents">{t('archive_include_docs_label')}</Label>
|
||||
<p className="text-xs leading-5 text-muted-foreground">
|
||||
{t('archive_include_docs_help')}
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
id="archive-include-documents"
|
||||
checked={includeDocuments}
|
||||
onCheckedChange={setIncludeDocuments}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div role="status" aria-live="polite" className="space-y-1">
|
||||
<p className="text-[13px] text-muted-foreground">
|
||||
{isLoadingEstimate ? (
|
||||
t('archive_calculating_size')
|
||||
) : estimate ? (
|
||||
<>
|
||||
{t('archive_estimated_size')}{' '}
|
||||
<strong className="font-medium tabular-nums text-foreground">
|
||||
{formatBytes(plannedSizeBytes)}
|
||||
</strong>{' '}
|
||||
({estimate.document_count}{' '}
|
||||
{estimate.document_count === 1
|
||||
? t('archive_attachment_singular')
|
||||
: t('archive_attachment_plural')}
|
||||
)
|
||||
</>
|
||||
) : (
|
||||
t('archive_size_pending')
|
||||
)}
|
||||
</p>
|
||||
{lastDownloadedAt && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('archive_last_download')}: {formatDateLong(lastDownloadedAt)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isOverLimit && (
|
||||
<AttnLine>
|
||||
{isMigrationResetSource
|
||||
? tCompany('reset_archive_over_limit', {
|
||||
limit: formatBytes(estimate!.size_limit_bytes),
|
||||
})
|
||||
: t('archive_over_limit', { limit: formatBytes(estimate!.size_limit_bytes) })}
|
||||
</AttnLine>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button onClick={handleDownload} disabled={!canDownload}>
|
||||
{isDownloading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
{t('archive_creating')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
{t('archive_download_button')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
const kb = bytes / 1024
|
||||
if (kb < 1024) return `${kb.toFixed(1)} kB`
|
||||
const mb = kb / 1024
|
||||
if (mb < 1024) return `${mb.toFixed(1)} MB`
|
||||
return `${(mb / 1024).toFixed(2)} GB`
|
||||
}
|
||||
|
||||
function readArchiveError(body: unknown, fallback: string): string {
|
||||
if (!body || typeof body !== 'object') return fallback
|
||||
const error = (body as { error?: unknown }).error
|
||||
if (typeof error === 'string') return error
|
||||
if (error && typeof error === 'object') {
|
||||
const message = (error as { message?: unknown }).message
|
||||
if (typeof message === 'string') return message
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,158 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import TheaterCanvas, { type TheaterCanvasHandle } from '@/components/import/TheaterCanvas'
|
||||
import type { ImportPreview } from '@/lib/import/types'
|
||||
import type { TheaterModel } from '@/lib/import/theater-model'
|
||||
|
||||
/**
|
||||
* The import theater: while the SIE import commits server-side (one opaque
|
||||
* call, up to ~5 minutes), the client-parsed file drives a knowledge graph
|
||||
* that draws itself, with narration lines pacing alongside. The final line
|
||||
* holds with the elapsed counter until the server answers, so the animation
|
||||
* never pretends to know more than the import does. Reduced motion renders
|
||||
* the settled graph and all narration instantly.
|
||||
*/
|
||||
|
||||
interface ImportTheaterProps {
|
||||
model: TheaterModel
|
||||
preview: ImportPreview
|
||||
/** Elapsed seconds since execute started (owned by ImportReviewStep). */
|
||||
elapsed: number
|
||||
}
|
||||
|
||||
export default function ImportTheater({ model, preview, elapsed }: ImportTheaterProps) {
|
||||
const t = useTranslations('import')
|
||||
const canvasRef = useRef<TheaterCanvasHandle | null>(null)
|
||||
const [lineCount, setLineCount] = useState(0)
|
||||
const [voucherTick, setVoucherTick] = useState(0)
|
||||
|
||||
const reduced =
|
||||
typeof window !== 'undefined' &&
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
|
||||
const lines: { title: string; sub: string | null; ok?: boolean; warn?: boolean }[] = [
|
||||
{
|
||||
title: t('theater_reading', { company: model.companyName || preview.companyName || '' }),
|
||||
sub: t('theater_years', { count: Math.max(model.years.length, 1) }),
|
||||
ok: true,
|
||||
},
|
||||
{
|
||||
title: t('theater_vouchers'),
|
||||
sub: `${voucherTick.toLocaleString('sv-SE')} ${t('theater_vouchers_unit')}`,
|
||||
},
|
||||
{
|
||||
title: t('theater_accounts'),
|
||||
sub: t('theater_accounts_sub', {
|
||||
mapped: preview.mappingStatus.mapped,
|
||||
total: preview.mappingStatus.total,
|
||||
}),
|
||||
},
|
||||
...(model.totalCounterparties > 0
|
||||
? [{
|
||||
title: t('theater_counterparties'),
|
||||
sub: t('theater_counterparties_sub', { count: model.totalCounterparties }),
|
||||
}]
|
||||
: []),
|
||||
{
|
||||
title: t('theater_balance'),
|
||||
sub: preview.trialBalance.isBalanced ? t('theater_balance_ok') : t('theater_balance_warn'),
|
||||
ok: preview.trialBalance.isBalanced,
|
||||
warn: !preview.trialBalance.isBalanced,
|
||||
},
|
||||
]
|
||||
const holdingVisible = lineCount > lines.length
|
||||
|
||||
// Narration pacing + graph spawn hooks: the narration and the constellation
|
||||
// always agree on what has "happened".
|
||||
useEffect(() => {
|
||||
const canvas = () => canvasRef.current
|
||||
if (reduced) {
|
||||
setLineCount(lines.length + 1)
|
||||
setVoucherTick(preview.voucherCount)
|
||||
return
|
||||
}
|
||||
const timers: number[] = []
|
||||
const at = (ms: number, fn: () => void) => timers.push(window.setTimeout(fn, ms))
|
||||
const hasCps = model.totalCounterparties > 0
|
||||
at(300, () => {
|
||||
setLineCount(1)
|
||||
canvas()?.spawn('ring')
|
||||
})
|
||||
at(1500, () => {
|
||||
setLineCount(2)
|
||||
canvas()?.spawn('bucket')
|
||||
canvas()?.feed(2100)
|
||||
;[0, 1, 2, 3].forEach((w) =>
|
||||
timers.push(window.setTimeout(() => canvas()?.spawn('account', w), 200 + w * 420))
|
||||
)
|
||||
const t0 = performance.now()
|
||||
const tick = () => {
|
||||
const p = Math.min(1, (performance.now() - t0) / 1600)
|
||||
setVoucherTick(Math.round(preview.voucherCount * p))
|
||||
if (p < 1) requestAnimationFrame(tick)
|
||||
}
|
||||
requestAnimationFrame(tick)
|
||||
})
|
||||
at(3400, () => setLineCount(3))
|
||||
if (hasCps) {
|
||||
at(4600, () => {
|
||||
setLineCount(4)
|
||||
;[0, 1, 2].forEach((w) =>
|
||||
timers.push(window.setTimeout(() => canvas()?.spawn('counterparty', w), 120 + w * 420))
|
||||
)
|
||||
})
|
||||
}
|
||||
at(hasCps ? 6000 : 4600, () => {
|
||||
setLineCount(hasCps ? 5 : 4)
|
||||
canvas()?.pulse()
|
||||
})
|
||||
at(hasCps ? 7100 : 5700, () => setLineCount(lines.length + 1))
|
||||
return () => timers.forEach((id) => window.clearTimeout(id))
|
||||
// The theater runs once per mount for one (model, preview) pair.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 md:grid-cols-[280px_1fr]">
|
||||
<div role="status" aria-live="polite">
|
||||
<ol className="space-y-0">
|
||||
{lines.map((line, i) => {
|
||||
const visible = lineCount > i
|
||||
const active = lineCount === i + 1 && !holdingVisible
|
||||
return (
|
||||
<li
|
||||
key={line.title}
|
||||
className={`border-b border-border/60 py-2.5 transition-opacity duration-500 last:border-b-0 ${
|
||||
visible ? 'opacity-100' : 'opacity-0'
|
||||
}`}
|
||||
>
|
||||
<p className="text-sm">{line.title}</p>
|
||||
<p
|
||||
className={`mt-0.5 min-h-4 text-xs tabular-nums ${
|
||||
visible && line.ok && !active
|
||||
? 'text-success'
|
||||
: visible && line.warn
|
||||
? 'text-warning'
|
||||
: 'text-muted-foreground'
|
||||
}`}
|
||||
>
|
||||
{visible ? line.sub : null}
|
||||
</p>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
{holdingVisible && (
|
||||
<p className="mt-4 text-xs text-muted-foreground tabular-nums">
|
||||
{t('theater_writing')} {elapsed}s
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="relative min-h-[340px] md:min-h-[420px]">
|
||||
<TheaterCanvas ref={canvasRef} model={model} />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import type { DetectedColumns, BalanceColumnLayout } from '@/lib/import/opening-balance/types'
|
||||
|
||||
interface OpeningBalanceColumnMappingStepProps {
|
||||
headers: string[]
|
||||
previewRows: string[][]
|
||||
detectedColumns: DetectedColumns
|
||||
onConfirm: (columns: DetectedColumns) => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export default function OpeningBalanceColumnMappingStep({
|
||||
headers,
|
||||
previewRows,
|
||||
detectedColumns,
|
||||
onConfirm,
|
||||
onBack,
|
||||
}: OpeningBalanceColumnMappingStepProps) {
|
||||
const [accountNumberCol, setAccountNumberCol] = useState(
|
||||
detectedColumns.account_number_col,
|
||||
)
|
||||
const [accountNameCol, setAccountNameCol] = useState<number | null>(
|
||||
detectedColumns.account_name_col,
|
||||
)
|
||||
const [layout, setLayout] = useState<BalanceColumnLayout>(
|
||||
detectedColumns.layout,
|
||||
)
|
||||
const [balanceCol, setBalanceCol] = useState<number | null>(
|
||||
detectedColumns.balance_col,
|
||||
)
|
||||
const [debitCol, setDebitCol] = useState<number | null>(
|
||||
detectedColumns.debit_col,
|
||||
)
|
||||
const [creditCol, setCreditCol] = useState<number | null>(
|
||||
detectedColumns.credit_col,
|
||||
)
|
||||
|
||||
const columnOptions = headers.map((h, i) => ({
|
||||
value: String(i),
|
||||
label: `${i + 1}: ${h || '(tom)'}`,
|
||||
}))
|
||||
|
||||
const canContinue =
|
||||
accountNumberCol >= 0 &&
|
||||
(layout === 'net' ? balanceCol !== null : debitCol !== null && creditCol !== null)
|
||||
|
||||
const handleConfirm = () => {
|
||||
onConfirm({
|
||||
account_number_col: accountNumberCol,
|
||||
account_name_col: accountNameCol,
|
||||
layout,
|
||||
balance_col: layout === 'net' ? balanceCol : null,
|
||||
debit_col: layout === 'debit_credit' ? debitCol : null,
|
||||
credit_col: layout === 'debit_credit' ? creditCol : null,
|
||||
confidence: 1, // User-confirmed
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Kolumnmappning</CardTitle>
|
||||
<CardDescription>
|
||||
Vi kunde inte automatiskt identifiera alla kolumner. Ange vilka kolumner
|
||||
som innehåller kontonummer och belopp.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Layout toggle */}
|
||||
<div className="space-y-2">
|
||||
<Label>Beloppslayout</Label>
|
||||
<Select value={layout} onValueChange={(v) => setLayout(v as BalanceColumnLayout)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="net">Nettobelopp (en kolumn)</SelectItem>
|
||||
<SelectItem value="debit_credit">Debet & kredit (två kolumner)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Required mappings */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Kontonummer *</Label>
|
||||
<Select
|
||||
value={String(accountNumberCol)}
|
||||
onValueChange={(v) => setAccountNumberCol(Number(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Kontonamn</Label>
|
||||
<Select
|
||||
value={accountNameCol !== null ? String(accountNameCol) : 'none'}
|
||||
onValueChange={(v) => setAccountNameCol(v === 'none' ? null : Number(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">(ingen)</SelectItem>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{layout === 'net' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Saldo/Belopp *</Label>
|
||||
<Select
|
||||
value={balanceCol !== null ? String(balanceCol) : ''}
|
||||
onValueChange={(v) => setBalanceCol(Number(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{layout === 'debit_credit' && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label>Debet *</Label>
|
||||
<Select
|
||||
value={debitCol !== null ? String(debitCol) : ''}
|
||||
onValueChange={(v) => setDebitCol(Number(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Kredit *</Label>
|
||||
<Select
|
||||
value={creditCol !== null ? String(creditCol) : ''}
|
||||
onValueChange={(v) => setCreditCol(Number(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Preview */}
|
||||
{previewRows.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-muted-foreground">Förhandsgranskning (5 första raderna)</Label>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b">
|
||||
{headers.map((h, i) => (
|
||||
/* data-ph-mask: CSV headers are user data */
|
||||
<th key={i} data-ph-mask="" className="px-3 py-2 text-left whitespace-nowrap">
|
||||
{h || `Kolumn ${i + 1}`}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{previewRows.slice(0, 5).map((row, ri) => (
|
||||
<tr key={ri} className="border-b last:border-0">
|
||||
{row.map((cell, ci) => (
|
||||
<td key={ci} className="px-3 py-1.5 whitespace-nowrap tabular-nums">
|
||||
{cell}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex justify-between">
|
||||
<Button variant="ghost" onClick={onBack}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={handleConfirm} disabled={!canContinue}>
|
||||
Fortsätt
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import type { ParsedOpeningBalanceRow } from '@/lib/import/opening-balance/types'
|
||||
import OpeningBalanceRowEditor, {
|
||||
type EditableRow,
|
||||
type OpeningBalanceEditorState,
|
||||
} from './OpeningBalanceRowEditor'
|
||||
|
||||
interface OpeningBalanceEditStepProps {
|
||||
rows: ParsedOpeningBalanceRow[]
|
||||
onContinue: (rows: EditableRow[]) => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
let idCounter = 0
|
||||
function generateId() {
|
||||
return `row_${++idCounter}_${Date.now()}`
|
||||
}
|
||||
|
||||
export default function OpeningBalanceEditStep({
|
||||
rows: initialRows,
|
||||
onContinue,
|
||||
onBack,
|
||||
}: OpeningBalanceEditStepProps) {
|
||||
const seedRows = useMemo<EditableRow[]>(
|
||||
() =>
|
||||
initialRows.map((r) => ({
|
||||
id: generateId(),
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
debit_amount: r.debit_amount,
|
||||
credit_amount: r.credit_amount,
|
||||
validation_errors: [...r.validation_errors],
|
||||
bas_match: r.bas_match,
|
||||
})),
|
||||
[initialRows],
|
||||
)
|
||||
const [state, setState] = useState<OpeningBalanceEditorState | null>(null)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Granska och redigera</CardTitle>
|
||||
<CardDescription>
|
||||
Kontrollera att kontonummer och belopp stämmer. Du kan lägga till, ta bort och ändra
|
||||
rader. Debet och kredit måste balansera innan du kan fortsätta.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<OpeningBalanceRowEditor initialRows={seedRows} onChange={setState} />
|
||||
|
||||
<div className="flex justify-between pt-2">
|
||||
<Button variant="ghost" onClick={onBack}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={() => state && onContinue(state.rows)} disabled={!state?.canSubmit}>
|
||||
Fortsätt
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { useFiscalPeriods } from '@/lib/reference-data/hooks'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { AlertCircle, Loader2, CheckCircle2 } from 'lucide-react'
|
||||
|
||||
interface EditableRow {
|
||||
id: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
debit_amount: number
|
||||
credit_amount: number
|
||||
}
|
||||
|
||||
interface OpeningBalancePeriodStepProps {
|
||||
rows: EditableRow[]
|
||||
/** `replace` is true when the selected period already has opening balances
|
||||
* (the existing IB verifikat will be stornoed and replaced). */
|
||||
onExecute: (fiscalPeriodId: string, replace: boolean) => void
|
||||
onBack: () => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export default function OpeningBalancePeriodStep({
|
||||
rows,
|
||||
onExecute,
|
||||
onBack,
|
||||
isLoading,
|
||||
error,
|
||||
}: OpeningBalancePeriodStepProps) {
|
||||
// Session-cached period list (lib/reference-data).
|
||||
const { periods, isLoading: loadingPeriods } = useFiscalPeriods()
|
||||
const [selectedPeriodId, setSelectedPeriodId] = useState<string>('')
|
||||
// Auto-select the first open period without OB once per load, never again
|
||||
// on a background refresh of the list (that would override a user pick).
|
||||
const autoSelectedRef = useRef(false)
|
||||
|
||||
// Compute totals
|
||||
let totalDebit = 0
|
||||
let totalCredit = 0
|
||||
for (const row of rows) {
|
||||
totalDebit = Math.round((totalDebit + row.debit_amount) * 100) / 100
|
||||
totalCredit = Math.round((totalCredit + row.credit_amount) * 100) / 100
|
||||
}
|
||||
// Compare in whole öre, mirroring the engine's validateBalance: a float
|
||||
// epsilon like (< 0.01) would misclassify exact 1-öre imbalances as
|
||||
// balanced, since e.g. 0.03 - 0.02 evaluates to just under 0.01.
|
||||
const balanceDiff = Math.round((totalDebit - totalCredit) * 100) / 100
|
||||
const isBalanced = Math.round((totalDebit - totalCredit) * 100) === 0
|
||||
|
||||
useEffect(() => {
|
||||
if (loadingPeriods || autoSelectedRef.current) return
|
||||
autoSelectedRef.current = true
|
||||
const openPeriod = periods.find(
|
||||
(p) => !p.is_closed && !p.locked_at && !p.opening_balances_set,
|
||||
)
|
||||
if (openPeriod) setSelectedPeriodId(openPeriod.id)
|
||||
}, [periods, loadingPeriods])
|
||||
|
||||
const selectedPeriod = periods.find((p) => p.id === selectedPeriodId)
|
||||
const periodHasOB = !!selectedPeriod?.opening_balances_set
|
||||
const periodIsClosed = selectedPeriod?.is_closed
|
||||
const periodIsLocked = !!selectedPeriod?.locked_at
|
||||
|
||||
// A period that already has IB can still be corrected, as long as it is open
|
||||
// and unlocked: the existing IB verifikat is stornoed and replaced.
|
||||
const canExecute =
|
||||
!!selectedPeriodId &&
|
||||
!periodIsClosed &&
|
||||
!periodIsLocked &&
|
||||
isBalanced &&
|
||||
!isLoading
|
||||
|
||||
const handleExecute = useCallback(() => {
|
||||
if (canExecute) {
|
||||
onExecute(selectedPeriodId, periodHasOB)
|
||||
}
|
||||
}, [canExecute, selectedPeriodId, periodHasOB, onExecute])
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Välj räkenskapsperiod</CardTitle>
|
||||
<CardDescription>
|
||||
Välj vilken räkenskapsperiod de ingående balanserna ska bokföras på.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Period selector */}
|
||||
<div className="space-y-2">
|
||||
<Label>Räkenskapsperiod</Label>
|
||||
{loadingPeriods ? (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground py-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Hämtar perioder...
|
||||
</div>
|
||||
) : periods.length === 0 ? (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<AlertCircle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-warning">
|
||||
Inga räkenskapsperioder hittades. Skapa en räkenskapsperiod under Bokföring först.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<Select value={selectedPeriodId} onValueChange={setSelectedPeriodId}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj period" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{periods.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id} disabled={p.is_closed || !!p.locked_at}>
|
||||
{p.name} ({p.period_start} till {p.period_end})
|
||||
{p.opening_balances_set && ', har redan IB'}
|
||||
{p.is_closed && ', stängd'}
|
||||
{p.locked_at && !p.is_closed && ', låst'}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Replace notice: selecting a period that already has IB corrects it */}
|
||||
{periodHasOB && !periodIsClosed && !periodIsLocked && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<AlertCircle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-warning">
|
||||
Denna period har redan ingående balanser. Om du fortsätter makuleras (stornas) den
|
||||
befintliga IB-verifikationen och en ny bokförs med beloppen nedan.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Summary */}
|
||||
<div className="rounded-lg border bg-muted/30 p-4 space-y-3">
|
||||
<h4 className="text-sm font-medium">Sammanfattning</h4>
|
||||
<div className="grid grid-cols-2 gap-y-2 text-sm">
|
||||
<span className="text-muted-foreground">Antal konton:</span>
|
||||
<span className="tabular-nums text-right">{rows.length}</span>
|
||||
<span className="text-muted-foreground">Total debet:</span>
|
||||
<span className="tabular-nums text-right">
|
||||
{totalDebit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK
|
||||
</span>
|
||||
<span className="text-muted-foreground">Total kredit:</span>
|
||||
<span className="tabular-nums text-right">
|
||||
{totalCredit.toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK
|
||||
</span>
|
||||
</div>
|
||||
{isBalanced ? (
|
||||
<div className="flex items-center gap-2 pt-1 border-t text-sm">
|
||||
<CheckCircle2 className="h-4 w-4 text-success" />
|
||||
<span className="text-success font-medium">Balanserar</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 pt-1 border-t text-sm">
|
||||
<AlertCircle className="h-4 w-4 text-destructive shrink-0" />
|
||||
<span className="text-destructive font-medium">
|
||||
Balanserar inte (differens{' '}
|
||||
<span className="tabular-nums">
|
||||
{balanceDiff.toLocaleString('sv-SE', { minimumFractionDigits: 2 })}
|
||||
</span>{' '}
|
||||
SEK)
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3">
|
||||
<AlertCircle className="h-4 w-4 text-destructive mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex justify-between pt-2">
|
||||
<Button variant="ghost" onClick={onBack} disabled={isLoading}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={handleExecute} disabled={!canExecute}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
{periodHasOB ? 'Ersätter...' : 'Bokför...'}
|
||||
</>
|
||||
) : periodHasOB ? (
|
||||
'Ersätt ingående balanser'
|
||||
) : (
|
||||
'Bokför ingående balanser'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
'use client'
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { CheckCircle2, XCircle, ArrowRight } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import type { OpeningBalanceExecuteResult } from '@/lib/import/opening-balance/types'
|
||||
|
||||
interface OpeningBalanceResultStepProps {
|
||||
result: OpeningBalanceExecuteResult
|
||||
onNewImport: () => void
|
||||
}
|
||||
|
||||
export default function OpeningBalanceResultStep({
|
||||
result,
|
||||
onNewImport,
|
||||
}: OpeningBalanceResultStepProps) {
|
||||
const isCorrection = !!result.reversed_entry_id
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
{result.success ? (
|
||||
<CheckCircle2 className="h-6 w-6 text-success" />
|
||||
) : (
|
||||
<XCircle className="h-6 w-6 text-destructive" />
|
||||
)}
|
||||
<CardTitle>
|
||||
{result.success
|
||||
? isCorrection
|
||||
? 'Ingående balanser korrigerade'
|
||||
: 'Ingående balanser bokförda'
|
||||
: 'Importen misslyckades'}
|
||||
</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{result.success ? (
|
||||
<>
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="rounded-lg border bg-muted/30 p-4 text-center">
|
||||
<p className="text-2xl font-semibold tabular-nums">
|
||||
{result.lines_created}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">Kontorader</p>
|
||||
</div>
|
||||
<div className="rounded-lg border bg-muted/30 p-4 text-center">
|
||||
<p className="text-2xl font-semibold tabular-nums">
|
||||
{result.total_debit.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 0,
|
||||
})}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">Debet (SEK)</p>
|
||||
</div>
|
||||
<div className="rounded-lg border bg-muted/30 p-4 text-center">
|
||||
<p className="text-2xl font-semibold tabular-nums">
|
||||
{result.total_credit.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 0,
|
||||
})}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">Kredit (SEK)</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Next steps */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium">Nästa steg</h4>
|
||||
<ol className="text-sm text-muted-foreground space-y-1.5 list-decimal list-inside">
|
||||
<li>Granska verifikationen i bokföringen</li>
|
||||
<li>Kontrollera balansrapporten att beloppen stämmer</li>
|
||||
<li>Börja importera banktransaktioner eller skapa verifikationer</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{result.journal_entry_id && (
|
||||
<Button asChild>
|
||||
<Link href={`/bookkeeping/${result.journal_entry_id}`}>
|
||||
Visa verifikation
|
||||
<ArrowRight className="h-4 w-4 ml-2" />
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/reports">
|
||||
Visa rapporter
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={onNewImport}>
|
||||
Ny import
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3">
|
||||
<p className="text-sm text-destructive">
|
||||
{result.error || 'Ett okänt fel uppstod vid importen.'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3">
|
||||
<Button variant="outline" onClick={onNewImport}>
|
||||
Försök igen
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useMemo, useCallback, useRef, useEffect } from 'react'
|
||||
import Fuse, { type IFuseOptions } from 'fuse.js'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Plus, Trash2, AlertTriangle, Scale } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getBasLoaded } from '@/lib/bookkeeping/bas-lazy'
|
||||
import { useBasReference } from '@/lib/bookkeeping/use-bas-reference'
|
||||
import type { BASReferenceAccount } from '@/lib/bookkeeping/bas-reference'
|
||||
|
||||
export interface EditableRow {
|
||||
id: string
|
||||
account_number: string
|
||||
account_name: string
|
||||
debit_amount: number
|
||||
credit_amount: number
|
||||
validation_errors: string[]
|
||||
bas_match: string | null
|
||||
}
|
||||
|
||||
export interface OpeningBalanceEditorState {
|
||||
rows: EditableRow[]
|
||||
totals: { debit: number; credit: number; diff: number; isBalanced: boolean }
|
||||
/** Balanced, no row errors, and at least two lines: safe to book/correct. */
|
||||
canSubmit: boolean
|
||||
}
|
||||
|
||||
interface OpeningBalanceRowEditorProps {
|
||||
/** Seed rows. Read once on mount (later prop changes are ignored: remount
|
||||
* via `key` or a conditional render to reset the grid). */
|
||||
initialRows: EditableRow[]
|
||||
/** Fires whenever rows / totals / validity change. Held in a ref internally,
|
||||
* so it does NOT need to be referentially stable: passing an inline arrow
|
||||
* is safe and will not cause an update-loop. */
|
||||
onChange: (state: OpeningBalanceEditorState) => void
|
||||
}
|
||||
|
||||
// Balance-sheet accounts (class 1-2) drive the primary suggestions; numeric
|
||||
// queries fall back to the full chart. The chart is a lazily loaded chunk
|
||||
// (lib/bookkeeping/bas-lazy.ts): the indexes are built on first use after
|
||||
// it has arrived, and the suggestion list is empty until then.
|
||||
const FUSE_OPTIONS: IFuseOptions<BASReferenceAccount> = {
|
||||
keys: ['account_number', 'account_name'],
|
||||
threshold: 0.3,
|
||||
includeScore: true,
|
||||
}
|
||||
|
||||
let fuseInstance: Fuse<BASReferenceAccount> | null = null
|
||||
function getFuse(): Fuse<BASReferenceAccount> | null {
|
||||
const chart = getBasLoaded()
|
||||
if (!chart) return null
|
||||
if (!fuseInstance) fuseInstance = new Fuse(chart, FUSE_OPTIONS)
|
||||
return fuseInstance
|
||||
}
|
||||
|
||||
let balanceFuseInstance: Fuse<BASReferenceAccount> | null = null
|
||||
function getBalanceFuse(): Fuse<BASReferenceAccount> | null {
|
||||
const chart = getBasLoaded()
|
||||
if (!chart) return null
|
||||
if (!balanceFuseInstance) {
|
||||
balanceFuseInstance = new Fuse(
|
||||
chart.filter((a) => a.account_class === 1 || a.account_class === 2),
|
||||
FUSE_OPTIONS,
|
||||
)
|
||||
}
|
||||
return balanceFuseInstance
|
||||
}
|
||||
|
||||
let idCounter = 0
|
||||
function generateId() {
|
||||
return `row_${++idCounter}_${Date.now()}`
|
||||
}
|
||||
|
||||
// Defense-in-depth dedup: if a seed source ever leaks duplicate accounts,
|
||||
// collapse them before the user sees them. Union validation_errors so a
|
||||
// warning surfaced only on the later row isn't silently dropped on merge.
|
||||
function dedupeRows(initialRows: EditableRow[]): EditableRow[] {
|
||||
const byAccount = new Map<string, EditableRow>()
|
||||
for (const r of initialRows) {
|
||||
const key = r.account_number.replace(/\D/g, '')
|
||||
const existing = byAccount.get(key)
|
||||
if (existing) {
|
||||
existing.debit_amount = Math.round((existing.debit_amount + r.debit_amount) * 100) / 100
|
||||
existing.credit_amount = Math.round((existing.credit_amount + r.credit_amount) * 100) / 100
|
||||
if (!existing.account_name && r.account_name) existing.account_name = r.account_name
|
||||
if (r.validation_errors?.length) {
|
||||
const seen = new Set(existing.validation_errors)
|
||||
for (const err of r.validation_errors) {
|
||||
if (!seen.has(err)) existing.validation_errors.push(err)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
byAccount.set(key, {
|
||||
id: r.id || generateId(),
|
||||
account_number: r.account_number,
|
||||
account_name: r.account_name,
|
||||
debit_amount: r.debit_amount,
|
||||
credit_amount: r.credit_amount,
|
||||
validation_errors: [...r.validation_errors],
|
||||
bas_match: r.bas_match,
|
||||
})
|
||||
}
|
||||
return Array.from(byAccount.values())
|
||||
}
|
||||
|
||||
/**
|
||||
* The opening-balance line grid: editable account / debet / kredit rows with
|
||||
* BAS autocomplete, a live debit-credit balance check, blocking of resultat-
|
||||
* konton (class 3-8), and a "round to 2099" auto-balance for sub-1-SEK drift.
|
||||
*
|
||||
* Stateless about WHY it's editing: the wizard seeds it from a parsed file,
|
||||
* the verifikat correction dialog seeds it from the booked IB's lines. Both
|
||||
* read the current rows + validity through `onChange`.
|
||||
*/
|
||||
export default function OpeningBalanceRowEditor({
|
||||
initialRows,
|
||||
onChange,
|
||||
}: OpeningBalanceRowEditorProps) {
|
||||
const [rows, setRows] = useState<EditableRow[]>(() => dedupeRows(initialRows))
|
||||
const [activeAutocomplete, setActiveAutocomplete] = useState<string | null>(null)
|
||||
const [autocompleteQuery, setAutocompleteQuery] = useState('')
|
||||
const autocompleteRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Hold onChange in a ref so an unstable (inline) callback identity can't
|
||||
// retrigger the notifying effect below. Synced after each commit rather than
|
||||
// during render (react-hooks/refs: refs must not be written while rendering).
|
||||
const onChangeRef = useRef(onChange)
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange
|
||||
})
|
||||
|
||||
const totals = useMemo(() => {
|
||||
let debit = 0
|
||||
let credit = 0
|
||||
for (const row of rows) {
|
||||
debit = Math.round((debit + row.debit_amount) * 100) / 100
|
||||
credit = Math.round((credit + row.credit_amount) * 100) / 100
|
||||
}
|
||||
const diff = Math.round((debit - credit) * 100) / 100
|
||||
return { debit, credit, diff, isBalanced: Math.abs(diff) < 0.01 }
|
||||
}, [rows])
|
||||
|
||||
const hasErrors = useMemo(() => {
|
||||
return rows.some((r) => {
|
||||
if (!/^\d{4}$/.test(r.account_number)) return true
|
||||
if (r.debit_amount === 0 && r.credit_amount === 0) return true
|
||||
if (r.validation_errors.length > 0) return true
|
||||
return false
|
||||
})
|
||||
}, [rows])
|
||||
|
||||
const canSubmit = totals.isBalanced && !hasErrors && rows.length >= 2
|
||||
|
||||
// Push state up via the ref so an unstable `onChange` identity can't retrigger
|
||||
// this effect. Memoised `totals` means it only fires when the user actually
|
||||
// edits a row, never in a loop.
|
||||
useEffect(() => {
|
||||
onChangeRef.current({ rows, totals, canSubmit })
|
||||
}, [rows, totals, canSubmit])
|
||||
|
||||
const basReady = useBasReference()
|
||||
const autocompleteResults = useMemo(() => {
|
||||
if (!autocompleteQuery || autocompleteQuery.length < 1) return []
|
||||
const isNumeric = /^\d+$/.test(autocompleteQuery)
|
||||
const fuse = isNumeric ? getFuse() : getBalanceFuse()
|
||||
if (!fuse) return []
|
||||
return fuse.search(autocompleteQuery, { limit: 8 }).map((r) => r.item)
|
||||
// basReady re-runs the search once the chart chunk has arrived.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [autocompleteQuery, basReady])
|
||||
|
||||
const updateRow = useCallback((id: string, updates: Partial<EditableRow>) => {
|
||||
setRows((prev) =>
|
||||
prev.map((r) => {
|
||||
if (r.id !== id) return r
|
||||
const updated = { ...r, ...updates }
|
||||
|
||||
// Re-validate
|
||||
const errors: string[] = []
|
||||
if (!/^\d{4}$/.test(updated.account_number)) {
|
||||
errors.push('Ogiltigt kontonummer')
|
||||
}
|
||||
const cls = parseInt(updated.account_number.charAt(0), 10)
|
||||
if (cls >= 3 && cls <= 8) {
|
||||
errors.push(`Resultatkonto (klass ${cls})`)
|
||||
}
|
||||
updated.validation_errors = errors
|
||||
|
||||
return updated
|
||||
}),
|
||||
)
|
||||
}, [])
|
||||
|
||||
const deleteRow = useCallback((id: string) => {
|
||||
setRows((prev) => prev.filter((r) => r.id !== id))
|
||||
}, [])
|
||||
|
||||
const addRow = useCallback(() => {
|
||||
setRows((prev) => [
|
||||
...prev,
|
||||
{
|
||||
id: generateId(),
|
||||
account_number: '',
|
||||
account_name: '',
|
||||
debit_amount: 0,
|
||||
credit_amount: 0,
|
||||
validation_errors: ['Ogiltigt kontonummer'],
|
||||
bas_match: null,
|
||||
},
|
||||
])
|
||||
}, [])
|
||||
|
||||
const selectAutocompleteItem = useCallback(
|
||||
(rowId: string, account: BASReferenceAccount) => {
|
||||
updateRow(rowId, {
|
||||
account_number: account.account_number,
|
||||
account_name: account.account_name,
|
||||
bas_match: account.account_name,
|
||||
})
|
||||
setActiveAutocomplete(null)
|
||||
setAutocompleteQuery('')
|
||||
},
|
||||
[updateRow],
|
||||
)
|
||||
|
||||
const handleAutoBalance = useCallback(() => {
|
||||
if (Math.abs(totals.diff) > 1) return // Only auto-balance ≤ 1 SEK
|
||||
if (totals.isBalanced) return
|
||||
|
||||
const adjustmentRow: EditableRow = {
|
||||
id: generateId(),
|
||||
account_number: '2099',
|
||||
account_name: 'Årets resultat',
|
||||
debit_amount: totals.diff > 0 ? 0 : Math.abs(totals.diff),
|
||||
credit_amount: totals.diff > 0 ? totals.diff : 0,
|
||||
validation_errors: [],
|
||||
bas_match: 'Årets resultat',
|
||||
}
|
||||
setRows((prev) => [...prev, adjustmentRow])
|
||||
}, [totals])
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Table */}
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b">
|
||||
<th className="px-3 py-2 text-left w-28">Konto</th>
|
||||
<th className="px-3 py-2 text-left">Kontonamn</th>
|
||||
<th className="px-3 py-2 text-right w-32">Debet</th>
|
||||
<th className="px-3 py-2 text-right w-32">Kredit</th>
|
||||
<th className="px-3 py-2 w-10" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={cn(
|
||||
'border-b last:border-0',
|
||||
row.validation_errors.length > 0 && 'bg-destructive/5',
|
||||
)}
|
||||
>
|
||||
<td className="px-3 py-1.5 relative">
|
||||
<Input
|
||||
value={row.account_number}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value.replace(/[^0-9]/g, '').slice(0, 4)
|
||||
updateRow(row.id, { account_number: val })
|
||||
setActiveAutocomplete(row.id)
|
||||
setAutocompleteQuery(val)
|
||||
}}
|
||||
onFocus={() => {
|
||||
setActiveAutocomplete(row.id)
|
||||
setAutocompleteQuery(row.account_number)
|
||||
}}
|
||||
onBlur={() => {
|
||||
// Delay to allow click on autocomplete items
|
||||
setTimeout(() => setActiveAutocomplete(null), 200)
|
||||
}}
|
||||
placeholder="1930"
|
||||
className="h-8 font-mono tabular-nums w-20"
|
||||
maxLength={4}
|
||||
/>
|
||||
{/* Autocomplete dropdown */}
|
||||
{activeAutocomplete === row.id && autocompleteResults.length > 0 && (
|
||||
<div
|
||||
ref={autocompleteRef}
|
||||
className="absolute z-50 top-full left-3 mt-1 w-72 max-h-48 overflow-y-auto rounded-lg border bg-popover shadow-md"
|
||||
>
|
||||
{autocompleteResults.map((item) => (
|
||||
<button
|
||||
key={item.account_number}
|
||||
className="flex items-center gap-2 w-full px-3 py-1.5 text-left text-sm hover:bg-accent transition-colors"
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault()
|
||||
selectAutocompleteItem(row.id, item)
|
||||
}}
|
||||
>
|
||||
<span className="font-mono text-muted-foreground tabular-nums">
|
||||
{item.account_number}
|
||||
</span>
|
||||
<span className="truncate">{item.account_name}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm truncate max-w-xs">{row.account_name}</span>
|
||||
{row.validation_errors.length > 0 && (
|
||||
<span
|
||||
className="text-destructive shrink-0"
|
||||
title={row.validation_errors.join(', ')}
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Input
|
||||
type="number"
|
||||
value={row.debit_amount || ''}
|
||||
onChange={(e) =>
|
||||
updateRow(row.id, {
|
||||
debit_amount: Math.round(parseFloat(e.target.value || '0') * 100) / 100,
|
||||
})
|
||||
}
|
||||
placeholder="0,00"
|
||||
className="h-8 text-right tabular-nums w-28"
|
||||
min={0}
|
||||
step={0.01}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Input
|
||||
type="number"
|
||||
value={row.credit_amount || ''}
|
||||
onChange={(e) =>
|
||||
updateRow(row.id, {
|
||||
credit_amount: Math.round(parseFloat(e.target.value || '0') * 100) / 100,
|
||||
})
|
||||
}
|
||||
placeholder="0,00"
|
||||
className="h-8 text-right tabular-nums w-28"
|
||||
min={0}
|
||||
step={0.01}
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-7 w-7"
|
||||
onClick={() => deleteRow(row.id)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr className="border-t-2 font-medium">
|
||||
<td className="px-3 py-2" colSpan={2}>
|
||||
Summa
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right tabular-nums">
|
||||
{totals.debit.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})}
|
||||
</td>
|
||||
<td className="px-3 py-2 text-right tabular-nums">
|
||||
{totals.credit.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})}
|
||||
</td>
|
||||
<td />
|
||||
</tr>
|
||||
{!totals.isBalanced && (
|
||||
<tr className="text-destructive">
|
||||
<td className="px-3 py-1 text-sm" colSpan={2}>
|
||||
Differens
|
||||
</td>
|
||||
<td className="px-3 py-1 text-right tabular-nums text-sm" colSpan={2}>
|
||||
{totals.diff.toLocaleString('sv-SE', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
})}{' '}
|
||||
SEK
|
||||
</td>
|
||||
<td />
|
||||
</tr>
|
||||
)}
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Actions row */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" onClick={addRow}>
|
||||
<Plus className="h-3.5 w-3.5 mr-1.5" />
|
||||
Lägg till rad
|
||||
</Button>
|
||||
{!totals.isBalanced && Math.abs(totals.diff) <= 1 && Math.abs(totals.diff) >= 0.01 && (
|
||||
<Button variant="outline" size="sm" onClick={handleAutoBalance}>
|
||||
<Scale className="h-3.5 w-3.5 mr-1.5" />
|
||||
Avrunda ({totals.diff > 0 ? '+' : ''}
|
||||
{totals.diff.toFixed(2)} till 2099)
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Warnings */}
|
||||
{!totals.isBalanced && Math.abs(totals.diff) > 1 && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-warning">
|
||||
Debet och kredit balanserar inte. Differens:{' '}
|
||||
{totals.diff.toLocaleString('sv-SE', { minimumFractionDigits: 2 })} SEK. Kontrollera
|
||||
beloppen innan du fortsätter.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useState } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Upload, FileSpreadsheet, AlertCircle, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface OpeningBalanceUploadStepProps {
|
||||
onFileSelect: (file: File) => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
/** Optional action rendered under the error text (e.g. route to the bank importer) */
|
||||
errorAction?: { label: string; onClick: () => void }
|
||||
}
|
||||
|
||||
export default function OpeningBalanceUploadStep({
|
||||
onFileSelect,
|
||||
isLoading,
|
||||
error,
|
||||
errorAction,
|
||||
}: OpeningBalanceUploadStepProps) {
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
const ACCEPTED_TYPES = '.xlsx,.xls,.csv,.ods'
|
||||
|
||||
const handleFile = useCallback((file: File) => {
|
||||
const ext = file.name.split('.').pop()?.toLowerCase()
|
||||
if (!ext || !['xlsx', 'xls', 'csv', 'ods'].includes(ext)) {
|
||||
return
|
||||
}
|
||||
onFileSelect(file)
|
||||
}, [onFileSelect])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file) handleFile(file)
|
||||
}, [handleFile])
|
||||
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}, [])
|
||||
|
||||
const handleDragLeave = useCallback(() => {
|
||||
setIsDragging(false)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Ladda upp fil med ingående balanser</CardTitle>
|
||||
<CardDescription>
|
||||
Ladda upp en Excel- eller CSV-fil med ditt företags ingående balanser.
|
||||
Filen bör innehålla kontonummer och belopp (debet/kredit eller saldo).
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Drop zone */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center rounded-lg border-2 border-dashed p-10 transition-colors',
|
||||
isDragging
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-muted-foreground/20 hover:border-muted-foreground/40',
|
||||
isLoading && 'pointer-events-none opacity-60',
|
||||
)}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
>
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground">Läser fil och identifierar kolumner...</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="h-8 w-8 text-muted-foreground/50 mb-3" />
|
||||
<p className="text-sm font-medium">
|
||||
Dra och släpp din fil här
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
eller
|
||||
</p>
|
||||
<label>
|
||||
<input
|
||||
type="file"
|
||||
accept={ACCEPTED_TYPES}
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleFile(file)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<Button variant="outline" size="sm" className="mt-2" asChild>
|
||||
<span>Välj fil</span>
|
||||
</Button>
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground mt-3">
|
||||
XLSX, XLS, CSV, ODS: max 10 MB
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3">
|
||||
<AlertCircle className="h-4 w-4 text-destructive mt-0.5 shrink-0" />
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
{errorAction && (
|
||||
<Button variant="outline" size="sm" onClick={errorAction.onClick}>
|
||||
{errorAction.label}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Info */}
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/50 px-4 py-3">
|
||||
<FileSpreadsheet className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<div className="text-sm text-muted-foreground space-y-1">
|
||||
<p className="font-medium text-foreground">Filformat</p>
|
||||
<p>
|
||||
Filen bör ha en rubrikrad med kolumner för kontonummer och belopp.
|
||||
Vanliga format stöds automatiskt: t.ex. kolumner som heter "Konto",
|
||||
"Debet", "Kredit" eller "Saldo".
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Label } from '@/components/ui/label'
|
||||
|
||||
/** A field that can be mapped to a column in the uploaded file. */
|
||||
export interface RegisterColumnSpec<K extends string> {
|
||||
key: K
|
||||
label: string
|
||||
required: boolean
|
||||
}
|
||||
|
||||
interface RegisterColumnMappingStepProps<K extends string> {
|
||||
headers: string[]
|
||||
previewRows: string[][]
|
||||
specs: RegisterColumnSpec<K>[]
|
||||
initial: Record<K, number | null>
|
||||
onConfirm: (mapping: Record<K, number | null>) => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export default function RegisterColumnMappingStep<K extends string>({
|
||||
headers,
|
||||
previewRows,
|
||||
specs,
|
||||
initial,
|
||||
onConfirm,
|
||||
onBack,
|
||||
}: RegisterColumnMappingStepProps<K>) {
|
||||
const [mapping, setMapping] = useState<Record<K, number | null>>(initial)
|
||||
|
||||
const columnOptions = headers.map((h, i) => ({
|
||||
value: String(i),
|
||||
label: `${i + 1}: ${h || '(tom)'}`,
|
||||
}))
|
||||
|
||||
const canContinue = specs
|
||||
.filter((s) => s.required)
|
||||
.every((s) => mapping[s.key] !== null && mapping[s.key]! >= 0)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Kolumnmappning</CardTitle>
|
||||
<CardDescription>
|
||||
Vi kunde inte automatiskt identifiera alla kolumner. Ange vilka kolumner i din fil
|
||||
som motsvarar respektive fält. Lämna tomt för fält som inte finns.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
{specs.map((spec) => (
|
||||
<div key={spec.key} className="space-y-2">
|
||||
<Label>
|
||||
{spec.label}
|
||||
{spec.required && ' *'}
|
||||
</Label>
|
||||
<Select
|
||||
value={mapping[spec.key] !== null ? String(mapping[spec.key]) : 'none'}
|
||||
onValueChange={(v) =>
|
||||
setMapping((prev) => ({
|
||||
...prev,
|
||||
[spec.key]: v === 'none' ? null : Number(v),
|
||||
}))
|
||||
}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{!spec.required && <SelectItem value="none">(ingen)</SelectItem>}
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{previewRows.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<Label className="text-muted-foreground">Förhandsgranskning (5 första raderna)</Label>
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b">
|
||||
{headers.map((h, i) => (
|
||||
/* data-ph-mask: CSV headers are user data */
|
||||
<th key={i} data-ph-mask="" className="px-3 py-2 text-left whitespace-nowrap">
|
||||
{h || `Kolumn ${i + 1}`}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{previewRows.slice(0, 5).map((row, ri) => (
|
||||
<tr key={ri} className="border-b last:border-0">
|
||||
{row.map((cell, ci) => (
|
||||
<td key={ci} className="px-3 py-1.5 whitespace-nowrap">
|
||||
{cell}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between">
|
||||
<Button variant="ghost" onClick={onBack}>Tillbaka</Button>
|
||||
<Button onClick={() => onConfirm(mapping)} disabled={!canContinue}>
|
||||
Fortsätt
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
'use client'
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { CheckCircle2, XCircle, ArrowRight, AlertTriangle } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
|
||||
export type RegisterResult = {
|
||||
success: boolean
|
||||
created: number
|
||||
updated: number
|
||||
skipped: number
|
||||
failed: number
|
||||
errors: { row_index: number; name: string; reason: string }[]
|
||||
/** Non-fatal notes (e.g. dropped revenue-account overrides on article import). */
|
||||
warnings?: string[]
|
||||
}
|
||||
|
||||
interface RegisterResultStepProps {
|
||||
entity: 'customers' | 'suppliers' | 'articles'
|
||||
result: RegisterResult
|
||||
onNewImport: () => void
|
||||
}
|
||||
|
||||
const ENTITY_COPY = {
|
||||
customers: {
|
||||
successTitle: 'Kunder importerade',
|
||||
failTitle: 'Importen misslyckades',
|
||||
listLabel: 'Visa alla kunder',
|
||||
listHref: '/customers',
|
||||
},
|
||||
suppliers: {
|
||||
successTitle: 'Leverantörer importerade',
|
||||
failTitle: 'Importen misslyckades',
|
||||
listLabel: 'Visa alla leverantörer',
|
||||
listHref: '/suppliers',
|
||||
},
|
||||
articles: {
|
||||
successTitle: 'Artiklar importerade',
|
||||
failTitle: 'Importen misslyckades',
|
||||
listLabel: 'Visa alla artiklar',
|
||||
listHref: '/articles',
|
||||
},
|
||||
} as const
|
||||
|
||||
export default function RegisterResultStep({
|
||||
entity,
|
||||
result,
|
||||
onNewImport,
|
||||
}: RegisterResultStepProps) {
|
||||
const copy = ENTITY_COPY[entity]
|
||||
const totalProcessed = result.created + result.updated + result.skipped + result.failed
|
||||
const isPartial = result.failed > 0 && result.created + result.updated > 0
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center gap-3">
|
||||
{result.success ? (
|
||||
<CheckCircle2 className="h-6 w-6 text-success" />
|
||||
) : isPartial ? (
|
||||
<AlertTriangle className="h-6 w-6 text-warning" />
|
||||
) : (
|
||||
<XCircle className="h-6 w-6 text-destructive" />
|
||||
)}
|
||||
<CardTitle>
|
||||
{result.success
|
||||
? copy.successTitle
|
||||
: isPartial
|
||||
? 'Import slutförd med fel'
|
||||
: copy.failTitle}
|
||||
</CardTitle>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Stats */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
|
||||
<Stat label="Skapade" value={result.created} accent="success" />
|
||||
<Stat label="Uppdaterade" value={result.updated} accent="warning" />
|
||||
<Stat label="Hoppades över" value={result.skipped} />
|
||||
<Stat label="Misslyckades" value={result.failed} accent={result.failed > 0 ? 'destructive' : 'muted'} />
|
||||
</div>
|
||||
|
||||
{totalProcessed === 0 && (
|
||||
<p className="text-sm text-muted-foreground">Inga rader bearbetades.</p>
|
||||
)}
|
||||
|
||||
{/* Errors */}
|
||||
{result.errors.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium">Rader som inte kunde importeras</h4>
|
||||
<div className="rounded-lg border border-destructive/30 bg-destructive/5 max-h-60 overflow-y-auto">
|
||||
<ul className="divide-y divide-destructive/20">
|
||||
{result.errors.map((e, i) => (
|
||||
<li key={i} className="px-3 py-2 text-sm">
|
||||
<span className="font-medium">Rad {e.row_index}: {e.name}</span>
|
||||
<span className="text-muted-foreground">: {e.reason}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Warnings (non-fatal: e.g. dropped revenue-account overrides) */}
|
||||
{result.warnings && result.warnings.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium">Att notera</h4>
|
||||
<div className="rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<ul className="space-y-1 text-sm text-muted-foreground">
|
||||
{result.warnings.map((w, i) => (
|
||||
<li key={i} className="flex items-start gap-2">
|
||||
<AlertTriangle className="h-3.5 w-3.5 text-warning mt-0.5 shrink-0" />
|
||||
<span>{w}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button asChild>
|
||||
<Link href={copy.listHref}>
|
||||
{copy.listLabel}
|
||||
<ArrowRight className="h-4 w-4 ml-2" />
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="ghost" onClick={onNewImport}>Ny import</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
function Stat({
|
||||
label,
|
||||
value,
|
||||
accent,
|
||||
}: {
|
||||
label: string
|
||||
value: number
|
||||
accent?: 'success' | 'warning' | 'destructive' | 'muted'
|
||||
}) {
|
||||
return (
|
||||
<div className="rounded-lg border bg-muted/30 p-4 text-center">
|
||||
<p
|
||||
className={
|
||||
accent === 'success' ? 'text-2xl font-semibold tabular-nums text-success' :
|
||||
accent === 'warning' ? 'text-2xl font-semibold tabular-nums text-warning' :
|
||||
accent === 'destructive' ? 'text-2xl font-semibold tabular-nums text-destructive' :
|
||||
'text-2xl font-semibold tabular-nums'
|
||||
}
|
||||
>
|
||||
{value}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">{label}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useState } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Upload, FileSpreadsheet, AlertCircle, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export type RegisterEntity = 'customers' | 'suppliers' | 'articles'
|
||||
|
||||
interface RegisterUploadStepProps {
|
||||
entity: RegisterEntity
|
||||
onFileSelect: (file: File) => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
}
|
||||
|
||||
const COPY: Record<RegisterEntity, { title: string; description: string; hint: string }> = {
|
||||
customers: {
|
||||
title: 'Ladda upp fil med kunder',
|
||||
description:
|
||||
'Ladda upp en Excel- eller CSV-fil med ditt kundregister. Filen bör innehålla minst en kolumn med kundnamn.',
|
||||
hint:
|
||||
'Vanliga kolumner identifieras automatiskt: t.ex. "Namn", "Orgnr", "E-post", "Telefon", "Adress", "Postort".',
|
||||
},
|
||||
suppliers: {
|
||||
title: 'Ladda upp fil med leverantörer',
|
||||
description:
|
||||
'Ladda upp en Excel- eller CSV-fil med ditt leverantörsregister. Filen bör innehålla minst en kolumn med leverantörsnamn.',
|
||||
hint:
|
||||
'Vanliga kolumner identifieras automatiskt: t.ex. "Namn", "Orgnr", "Bankgiro", "Plusgiro", "IBAN", "E-post".',
|
||||
},
|
||||
articles: {
|
||||
title: 'Ladda upp fil med artiklar',
|
||||
description:
|
||||
'Ladda upp en Excel- eller CSV-fil med ditt artikelregister. Filen bör innehålla minst en kolumn med benämning. Filer exporterade från Fortnox, Visma och Bokio känns igen automatiskt.',
|
||||
hint:
|
||||
'Vanliga kolumner identifieras automatiskt: t.ex. "Benämning", "Artikelnummer", "Pris", "Moms", "Enhet", "Försäljningskonto".',
|
||||
},
|
||||
}
|
||||
|
||||
export default function RegisterUploadStep({
|
||||
entity,
|
||||
onFileSelect,
|
||||
isLoading,
|
||||
error,
|
||||
}: RegisterUploadStepProps) {
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const copy = COPY[entity]
|
||||
|
||||
const handleFile = useCallback((file: File) => {
|
||||
const ext = file.name.split('.').pop()?.toLowerCase()
|
||||
if (!ext || !['xlsx', 'xls', 'csv', 'ods'].includes(ext)) return
|
||||
onFileSelect(file)
|
||||
}, [onFileSelect])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
const file = e.dataTransfer.files[0]
|
||||
if (file) handleFile(file)
|
||||
}, [handleFile])
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{copy.title}</CardTitle>
|
||||
<CardDescription>{copy.description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center rounded-lg border-2 border-dashed p-10 transition-colors',
|
||||
isDragging
|
||||
? 'border-primary bg-primary/5'
|
||||
: 'border-muted-foreground/20 hover:border-muted-foreground/40',
|
||||
isLoading && 'pointer-events-none opacity-60',
|
||||
)}
|
||||
onDrop={handleDrop}
|
||||
onDragOver={(e) => { e.preventDefault(); setIsDragging(true) }}
|
||||
onDragLeave={() => setIsDragging(false)}
|
||||
>
|
||||
{isLoading ? (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground">Läser fil och identifierar kolumner...</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="h-8 w-8 text-muted-foreground/50 mb-3" />
|
||||
<p className="text-sm font-medium">Dra och släpp din fil här</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">eller</p>
|
||||
<label>
|
||||
<input
|
||||
type="file"
|
||||
accept=".xlsx,.xls,.csv,.ods"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0]
|
||||
if (file) handleFile(file)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<Button variant="outline" size="sm" className="mt-2" asChild>
|
||||
<span>Välj fil</span>
|
||||
</Button>
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground mt-3">XLSX, XLS, CSV, ODS: max 10 MB</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3">
|
||||
<AlertCircle className="h-4 w-4 text-destructive mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/50 px-4 py-3">
|
||||
<FileSpreadsheet className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
|
||||
<div className="text-sm text-muted-foreground space-y-1">
|
||||
<p className="font-medium text-foreground">Filformat</p>
|
||||
<p>{copy.hint}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Undo2 } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { DestructiveConfirmDialog } from '@/components/ui/destructive-confirm-dialog'
|
||||
import { TH_CLASS, TD_CLASS } from '@/components/ui/dry-table'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { cn, formatDate } from '@/lib/utils'
|
||||
|
||||
/**
|
||||
* Subset of the sie_imports row (GET /api/import/sie) actually rendered here.
|
||||
* `status` stays a plain string: the DB CHECK also allows values this table
|
||||
* never renders specially (e.g. the legacy 'mapped'), which fall back to raw
|
||||
* muted text instead of crashing on a missing translation key.
|
||||
*/
|
||||
interface SIEImportListRow {
|
||||
id: string
|
||||
filename: string
|
||||
fiscal_year_start: string | null
|
||||
fiscal_year_end: string | null
|
||||
transactions_count: number
|
||||
status: string
|
||||
imported_at: string | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* At or above this voucher count the undo confirm adds a warning that undoing
|
||||
* can leave gaps in the voucher numbering when other vouchers were booked
|
||||
* after the import (gaps need a documented explanation per BFNAR 2013:2).
|
||||
*/
|
||||
const GAP_WARNING_VOUCHER_COUNT = 100
|
||||
|
||||
const STATUS_LABEL_KEY: Record<string, string> = {
|
||||
completed: 'sie_history_status_completed',
|
||||
undone: 'sie_history_status_undone',
|
||||
replaced: 'sie_history_status_replaced',
|
||||
failed: 'sie_history_status_failed',
|
||||
pending: 'sie_history_status_pending',
|
||||
}
|
||||
|
||||
/**
|
||||
* Chips mark exceptions (design.md convention 5): the normal 'completed'
|
||||
* state renders as muted text; only deviating states get a Badge.
|
||||
*/
|
||||
const STATUS_BADGE_VARIANT: Record<string, 'secondary' | 'warning' | 'destructive'> = {
|
||||
undone: 'secondary',
|
||||
replaced: 'secondary',
|
||||
failed: 'destructive',
|
||||
pending: 'warning',
|
||||
}
|
||||
|
||||
/**
|
||||
* History of past SIE imports with per-row undo for completed ones.
|
||||
* Rendered fold-open from the 'Tidigare SIE-importer' row on the import tab.
|
||||
*/
|
||||
export default function SIEImportHistory() {
|
||||
const t = useTranslations('import')
|
||||
const { toast } = useToast()
|
||||
const [rows, setRows] = useState<SIEImportListRow[] | null>(null)
|
||||
const [loadFailed, setLoadFailed] = useState(false)
|
||||
const [pendingUndo, setPendingUndo] = useState<SIEImportListRow | null>(null)
|
||||
|
||||
const fetchImports = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/import/sie?limit=20')
|
||||
if (!res.ok) {
|
||||
setLoadFailed(true)
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
setRows(Array.isArray(data.data) ? data.data : [])
|
||||
setLoadFailed(false)
|
||||
} catch {
|
||||
setLoadFailed(true)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
void fetchImports()
|
||||
}, [fetchImports])
|
||||
|
||||
// Deliberately no client-side timeout: undoing a large import can take
|
||||
// minutes (the route runs with maxDuration 300) and the confirm dialog
|
||||
// stays open with its spinner until this resolves.
|
||||
const handleUndoConfirm = useCallback(async () => {
|
||||
if (!pendingUndo) return
|
||||
try {
|
||||
const res = await fetch(`/api/import/sie/${pendingUndo.id}/undo`, { method: 'DELETE' })
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
toast({
|
||||
title: t('sie_history_undo_failed'),
|
||||
description: getErrorMessage(data),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('sie_history_undo_success_title'),
|
||||
description: t('sie_history_undo_success', { count: data.deletedEntries ?? 0 }),
|
||||
})
|
||||
await fetchImports()
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('sie_history_undo_failed'),
|
||||
description: getErrorMessage(err),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}, [pendingUndo, fetchImports, t, toast])
|
||||
|
||||
const fiscalYearLabel = (row: SIEImportListRow): string => {
|
||||
if (row.fiscal_year_start && row.fiscal_year_end) {
|
||||
return t('sie_history_fiscal_year_range', {
|
||||
start: formatDate(row.fiscal_year_start),
|
||||
end: formatDate(row.fiscal_year_end),
|
||||
})
|
||||
}
|
||||
if (row.fiscal_year_start) return formatDate(row.fiscal_year_start)
|
||||
if (row.fiscal_year_end) return formatDate(row.fiscal_year_end)
|
||||
return '-'
|
||||
}
|
||||
|
||||
const statusCell = (status: string) => {
|
||||
const labelKey = STATUS_LABEL_KEY[status]
|
||||
const label = labelKey ? t(labelKey) : status
|
||||
const variant = STATUS_BADGE_VARIANT[status]
|
||||
if (!variant) {
|
||||
return <span className="text-xs text-muted-foreground">{label}</span>
|
||||
}
|
||||
return (
|
||||
<Badge variant={variant} className="font-normal">
|
||||
{label}
|
||||
</Badge>
|
||||
)
|
||||
}
|
||||
|
||||
if (loadFailed) {
|
||||
return <p className="px-1 text-xs leading-5 text-muted-foreground">{t('sie_history_load_error')}</p>
|
||||
}
|
||||
|
||||
if (rows === null) {
|
||||
return (
|
||||
<div className="space-y-2" role="status">
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-full" />
|
||||
<Skeleton className="h-8 w-full" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (rows.length === 0) {
|
||||
return <p className="px-1 text-xs leading-5 text-muted-foreground">{t('sie_history_empty')}</p>
|
||||
}
|
||||
|
||||
const confirmDescription = pendingUndo
|
||||
? t('sie_history_undo_confirm_description', { count: pendingUndo.transactions_count }) +
|
||||
(pendingUndo.transactions_count >= GAP_WARNING_VOUCHER_COUNT
|
||||
? '\n\n' + t('sie_history_undo_gap_warning')
|
||||
: '')
|
||||
: ''
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full border-collapse text-[13px]">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={TH_CLASS}>{t('sie_history_col_file')}</th>
|
||||
<th className={TH_CLASS}>{t('sie_history_col_date')}</th>
|
||||
<th className={TH_CLASS}>{t('sie_history_col_fiscal_year')}</th>
|
||||
<th className={cn(TH_CLASS, 'text-right')}>{t('sie_history_col_vouchers')}</th>
|
||||
<th className={TH_CLASS}>{t('sie_history_col_status')}</th>
|
||||
<th className={TH_CLASS}>
|
||||
<span className="sr-only">{t('sie_history_undo_button')}</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="stagger-enter">
|
||||
{rows.map((row) => (
|
||||
<tr key={row.id} className="transition-colors duration-150 hover:bg-secondary/35">
|
||||
<td className={TD_CLASS}>{row.filename}</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums')}>
|
||||
{formatDate(row.imported_at ?? row.created_at)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap tabular-nums')}>
|
||||
{fiscalYearLabel(row)}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'text-right tabular-nums')}>{row.transactions_count}</td>
|
||||
<td className={TD_CLASS}>{statusCell(row.status)}</td>
|
||||
<td className={cn(TD_CLASS, 'text-right')}>
|
||||
{row.status === 'completed' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="text-destructive hover:text-destructive"
|
||||
onClick={() => setPendingUndo(row)}
|
||||
>
|
||||
<Undo2 className="mr-2 h-4 w-4" />
|
||||
{t('sie_history_undo_button')}
|
||||
</Button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<DestructiveConfirmDialog
|
||||
open={pendingUndo !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPendingUndo(null)
|
||||
}}
|
||||
title={t('sie_history_undo_confirm_title')}
|
||||
description={confirmDescription}
|
||||
confirmLabel={t('sie_history_undo_confirm_label')}
|
||||
onConfirm={handleUndoConfirm}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import {
|
||||
Calendar,
|
||||
FileText,
|
||||
CheckCircle,
|
||||
AlertCircle,
|
||||
XCircle,
|
||||
ArrowRight,
|
||||
BarChart3,
|
||||
Info,
|
||||
Briefcase,
|
||||
} from 'lucide-react'
|
||||
import type { ImportPreview, ParseIssue } from '@/lib/import/types'
|
||||
|
||||
interface SIEPreviewStepProps {
|
||||
preview: ImportPreview
|
||||
issues: ParseIssue[]
|
||||
missingAccounts: { number: string; name: string }[]
|
||||
onCreateAccounts: () => Promise<void>
|
||||
isCreatingAccounts: boolean
|
||||
onContinue: () => void
|
||||
onBack: () => void
|
||||
/**
|
||||
* Opens the manual "Ingående balanser" wizard (issue #2082). Offered next to
|
||||
* the IB-imbalance acknowledgement so a user who rightly hesitates to book an
|
||||
* unexplained amount to 2099 has somewhere to go other than support.
|
||||
*/
|
||||
onOpenManualOpeningBalances?: () => void
|
||||
}
|
||||
|
||||
export default function SIEPreviewStep({
|
||||
preview,
|
||||
issues,
|
||||
missingAccounts,
|
||||
onCreateAccounts,
|
||||
isCreatingAccounts,
|
||||
onContinue,
|
||||
onBack,
|
||||
onOpenManualOpeningBalances,
|
||||
}: SIEPreviewStepProps) {
|
||||
const t = useTranslations('import')
|
||||
const errors = issues.filter((i) => i.severity === 'error')
|
||||
const warnings = issues.filter((i) => i.severity === 'warning')
|
||||
|
||||
// Both blocks are optional: a preview built by an older parse response
|
||||
// lacks them, and the card then falls back to the BAS-reference counts.
|
||||
const chart = preview.chart
|
||||
const fiscalYear = preview.fiscalYear
|
||||
// Both refusals carry the import's own text: an overlap with a period that
|
||||
// has content, or #RAR dates that break a BFL 3 kap. shape rule.
|
||||
const fiscalYearRefused =
|
||||
fiscalYear?.verdict === 'conflict' || fiscalYear?.verdict === 'invalid'
|
||||
|
||||
// Opening-balance imbalance. The importer plugs any diff > 0.01 to 2099, but a
|
||||
// diff under ~1 SEK is genuine öresavrundning. Anything larger is a real
|
||||
// imbalance (incomplete export: missing liabilities / unappropriated prior-year
|
||||
// result) that would silently book a bogus amount to 2099. Mirrors the importer's
|
||||
// own `fileImbalance > 1.00` "serious" threshold (lib/import/sie-import.ts).
|
||||
const ibDiff = Math.round((preview.trialBalance.totalDebit - preview.trialBalance.totalCredit) * 100) / 100
|
||||
const significantImbalance = !preview.trialBalance.isBalanced && Math.abs(ibDiff) > 1
|
||||
const [ackImbalance, setAckImbalance] = useState(false)
|
||||
|
||||
// Only block on actual parsing errors, not unmapped accounts
|
||||
// (users need to proceed to mapping step to fix unmapped accounts).
|
||||
// A significant IB imbalance is a soft block: the user must acknowledge it.
|
||||
const hasBlockingErrors = errors.length > 0
|
||||
const blockContinue = hasBlockingErrors || (significantImbalance && !ackImbalance)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Company info */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Briefcase className="h-5 w-5" />
|
||||
Företagsinformation
|
||||
</CardTitle>
|
||||
<CardDescription>Information från SIE-filen</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Företagsnamn</p>
|
||||
<p className="font-medium">{preview.companyName || 'Ej angivet'}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Organisationsnummer</p>
|
||||
<p className="font-medium">{preview.orgNumber || 'Ej angivet'}</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Fiscal year */}
|
||||
<Card className={fiscalYearRefused ? 'border-destructive/50' : undefined}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Calendar className="h-5 w-5" />
|
||||
Räkenskapsår
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center gap-4">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Start</p>
|
||||
<p className="font-medium">
|
||||
{preview.fiscalYearStart ?? 'Okänt'}
|
||||
</p>
|
||||
</div>
|
||||
<ArrowRight className="h-4 w-4 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Slut</p>
|
||||
<p className="font-medium">
|
||||
{preview.fiscalYearEnd ?? 'Okänt'}
|
||||
</p>
|
||||
</div>
|
||||
{fiscalYear && (fiscalYear.verdict === 'match' || fiscalYear.verdict === 'create') && (
|
||||
<span className="ml-auto text-sm text-muted-foreground">
|
||||
{fiscalYear.verdict === 'match'
|
||||
? t('fiscal_year_match')
|
||||
: fiscalYear.replacesEmptyPeriodId
|
||||
? t('fiscal_year_create_replaces')
|
||||
: t('fiscal_year_create')}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{fiscalYear && (fiscalYear.verdict === 'conflict' || fiscalYear.verdict === 'invalid') && (
|
||||
<div className="mt-4 flex items-start gap-2 text-sm text-destructive">
|
||||
<XCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<span>{fiscalYear.message}</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Statistics */}
|
||||
<div className="grid grid-cols-2 gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span className="text-sm">Konton</span>
|
||||
</div>
|
||||
<p className="text-2xl font-display tabular-nums">{preview.accountCount}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<BarChart3 className="h-4 w-4" />
|
||||
<span className="text-sm">Verifikationer</span>
|
||||
</div>
|
||||
<p className="text-2xl font-display tabular-nums">{preview.voucherCount}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<span className="text-sm">Transaktionsrader</span>
|
||||
</div>
|
||||
<p className="text-2xl font-display tabular-nums">{preview.transactionLineCount}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<span className="text-sm">IB, summa debet</span>
|
||||
</div>
|
||||
<p className="text-2xl font-display tabular-nums">{formatCurrency(preview.openingBalanceTotal)}</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Summan av alla debetsaldon i ingående balans, inte ett enskilt kontosaldo.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Trial balance check */}
|
||||
<Card className={preview.trialBalance.isBalanced ? 'border-success/50' : 'border-border'}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
{preview.trialBalance.isBalanced ? (
|
||||
<CheckCircle className="h-5 w-5 text-success" />
|
||||
) : (
|
||||
<AlertCircle className="h-5 w-5 text-warning" />
|
||||
)}
|
||||
Balansräkning (IB)
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Total debet</p>
|
||||
<p className="font-medium">{formatCurrency(preview.trialBalance.totalDebit)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Total kredit</p>
|
||||
<p className="font-medium">{formatCurrency(preview.trialBalance.totalCredit)}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Status</p>
|
||||
{preview.trialBalance.isBalanced ? (
|
||||
<Badge variant="success">Balanserar</Badge>
|
||||
) : (
|
||||
<Badge variant="secondary">
|
||||
Diff: {formatCurrency(ibDiff)}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Significant imbalance: explain + require acknowledgement before continuing */}
|
||||
{significantImbalance && (
|
||||
<div className="mt-4 space-y-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<div className="flex items-start gap-2 text-sm">
|
||||
<AlertCircle className="h-4 w-4 text-warning mt-0.5 flex-shrink-0" />
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-warning">
|
||||
Ingående balanser balanserar inte ({formatCurrency(Math.abs(ibDiff))})
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
Vanligaste orsaken är att föregående års resultat aldrig fördes över till
|
||||
eget kapital i det gamla programmet. SpeedLedger parkerar det till exempel på
|
||||
egna 9xxx-konton (9030/9031 Obokat resultat), och då summerar inte filens
|
||||
ingående balanser till noll: differensen är det oförda resultatet. En annan
|
||||
orsak är en ofullständig export, till exempel att skulder saknas.
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
Rätta i källsystemet och ladda upp filen på nytt, eller lägg in de ingående
|
||||
balanserna för hand i guiden Ingående balanser, där du kan rätta raderna
|
||||
själv innan de bokförs (den här filen importeras då inte). Fortsätter du ändå
|
||||
bokförs differensen på konto 2099 (Årets resultat), vilket nästan alltid blir
|
||||
fel.
|
||||
</p>
|
||||
{onOpenManualOpeningBalances && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mt-1"
|
||||
onClick={onOpenManualOpeningBalances}
|
||||
>
|
||||
Lägg in ingående balanser för hand
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<label className="flex items-start gap-2 text-sm cursor-pointer">
|
||||
<Checkbox
|
||||
checked={ackImbalance}
|
||||
onCheckedChange={(v) => setAckImbalance(v === true)}
|
||||
className="mt-0.5"
|
||||
/>
|
||||
<span className="text-muted-foreground">
|
||||
Jag förstår att differensen bokförs på 2099 och vill fortsätta ändå.
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Mapping status */}
|
||||
<Card
|
||||
className={
|
||||
preview.mappingStatus.unmapped > 0
|
||||
? 'border-destructive/50'
|
||||
: preview.mappingStatus.lowConfidence > 0
|
||||
? 'border-border'
|
||||
: 'border-success/50'
|
||||
}
|
||||
>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
{preview.mappingStatus.unmapped > 0 ? (
|
||||
<XCircle className="h-5 w-5 text-destructive" />
|
||||
) : preview.mappingStatus.lowConfidence > 0 ? (
|
||||
<AlertCircle className="h-5 w-5 text-warning" />
|
||||
) : (
|
||||
<CheckCircle className="h-5 w-5 text-success" />
|
||||
)}
|
||||
{t('chart_card_title')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{chart
|
||||
? t('chart_summary', { toCreate: chart.toCreate, existing: chart.existing })
|
||||
: 'Hur väl kunde kontona i filen matchas mot din kontoplan'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-4 md:grid-cols-4">
|
||||
{chart ? (
|
||||
<>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">{t('chart_to_create')}</p>
|
||||
<p className="font-medium tabular-nums">{chart.toCreate}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">{t('chart_existing')}</p>
|
||||
<p className="font-medium tabular-nums">{chart.existing}</p>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Totalt</p>
|
||||
<p className="font-medium">{preview.mappingStatus.total}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Mappade</p>
|
||||
<p className="font-medium text-success">{preview.mappingStatus.mapped}</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Ej mappade</p>
|
||||
<p className={`font-medium tabular-nums ${preview.mappingStatus.unmapped > 0 ? 'text-destructive' : ''}`}>
|
||||
{preview.mappingStatus.unmapped}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-muted-foreground">Osäkra</p>
|
||||
<p className={`font-medium tabular-nums ${preview.mappingStatus.lowConfidence > 0 ? 'text-warning' : ''}`}>
|
||||
{preview.mappingStatus.lowConfidence}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{chart && chart.sample.length > 0 && (
|
||||
<div className="mt-4 space-y-1 text-sm">
|
||||
{chart.sample.map((acc) => (
|
||||
<div key={acc.number} className="flex gap-2 text-muted-foreground">
|
||||
<span className="font-mono">{acc.number}</span>
|
||||
<span>{acc.name}</span>
|
||||
</div>
|
||||
))}
|
||||
{chart.toCreate > chart.sample.length && (
|
||||
<div className="text-muted-foreground">
|
||||
{t('chart_sample_more', { count: chart.toCreate - chart.sample.length })}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Excluded system accounts info */}
|
||||
{preview.excludedSystemAccounts.length > 0 && (
|
||||
<div className="flex items-start gap-2 rounded-lg border bg-muted/50 px-4 py-3 text-sm text-muted-foreground">
|
||||
<Info className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<span>
|
||||
{preview.excludedSystemAccounts.length} internt systemkonto från källsystemet exkluderades ({preview.excludedSystemAccounts.map((a) => a.number).join(', ')}), inte bokföringskonton
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Create missing accounts */}
|
||||
{missingAccounts.length > 0 ? (
|
||||
<Card className="border-primary/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5 text-primary" />
|
||||
Skapa saknade konton
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{missingAccounts.length} konton från SIE-filen finns inte i din kontoplan ännu.
|
||||
Klicka nedan för att skapa dem: de kopplas sedan automatiskt i nästa steg.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
<div className="max-h-32 overflow-y-auto text-sm space-y-1">
|
||||
{missingAccounts.slice(0, 10).map((acc) => (
|
||||
<div key={acc.number} className="flex gap-2 text-muted-foreground">
|
||||
<span className="font-mono">{acc.number}</span>
|
||||
<span>{acc.name}</span>
|
||||
</div>
|
||||
))}
|
||||
{missingAccounts.length > 10 && (
|
||||
<div className="text-muted-foreground">
|
||||
... och {missingAccounts.length - 10} till
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={onCreateAccounts}
|
||||
disabled={isCreatingAccounts}
|
||||
className="w-full"
|
||||
>
|
||||
{isCreatingAccounts ? (
|
||||
<>Skapar konton...</>
|
||||
) : (
|
||||
<>Skapa {missingAccounts.length} konton</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : preview.mappingStatus.mapped === preview.mappingStatus.total && preview.mappingStatus.total > 0 && (
|
||||
<div className="flex items-center gap-2 rounded-lg border border-success/50 bg-success/5 px-4 py-3 text-sm">
|
||||
<CheckCircle className="h-4 w-4 text-success flex-shrink-0" />
|
||||
<span>Alla konton skapade och automatiskt kopplade</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Errors */}
|
||||
{errors.length > 0 && (
|
||||
<Card className="border-destructive/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<XCircle className="h-5 w-5 text-destructive" />
|
||||
Tolkningsfel ({errors.length})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Dessa fel hittades under tolkningen av SIE-filen och kan påverka importresultatet.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 max-h-48 overflow-y-auto">
|
||||
{errors.map((issue, i) => (
|
||||
<div key={`error-${i}`} className="text-sm flex gap-2 text-destructive">
|
||||
<XCircle className="h-4 w-4 flex-shrink-0 mt-0.5" />
|
||||
<span>
|
||||
<span className="font-mono text-xs opacity-70">Rad {issue.line}</span>{' '}
|
||||
{issue.message}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Warnings */}
|
||||
{warnings.length > 0 && (
|
||||
<Card className="border-border">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-warning" />
|
||||
Varningar ({warnings.length})
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Dessa varningar blockerar inte importen men bör granskas.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-2 max-h-48 overflow-y-auto">
|
||||
{warnings.map((issue, i) => (
|
||||
<div key={`warning-${i}`} className="text-sm flex gap-2 text-warning">
|
||||
<AlertCircle className="h-4 w-4 flex-shrink-0 mt-0.5" />
|
||||
<span>
|
||||
<span className="font-mono text-xs opacity-70">Rad {issue.line}</span>{' '}
|
||||
{issue.message}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row sm:justify-between">
|
||||
<Button variant="outline" className="min-h-11" onClick={onBack}>
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button className="min-h-11" onClick={onContinue} disabled={blockContinue}>
|
||||
{preview.mappingStatus.lowConfidence > 0 || preview.mappingStatus.unmapped > 0
|
||||
? 'Granska mappningar'
|
||||
: 'Fortsätt'}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback, useEffect } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Upload, AlertCircle, CheckCircle, Loader2, XCircle, RefreshCw } from 'lucide-react'
|
||||
|
||||
const LOADING_PHASES = [
|
||||
{ message: 'Läser fil...', progress: 10 },
|
||||
{ message: 'Identifierar teckenkodning...', progress: 30 },
|
||||
{ message: 'Tolkar SIE-data...', progress: 55 },
|
||||
{ message: 'Matchar konton mot BAS-kontoplanen...', progress: 85 },
|
||||
] as const
|
||||
|
||||
interface SIEUploadStepProps {
|
||||
onFileSelect: (file: File) => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
errorType?: 'duplicate' | 'duplicate_period' | 'validation' | 'parse' | 'network'
|
||||
validationErrors?: string[]
|
||||
validationWarnings?: string[]
|
||||
duplicateImportId?: string | null
|
||||
onReplace?: (importId: string) => Promise<void>
|
||||
isReplacing?: boolean
|
||||
}
|
||||
|
||||
export default function SIEUploadStep({ onFileSelect, isLoading, error, errorType, validationErrors, validationWarnings, duplicateImportId, onReplace, isReplacing }: SIEUploadStepProps) {
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [loadingPhase, setLoadingPhase] = useState(0)
|
||||
const [fileTypeError, setFileTypeError] = useState<string | null>(null)
|
||||
|
||||
// Cycle through loading phases on timers
|
||||
useEffect(() => {
|
||||
if (!isLoading) {
|
||||
setLoadingPhase(0)
|
||||
return
|
||||
}
|
||||
|
||||
const timers = [
|
||||
setTimeout(() => setLoadingPhase(1), 2000),
|
||||
setTimeout(() => setLoadingPhase(2), 4000),
|
||||
setTimeout(() => setLoadingPhase(3), 7000),
|
||||
]
|
||||
|
||||
return () => timers.forEach(clearTimeout)
|
||||
}, [isLoading])
|
||||
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}, [])
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
}, [])
|
||||
|
||||
// No `accept` attribute on the input and no silent rejection here: Safari
|
||||
// maps accept extensions to system file types, and unregistered extensions
|
||||
// like .sie/.se grey out perfectly valid files in the picker. All filtering
|
||||
// happens after selection, with a visible error instead of a dead drop.
|
||||
const trySelectFile = useCallback((file: File) => {
|
||||
const name = file.name.toLowerCase()
|
||||
if (name.endsWith('.sie') || name.endsWith('.se')) {
|
||||
setFileTypeError(null)
|
||||
setSelectedFile(file)
|
||||
onFileSelect(file)
|
||||
return
|
||||
}
|
||||
if (name.endsWith('.zip')) {
|
||||
setFileTypeError(`Filen "${file.name}" är en zip-fil. Packa upp den först och välj SIE-filen inuti (slutar på .sie eller .se).`)
|
||||
} else {
|
||||
setFileTypeError(`Filen "${file.name}" stöds inte. Välj en SIE-fil som slutar på .sie eller .se.`)
|
||||
}
|
||||
}, [onFileSelect])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
|
||||
const files = e.dataTransfer.files
|
||||
if (files.length > 0) {
|
||||
trySelectFile(files[0])
|
||||
}
|
||||
}, [trySelectFile])
|
||||
|
||||
const handleFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files
|
||||
if (files && files.length > 0) {
|
||||
trySelectFile(files[0])
|
||||
}
|
||||
// Allow re-picking the same file after a rejection
|
||||
e.target.value = ''
|
||||
}, [trySelectFile])
|
||||
|
||||
const phase = LOADING_PHASES[loadingPhase]
|
||||
|
||||
// Full-card takeover while analyzing the file
|
||||
if (isLoading && selectedFile) {
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-8 pb-8">
|
||||
<div className="flex flex-col items-center text-center space-y-6">
|
||||
<Loader2 className="h-10 w-10 text-primary animate-spin" />
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium text-lg">{phase.message}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedFile.name} ({(selectedFile.size / 1024).toFixed(1)} KB)
|
||||
</p>
|
||||
</div>
|
||||
<Progress value={phase.progress} className="w-64 mx-auto transition-all duration-1000" />
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Lämna inte sidan förrän analysen är klar
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Ladda upp SIE-fil
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Exportera en SIE4-fil från ditt nuvarande bokföringssystem (Fortnox, Visma, etc.)
|
||||
och ladda upp den här för att importera din bokföring.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{/* Drop zone */}
|
||||
<div
|
||||
className={`
|
||||
relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer hover:border-primary/50
|
||||
${isDragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25'}
|
||||
${error || fileTypeError ? 'border-destructive bg-destructive/5' : ''}
|
||||
`}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
onClick={() => document.getElementById('file-input')?.click()}
|
||||
>
|
||||
<input
|
||||
id="file-input"
|
||||
type="file"
|
||||
className="hidden"
|
||||
onChange={handleFileInput}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
{selectedFile ? (
|
||||
<div className="space-y-4">
|
||||
<CheckCircle className="mx-auto h-12 w-12 text-success" />
|
||||
<div>
|
||||
<p className="font-medium">{selectedFile.name}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{(selectedFile.size / 1024).toFixed(1)} KB
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<Upload className="mx-auto h-12 w-12 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="font-medium hidden sm:block">Dra och släpp SIE-fil här</p>
|
||||
<p className="font-medium sm:hidden">Tryck för att välja SIE-fil</p>
|
||||
<p className="text-sm text-muted-foreground hidden sm:block">eller klicka för att välja fil</p>
|
||||
<p className="text-sm text-muted-foreground sm:hidden">.sie eller .se-filer</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Rejected file type (client-side, before upload) */}
|
||||
{fileTypeError && (
|
||||
<div className="mt-4 p-4 rounded-lg flex gap-3 bg-destructive/10 border border-destructive/20">
|
||||
<AlertCircle className="h-5 w-5 flex-shrink-0 mt-0.5 text-destructive" />
|
||||
<div className="space-y-1.5 min-w-0">
|
||||
<p className="font-medium text-destructive">Filen kan inte användas</p>
|
||||
<p className="text-sm text-muted-foreground">{fileTypeError}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error display */}
|
||||
{error && (
|
||||
<div className="mt-4 space-y-3">
|
||||
<div className={`p-4 rounded-lg flex gap-3 ${
|
||||
errorType === 'duplicate' || errorType === 'duplicate_period'
|
||||
? 'bg-muted/30 border border-border'
|
||||
: 'bg-destructive/10 border border-destructive/20'
|
||||
}`}>
|
||||
<AlertCircle className={`h-5 w-5 flex-shrink-0 mt-0.5 ${
|
||||
errorType === 'duplicate' || errorType === 'duplicate_period'
|
||||
? 'text-warning'
|
||||
: 'text-destructive'
|
||||
}`} />
|
||||
<div className="space-y-1.5 min-w-0">
|
||||
<p className={`font-medium ${
|
||||
errorType === 'duplicate' || errorType === 'duplicate_period'
|
||||
? 'text-warning'
|
||||
: 'text-destructive'
|
||||
}`}>
|
||||
{errorType === 'duplicate' && 'Filen har redan importerats'}
|
||||
{errorType === 'duplicate_period' && 'Överlappande räkenskapsår'}
|
||||
{errorType === 'validation' && 'Filen innehåller valideringsfel'}
|
||||
{errorType === 'parse' && 'Kunde inte tolka filen'}
|
||||
{errorType === 'network' && 'Uppladdningen misslyckades'}
|
||||
{!errorType && 'Ett fel uppstod'}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
|
||||
{/* Actionable guidance */}
|
||||
<div className="text-sm text-muted-foreground pt-1 border-t border-border/50 mt-2">
|
||||
{(errorType === 'duplicate' || errorType === 'duplicate_period') && (
|
||||
<div className="space-y-2">
|
||||
<p>Den befintliga importens verifikationer kommer att makuleras (status ändras till "makulerad"). De finns kvar som spårbar historik.</p>
|
||||
{duplicateImportId && onReplace && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="border-border text-warning hover:bg-muted/30"
|
||||
disabled={isReplacing}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onReplace(duplicateImportId)
|
||||
}}
|
||||
>
|
||||
{isReplacing ? (
|
||||
<><Loader2 className="h-4 w-4 mr-2 animate-spin" />Ersätter...</>
|
||||
) : (
|
||||
<><RefreshCw className="h-4 w-4 mr-2" />Ersätt befintlig import</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{errorType === 'validation' && (
|
||||
<p>Prova att exportera filen igen från ditt bokföringsprogram. Om felet kvarstår, kontrollera att alla verifikationer är korrekt bokförda i källsystemet.</p>
|
||||
)}
|
||||
{errorType === 'parse' && (
|
||||
<p>Kontrollera att filen är en SIE4-fil exporterad från ett bokföringsprogram (Fortnox, Visma, Bokio etc). Filen kan vara skadad om den redigerats manuellt.</p>
|
||||
)}
|
||||
{errorType === 'network' && (
|
||||
<p>Kontrollera din internetanslutning och försök igen. Om problemet kvarstår, prova att ladda upp filen från en dator eller hör av dig till support.</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Validation errors list */}
|
||||
{validationErrors && validationErrors.length > 0 && (
|
||||
<div className="p-4 bg-destructive/5 border border-destructive/15 rounded-lg space-y-2">
|
||||
<p className="text-sm font-medium text-destructive">Fel som blockerar import ({validationErrors.length})</p>
|
||||
<div className="space-y-1.5 max-h-48 overflow-y-auto">
|
||||
{validationErrors.map((err, i) => (
|
||||
<div key={i} className="text-sm flex gap-2">
|
||||
<XCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<span className="text-muted-foreground">{err}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Validation warnings list */}
|
||||
{validationWarnings && validationWarnings.length > 0 && (
|
||||
<div className="p-4 bg-muted/30 border border-border rounded-lg space-y-2">
|
||||
<p className="text-sm font-medium text-warning">Varningar ({validationWarnings.length})</p>
|
||||
<div className="space-y-1.5 max-h-32 overflow-y-auto">
|
||||
{validationWarnings.map((warn, i) => (
|
||||
<div key={i} className="text-sm flex gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-warning flex-shrink-0 mt-0.5" />
|
||||
<span className="text-muted-foreground">{warn}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Info cards */}
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Vad är SIE?</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm text-muted-foreground">
|
||||
<p>
|
||||
SIE (Standard Import Export) är det svenska standardformatet för att överföra
|
||||
bokföringsdata mellan system. Det används av alla större bokföringsprogram i Sverige.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Vilken SIE-typ?</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm text-muted-foreground">
|
||||
<ul className="space-y-1">
|
||||
<li><strong>SIE4</strong> - Full historik med alla verifikationer (rekommenderas)</li>
|
||||
<li><strong>SIE1</strong> - Endast årssaldon (enklare import)</li>
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Export instructions */}
|
||||
<Card className="bg-muted/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Så exporterar du från...</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm space-y-3">
|
||||
<div>
|
||||
<p className="font-medium">Fortnox</p>
|
||||
<p className="text-muted-foreground">Inställningar → Import/Export → Exportera SIE</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Visma</p>
|
||||
<p className="text-muted-foreground">Rapporter → Övrigt → Exportera till SIE</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Bokio</p>
|
||||
<p className="text-muted-foreground">Inställningar → Bokföring → Exportera SIE-fil</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import { ArrowLeft, ArrowRight, AlertTriangle, Calendar, FileText, Scale } from 'lucide-react'
|
||||
import { formatCurrency, cn } from '@/lib/utils'
|
||||
import { roundOre } from '@/lib/money'
|
||||
import type { SkattekontoFileParseResult } from '@/lib/import/skattekonto-file/types'
|
||||
|
||||
interface SkattekontoFilePreviewStepProps {
|
||||
parseResult: SkattekontoFileParseResult
|
||||
duplicateIndexes: number[]
|
||||
promotionIndexes: number[]
|
||||
orgNumberMismatch: boolean
|
||||
isLoading: boolean
|
||||
onExecute: () => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
const PREVIEW_ROW_LIMIT = 100
|
||||
|
||||
export default function SkattekontoFilePreviewStep({
|
||||
parseResult,
|
||||
duplicateIndexes,
|
||||
promotionIndexes,
|
||||
orgNumberMismatch,
|
||||
isLoading,
|
||||
onExecute,
|
||||
onBack,
|
||||
}: SkattekontoFilePreviewStepProps) {
|
||||
const t = useTranslations('import')
|
||||
const [mismatchConfirmed, setMismatchConfirmed] = useState(false)
|
||||
const [sumGapConfirmed, setSumGapConfirmed] = useState(false)
|
||||
const {
|
||||
rows,
|
||||
stats,
|
||||
issues,
|
||||
date_from,
|
||||
date_to,
|
||||
opening_saldo,
|
||||
closing_saldo,
|
||||
events_sum,
|
||||
sum_difference,
|
||||
sum_valid,
|
||||
} = parseResult
|
||||
|
||||
const duplicateSet = new Set(duplicateIndexes)
|
||||
const promotionSet = new Set(promotionIndexes)
|
||||
const newCount = rows.length - duplicateIndexes.length
|
||||
const warnings = issues.filter((i) => i.severity !== 'error')
|
||||
// A statement that does not sum (truncated, filtered, unreadable rows) is
|
||||
// a confirm gate, not a block: nothing is booked at import and every event
|
||||
// is reviewed on the skattekonto page, so importing what IS in the file is
|
||||
// safe. The gate exists so the user knows the picture is incomplete.
|
||||
const sumGap = sum_valid === false
|
||||
const sumGapHasFigures =
|
||||
opening_saldo !== null && closing_saldo !== null && events_sum !== null && sum_difference !== null
|
||||
const importBlocked =
|
||||
(orgNumberMismatch && !mismatchConfirmed) || (sumGap && !sumGapConfirmed)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4 md:grid-cols-3">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span className="text-sm">{t('skattekonto_preview_rows')}</span>
|
||||
</div>
|
||||
<p className="text-2xl font-display tabular-nums">{stats.parsed_rows}</p>
|
||||
{stats.skipped_rows > 0 && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{t('skattekonto_preview_skipped', { count: stats.skipped_rows })}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Calendar className="h-4 w-4" />
|
||||
<span className="text-sm">{t('skattekonto_preview_period')}</span>
|
||||
</div>
|
||||
<p className="text-sm font-medium tabular-nums">
|
||||
{date_from || '-'} – {date_to || '-'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Scale className="h-4 w-4" />
|
||||
<span className="text-sm">{t('skattekonto_preview_closing_saldo')}</span>
|
||||
</div>
|
||||
<p className="text-lg font-display tabular-nums">
|
||||
{closing_saldo !== null ? formatCurrency(closing_saldo) : '-'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{orgNumberMismatch && (
|
||||
<Card className="border-destructive/40">
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-sm flex items-center gap-2 text-destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{t('skattekonto_org_mismatch_title')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
<p className="text-muted-foreground">
|
||||
{t('skattekonto_org_mismatch_body', {
|
||||
orgNumber: parseResult.org_number ?? '?',
|
||||
companyName: parseResult.company_name ?? '?',
|
||||
})}
|
||||
</p>
|
||||
<label className="flex cursor-pointer items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5 h-4 w-4 rounded-sm border-border"
|
||||
checked={mismatchConfirmed}
|
||||
onChange={(e) => setMismatchConfirmed(e.target.checked)}
|
||||
/>
|
||||
<span>{t('skattekonto_org_mismatch_confirm')}</span>
|
||||
</label>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{sumGap && (
|
||||
<Card className="border-destructive/40">
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-sm flex items-center gap-2 text-destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{t('skattekonto_sum_gap_title')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 text-sm">
|
||||
{sumGapHasFigures ? (
|
||||
<dl className="grid max-w-sm grid-cols-[auto_1fr] gap-x-6 gap-y-1 tabular-nums">
|
||||
<dt className="text-muted-foreground">{t('skattekonto_sum_gap_opening')}</dt>
|
||||
<dd className="text-right">{formatCurrency(opening_saldo)}</dd>
|
||||
<dt className="text-muted-foreground">{t('skattekonto_sum_gap_events')}</dt>
|
||||
<dd className="text-right">{formatCurrency(roundOre(events_sum - opening_saldo))}</dd>
|
||||
<dt className="text-muted-foreground">{t('skattekonto_sum_gap_expected')}</dt>
|
||||
<dd className="text-right">{formatCurrency(events_sum)}</dd>
|
||||
<dt className="text-muted-foreground">{t('skattekonto_sum_gap_closing')}</dt>
|
||||
<dd className="text-right">{formatCurrency(closing_saldo)}</dd>
|
||||
<dt className="font-medium">{t('skattekonto_sum_gap_difference')}</dt>
|
||||
<dd className="text-right font-medium">{formatCurrency(sum_difference)}</dd>
|
||||
</dl>
|
||||
) : (
|
||||
<p className="text-muted-foreground">{t('skattekonto_sum_gap_no_saldo')}</p>
|
||||
)}
|
||||
<p className="text-muted-foreground">
|
||||
{stats.unreadable_amount_rows > 0
|
||||
? t('skattekonto_sum_gap_body_unreadable', { count: stats.unreadable_amount_rows })
|
||||
: t('skattekonto_sum_gap_body')}
|
||||
</p>
|
||||
<label className="flex cursor-pointer items-start gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="mt-0.5 h-4 w-4 rounded-sm border-border"
|
||||
checked={sumGapConfirmed}
|
||||
onChange={(e) => setSumGapConfirmed(e.target.checked)}
|
||||
/>
|
||||
<span>{t('skattekonto_sum_gap_confirm')}</span>
|
||||
</label>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{duplicateIndexes.length > 0 && (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('skattekonto_duplicates_note', { count: duplicateIndexes.length })}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* What happens after import: nothing is booked automatically, and an
|
||||
event that already has a 1630 verifikat (a deposit booked from the
|
||||
bank side) is offered as a link, not a second booking. Answers the
|
||||
"some of these are already booked" question before the click. */}
|
||||
<p className="text-sm text-muted-foreground">{t('skattekonto_after_import_note')}</p>
|
||||
|
||||
{warnings.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-sm flex items-center gap-2 text-warning">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{t('skattekonto_issues_title', { count: warnings.length })}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm text-muted-foreground space-y-1">
|
||||
{warnings.slice(0, 5).map((issue, i) => (
|
||||
<p key={i}>
|
||||
{issue.row > 0 ? `${t('skattekonto_issue_row', { row: issue.row })}: ` : ''}
|
||||
{issue.message}
|
||||
</p>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>{t('skattekonto_col_date')}</TableHead>
|
||||
<TableHead>{t('skattekonto_col_text')}</TableHead>
|
||||
<TableHead className="text-right">{t('skattekonto_col_amount')}</TableHead>
|
||||
<TableHead />
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{rows.slice(0, PREVIEW_ROW_LIMIT).map((row, index) => {
|
||||
const isDuplicate = duplicateSet.has(index)
|
||||
return (
|
||||
<TableRow key={index} className={cn(isDuplicate && 'opacity-60')}>
|
||||
<TableCell className="tabular-nums">{row.transaktionsdatum}</TableCell>
|
||||
<TableCell>{row.transaktionstext}</TableCell>
|
||||
<TableCell
|
||||
className={cn(
|
||||
'text-right tabular-nums',
|
||||
row.belopp < 0 ? 'text-destructive' : undefined,
|
||||
)}
|
||||
>
|
||||
{formatCurrency(row.belopp)}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
{isDuplicate ? (
|
||||
<Badge variant="secondary">{t('skattekonto_chip_duplicate')}</Badge>
|
||||
) : promotionSet.has(index) ? (
|
||||
<Badge variant="outline">{t('skattekonto_chip_promotion')}</Badge>
|
||||
) : null}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
{rows.length > PREVIEW_ROW_LIMIT && (
|
||||
<p className="px-4 py-3 text-xs text-muted-foreground">
|
||||
{t('skattekonto_preview_truncated', {
|
||||
shown: PREVIEW_ROW_LIMIT,
|
||||
total: rows.length,
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onBack} disabled={isLoading}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
{t('skattekonto_back')}
|
||||
</Button>
|
||||
<Button onClick={onExecute} disabled={isLoading || importBlocked || newCount === 0}>
|
||||
{t('skattekonto_import_button', { count: newCount })}
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { CheckCircle } from 'lucide-react'
|
||||
|
||||
export interface SkattekontoFileImportResult {
|
||||
imported: number
|
||||
duplicates: number
|
||||
promoted: number
|
||||
errors: number
|
||||
}
|
||||
|
||||
interface SkattekontoFileResultStepProps {
|
||||
result: SkattekontoFileImportResult
|
||||
onNewImport: () => void
|
||||
}
|
||||
|
||||
export default function SkattekontoFileResultStep({
|
||||
result,
|
||||
onNewImport,
|
||||
}: SkattekontoFileResultStepProps) {
|
||||
const t = useTranslations('import')
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex flex-col items-center gap-4 py-6 text-center">
|
||||
<CheckCircle className="h-12 w-12 text-success" />
|
||||
<div>
|
||||
<p className="font-display text-xl">{t('skattekonto_result_title')}</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground">
|
||||
{t('skattekonto_result_summary', {
|
||||
imported: result.imported,
|
||||
duplicates: result.duplicates,
|
||||
})}
|
||||
{result.promoted > 0 &&
|
||||
` ${t('skattekonto_result_promoted', { count: result.promoted })}`}
|
||||
</p>
|
||||
{result.errors > 0 && (
|
||||
<p className="mt-1 text-sm text-destructive">
|
||||
{t('skattekonto_result_errors', { count: result.errors })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:justify-center">
|
||||
<Button asChild>
|
||||
<Link href="/skattekonto">{t('skattekonto_result_open_skattekonto')}</Link>
|
||||
</Button>
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/transactions">{t('skattekonto_result_book_rows')}</Link>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={onNewImport}>
|
||||
{t('skattekonto_result_new_import')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import { Upload, FileText, AlertCircle, HelpCircle } from 'lucide-react'
|
||||
|
||||
interface SkattekontoFileUploadStepProps {
|
||||
onFileSelect: (file: File) => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
errorTitle?: string | null
|
||||
}
|
||||
|
||||
const ACCEPTED_EXTENSIONS = ['.csv', '.txt', '.skv']
|
||||
|
||||
export default function SkattekontoFileUploadStep({
|
||||
onFileSelect,
|
||||
isLoading,
|
||||
error,
|
||||
errorTitle,
|
||||
}: SkattekontoFileUploadStepProps) {
|
||||
const t = useTranslations('import')
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
const acceptFile = useCallback(
|
||||
(file: File | undefined) => {
|
||||
if (!file) return
|
||||
const name = file.name.toLowerCase()
|
||||
if (ACCEPTED_EXTENSIONS.some((ext) => name.endsWith(ext))) {
|
||||
onFileSelect(file)
|
||||
}
|
||||
},
|
||||
[onFileSelect],
|
||||
)
|
||||
|
||||
const handleDrop = useCallback(
|
||||
(e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
acceptFile(e.dataTransfer.files[0])
|
||||
},
|
||||
[acceptFile],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
{t('skattekonto_upload_title')}
|
||||
</CardTitle>
|
||||
<CardDescription>{t('skattekonto_upload_description')}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={isLoading ? -1 : 0}
|
||||
aria-label={t('skattekonto_tap_select')}
|
||||
className={`
|
||||
relative border-2 border-dashed rounded-lg p-8 text-center transition-colors
|
||||
${isDragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25'}
|
||||
${error ? 'border-destructive bg-destructive/5' : ''}
|
||||
${isLoading ? 'pointer-events-none opacity-50' : 'cursor-pointer hover:border-primary/50'}
|
||||
`}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
}}
|
||||
onDrop={handleDrop}
|
||||
onClick={() => document.getElementById('skattekonto-file-input')?.click()}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault()
|
||||
document.getElementById('skattekonto-file-input')?.click()
|
||||
}
|
||||
}}
|
||||
>
|
||||
<input
|
||||
id="skattekonto-file-input"
|
||||
type="file"
|
||||
accept={ACCEPTED_EXTENSIONS.join(',')}
|
||||
className="hidden"
|
||||
onChange={(e) => acceptFile(e.target.files?.[0])}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
<FileText className="mx-auto h-12 w-12 text-muted-foreground animate-pulse" />
|
||||
<p className="text-muted-foreground">{t('skattekonto_analyzing')}</p>
|
||||
<Progress value={33} className="w-48 mx-auto" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<Upload className="mx-auto h-12 w-12 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="font-medium hidden sm:block">{t('skattekonto_drop_here')}</p>
|
||||
<p className="font-medium sm:hidden">{t('skattekonto_tap_select')}</p>
|
||||
<p className="text-sm text-muted-foreground">{t('skattekonto_file_types')}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-4 bg-destructive/10 border border-destructive/20 rounded-lg flex gap-3">
|
||||
<AlertCircle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-destructive">
|
||||
{errorTitle || t('skattekonto_error_title')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="bg-muted/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<HelpCircle className="h-4 w-4" />
|
||||
{t('skattekonto_howto_title')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm space-y-3">
|
||||
<div>
|
||||
<p className="font-medium">Skatteverket</p>
|
||||
<p className="text-muted-foreground">{t('skattekonto_howto_steps')}</p>
|
||||
</div>
|
||||
<p className="text-muted-foreground">{t('skattekonto_howto_note')}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
'use client'
|
||||
|
||||
import { useMemo, useState, useCallback } from 'react'
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Trash2, AlertTriangle, Loader2, RefreshCw } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { SupplierType } from '@/types'
|
||||
import type { AnnotatedSupplierRow } from '@/lib/import/suppliers/types'
|
||||
|
||||
let idCounter = 0
|
||||
const newId = () => `supp_row_${++idCounter}_${Date.now()}`
|
||||
|
||||
interface EditableSupplierRow extends AnnotatedSupplierRow {
|
||||
id: string
|
||||
}
|
||||
|
||||
interface SuppliersEditStepProps {
|
||||
rows: AnnotatedSupplierRow[]
|
||||
onExecute: (rows: AnnotatedSupplierRow[], updateDuplicates: boolean) => void
|
||||
onBack: () => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
}
|
||||
|
||||
const TYPE_LABELS: Record<SupplierType, string> = {
|
||||
swedish_business: 'Svenskt företag eller organisation',
|
||||
eu_business: 'EU-företag',
|
||||
non_eu_business: 'Utomeuropeiskt företag',
|
||||
}
|
||||
|
||||
export default function SuppliersEditStep({
|
||||
rows: initialRows,
|
||||
onExecute,
|
||||
onBack,
|
||||
isLoading,
|
||||
error,
|
||||
}: SuppliersEditStepProps) {
|
||||
const [rows, setRows] = useState<EditableSupplierRow[]>(() =>
|
||||
initialRows.map((r) => ({ ...r, id: newId() })),
|
||||
)
|
||||
const [updateDuplicates, setUpdateDuplicates] = useState(false)
|
||||
|
||||
const liveDuplicateCount = useMemo(
|
||||
() => rows.filter((r) => r.duplicate_match !== null).length,
|
||||
[rows],
|
||||
)
|
||||
const newCount = rows.length - liveDuplicateCount
|
||||
|
||||
const hasErrors = useMemo(() => rows.some((r) => !r.is_valid), [rows])
|
||||
|
||||
const canContinue = rows.length > 0 && !hasErrors && !isLoading
|
||||
|
||||
const updateRow = useCallback((id: string, updates: Partial<EditableSupplierRow>) => {
|
||||
setRows((prev) => prev.map((r) => (r.id === id ? { ...r, ...updates } : r)))
|
||||
}, [])
|
||||
|
||||
const deleteRow = useCallback((id: string) => {
|
||||
setRows((prev) => prev.filter((r) => r.id !== id))
|
||||
}, [])
|
||||
|
||||
const handleExecute = () => {
|
||||
if (!canContinue) return
|
||||
const stripped: AnnotatedSupplierRow[] = rows.map(({ id: _id, ...rest }) => rest)
|
||||
onExecute(stripped, updateDuplicates)
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Granska leverantörer</CardTitle>
|
||||
<CardDescription>
|
||||
Kontrollera att uppgifterna stämmer. {newCount} ny{newCount === 1 ? '' : 'a'} leverantör{newCount === 1 ? '' : 'er'} skapas
|
||||
{liveDuplicateCount > 0 ? ` och ${liveDuplicateCount} matchar befintliga.` : '.'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{liveDuplicateCount > 0 && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<RefreshCw className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<div className="flex-1 space-y-2">
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{liveDuplicateCount} rader</span> matchar befintliga
|
||||
leverantörer (på orgnummer eller e-post).
|
||||
</p>
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
id="update-duplicates-supp"
|
||||
checked={updateDuplicates}
|
||||
onCheckedChange={setUpdateDuplicates}
|
||||
/>
|
||||
<Label htmlFor="update-duplicates-supp" className="text-sm cursor-pointer">
|
||||
{updateDuplicates
|
||||
? 'Uppdatera befintliga leverantörer med ny information'
|
||||
: 'Hoppa över befintliga leverantörer'}
|
||||
</Label>
|
||||
</div>
|
||||
{updateDuplicates && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Endast fält med värden i filen skrivs över. Tomma fält i filen lämnar
|
||||
befintliga värden orörda.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="overflow-x-auto rounded-lg border">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="[&_th]:font-medium [&_th]:text-[11px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
|
||||
<tr className="border-b">
|
||||
<th className="px-3 py-2 text-left">Namn</th>
|
||||
<th className="px-3 py-2 text-left w-44">Typ</th>
|
||||
<th className="px-3 py-2 text-left w-36">Orgnr</th>
|
||||
<th className="px-3 py-2 text-left w-32">Bankgiro/IBAN</th>
|
||||
<th className="px-3 py-2 text-left w-32">Status</th>
|
||||
<th className="px-3 py-2 w-10" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.id}
|
||||
className={cn(
|
||||
'border-b last:border-0',
|
||||
!row.is_valid && 'bg-destructive/5',
|
||||
)}
|
||||
>
|
||||
<td className="px-3 py-1.5">
|
||||
<Input
|
||||
value={row.name}
|
||||
onChange={(e) => updateRow(row.id, { name: e.target.value })}
|
||||
className="h-8"
|
||||
/>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Select
|
||||
value={row.supplier_type}
|
||||
onValueChange={(v) => updateRow(row.id, { supplier_type: v as SupplierType })}
|
||||
>
|
||||
<SelectTrigger className="h-8">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(Object.keys(TYPE_LABELS) as SupplierType[]).map((t) => (
|
||||
<SelectItem key={t} value={t}>
|
||||
{TYPE_LABELS[t]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</td>
|
||||
<td className="px-3 py-1.5 text-muted-foreground tabular-nums">
|
||||
{row.org_number || '-'}
|
||||
</td>
|
||||
<td className="px-3 py-1.5 text-muted-foreground tabular-nums truncate max-w-[10rem]">
|
||||
{row.bankgiro || row.plusgiro || row.iban || '-'}
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<div className="flex items-center gap-1.5">
|
||||
{!row.is_valid && (
|
||||
<span
|
||||
className="text-destructive shrink-0"
|
||||
title={row.validation_errors.join(', ')}
|
||||
>
|
||||
<AlertTriangle className="h-3.5 w-3.5" />
|
||||
</span>
|
||||
)}
|
||||
{row.duplicate_match ? (
|
||||
<span
|
||||
className={cn(
|
||||
'text-[11px] font-medium px-1.5 py-0.5 rounded-full',
|
||||
updateDuplicates
|
||||
? 'bg-muted text-warning'
|
||||
: 'bg-muted text-muted-foreground',
|
||||
)}
|
||||
title={`Matchar ${row.duplicate_match.existing_name} (${row.duplicate_match.matched_by})`}
|
||||
>
|
||||
{updateDuplicates ? 'Uppdateras' : 'Hoppas över'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-[11px] font-medium px-1.5 py-0.5 rounded-full bg-success/15 text-success">
|
||||
Ny
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3 py-1.5">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
aria-label="Ta bort rad"
|
||||
onClick={() => deleteRow(row.id)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
</Button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{hasErrors && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/30 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-warning mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-warning">
|
||||
Vissa rader har valideringsfel (markerade i rött). Åtgärda eller ta bort dem
|
||||
innan du fortsätter.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-3">
|
||||
<AlertTriangle className="h-4 w-4 text-destructive mt-0.5 shrink-0" />
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-between pt-2">
|
||||
<Button variant="ghost" onClick={onBack} disabled={isLoading}>Tillbaka</Button>
|
||||
<Button onClick={handleExecute} disabled={!canContinue}>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 animate-spin mr-2" />
|
||||
Importerar...
|
||||
</>
|
||||
) : (
|
||||
`Importera ${rows.length} rad${rows.length === 1 ? '' : 'er'}`
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user