Files
accounted/components/import/RegisterUploadStep.tsx
T
Jakob WennbergandClaude Opus 4.8 2d6ddeafc5 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>
2026-06-17 14:38:44 +02:00

131 lines
5.0 KiB
TypeScript

'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>
)
}