feat(import/export): article import + register export (xlsx/csv) (#750)

* feat(import/export): article import + register export (xlsx/csv)

Add CSV/Excel import for the article register (artiklar), mirroring the
existing customer/supplier import pipeline, plus Excel + CSV export for
articles, customers and suppliers.

Import (lib/import/articles + app/api/import/articles):
- Column auto-detection tuned to Fortnox/Visma/Bokio export headers,
  Swedish-decimal price parsing, VAT snapped to {0,6,12,25}, type/unit
  normalization.
- Dedup by article number then name; 23505 soft-skip; auto-number
  backfill; revenue-account override kept only when active, otherwise
  dropped with a warning (never mutates the chart of accounts).
- New "Artiklar" flow in the /import hub.

Export (app/api/export/* + lib/export/register-export):
- Read-only xlsx (default) / csv (?format=csv, UTF-8 BOM) downloads.
- Headers chosen so files round-trip back through the importer.
- "Exportera" menu added to the articles, customers and suppliers pages.

Refs #746. Direct Fortnox/Visma API article fetch tracked in #749.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(import/export): address PR review — lint ratchet + export hardening

- xlsx-export: keep `SheetSpec<any>` on the eslint-disabled line (fixes the
  core-only lint ratchet regression: no-explicit-any 16 -> 15) and define
  UTF8_BOM as an explicit `` escape instead of a raw BOM character.
- export routes (articles/customers/suppliers): move the data queries inside
  the try/catch, add `Cache-Control: no-store`, and emit a `register exported`
  audit log line (entity, format, rowCount).
- articles parse route: validate `column_overrides` against a Zod schema before
  trusting it to drive the parser.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(import): drop öre-round pattern on article column-detector confidence

The confidence score is a 0-1 heuristic, not money, and is only compared
against the 0.8 skip-mapping threshold. Removing the Math.round(x*100)/100
form clears the core-only antipattern ratchet (naive-ore-round 660 -> 659).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* feat(import): flag adjusted VAT rows in the article import edit step

Surface VAT snapping/defaulting per row, not just as a file-level warning:
the parser sets `vat_rate_adjusted`, the edit step highlights those rows'
VAT selector and shows a count banner, and confirming a rate clears the flag.
Addresses the Swedish-compliance review note that silent snapping could
otherwise store a wrong VAT rate at scale.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-17 14:38:44 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 7aa37fd3b8
commit 2d6ddeafc5
28 changed files with 2614 additions and 85 deletions
+308
View File
@@ -0,0 +1,308 @@
'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-warning/30 bg-warning/5 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-warning/30 bg-warning/5 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-md 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">
<Input
value={String(row.price_excl_vat)}
inputMode="decimal"
onChange={(e) => handlePriceChange(row.id, e.target.value)}
className="h-8 text-right tabular-nums"
/>
</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-warning 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',
updateDuplicates
? 'bg-warning/15 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 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-warning/30 bg-warning/5 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>
)
}
+26 -1
View File
@@ -12,10 +12,12 @@ export type RegisterResult = {
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'
entity: 'customers' | 'suppliers' | 'articles'
result: RegisterResult
onNewImport: () => void
}
@@ -33,6 +35,12 @@ const ENTITY_COPY = {
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({
@@ -94,6 +102,23 @@ export default function RegisterResultStep({
</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-warning/30 bg-warning/5 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}>
+8 -1
View File
@@ -6,7 +6,7 @@ import { Button } from '@/components/ui/button'
import { Upload, FileSpreadsheet, AlertCircle, Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
export type RegisterEntity = 'customers' | 'suppliers'
export type RegisterEntity = 'customers' | 'suppliers' | 'articles'
interface RegisterUploadStepProps {
entity: RegisterEntity
@@ -30,6 +30,13 @@ const COPY: Record<RegisterEntity, { title: string; description: string; hint: s
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({
+12 -4
View File
@@ -1,6 +1,6 @@
'use client'
import { Download, FileSpreadsheet, FileText } from 'lucide-react'
import { Download, FileSpreadsheet, FileText, Table } from 'lucide-react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import {
@@ -9,10 +9,12 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import type { ReportExportFormat } from '@/lib/reports/catalog'
/** pdf/xlsx for reports; csv is additionally used by register exports. */
export type ExportMenuFormat = 'pdf' | 'xlsx' | 'csv'
export interface ReportExportItem {
format: ReportExportFormat
format: ExportMenuFormat
href: string
}
@@ -50,10 +52,16 @@ export function ReportExportMenu({
>
{item.format === 'pdf' ? (
<FileText className="h-4 w-4 mr-2" />
) : item.format === 'csv' ? (
<Table className="h-4 w-4 mr-2" />
) : (
<FileSpreadsheet className="h-4 w-4 mr-2" />
)}
{item.format === 'pdf' ? t('download_pdf') : t('download_excel')}
{item.format === 'pdf'
? t('download_pdf')
: item.format === 'csv'
? t('download_csv')
: t('download_excel')}
</DropdownMenuItem>
))}
</DropdownMenuContent>