Add/csv import options (#420)

* feat(import): add customer and supplier parsing functionality

- Implemented customer file parsing in `lib/import/customers/parser.ts` with support for Excel and CSV formats.
- Created types for detected customer columns and parsed customer rows in `lib/import/customers/types.ts`.
- Added tests for customer classification logic in `lib/import/shared/__tests__/classify.test.ts`.
- Developed classification functions for customers and suppliers in `lib/import/shared/classify.ts`.
- Introduced shared column utility functions in `lib/import/shared/column-utils.ts`.
- Implemented supplier file parsing in `lib/import/suppliers/parser.ts` with validation for various fields.
- Created types for detected supplier columns and parsed supplier rows in `lib/import/suppliers/types.ts`.
- Added tests for supplier column detection and parsing in `lib/import/suppliers/__tests__/column-detector.test.ts` and `lib/import/suppliers/__tests__/parser.test.ts`.

* fix(labels): update 'Svenskt företag' to 'Svenskt företag eller organisation' for clarity

* feat(import): refactor encoding handling for Swedish files and add tests for character preservation

* feat(recapt): implement clearRecaptIdentity function and integrate into logout flow

* feat(bookkeeping): implement copy functionality and next voucher sequence retrieval

* feat(import): enhance customer and supplier import functionality with normalization and event handling
This commit is contained in:
Mattsson
2026-05-08 15:42:06 +02:00
committed by GitHub
parent 6c5c49f588
commit 81e9dd224e
62 changed files with 4468 additions and 124 deletions
+12 -20
View File
@@ -2,21 +2,6 @@
import { useEffect } from 'react'
declare global {
interface Window {
Recapt?: {
session: {
setIdentity: (identity: {
uid: string
email?: string
nickname?: string
fullName?: string
}) => void
}
}
}
}
export function RecaptIdentify({
userId,
email,
@@ -27,16 +12,23 @@ export function RecaptIdentify({
displayName?: string
}) {
useEffect(() => {
let attempts = 0
const maxAttempts = 50
const interval = setInterval(() => {
if (typeof window.Recapt?.session?.setIdentity === 'function') {
window.Recapt.session.setIdentity({
if (typeof window.recapt === 'function') {
window.recapt('identify', {
uid: userId,
email: email,
fullName: displayName,
email,
nickname: displayName,
})
clearInterval(interval)
return
}
}, 500)
attempts++
if (attempts >= maxAttempts) {
clearInterval(interval)
}
}, 100)
return () => clearInterval(interval)
}, [userId, email, displayName])
+12 -1
View File
@@ -2,12 +2,13 @@
import { useState, useEffect, useCallback } from 'react'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { ArrowDownNarrowWide, ArrowUpNarrowWide, ChevronDown, ChevronRight, Paperclip, AlertTriangle, Loader2, BookOpen, X } from 'lucide-react'
import { ArrowDownNarrowWide, ArrowUpNarrowWide, ChevronDown, ChevronRight, Paperclip, AlertTriangle, Loader2, BookOpen, X, Copy } from 'lucide-react'
import { Input } from '@/components/ui/input'
import { AccountNumber } from '@/components/ui/account-number'
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
@@ -30,6 +31,7 @@ interface Props {
}
export default function JournalEntryList({ periodId }: Props) {
const router = useRouter()
const [entries, setEntries] = useState<JournalEntry[]>([])
const [loading, setLoading] = useState(true)
const [expandedId, setExpandedId] = useState<string | null>(null)
@@ -463,6 +465,15 @@ export default function JournalEntryList({ periodId }: Props) {
Skapa ändringsverifikation
</Button>
)}
<Button
variant="outline"
size="sm"
className="w-full sm:w-auto"
onClick={() => router.push(`/bookkeeping?copy_from=${entry.id}`)}
>
<Copy className="mr-2 h-4 w-4" />
Kopiera
</Button>
</div>
</CardContent>
)}
+1 -1
View File
@@ -144,7 +144,7 @@ export default function CustomerForm({
</SelectTrigger>
<SelectContent>
<SelectItem value="individual">Privatperson (Sverige)</SelectItem>
<SelectItem value="swedish_business">Svenskt företag</SelectItem>
<SelectItem value="swedish_business">Svenskt företag eller organisation</SelectItem>
<SelectItem value="eu_business">EU-företag</SelectItem>
<SelectItem value="non_eu_business">Företag utanför EU</SelectItem>
</SelectContent>
+2
View File
@@ -33,6 +33,7 @@ import { resolveIcon } from '@/lib/extensions/icon-resolver'
import { SupportLink } from '@/components/ui/support-link'
import CompanySwitcher from '@/components/dashboard/CompanySwitcher'
import { useCompany } from '@/contexts/CompanyContext'
import { clearRecaptIdentity } from '@/lib/recapt'
import type { EntityType } from '@/types'
interface ExtensionNavItem {
@@ -127,6 +128,7 @@ export default function DashboardNav({ companyName: _companyName, entityType, un
}
const handleLogout = async () => {
clearRecaptIdentity()
await supabase.auth.signOut()
router.push(isSandbox ? '/sandbox' : '/login')
}
+253
View File
@@ -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-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
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-md border">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-muted/50">
<th className="px-3 py-2 text-left font-medium">Namn</th>
<th className="px-3 py-2 text-left font-medium w-44">Kundtyp</th>
<th className="px-3 py-2 text-left font-medium w-36">Orgnr</th>
<th className="px-3 py-2 text-left font-medium">E-post</th>
<th className="px-3 py-2 text-left font-medium 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',
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>
)
}
@@ -0,0 +1,125 @@
'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-md border">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-muted/50">
{headers.map((h, i) => (
<th key={i} className="px-3 py-2 text-left font-medium 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>
)
}
+135
View File
@@ -0,0 +1,135 @@
'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 }[]
}
interface RegisterResultStepProps {
entity: 'customers' | 'suppliers'
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',
},
} 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>
)}
<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>
)
}
+123
View File
@@ -0,0 +1,123 @@
'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'
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".',
},
}
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>
)
}
+241
View File
@@ -0,0 +1,241 @@
'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-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
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-md border">
<table className="w-full text-sm">
<thead>
<tr className="border-b bg-muted/50">
<th className="px-3 py-2 text-left font-medium">Namn</th>
<th className="px-3 py-2 text-left font-medium w-44">Typ</th>
<th className="px-3 py-2 text-left font-medium w-36">Orgnr</th>
<th className="px-3 py-2 text-left font-medium w-32">Bankgiro/IBAN</th>
<th className="px-3 py-2 text-left font-medium 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',
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>
)
}
+1 -1
View File
@@ -42,7 +42,7 @@ export function InvoiceReviewContent({
}: InvoiceReviewContentProps) {
const customerTypeLabel: Record<string, string> = {
individual: 'Privatperson',
swedish_business: 'Svenskt företag',
swedish_business: 'Svenskt företag eller organisation',
eu_business: 'EU-företag',
non_eu_business: 'Utanför EU',
}
+1 -1
View File
@@ -98,7 +98,7 @@ export default function SupplierForm({
<SelectValue placeholder="Välj typ" />
</SelectTrigger>
<SelectContent>
<SelectItem value="swedish_business">Svenskt företag</SelectItem>
<SelectItem value="swedish_business">Svenskt företag eller organisation</SelectItem>
<SelectItem value="eu_business">EU-företag</SelectItem>
<SelectItem value="non_eu_business">Företag utanför EU</SelectItem>
</SelectContent>