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:
co-authored by
Claude Opus 4.8
parent
7aa37fd3b8
commit
2d6ddeafc5
@@ -29,6 +29,7 @@ import {
|
||||
} from '@/lib/hooks/use-submit-with-account-activation'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { ReportExportMenu } from '@/components/reports/ReportExportMenu'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import Link from 'next/link'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
@@ -237,30 +238,38 @@ function ArticlesPageInner() {
|
||||
<PageHeader
|
||||
title={t('title')}
|
||||
action={
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t('new_article')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('add_article')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ArticleForm
|
||||
onSubmit={handleCreateArticle}
|
||||
isLoading={isCreating}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<div className="flex items-center gap-2">
|
||||
<ReportExportMenu
|
||||
items={[
|
||||
{ format: 'xlsx', href: '/api/export/articles' },
|
||||
{ format: 'csv', href: '/api/export/articles?format=csv' },
|
||||
]}
|
||||
/>
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t('new_article')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('add_article')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<ArticleForm
|
||||
onSubmit={handleCreateArticle}
|
||||
isLoading={isCreating}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
@@ -24,6 +24,7 @@ import { Plus, Search, Users, Lock, ChevronUp, ChevronDown, ChevronsUpDown } fro
|
||||
import CustomerForm from '@/components/customers/CustomerForm'
|
||||
import { EmptyCustomers, EmptyState } from '@/components/ui/empty-state'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { ReportExportMenu } from '@/components/reports/ReportExportMenu'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import Link from 'next/link'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
@@ -241,30 +242,38 @@ function CustomersPageInner() {
|
||||
<PageHeader
|
||||
title={t('title')}
|
||||
action={
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t('new_customer')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('add_customer')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CustomerForm
|
||||
onSubmit={handleCreateCustomer}
|
||||
isLoading={isCreating}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<div className="flex items-center gap-2">
|
||||
<ReportExportMenu
|
||||
items={[
|
||||
{ format: 'xlsx', href: '/api/export/customers' },
|
||||
{ format: 'csv', href: '/api/export/customers?format=csv' },
|
||||
]}
|
||||
/>
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t('new_customer')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('add_customer')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<CustomerForm
|
||||
onSubmit={handleCreateCustomer}
|
||||
isLoading={isCreating}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ import RegisterUploadStep from '@/components/import/RegisterUploadStep'
|
||||
import RegisterColumnMappingStep, { type RegisterColumnSpec } from '@/components/import/RegisterColumnMappingStep'
|
||||
import CustomersEditStep from '@/components/import/CustomersEditStep'
|
||||
import SuppliersEditStep from '@/components/import/SuppliersEditStep'
|
||||
import ArticlesEditStep from '@/components/import/ArticlesEditStep'
|
||||
import RegisterResultStep, { type RegisterResult } from '@/components/import/RegisterResultStep'
|
||||
import type {
|
||||
CustomerImportParseResult,
|
||||
@@ -50,6 +51,11 @@ import type {
|
||||
AnnotatedSupplierRow,
|
||||
DetectedSupplierColumns,
|
||||
} from '@/lib/import/suppliers/types'
|
||||
import type {
|
||||
ArticleImportParseResult,
|
||||
AnnotatedArticleRow,
|
||||
DetectedArticleColumns,
|
||||
} from '@/lib/import/articles/types'
|
||||
|
||||
// SIE import components
|
||||
import SIEUploadStep from '@/components/import/SIEUploadStep'
|
||||
@@ -1568,16 +1574,260 @@ function SuppliersFlow() {
|
||||
)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Articles Flow (entity = "articles" inside CSVDataImportWizard)
|
||||
// ============================================================
|
||||
|
||||
const ARTICLE_COLUMN_SPECS: RegisterColumnSpec<keyof DetectedArticleColumns>[] = [
|
||||
{ key: 'name_col', label: 'Benämning', required: true },
|
||||
{ key: 'article_number_col', label: 'Artikelnummer', required: false },
|
||||
{ key: 'type_col', label: 'Typ (vara/tjänst)', required: false },
|
||||
{ key: 'unit_col', label: 'Enhet', required: false },
|
||||
{ key: 'price_col', label: 'Pris exkl moms', required: false },
|
||||
{ key: 'vat_rate_col', label: 'Moms (%)', required: false },
|
||||
{ key: 'revenue_account_col', label: 'Försäljningskonto', required: false },
|
||||
{ key: 'cost_price_col', label: 'Inköpspris', required: false },
|
||||
{ key: 'ean_col', label: 'EAN', required: false },
|
||||
{ key: 'housework_type_col', label: 'ROT/RUT-arbetstyp', required: false },
|
||||
{ key: 'name_en_col', label: 'Benämning (engelska)', required: false },
|
||||
{ key: 'notes_col', label: 'Anteckning', required: false },
|
||||
]
|
||||
|
||||
function ArticlesFlow() {
|
||||
const { toast } = useToast()
|
||||
|
||||
const [step, setStep] = useState<RegisterStep>('upload')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [parseResult, setParseResult] = useState<ArticleImportParseResult | null>(null)
|
||||
const [executeResult, setExecuteResult] = useState<RegisterResult | null>(null)
|
||||
|
||||
const needsMapping = parseResult && parseResult.detected_columns.confidence < 0.8
|
||||
const steps: RegisterStep[] = needsMapping
|
||||
? ['upload', 'column_mapping', 'edit', 'result']
|
||||
: ['upload', 'edit', 'result']
|
||||
const currentStepIndex = steps.indexOf(step)
|
||||
const progress = ((currentStepIndex + 1) / steps.length) * 100
|
||||
|
||||
const handleFileSelect = useCallback(async (selectedFile: File) => {
|
||||
setError(null)
|
||||
setIsLoading(true)
|
||||
setFile(selectedFile)
|
||||
|
||||
try {
|
||||
const formData = new FormData()
|
||||
formData.append('file', selectedFile)
|
||||
|
||||
const res = await fetch('/api/import/articles/parse', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
setError(data.error?.message_sv || data.error?.message || data.error || 'Kunde inte läsa filen')
|
||||
return
|
||||
}
|
||||
|
||||
const result = data.data as ArticleImportParseResult
|
||||
setParseResult(result)
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
setError('Inga giltiga artiklar hittades. Kontrollera att filen innehåller en benämningskolumn.')
|
||||
return
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Fil analyserad',
|
||||
description: `${result.rows.length} artiklar hittades${result.duplicate_count > 0 ? ` (${result.duplicate_count} matchar befintliga)` : ''}`,
|
||||
})
|
||||
|
||||
setStep(result.detected_columns.confidence < 0.8 ? 'column_mapping' : 'edit')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Kunde inte läsa filen')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [toast])
|
||||
|
||||
const handleColumnMappingConfirm = useCallback(async (
|
||||
mapping: Record<keyof DetectedArticleColumns, number | null>,
|
||||
) => {
|
||||
if (!file) return
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const overrides: DetectedArticleColumns = {
|
||||
name_col: mapping.name_col ?? 0,
|
||||
article_number_col: mapping.article_number_col,
|
||||
name_en_col: mapping.name_en_col,
|
||||
type_col: mapping.type_col,
|
||||
unit_col: mapping.unit_col,
|
||||
price_col: mapping.price_col,
|
||||
vat_rate_col: mapping.vat_rate_col,
|
||||
revenue_account_col: mapping.revenue_account_col,
|
||||
cost_price_col: mapping.cost_price_col,
|
||||
ean_col: mapping.ean_col,
|
||||
housework_type_col: mapping.housework_type_col,
|
||||
notes_col: mapping.notes_col,
|
||||
confidence: 1,
|
||||
}
|
||||
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('column_overrides', JSON.stringify(overrides))
|
||||
|
||||
const res = await fetch('/api/import/articles/parse', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
setError(data.error?.message_sv || data.error?.message || 'Kunde inte tolka filen med de valda kolumnerna')
|
||||
return
|
||||
}
|
||||
|
||||
setParseResult(data.data)
|
||||
setStep('edit')
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Kunde inte läsa filen')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [file])
|
||||
|
||||
const handleExecute = useCallback(async (
|
||||
rows: AnnotatedArticleRow[],
|
||||
updateDuplicates: boolean,
|
||||
) => {
|
||||
setIsLoading(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/import/articles/execute', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
rows: rows.map(({ duplicate_match: _dup, is_valid: _v, validation_errors: _ve, vat_rate_adjusted: _vra, ...rest }) => rest),
|
||||
update_duplicates: updateDuplicates,
|
||||
}),
|
||||
})
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
setError(data.error?.message_sv || data.error?.message || 'Importen misslyckades')
|
||||
return
|
||||
}
|
||||
|
||||
setExecuteResult(data.data as RegisterResult)
|
||||
setStep('result')
|
||||
|
||||
const r = data.data as RegisterResult
|
||||
toast({
|
||||
title: r.success ? 'Artiklar importerade' : 'Importen slutfördes med fel',
|
||||
description: `${r.created} skapade, ${r.updated} uppdaterade, ${r.skipped} hoppade över${r.failed > 0 ? `, ${r.failed} misslyckades` : ''}`,
|
||||
variant: r.success ? 'default' : 'destructive',
|
||||
})
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Importen misslyckades')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}, [toast])
|
||||
|
||||
const handleNewImport = () => {
|
||||
setStep('upload')
|
||||
setFile(null)
|
||||
setParseResult(null)
|
||||
setExecuteResult(null)
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const initialMapping = parseResult
|
||||
? columnsToMapping<keyof DetectedArticleColumns>(parseResult.detected_columns as unknown as { [key: string]: unknown }, ARTICLE_COLUMN_SPECS)
|
||||
: null
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="sm:hidden text-primary font-medium">
|
||||
Steg {currentStepIndex + 1}/{steps.length}: {REGISTER_STEP_LABELS[step]}
|
||||
</span>
|
||||
{steps.map((s, i) => (
|
||||
<span
|
||||
key={s}
|
||||
className={cn(
|
||||
'hidden sm:inline',
|
||||
i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{REGISTER_STEP_LABELS[s]}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<Progress value={progress} className="h-2" />
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{step === 'upload' && (
|
||||
<RegisterUploadStep
|
||||
entity="articles"
|
||||
onFileSelect={handleFileSelect}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 'column_mapping' && parseResult && initialMapping && (
|
||||
<RegisterColumnMappingStep<keyof DetectedArticleColumns>
|
||||
headers={parseResult.headers}
|
||||
previewRows={parseResult.preview_rows}
|
||||
specs={ARTICLE_COLUMN_SPECS}
|
||||
initial={initialMapping}
|
||||
onConfirm={handleColumnMappingConfirm}
|
||||
onBack={() => setStep('upload')}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 'edit' && parseResult && (
|
||||
<ArticlesEditStep
|
||||
rows={parseResult.rows}
|
||||
onExecute={handleExecute}
|
||||
onBack={() => setStep(needsMapping ? 'column_mapping' : 'upload')}
|
||||
isLoading={isLoading}
|
||||
error={error}
|
||||
/>
|
||||
)}
|
||||
|
||||
{step === 'result' && executeResult && (
|
||||
<RegisterResultStep
|
||||
entity="articles"
|
||||
result={executeResult}
|
||||
onNewImport={handleNewImport}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// CSV/Excel Data Import Wizard — entity selector + sub-flow
|
||||
// ============================================================
|
||||
|
||||
type CSVDataEntity = 'opening_balance' | 'customers' | 'suppliers'
|
||||
type CSVDataEntity = 'opening_balance' | 'customers' | 'suppliers' | 'articles'
|
||||
|
||||
const ENTITY_OPTIONS: { value: CSVDataEntity; label: string }[] = [
|
||||
{ value: 'opening_balance', label: 'Ingående balanser' },
|
||||
{ value: 'customers', label: 'Kunder' },
|
||||
{ value: 'suppliers', label: 'Leverantörer' },
|
||||
{ value: 'articles', label: 'Artiklar' },
|
||||
]
|
||||
|
||||
function CSVDataImportWizard() {
|
||||
@@ -1633,6 +1883,7 @@ function CSVDataImportWizard() {
|
||||
{entity === 'opening_balance' && <OpeningBalanceFlow key="ob-flow" />}
|
||||
{entity === 'customers' && <CustomersFlow key="cust-flow" />}
|
||||
{entity === 'suppliers' && <SuppliersFlow key="supp-flow" />}
|
||||
{entity === 'articles' && <ArticlesFlow key="art-flow" />}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2074,6 +2325,7 @@ export default function ImportPage() {
|
||||
{ key: 'opening_balances', label: t('csv_chip_opening_balances') },
|
||||
{ key: 'customers', label: t('csv_chip_customers') },
|
||||
{ key: 'suppliers', label: t('csv_chip_suppliers') },
|
||||
{ key: 'articles', label: t('csv_chip_articles') },
|
||||
].map(chip => (
|
||||
<span key={chip.key} className="text-[11px] text-muted-foreground/80 bg-muted/80 px-1.5 py-0.5 rounded leading-none">
|
||||
{chip.label}
|
||||
|
||||
@@ -8,6 +8,7 @@ import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { ReportExportMenu } from '@/components/reports/ReportExportMenu'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Plus, Search, Building2, Lock } from 'lucide-react'
|
||||
import SupplierForm from '@/components/suppliers/SupplierForm'
|
||||
@@ -118,30 +119,38 @@ export default function SuppliersPage() {
|
||||
{t('subtitle')}
|
||||
</p>
|
||||
</div>
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t('new_supplier')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('add_supplier')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<SupplierForm
|
||||
onSubmit={handleCreateSupplier}
|
||||
isLoading={isCreating}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<div className="flex items-center gap-2">
|
||||
<ReportExportMenu
|
||||
items={[
|
||||
{ format: 'xlsx', href: '/api/export/suppliers' },
|
||||
{ format: 'csv', href: '/api/export/suppliers?format=csv' },
|
||||
]}
|
||||
/>
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
disabled={!canWrite}
|
||||
title={!canWrite ? t('viewer_disabled_tooltip') : undefined}
|
||||
>
|
||||
{canWrite ? (
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
) : (
|
||||
<Lock className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
{t('new_supplier')}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[95dvh] sm:max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('add_supplier')}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<SupplierForm
|
||||
onSubmit={handleCreateSupplier}
|
||||
isLoading={isCreating}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { detectArticleColumns } from '@/lib/import/articles/column-detector'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const mockFetchAllRows = vi.fn()
|
||||
vi.mock('@/lib/supabase/fetch-all', () => ({
|
||||
fetchAllRows: (...a: unknown[]) => mockFetchAllRows(...a),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
const ARTICLE = {
|
||||
id: 'a1',
|
||||
article_number: '100',
|
||||
name: 'Webdesign',
|
||||
name_en: 'Web design',
|
||||
type: 'tjanst',
|
||||
unit: 'st',
|
||||
price_excl_vat: 1200,
|
||||
vat_rate: 25,
|
||||
revenue_account: '3001',
|
||||
cost_price: 400,
|
||||
ean: '7350000000001',
|
||||
housework_type: null,
|
||||
notes: 'Kommentar med åäö',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
mockFetchAllRows.mockResolvedValue([ARTICLE])
|
||||
})
|
||||
|
||||
describe('GET /api/export/articles', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const res = await GET(createMockRequest('/api/export/articles'))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns an xlsx workbook whose headers round-trip through the importer', async () => {
|
||||
enqueue({ data: { company_name: 'Acme AB' } })
|
||||
|
||||
const res = await GET(createMockRequest('/api/export/articles'))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toContain('spreadsheetml')
|
||||
const disposition = res.headers.get('Content-Disposition') || ''
|
||||
expect(disposition).toContain('attachment')
|
||||
expect(disposition).toContain('artiklar-acme-ab')
|
||||
expect(disposition).toContain('.xlsx')
|
||||
|
||||
const buf = Buffer.from(await res.arrayBuffer())
|
||||
expect(buf.length).toBeGreaterThan(0)
|
||||
|
||||
const wb = XLSX.read(new Uint8Array(buf), { type: 'array' })
|
||||
const sheet = wb.Sheets[wb.SheetNames[0]]
|
||||
const rows = XLSX.utils.sheet_to_json<string[]>(sheet, { header: 1 })
|
||||
const headers = (rows[0] as string[]).map(String)
|
||||
// Round-trip: the exported headers must re-detect with high confidence.
|
||||
const detected = detectArticleColumns(headers)
|
||||
expect(detected.confidence).toBeGreaterThanOrEqual(0.8)
|
||||
expect(detected.name_col).toBeGreaterThanOrEqual(0)
|
||||
expect(detected.price_col).not.toBeNull()
|
||||
expect(detected.vat_rate_col).not.toBeNull()
|
||||
expect(detected.revenue_account_col).not.toBeNull()
|
||||
})
|
||||
|
||||
it('returns a UTF-8 BOM CSV when format=csv', async () => {
|
||||
enqueue({ data: { company_name: 'Acme AB' } })
|
||||
|
||||
const res = await GET(createMockRequest('/api/export/articles', { searchParams: { format: 'csv' } }))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toContain('text/csv')
|
||||
expect(res.headers.get('Content-Disposition')).toContain('.csv')
|
||||
|
||||
const buf = Buffer.from(await res.arrayBuffer())
|
||||
// UTF-8 BOM
|
||||
expect([buf[0], buf[1], buf[2]]).toEqual([0xef, 0xbb, 0xbf])
|
||||
expect(buf.toString('utf-8')).toContain('Webdesign')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,94 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { textColumn, currencyColumn, integerColumn } from '@/lib/reports/xlsx-export'
|
||||
import { buildRegisterExport, parseExportFormat, todayIso } from '@/lib/export/register-export'
|
||||
import type { Article } from '@/types'
|
||||
|
||||
/**
|
||||
* GET /api/export/articles[?format=csv][&include_inactive=1]
|
||||
*
|
||||
* Downloads the article register as xlsx (default) or csv. Read-only — viewers
|
||||
* may export. Column headers match the article importer's detector keywords so
|
||||
* the file round-trips (export → edit → re-import).
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'article.export',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const url = new URL(request.url)
|
||||
const format = parseExportFormat(url.searchParams.get('format'))
|
||||
const includeInactive = url.searchParams.get('include_inactive') === '1'
|
||||
|
||||
try {
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
const articles = (await fetchAllRows(({ from, to }) => {
|
||||
let query = supabase
|
||||
.from('articles')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
if (!includeInactive) query = query.eq('active', true)
|
||||
return query.order('name', { ascending: true }).range(from, to)
|
||||
})) as unknown as Article[]
|
||||
|
||||
const { buffer, contentType, filename } = buildRegisterExport(
|
||||
[
|
||||
{
|
||||
name: 'Artiklar',
|
||||
columns: [
|
||||
textColumn('Artikelnummer'),
|
||||
textColumn('Benämning'),
|
||||
textColumn('Benämning (engelska)'),
|
||||
textColumn('Typ'),
|
||||
textColumn('Enhet'),
|
||||
currencyColumn('Försäljningspris'),
|
||||
integerColumn('Moms %'),
|
||||
textColumn('Försäljningskonto'),
|
||||
currencyColumn('Inköpspris'),
|
||||
textColumn('EAN'),
|
||||
textColumn('ROT/RUT'),
|
||||
textColumn('Anteckning'),
|
||||
],
|
||||
rows: articles,
|
||||
mapRow: (a) => [
|
||||
a.article_number,
|
||||
a.name,
|
||||
a.name_en,
|
||||
a.type,
|
||||
a.unit,
|
||||
a.price_excl_vat,
|
||||
a.vat_rate,
|
||||
a.revenue_account,
|
||||
a.cost_price,
|
||||
a.ean,
|
||||
a.housework_type,
|
||||
a.notes,
|
||||
],
|
||||
},
|
||||
],
|
||||
{ format, slug: 'artiklar', companyName: companyRow?.company_name ?? '', date: todayIso() },
|
||||
)
|
||||
|
||||
// Audit trail: who exported what, when (sensitive bulk register download).
|
||||
log.info('register exported', { entity: 'articles', format, rowCount: articles.length })
|
||||
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
log.error('article export failed', err as Error)
|
||||
return errorResponse(err, log, { requestId })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,84 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const mockFetchAllRows = vi.fn()
|
||||
vi.mock('@/lib/supabase/fetch-all', () => ({
|
||||
fetchAllRows: (...a: unknown[]) => mockFetchAllRows(...a),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
const CUSTOMER = {
|
||||
id: 'c1',
|
||||
name: 'Acme AB',
|
||||
customer_type: 'swedish_business',
|
||||
org_number: '5560217780',
|
||||
personal_number: null,
|
||||
email: 'kontakt@acme.se',
|
||||
phone: '0701234567',
|
||||
address_line1: 'Storgatan 1',
|
||||
address_line2: null,
|
||||
postal_code: '11122',
|
||||
city: 'Göteborg',
|
||||
country: 'Sweden',
|
||||
vat_number: 'SE556021778001',
|
||||
default_payment_terms: 30,
|
||||
notes: null,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
mockFetchAllRows.mockResolvedValue([CUSTOMER])
|
||||
})
|
||||
|
||||
describe('GET /api/export/customers', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const res = await GET(createMockRequest('/api/export/customers'))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns an xlsx customer register', async () => {
|
||||
enqueue({ data: { company_name: 'Acme AB' } })
|
||||
const res = await GET(createMockRequest('/api/export/customers'))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toContain('spreadsheetml')
|
||||
expect(res.headers.get('Content-Disposition')).toContain('kunder-')
|
||||
|
||||
const buf = Buffer.from(await res.arrayBuffer())
|
||||
const wb = XLSX.read(new Uint8Array(buf), { type: 'array' })
|
||||
const sheet = wb.Sheets[wb.SheetNames[0]]
|
||||
const rows = XLSX.utils.sheet_to_json<string[]>(sheet, { header: 1 })
|
||||
expect((rows[0] as string[])[0]).toBe('Namn')
|
||||
expect((rows[1] as string[])).toContain('Acme AB')
|
||||
})
|
||||
|
||||
it('returns a CSV with BOM when format=csv', async () => {
|
||||
enqueue({ data: { company_name: 'Acme AB' } })
|
||||
const res = await GET(createMockRequest('/api/export/customers', { searchParams: { format: 'csv' } }))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Type')).toContain('text/csv')
|
||||
const buf = Buffer.from(await res.arrayBuffer())
|
||||
expect([buf[0], buf[1], buf[2]]).toEqual([0xef, 0xbb, 0xbf])
|
||||
expect(buf.toString('utf-8')).toContain('Göteborg')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { textColumn, integerColumn } from '@/lib/reports/xlsx-export'
|
||||
import { buildRegisterExport, parseExportFormat, todayIso } from '@/lib/export/register-export'
|
||||
import type { Customer } from '@/types'
|
||||
|
||||
/**
|
||||
* GET /api/export/customers[?format=csv]
|
||||
*
|
||||
* Downloads the customer register as xlsx (default) or csv. Read-only — viewers
|
||||
* may export. Headers match the customer importer's detector keywords so files
|
||||
* round-trip.
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'customer.export',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const format = parseExportFormat(new URL(request.url).searchParams.get('format'))
|
||||
|
||||
try {
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
const customers = (await fetchAllRows(({ from, to }) =>
|
||||
supabase
|
||||
.from('customers')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.order('name', { ascending: true })
|
||||
.range(from, to),
|
||||
)) as unknown as Customer[]
|
||||
|
||||
const { buffer, contentType, filename } = buildRegisterExport(
|
||||
[
|
||||
{
|
||||
name: 'Kunder',
|
||||
columns: [
|
||||
textColumn('Namn'),
|
||||
textColumn('Org-/personnummer'),
|
||||
textColumn('Kundtyp'),
|
||||
textColumn('E-post'),
|
||||
textColumn('Telefon'),
|
||||
textColumn('Adress'),
|
||||
textColumn('Adressrad 2'),
|
||||
textColumn('Postnummer'),
|
||||
textColumn('Ort'),
|
||||
textColumn('Land'),
|
||||
textColumn('VAT-nummer'),
|
||||
integerColumn('Betalningsvillkor'),
|
||||
textColumn('Anteckning'),
|
||||
],
|
||||
rows: customers,
|
||||
mapRow: (c) => [
|
||||
c.name,
|
||||
c.org_number ?? c.personal_number,
|
||||
c.customer_type,
|
||||
c.email,
|
||||
c.phone,
|
||||
c.address_line1,
|
||||
c.address_line2,
|
||||
c.postal_code,
|
||||
c.city,
|
||||
c.country,
|
||||
c.vat_number,
|
||||
c.default_payment_terms,
|
||||
c.notes,
|
||||
],
|
||||
},
|
||||
],
|
||||
{ format, slug: 'kunder', companyName: companyRow?.company_name ?? '', date: todayIso() },
|
||||
)
|
||||
|
||||
log.info('register exported', { entity: 'customers', format, rowCount: customers.length })
|
||||
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
log.error('customer export failed', err as Error)
|
||||
return errorResponse(err, log, { requestId })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { createMockRequest, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const mockFetchAllRows = vi.fn()
|
||||
vi.mock('@/lib/supabase/fetch-all', () => ({
|
||||
fetchAllRows: (...a: unknown[]) => mockFetchAllRows(...a),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
const SUPPLIER = {
|
||||
id: 's1',
|
||||
name: 'Leverantör AB',
|
||||
supplier_type: 'swedish_business',
|
||||
org_number: '5560217780',
|
||||
vat_number: 'SE556021778001',
|
||||
email: 'faktura@lev.se',
|
||||
phone: null,
|
||||
address_line1: null,
|
||||
address_line2: null,
|
||||
postal_code: null,
|
||||
city: 'Malmö',
|
||||
country: 'Sweden',
|
||||
bankgiro: '5050-1055',
|
||||
plusgiro: null,
|
||||
bank_account: null,
|
||||
iban: null,
|
||||
bic: null,
|
||||
default_payment_terms: 30,
|
||||
default_currency: 'SEK',
|
||||
notes: null,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
mockFetchAllRows.mockResolvedValue([SUPPLIER])
|
||||
})
|
||||
|
||||
describe('GET /api/export/suppliers', () => {
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const res = await GET(createMockRequest('/api/export/suppliers'))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns an xlsx supplier register with banking columns', async () => {
|
||||
enqueue({ data: { company_name: 'Acme AB' } })
|
||||
const res = await GET(createMockRequest('/api/export/suppliers'))
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('Content-Disposition')).toContain('leverantorer-')
|
||||
|
||||
const buf = Buffer.from(await res.arrayBuffer())
|
||||
const wb = XLSX.read(new Uint8Array(buf), { type: 'array' })
|
||||
const sheet = wb.Sheets[wb.SheetNames[0]]
|
||||
const rows = XLSX.utils.sheet_to_json<string[]>(sheet, { header: 1 })
|
||||
const headers = (rows[0] as string[]).map(String)
|
||||
expect(headers).toContain('Bankgiro')
|
||||
expect(headers).toContain('Valuta')
|
||||
expect((rows[1] as string[])).toContain('Leverantör AB')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,105 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponse } from '@/lib/errors/get-structured-error'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { textColumn, integerColumn } from '@/lib/reports/xlsx-export'
|
||||
import { buildRegisterExport, parseExportFormat, todayIso } from '@/lib/export/register-export'
|
||||
import type { Supplier } from '@/types'
|
||||
|
||||
/**
|
||||
* GET /api/export/suppliers[?format=csv]
|
||||
*
|
||||
* Downloads the supplier register as xlsx (default) or csv. Read-only — viewers
|
||||
* may export. Headers match the supplier importer's detector keywords so files
|
||||
* round-trip.
|
||||
*/
|
||||
export const GET = withRouteContext(
|
||||
'supplier.export',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const format = parseExportFormat(new URL(request.url).searchParams.get('format'))
|
||||
|
||||
try {
|
||||
const { data: companyRow } = await supabase
|
||||
.from('company_settings')
|
||||
.select('company_name')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
const suppliers = (await fetchAllRows(({ from, to }) =>
|
||||
supabase
|
||||
.from('suppliers')
|
||||
.select('*')
|
||||
.eq('company_id', companyId)
|
||||
.order('name', { ascending: true })
|
||||
.range(from, to),
|
||||
)) as unknown as Supplier[]
|
||||
|
||||
const { buffer, contentType, filename } = buildRegisterExport(
|
||||
[
|
||||
{
|
||||
name: 'Leverantörer',
|
||||
columns: [
|
||||
textColumn('Namn'),
|
||||
textColumn('Org-/personnummer'),
|
||||
textColumn('Leverantörstyp'),
|
||||
textColumn('E-post'),
|
||||
textColumn('Telefon'),
|
||||
textColumn('Adress'),
|
||||
textColumn('Adressrad 2'),
|
||||
textColumn('Postnummer'),
|
||||
textColumn('Ort'),
|
||||
textColumn('Land'),
|
||||
textColumn('VAT-nummer'),
|
||||
textColumn('Bankgiro'),
|
||||
textColumn('Plusgiro'),
|
||||
textColumn('Bankkonto'),
|
||||
textColumn('IBAN'),
|
||||
textColumn('BIC'),
|
||||
integerColumn('Betalningsvillkor'),
|
||||
textColumn('Valuta'),
|
||||
textColumn('Anteckning'),
|
||||
],
|
||||
rows: suppliers,
|
||||
mapRow: (s) => [
|
||||
s.name,
|
||||
s.org_number,
|
||||
s.supplier_type,
|
||||
s.email,
|
||||
s.phone,
|
||||
s.address_line1,
|
||||
s.address_line2,
|
||||
s.postal_code,
|
||||
s.city,
|
||||
s.country,
|
||||
s.vat_number,
|
||||
s.bankgiro,
|
||||
s.plusgiro,
|
||||
s.bank_account,
|
||||
s.iban,
|
||||
s.bic,
|
||||
s.default_payment_terms,
|
||||
s.default_currency,
|
||||
s.notes,
|
||||
],
|
||||
},
|
||||
],
|
||||
{ format, slug: 'leverantorer', companyName: companyRow?.company_name ?? '', date: todayIso() },
|
||||
)
|
||||
|
||||
log.info('register exported', { entity: 'suppliers', format, rowCount: suppliers.length })
|
||||
|
||||
return new NextResponse(new Uint8Array(buffer), {
|
||||
headers: {
|
||||
'Content-Type': contentType,
|
||||
'Content-Disposition': `attachment; filename="${filename}"`,
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
})
|
||||
} catch (err) {
|
||||
log.error('supplier export failed', err as Error)
|
||||
return errorResponse(err, log, { requestId })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,182 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createMockRequest,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const mockEmit = vi.fn().mockResolvedValue(undefined)
|
||||
vi.mock('@/lib/events', () => ({ eventBus: { emit: (...a: unknown[]) => mockEmit(...a) } }))
|
||||
|
||||
const mockFetchAllRows = vi.fn()
|
||||
vi.mock('@/lib/supabase/fetch-all', () => ({
|
||||
fetchAllRows: (...a: unknown[]) => mockFetchAllRows(...a),
|
||||
}))
|
||||
|
||||
const mockEnsureArticleNumber = vi.fn().mockResolvedValue('AUTO-1')
|
||||
vi.mock('@/lib/articles/ensure-article-number', () => ({
|
||||
ensureArticleNumber: (...a: unknown[]) => mockEnsureArticleNumber(...a),
|
||||
}))
|
||||
|
||||
const mockCheckRevenueAccount = vi.fn().mockResolvedValue('ok')
|
||||
vi.mock('@/lib/articles/validate-revenue-account', () => ({
|
||||
checkRevenueAccount: (...a: unknown[]) => mockCheckRevenueAccount(...a),
|
||||
}))
|
||||
|
||||
import { POST } from '../execute/route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
||||
|
||||
function row(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
row_index: 2,
|
||||
name: 'Konsulttimme',
|
||||
name_en: null,
|
||||
article_number: null,
|
||||
type: 'tjanst',
|
||||
unit: 'tim',
|
||||
price_excl_vat: 950,
|
||||
vat_rate: 25,
|
||||
revenue_account: null,
|
||||
cost_price: null,
|
||||
ean: null,
|
||||
housework_type: null,
|
||||
notes: null,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function makeRequest(body: unknown) {
|
||||
return createMockRequest('/api/import/articles/execute', { method: 'POST', body })
|
||||
}
|
||||
|
||||
describe('POST /api/import/articles/execute', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
mockFetchAllRows.mockResolvedValue([])
|
||||
mockCheckRevenueAccount.mockResolvedValue('ok')
|
||||
mockEnsureArticleNumber.mockResolvedValue('AUTO-1')
|
||||
})
|
||||
|
||||
it('returns 401 for unauthenticated requests', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const res = await POST(makeRequest({ rows: [row()], update_duplicates: false }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 for an empty rows array', async () => {
|
||||
const res = await POST(makeRequest({ rows: [], update_duplicates: false }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('creates new articles and emits article.created', async () => {
|
||||
enqueue({ data: { id: 'a1', name: 'Konsulttimme', article_number: null } })
|
||||
enqueue({ data: { id: 'a2', name: 'Skruv', article_number: 'A-200' } })
|
||||
|
||||
const res = await POST(makeRequest({
|
||||
rows: [row(), row({ row_index: 3, name: 'Skruv', article_number: 'A-200', type: 'vara' })],
|
||||
update_duplicates: false,
|
||||
}))
|
||||
const { status, body } = await parseJsonResponse(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.created).toBe(2)
|
||||
expect(body.data.failed).toBe(0)
|
||||
expect(mockEmit).toHaveBeenCalledTimes(2)
|
||||
// The numberless row gets auto-numbered; the one with A-200 does not.
|
||||
expect(mockEnsureArticleNumber).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('skips a duplicate matched by article number when update_duplicates is false', async () => {
|
||||
mockFetchAllRows.mockResolvedValue([{ id: 'x', name: 'Existing', article_number: 'A-1' }])
|
||||
|
||||
const res = await POST(makeRequest({
|
||||
rows: [row({ article_number: 'A-1' })],
|
||||
update_duplicates: false,
|
||||
}))
|
||||
const { status, body } = await parseJsonResponse(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.skipped).toBe(1)
|
||||
expect(body.data.created).toBe(0)
|
||||
})
|
||||
|
||||
it('updates a duplicate matched by article number when update_duplicates is true', async () => {
|
||||
mockFetchAllRows.mockResolvedValue([{ id: 'x', name: 'Old', article_number: 'A-1' }])
|
||||
enqueue({ data: { id: 'x', name: 'New name', article_number: 'A-1' } })
|
||||
|
||||
const res = await POST(makeRequest({
|
||||
rows: [row({ article_number: 'A-1', name: 'New name' })],
|
||||
update_duplicates: true,
|
||||
}))
|
||||
const { status, body } = await parseJsonResponse(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.updated).toBe(1)
|
||||
expect(body.data.created).toBe(0)
|
||||
})
|
||||
|
||||
it('matches a duplicate by name (case-insensitive)', async () => {
|
||||
mockFetchAllRows.mockResolvedValue([{ id: 'x', name: 'Konsulttimme', article_number: null }])
|
||||
|
||||
const res = await POST(makeRequest({
|
||||
rows: [row({ name: 'KONSULTTIMME' })],
|
||||
update_duplicates: false,
|
||||
}))
|
||||
const { status, body } = await parseJsonResponse(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.skipped).toBe(1)
|
||||
})
|
||||
|
||||
it('treats a 23505 unique violation as a soft skip', async () => {
|
||||
enqueue({ data: null, error: { code: '23505', message: 'duplicate key' } })
|
||||
|
||||
const res = await POST(makeRequest({
|
||||
rows: [row({ article_number: 'A-DUP' })],
|
||||
update_duplicates: false,
|
||||
}))
|
||||
const { status, body } = await parseJsonResponse(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.skipped).toBe(1)
|
||||
expect(body.data.failed).toBe(0)
|
||||
})
|
||||
|
||||
it('drops an inactive/unknown revenue account and records a warning', async () => {
|
||||
mockCheckRevenueAccount.mockResolvedValue('activatable')
|
||||
enqueue({ data: { id: 'a1', name: 'Konsulttimme', article_number: 'A-1' } })
|
||||
|
||||
const res = await POST(makeRequest({
|
||||
rows: [row({ article_number: 'A-1', revenue_account: '3999' })],
|
||||
update_duplicates: false,
|
||||
}))
|
||||
const { status, body } = await parseJsonResponse(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.created).toBe(1)
|
||||
expect(body.data.warnings.length).toBeGreaterThan(0)
|
||||
expect(body.data.warnings[0]).toContain('3999')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,233 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { ArticleImportExecuteSchema } from '@/lib/api/schemas'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { ensureArticleNumber } from '@/lib/articles/ensure-article-number'
|
||||
import { checkRevenueAccount, type RevenueAccountStatus } from '@/lib/articles/validate-revenue-account'
|
||||
import type { Article } from '@/types'
|
||||
import type { ArticleImportExecuteResult } from '@/lib/import/articles/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
interface ExistingArticle {
|
||||
id: string
|
||||
name: string
|
||||
article_number: string | null
|
||||
}
|
||||
|
||||
function nameKey(value: string | null): string | null {
|
||||
if (!value) return null
|
||||
return value.trim().toLowerCase() || null
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/import/articles/execute
|
||||
*
|
||||
* Imports validated article rows. Duplicates (matched by article number, then
|
||||
* by name) are either updated (merge — only non-empty fields overwrite) or
|
||||
* skipped based on `update_duplicates`. An optional BAS revenue-account override
|
||||
* is kept only when it is an active class-3 account; unknown/inactive accounts
|
||||
* are dropped (with a warning) rather than mutating the chart of accounts.
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'register_import.articles.execute',
|
||||
async (request, ctx) => {
|
||||
const { user, supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const result = await validateBody(request, ArticleImportExecuteSchema, {
|
||||
log,
|
||||
operation: 'register_import.articles.execute',
|
||||
})
|
||||
if (!result.success) return result.response
|
||||
|
||||
const { rows, update_duplicates } = result.data
|
||||
const opLog = log.child({ rowCount: rows.length, updateDuplicates: update_duplicates })
|
||||
|
||||
if (rows.length === 0) {
|
||||
return errorResponseFromCode('REG_IMPORT_NO_ROWS', opLog, { requestId })
|
||||
}
|
||||
|
||||
try {
|
||||
const existingRaw = await fetchAllRows(({ from, to }) =>
|
||||
supabase
|
||||
.from('articles')
|
||||
.select('id, name, article_number')
|
||||
.eq('company_id', companyId)
|
||||
.range(from, to),
|
||||
)
|
||||
const existing = existingRaw as unknown as ExistingArticle[]
|
||||
|
||||
const byNumber = new Map<string, ExistingArticle>()
|
||||
const byName = new Map<string, ExistingArticle>()
|
||||
for (const a of existing) {
|
||||
if (a.article_number) byNumber.set(a.article_number, a)
|
||||
const nk = nameKey(a.name)
|
||||
if (nk && !byName.has(nk)) byName.set(nk, a)
|
||||
}
|
||||
|
||||
// Revenue-account validation is cached per distinct account so a large
|
||||
// import doesn't re-query the chart for every row.
|
||||
const accountStatusCache = new Map<string, RevenueAccountStatus>()
|
||||
const droppedAccounts = new Set<string>()
|
||||
const warnings: string[] = []
|
||||
const resolveRevenueAccount = async (acc: string | null): Promise<string | null> => {
|
||||
if (!acc) return null
|
||||
let status = accountStatusCache.get(acc)
|
||||
if (!status) {
|
||||
status = await checkRevenueAccount(supabase, companyId!, acc)
|
||||
accountStatusCache.set(acc, status)
|
||||
}
|
||||
if (status === 'ok') return acc
|
||||
if (!droppedAccounts.has(acc)) {
|
||||
droppedAccounts.add(acc)
|
||||
warnings.push(
|
||||
status === 'activatable'
|
||||
? `Försäljningskonto ${acc} är inte aktiverat i kontoplanen — artiklar importerades utan kontoöverstyrning.`
|
||||
: `Försäljningskonto ${acc} är ogiltigt — ignorerades.`,
|
||||
)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const created: Article[] = []
|
||||
const updated: Article[] = []
|
||||
let skipped = 0
|
||||
const errors: { row_index: number; name: string; reason: string }[] = []
|
||||
|
||||
for (const row of rows) {
|
||||
const nk = nameKey(row.name)
|
||||
const match =
|
||||
(row.article_number ? byNumber.get(row.article_number) : undefined) ??
|
||||
(nk ? byName.get(nk) : undefined) ??
|
||||
null
|
||||
|
||||
const revenueAccount = await resolveRevenueAccount(row.revenue_account)
|
||||
|
||||
if (match) {
|
||||
if (!update_duplicates) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
// Merge mode: overwrite only fields the file clearly carries a value
|
||||
// for. type/unit/vat_rate carry parser defaults that can't be told
|
||||
// apart from "absent", so they are left untouched to avoid clobbering.
|
||||
const merged: Record<string, unknown> = {}
|
||||
if (row.name) merged.name = row.name
|
||||
if (row.name_en) merged.name_en = row.name_en
|
||||
if (row.price_excl_vat > 0) merged.price_excl_vat = row.price_excl_vat
|
||||
if (row.cost_price !== null) merged.cost_price = row.cost_price
|
||||
if (row.ean) merged.ean = row.ean
|
||||
if (row.housework_type) merged.housework_type = row.housework_type
|
||||
if (row.notes) merged.notes = row.notes
|
||||
if (revenueAccount) merged.revenue_account = revenueAccount
|
||||
|
||||
if (Object.keys(merged).length === 0) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('articles')
|
||||
.update(merged)
|
||||
.eq('id', match.id)
|
||||
.eq('company_id', companyId)
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
errors.push({ row_index: row.row_index, name: row.name, reason: error.message })
|
||||
continue
|
||||
}
|
||||
if (data) updated.push(data as Article)
|
||||
continue
|
||||
}
|
||||
|
||||
// No match — create.
|
||||
const { data, error } = await supabase
|
||||
.from('articles')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
company_id: companyId,
|
||||
name: row.name,
|
||||
name_en: row.name_en,
|
||||
type: row.type,
|
||||
unit: row.unit || 'st',
|
||||
price_excl_vat: row.price_excl_vat,
|
||||
vat_rate: row.vat_rate,
|
||||
revenue_account: revenueAccount,
|
||||
cost_price: row.cost_price,
|
||||
ean: row.ean,
|
||||
housework_type: row.housework_type,
|
||||
notes: row.notes,
|
||||
article_number: row.article_number,
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
// Unique violation on (company_id, article_number) — treat as a soft
|
||||
// skip (manual number collided with an existing or in-batch article).
|
||||
if (error.code === '23505') {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
errors.push({ row_index: row.row_index, name: row.name, reason: error.message })
|
||||
continue
|
||||
}
|
||||
|
||||
if (data) {
|
||||
// Auto-number when the file didn't supply one. Non-fatal: an
|
||||
// unnumbered article is still usable and can be numbered later.
|
||||
if (!data.article_number) {
|
||||
try {
|
||||
data.article_number = await ensureArticleNumber(supabase, companyId!, data.id)
|
||||
} catch (err) {
|
||||
opLog.warn('article number assignment failed', err as Error, { articleId: data.id })
|
||||
}
|
||||
}
|
||||
created.push(data as Article)
|
||||
// Track newly inserted number + name so later rows in the same batch
|
||||
// dedup against them too.
|
||||
const newArticle = data as ExistingArticle
|
||||
if (newArticle.article_number) byNumber.set(newArticle.article_number, newArticle)
|
||||
const nk = nameKey(newArticle.name)
|
||||
if (nk && !byName.has(nk)) byName.set(nk, newArticle)
|
||||
}
|
||||
}
|
||||
|
||||
// Emit events for downstream listeners (non-blocking).
|
||||
for (const a of created) {
|
||||
await eventBus.emit({
|
||||
type: 'article.created',
|
||||
payload: { article: a, companyId: companyId!, userId: user.id },
|
||||
})
|
||||
}
|
||||
|
||||
const response: ArticleImportExecuteResult = {
|
||||
success: errors.length === 0,
|
||||
created: created.length,
|
||||
updated: updated.length,
|
||||
skipped,
|
||||
failed: errors.length,
|
||||
errors,
|
||||
warnings,
|
||||
}
|
||||
|
||||
opLog.info('article import complete', response)
|
||||
|
||||
return NextResponse.json({ data: response })
|
||||
} catch (err) {
|
||||
opLog.error('article import execute failed', err as Error)
|
||||
return errorResponseFromCode('REG_IMPORT_EXECUTE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: err instanceof Error ? err.message : 'unknown' },
|
||||
})
|
||||
}
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -0,0 +1,134 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { parseArticlesFile } from '@/lib/import/articles/parser'
|
||||
import { fetchAllRows } from '@/lib/supabase/fetch-all'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { errorResponseFromCode } from '@/lib/errors/get-structured-error'
|
||||
import { ArticleColumnOverridesSchema } from '@/lib/api/schemas'
|
||||
import type {
|
||||
AnnotatedArticleRow,
|
||||
ArticleImportParseResult,
|
||||
DetectedArticleColumns,
|
||||
} from '@/lib/import/articles/types'
|
||||
|
||||
const ALLOWED_EXTENSIONS = ['.xlsx', '.xls', '.csv', '.ods']
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
|
||||
|
||||
/** Lowercased dedup key for matching an article by name. */
|
||||
function nameKey(value: string | null): string | null {
|
||||
if (!value) return null
|
||||
return value.trim().toLowerCase() || null
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/import/articles/parse
|
||||
*
|
||||
* Accepts an Excel/CSV file via FormData, auto-detects columns, parses rows,
|
||||
* and annotates each row with any duplicate-match against existing articles
|
||||
* (by article number first, then by name).
|
||||
*/
|
||||
export const POST = withRouteContext(
|
||||
'register_import.articles.parse',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, log, requestId } = ctx
|
||||
|
||||
const formData = await request.formData()
|
||||
const file = formData.get('file') as File | null
|
||||
const columnOverridesRaw = formData.get('column_overrides') as string | null
|
||||
|
||||
if (!file) {
|
||||
return errorResponseFromCode('REG_IMPORT_NO_FILE', log, { requestId })
|
||||
}
|
||||
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
return errorResponseFromCode('REG_IMPORT_FILE_TOO_LARGE', log, {
|
||||
requestId,
|
||||
details: { sizeMb: +(file.size / 1024 / 1024).toFixed(1) },
|
||||
})
|
||||
}
|
||||
|
||||
const ext = '.' + file.name.split('.').pop()?.toLowerCase()
|
||||
if (!ALLOWED_EXTENSIONS.includes(ext)) {
|
||||
return errorResponseFromCode('REG_IMPORT_INVALID_FORMAT', log, {
|
||||
requestId,
|
||||
details: { extension: ext, allowed: ALLOWED_EXTENSIONS },
|
||||
})
|
||||
}
|
||||
|
||||
const opLog = log.child({ filename: file.name, sizeBytes: file.size })
|
||||
|
||||
let columnOverrides: DetectedArticleColumns | undefined
|
||||
if (columnOverridesRaw) {
|
||||
let raw: unknown
|
||||
try {
|
||||
raw = JSON.parse(columnOverridesRaw)
|
||||
} catch {
|
||||
return errorResponseFromCode('REG_IMPORT_INVALID_COLUMN_OVERRIDES', opLog, { requestId })
|
||||
}
|
||||
// Validate shape/indices before trusting it to drive the parser.
|
||||
const parsed = ArticleColumnOverridesSchema.safeParse(raw)
|
||||
if (!parsed.success) {
|
||||
return errorResponseFromCode('REG_IMPORT_INVALID_COLUMN_OVERRIDES', opLog, { requestId })
|
||||
}
|
||||
columnOverrides = parsed.data
|
||||
}
|
||||
|
||||
try {
|
||||
const buffer = await file.arrayBuffer()
|
||||
const parsed = parseArticlesFile(buffer, file.name, columnOverrides)
|
||||
|
||||
// Fetch existing articles for duplicate detection.
|
||||
const existing = await fetchAllRows(({ from, to }) =>
|
||||
supabase
|
||||
.from('articles')
|
||||
.select('id, name, article_number')
|
||||
.eq('company_id', companyId)
|
||||
.range(from, to),
|
||||
)
|
||||
|
||||
const byNumber = new Map<string, { id: string; name: string }>()
|
||||
const byName = new Map<string, { id: string; name: string }>()
|
||||
for (const a of existing) {
|
||||
if (a.article_number) byNumber.set(String(a.article_number), { id: a.id, name: a.name })
|
||||
const nk = nameKey(a.name)
|
||||
if (nk && !byName.has(nk)) byName.set(nk, { id: a.id, name: a.name })
|
||||
}
|
||||
|
||||
let duplicateCount = 0
|
||||
const annotated: AnnotatedArticleRow[] = parsed.rows.map((r) => {
|
||||
let match: AnnotatedArticleRow['duplicate_match'] = null
|
||||
if (r.article_number && byNumber.has(r.article_number)) {
|
||||
const e = byNumber.get(r.article_number)!
|
||||
match = { article_id: e.id, matched_by: 'article_number', existing_name: e.name }
|
||||
} else {
|
||||
const nk = nameKey(r.name)
|
||||
if (nk && byName.has(nk)) {
|
||||
const e = byName.get(nk)!
|
||||
match = { article_id: e.id, matched_by: 'name', existing_name: e.name }
|
||||
}
|
||||
}
|
||||
if (match) duplicateCount++
|
||||
return { ...r, duplicate_match: match }
|
||||
})
|
||||
|
||||
const result: ArticleImportParseResult = {
|
||||
filename: parsed.filename,
|
||||
sheet_name: parsed.sheet_name,
|
||||
total_rows: annotated.length,
|
||||
detected_columns: parsed.detected_columns,
|
||||
headers: parsed.headers,
|
||||
preview_rows: parsed.preview_rows,
|
||||
rows: annotated,
|
||||
duplicate_count: duplicateCount,
|
||||
warnings: parsed.warnings,
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
opLog.error('article import parse failed', err as Error)
|
||||
return errorResponseFromCode('REG_IMPORT_PARSE_FAILED', opLog, {
|
||||
requestId,
|
||||
details: { reason: err instanceof Error ? err.message : 'unknown' },
|
||||
})
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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}>
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -1430,6 +1430,49 @@ export const SupplierImportExecuteSchema = z.object({
|
||||
update_duplicates: z.boolean(),
|
||||
})
|
||||
|
||||
const ImportedArticleRowSchema = z.object({
|
||||
row_index: z.number().int(),
|
||||
name: z.string().min(1),
|
||||
name_en: z.string().nullable(),
|
||||
article_number: z.string().nullable(),
|
||||
type: ArticleTypeSchema,
|
||||
unit: z.string(),
|
||||
price_excl_vat: nonNegativeAmount,
|
||||
vat_rate: vatRatePercent,
|
||||
// The execute route re-validates against the chart of accounts (and drops
|
||||
// unknown/inactive overrides), so a loose nullable string is enough here.
|
||||
revenue_account: z.string().nullable(),
|
||||
cost_price: nonNegativeAmount.nullable(),
|
||||
ean: z.string().nullable(),
|
||||
housework_type: z.string().nullable(),
|
||||
notes: z.string().nullable(),
|
||||
})
|
||||
|
||||
export const ArticleImportExecuteSchema = z.object({
|
||||
rows: z.array(ImportedArticleRowSchema).min(1, 'At least one row is required'),
|
||||
update_duplicates: z.boolean(),
|
||||
})
|
||||
|
||||
// Validates the optional column-mapping override posted to the parse route, so
|
||||
// a malformed/hostile blob can't drive the parser with non-numeric or
|
||||
// unexpected column indices. Mirrors DetectedArticleColumns.
|
||||
const articleColumnIndex = z.number().int().min(0).nullable()
|
||||
export const ArticleColumnOverridesSchema = z.object({
|
||||
name_col: z.number().int().min(0),
|
||||
article_number_col: articleColumnIndex,
|
||||
name_en_col: articleColumnIndex,
|
||||
type_col: articleColumnIndex,
|
||||
unit_col: articleColumnIndex,
|
||||
price_col: articleColumnIndex,
|
||||
vat_rate_col: articleColumnIndex,
|
||||
revenue_account_col: articleColumnIndex,
|
||||
cost_price_col: articleColumnIndex,
|
||||
ean_col: articleColumnIndex,
|
||||
housework_type_col: articleColumnIndex,
|
||||
notes_col: articleColumnIndex,
|
||||
confidence: z.number(),
|
||||
})
|
||||
|
||||
// ============================================================
|
||||
// Salary schemas
|
||||
// ============================================================
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
reportToWorkbook,
|
||||
exportFilename,
|
||||
UTF8_BOM,
|
||||
} from '@/lib/reports/xlsx-export'
|
||||
|
||||
export type RegisterExportFormat = 'xlsx' | 'csv'
|
||||
|
||||
const XLSX_MIME = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
|
||||
/** Normalize the `?format=` query param to a supported export format. */
|
||||
export function parseExportFormat(raw: string | null): RegisterExportFormat {
|
||||
return raw === 'csv' ? 'csv' : 'xlsx'
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the download body + headers for a register export (customers,
|
||||
* suppliers, articles) in either xlsx or csv. CSV is a single sheet with a
|
||||
* UTF-8 BOM so Excel renders åäö correctly; both formats share the same
|
||||
* column/row spec so files round-trip back through the importer.
|
||||
*/
|
||||
export function buildRegisterExport(
|
||||
spec: Parameters<typeof reportToWorkbook>[0],
|
||||
opts: { format: RegisterExportFormat; slug: string; companyName: string; date: string },
|
||||
): { buffer: Buffer; contentType: string; filename: string } {
|
||||
const { format, slug, companyName, date } = opts
|
||||
|
||||
if (format === 'csv') {
|
||||
const buf = reportToWorkbook(spec, { bookType: 'csv' })
|
||||
return {
|
||||
buffer: Buffer.concat([Buffer.from(UTF8_BOM, 'utf-8'), buf]),
|
||||
contentType: 'text/csv; charset=utf-8',
|
||||
filename: exportFilename(slug, companyName, date, 'csv'),
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
buffer: reportToWorkbook(spec),
|
||||
contentType: XLSX_MIME,
|
||||
filename: exportFilename(slug, companyName, date, 'xlsx'),
|
||||
}
|
||||
}
|
||||
|
||||
/** Today's date as `YYYY-MM-DD` for export filenames. */
|
||||
export function todayIso(): string {
|
||||
return new Date().toISOString().slice(0, 10)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { detectArticleColumns } from '../column-detector'
|
||||
|
||||
describe('detectArticleColumns', () => {
|
||||
it('detects a rich Swedish header at high confidence', () => {
|
||||
const cols = detectArticleColumns([
|
||||
'Artikelnummer', 'Benämning', 'Typ', 'Enhet', 'Pris', 'Moms', 'Försäljningskonto',
|
||||
])
|
||||
expect(cols.name_col).toBe(1)
|
||||
expect(cols.article_number_col).toBe(0)
|
||||
expect(cols.type_col).toBe(2)
|
||||
expect(cols.unit_col).toBe(3)
|
||||
expect(cols.price_col).toBe(4)
|
||||
expect(cols.vat_rate_col).toBe(5)
|
||||
expect(cols.revenue_account_col).toBe(6)
|
||||
expect(cols.confidence).toBeGreaterThanOrEqual(0.8)
|
||||
})
|
||||
|
||||
it('keeps price, VAT and account in distinct columns (no keyword collision)', () => {
|
||||
const cols = detectArticleColumns([
|
||||
'Benämning', 'Pris exkl moms', 'Moms %', 'Försäljningskonto',
|
||||
])
|
||||
expect(cols.price_col).toBe(1) // "Pris exkl moms" → price, not VAT
|
||||
expect(cols.vat_rate_col).toBe(2)
|
||||
expect(cols.revenue_account_col).toBe(3)
|
||||
expect(cols.price_col).not.toBe(cols.vat_rate_col)
|
||||
})
|
||||
|
||||
it('does not read Fortnox "Momskod" as the article number', () => {
|
||||
const cols = detectArticleColumns(['Benämning', 'Momskod'])
|
||||
expect(cols.vat_rate_col).toBe(1)
|
||||
expect(cols.article_number_col).toBeNull()
|
||||
})
|
||||
|
||||
it('claims EAN before the generic article number', () => {
|
||||
const cols = detectArticleColumns(['Benämning', 'EAN-nummer', 'Artikelnummer'])
|
||||
expect(cols.ean_col).toBe(1)
|
||||
expect(cols.article_number_col).toBe(2)
|
||||
})
|
||||
|
||||
it('detects the English name column separately from the main name', () => {
|
||||
const cols = detectArticleColumns(['Benämning', 'Benämning engelska'])
|
||||
expect(cols.name_col).toBe(0)
|
||||
expect(cols.name_en_col).toBe(1)
|
||||
})
|
||||
|
||||
it('detects Fortnox-style headers', () => {
|
||||
const cols = detectArticleColumns([
|
||||
'Artikelnr', 'Benämning', 'Försäljningspris', 'Inköpspris', 'Momskod', 'Enhet',
|
||||
])
|
||||
expect(cols.article_number_col).toBe(0)
|
||||
expect(cols.price_col).toBe(2)
|
||||
expect(cols.cost_price_col).toBe(3)
|
||||
expect(cols.vat_rate_col).toBe(4)
|
||||
})
|
||||
|
||||
it('reports low confidence when only a name column is present', () => {
|
||||
const cols = detectArticleColumns(['Benämning'])
|
||||
expect(cols.name_col).toBe(0)
|
||||
expect(cols.confidence).toBeLessThan(0.8)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import * as XLSX from 'xlsx'
|
||||
import { parseArticlesFile } from '../parser'
|
||||
|
||||
function buildXlsx(rows: (string | number)[][]): ArrayBuffer {
|
||||
const ws = XLSX.utils.aoa_to_sheet(rows)
|
||||
const wb = XLSX.utils.book_new()
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Artiklar')
|
||||
return XLSX.write(wb, { type: 'array', bookType: 'xlsx' }) as ArrayBuffer
|
||||
}
|
||||
|
||||
describe('parseArticlesFile', () => {
|
||||
it('parses a basic Swedish article register', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Artikelnummer', 'Pris', 'Moms', 'Enhet', 'Typ'],
|
||||
['Konsulttimme', 'A-100', '950', '25', 'tim', 'tjänst'],
|
||||
['Skruv', 'A-200', '2,50', '25', 'st', 'vara'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'artiklar.xlsx')
|
||||
|
||||
expect(result.total_rows).toBe(2)
|
||||
expect(result.rows[0].name).toBe('Konsulttimme')
|
||||
expect(result.rows[0].article_number).toBe('A-100')
|
||||
expect(result.rows[0].price_excl_vat).toBe(950)
|
||||
expect(result.rows[0].vat_rate).toBe(25)
|
||||
expect(result.rows[0].unit).toBe('tim')
|
||||
expect(result.rows[0].type).toBe('tjanst')
|
||||
expect(result.rows[1].type).toBe('vara')
|
||||
expect(result.rows[1].price_excl_vat).toBe(2.5)
|
||||
expect(result.rows[0].is_valid).toBe(true)
|
||||
// A clean, valid VAT rate is not flagged as adjusted.
|
||||
expect(result.rows[0].vat_rate_adjusted).toBe(false)
|
||||
})
|
||||
|
||||
it('detects Fortnox-style export headers', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Artikelnummer', 'Benämning', 'Försäljningspris', 'Momskod', 'Försäljningskonto', 'Enhet'],
|
||||
['100', 'Webdesign', '1 200', '25', '3001', 'st'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'fortnox.xlsx')
|
||||
const r = result.rows[0]
|
||||
expect(r.article_number).toBe('100')
|
||||
expect(r.name).toBe('Webdesign')
|
||||
expect(r.price_excl_vat).toBe(1200) // "1 200" → 1200
|
||||
expect(r.vat_rate).toBe(25)
|
||||
expect(r.revenue_account).toBe('3001')
|
||||
})
|
||||
|
||||
it('parses Swedish decimal prices', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Pris'],
|
||||
['A', '1 234,56'],
|
||||
['B', '1.234,50'],
|
||||
['C', '500'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'priser.xlsx')
|
||||
expect(result.rows[0].price_excl_vat).toBe(1234.56)
|
||||
expect(result.rows[1].price_excl_vat).toBe(1234.5)
|
||||
expect(result.rows[2].price_excl_vat).toBe(500)
|
||||
})
|
||||
|
||||
it('snaps VAT to the nearest statutory rate and warns', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Moms'],
|
||||
['A', '25%'],
|
||||
['B', '7'], // → 6
|
||||
['C', ''], // → 25 default
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'moms.xlsx')
|
||||
expect(result.rows[0].vat_rate).toBe(25)
|
||||
expect(result.rows[1].vat_rate).toBe(6)
|
||||
expect(result.rows[2].vat_rate).toBe(25)
|
||||
// The "7" → 6 snap should surface a file-level warning.
|
||||
expect(result.warnings.some((w) => w.includes('momssats'))).toBe(true)
|
||||
// Per-row flag: only the snapped row (7 → 6) is marked adjusted.
|
||||
expect(result.rows[0].vat_rate_adjusted).toBe(false) // "25%" is already valid
|
||||
expect(result.rows[1].vat_rate_adjusted).toBe(true) // 7 → 6
|
||||
expect(result.rows[2].vat_rate_adjusted).toBe(false) // empty → default 25
|
||||
})
|
||||
|
||||
it('defaults an unparseable momskod to 25 with a warning', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Momskod'],
|
||||
['A', 'MP1'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'momskod.xlsx')
|
||||
expect(result.rows[0].vat_rate).toBe(25)
|
||||
expect(result.rows[0].vat_rate_adjusted).toBe(true)
|
||||
expect(result.warnings.some((w) => w.toLowerCase().includes('moms'))).toBe(true)
|
||||
})
|
||||
|
||||
it('normalizes article type and falls back to tjanst', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Typ'],
|
||||
['A', 'Produkt'],
|
||||
['B', 'service'],
|
||||
['C', ''],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'typ.xlsx')
|
||||
expect(result.rows[0].type).toBe('vara')
|
||||
expect(result.rows[1].type).toBe('tjanst')
|
||||
expect(result.rows[2].type).toBe('tjanst')
|
||||
})
|
||||
|
||||
it('falls back to "st" when no unit is given', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning'],
|
||||
['A'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'unit.xlsx')
|
||||
expect(result.rows[0].unit).toBe('st')
|
||||
})
|
||||
|
||||
it('keeps a valid 3xxx revenue account and drops a non-3xxx one', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Försäljningskonto'],
|
||||
['A', '3001'],
|
||||
['B', '1930'],
|
||||
])
|
||||
|
||||
const result = parseArticlesFile(buffer, 'konto.xlsx')
|
||||
expect(result.rows[0].revenue_account).toBe('3001')
|
||||
expect(result.rows[1].revenue_account).toBeNull()
|
||||
expect(result.warnings.some((w) => w.toLowerCase().includes('försäljningskonto'))).toBe(true)
|
||||
})
|
||||
|
||||
it('treats a blank cost price as null (not 0)', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Inköpspris'],
|
||||
['A', ''],
|
||||
['B', '100'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'cost.xlsx')
|
||||
expect(result.rows[0].cost_price).toBeNull()
|
||||
expect(result.rows[1].cost_price).toBe(100)
|
||||
})
|
||||
|
||||
it('warns when the price column looks incl-VAT', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Pris inkl moms'],
|
||||
['A', '125'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'brutto.xlsx')
|
||||
expect(result.warnings.some((w) => w.toLowerCase().includes('inkl'))).toBe(true)
|
||||
})
|
||||
|
||||
it('skips rows with empty name and preserves row_index', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning'],
|
||||
['A'],
|
||||
[''],
|
||||
['C'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'sparse.xlsx')
|
||||
expect(result.total_rows).toBe(2)
|
||||
expect(result.rows.map((r) => r.name)).toEqual(['A', 'C'])
|
||||
expect(result.rows[0].row_index).toBe(2)
|
||||
expect(result.rows[1].row_index).toBe(4)
|
||||
})
|
||||
|
||||
it('flags a negative price as invalid', () => {
|
||||
const buffer = buildXlsx([
|
||||
['Benämning', 'Pris'],
|
||||
['A', '-50'],
|
||||
])
|
||||
const result = parseArticlesFile(buffer, 'neg.xlsx')
|
||||
expect(result.rows[0].is_valid).toBe(false)
|
||||
expect(result.rows[0].validation_errors).toContain('Priset kan inte vara negativt')
|
||||
})
|
||||
|
||||
it('returns a warning when zero rows match', () => {
|
||||
const buffer = buildXlsx([['Benämning']])
|
||||
const result = parseArticlesFile(buffer, 'empty.xlsx')
|
||||
expect(result.total_rows).toBe(0)
|
||||
expect(result.warnings.length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('preserves Swedish characters when reading a UTF-8 CSV', () => {
|
||||
const csv = new TextEncoder().encode(
|
||||
'Benämning,Enhet\nMöbel,st\nKärra,st\n',
|
||||
).buffer
|
||||
const result = parseArticlesFile(csv, 'artiklar.csv')
|
||||
expect(result.rows[0].name).toBe('Möbel')
|
||||
expect(result.rows[1].name).toBe('Kärra')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
import { findColumn } from '../shared/column-utils'
|
||||
import type { DetectedArticleColumns } from './types'
|
||||
|
||||
// Keyword lists cover the export headers of Fortnox, Visma and Bokio so files
|
||||
// from those systems auto-map. Header-only matching (register imports always
|
||||
// have a header row).
|
||||
|
||||
const NAME_KEYWORDS = [
|
||||
'benämning', 'benamning', 'artikelnamn', 'artikel namn', 'namn', 'name',
|
||||
'produktnamn', 'produkt namn', 'product name', 'article name', 'beskrivning',
|
||||
'description', 'title',
|
||||
]
|
||||
|
||||
const NAME_EN_KEYWORDS = [
|
||||
'engelska', 'english', 'name en', 'name english', 'name_english',
|
||||
'engelskt namn', 'benämning engelska',
|
||||
]
|
||||
|
||||
// Note: bare 'kod'/'code' are deliberately excluded — they collide with
|
||||
// Fortnox's "Momskod" (a VAT column). EAN is detected first so "EAN-nummer"
|
||||
// is claimed before the generic 'nummer'/'number' here.
|
||||
const ARTICLE_NUMBER_KEYWORDS = [
|
||||
'artikelnummer', 'artikelnr', 'artnr', 'art nr', 'art no', 'artikelkod',
|
||||
'article code', 'sku', 'nummer', 'number',
|
||||
]
|
||||
|
||||
const TYPE_KEYWORDS = ['typ', 'type', 'artikeltyp', 'article type', 'varutyp']
|
||||
|
||||
const UNIT_KEYWORDS = ['enhet', 'unit', 'enh', 'uom', 'måttenhet', 'mattenhet']
|
||||
|
||||
const VAT_RATE_KEYWORDS = [
|
||||
'momssats', 'momskod', 'moms %', 'moms', 'momsprocent', 'vat rate', 'vat code',
|
||||
'vat %', 'vat', 'tax rate',
|
||||
]
|
||||
|
||||
const REVENUE_ACCOUNT_KEYWORDS = [
|
||||
'försäljningskonto', 'forsaljningskonto', 'intäktskonto', 'intaktskonto',
|
||||
'bokföringskonto', 'bokforingskonto', 'sales account', 'revenue account',
|
||||
'kontering', 'coding', 'konto', 'account',
|
||||
]
|
||||
|
||||
const COST_PRICE_KEYWORDS = [
|
||||
'inköpspris', 'inkopspris', 'självkostnad', 'sjalvkostnad', 'kostpris',
|
||||
'kostnadspris', 'purchase price', 'cost price', 'cost',
|
||||
]
|
||||
|
||||
const PRICE_KEYWORDS = [
|
||||
'försäljningspris', 'forsaljningspris', 'pris exkl moms', 'pris exkl. moms',
|
||||
'à-pris', 'a-pris', 'apris', 'styckpris', 'nettopris', 'net price',
|
||||
'unit price', 'pris', 'price', 'belopp', 'sales price',
|
||||
]
|
||||
|
||||
const EAN_KEYWORDS = ['ean', 'ean-kod', 'streckkod', 'gtin', 'barcode']
|
||||
|
||||
const HOUSEWORK_KEYWORDS = [
|
||||
'rot/rut', 'rot rut', 'arbetstyp', 'husarbete', 'housework', 'rot', 'rut',
|
||||
]
|
||||
|
||||
const NOTES_KEYWORDS = [
|
||||
'anteckning', 'anteckningar', 'kommentar', 'kommentarer', 'comment', 'notes',
|
||||
'note', 'övrigt', 'ovrigt',
|
||||
]
|
||||
|
||||
/**
|
||||
* Detect article-register columns from headers.
|
||||
*
|
||||
* Detection order matters: more specific columns are claimed first (via the
|
||||
* shared `taken` set) so a generic keyword can't swallow them — e.g. EAN before
|
||||
* the article number ("EAN-nummer" must not be read as the article number), and
|
||||
* the English name before the generic name column.
|
||||
*/
|
||||
export function detectArticleColumns(headers: string[]): DetectedArticleColumns {
|
||||
const taken = new Set<number>()
|
||||
|
||||
// Order matters (shared `taken` set): claim specific columns before generic
|
||||
// ones. EAN before the article number ("EAN-nummer"), the price columns
|
||||
// before VAT (so "Pris exkl moms" isn't read as the VAT column), and the
|
||||
// generic name column dead last.
|
||||
const name_en_col = findColumn(headers, NAME_EN_KEYWORDS, taken)
|
||||
const ean_col = findColumn(headers, EAN_KEYWORDS, taken)
|
||||
const article_number_col = findColumn(headers, ARTICLE_NUMBER_KEYWORDS, taken)
|
||||
const revenue_account_col = findColumn(headers, REVENUE_ACCOUNT_KEYWORDS, taken)
|
||||
const cost_price_col = findColumn(headers, COST_PRICE_KEYWORDS, taken)
|
||||
const price_col = findColumn(headers, PRICE_KEYWORDS, taken)
|
||||
const vat_rate_col = findColumn(headers, VAT_RATE_KEYWORDS, taken)
|
||||
const type_col = findColumn(headers, TYPE_KEYWORDS, taken)
|
||||
const unit_col = findColumn(headers, UNIT_KEYWORDS, taken)
|
||||
const housework_type_col = findColumn(headers, HOUSEWORK_KEYWORDS, taken)
|
||||
const notes_col = findColumn(headers, NOTES_KEYWORDS, taken)
|
||||
const name_col = findColumn(headers, NAME_KEYWORDS, taken) ?? -1
|
||||
|
||||
// Confidence: name is required; bonus from how many other columns matched.
|
||||
let confidence = 0
|
||||
if (name_col >= 0) {
|
||||
const matched = [
|
||||
article_number_col, price_col, vat_rate_col, unit_col,
|
||||
revenue_account_col, type_col,
|
||||
].filter((c) => c !== null).length
|
||||
confidence = 0.55 + Math.min(matched, 6) * 0.075
|
||||
}
|
||||
|
||||
return {
|
||||
name_col: name_col >= 0 ? name_col : 0,
|
||||
article_number_col,
|
||||
name_en_col,
|
||||
type_col,
|
||||
unit_col,
|
||||
price_col,
|
||||
vat_rate_col,
|
||||
revenue_account_col,
|
||||
cost_price_col,
|
||||
ean_col,
|
||||
housework_type_col,
|
||||
notes_col,
|
||||
// Confidence is a 0–1 heuristic score (not money), only compared against the
|
||||
// 0.8 skip-mapping threshold — no öre rounding needed.
|
||||
confidence: Math.min(confidence, 1),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import type { ArticleType } from '@/types'
|
||||
import { detectArticleColumns } from './column-detector'
|
||||
import { cellOrNull } from '../shared/column-utils'
|
||||
import { parseAmount } from '../opening-balance/parser'
|
||||
import { readBestSheet } from '../shared/workbook-reader'
|
||||
import type { DetectedArticleColumns, ParsedArticleRow } from './types'
|
||||
|
||||
const VALID_VAT_RATES = [0, 6, 12, 25] as const
|
||||
|
||||
/** Snap an arbitrary VAT percentage to the nearest Swedish statutory rate. */
|
||||
function snapVatRate(n: number): number {
|
||||
let best: number = VALID_VAT_RATES[0]
|
||||
let bestDist = Math.abs(n - best)
|
||||
for (const r of VALID_VAT_RATES) {
|
||||
const d = Math.abs(n - r)
|
||||
if (d < bestDist) {
|
||||
best = r
|
||||
bestDist = d
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a VAT cell to one of {0,6,12,25}. Handles "25%", "25", "0,25"
|
||||
* (fraction), and Swedish decimal commas. Returns the snapped rate plus an
|
||||
* optional human note when the raw value was non-empty but not already valid
|
||||
* (e.g. a Fortnox `momskod` letter code or an unsupported percentage).
|
||||
*/
|
||||
function normalizeVatRate(raw: string | null): { rate: number; note: string | null } {
|
||||
if (!raw) return { rate: 25, note: null }
|
||||
const cleaned = raw
|
||||
.replace(/%/g, '')
|
||||
.replace(/\s/g, '')
|
||||
.replace(/\.(?=\d{3})/g, '') // dot thousand-separator
|
||||
.replace(',', '.') // Swedish decimal comma
|
||||
.trim()
|
||||
let n = parseFloat(cleaned)
|
||||
// Unparseable (e.g. a Fortnox `momskod` like "MP1") → default with a note.
|
||||
if (Number.isNaN(n)) {
|
||||
return { rate: 25, note: `Kunde inte tolka momssats "${raw}" — satt till 25 %` }
|
||||
}
|
||||
// Fraction form (0.25 → 25).
|
||||
if (n > 0 && n < 1) n = n * 100
|
||||
const snapped = snapVatRate(n)
|
||||
const wasValid = (VALID_VAT_RATES as readonly number[]).includes(Math.round(n))
|
||||
return {
|
||||
rate: snapped,
|
||||
note: wasValid ? null : `Momssats ${raw} avrundades till ${snapped} %`,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeArticleType(value: string | null): ArticleType {
|
||||
if (!value) return 'tjanst'
|
||||
const lower = value.toLowerCase().trim()
|
||||
if (
|
||||
lower === 'vara' || lower === 'varor' || lower === 'produkt' ||
|
||||
lower === 'product' || lower === 'goods' || lower === 'artikel' ||
|
||||
lower === 'lagervara' || lower === 'stock'
|
||||
) {
|
||||
return 'vara'
|
||||
}
|
||||
// Everything else (tjänst/service/…) maps to the DB default.
|
||||
return 'tjanst'
|
||||
}
|
||||
|
||||
const INCL_VAT_HEADER_RE = /brutto|inkl|incl|gross/i
|
||||
|
||||
/**
|
||||
* Parse an article-register file (Excel or CSV) into structured rows.
|
||||
*
|
||||
* Prices are read as EXCLUDING VAT (what the `articles` table stores). When the
|
||||
* matched price header looks like an incl-VAT column a file-level warning is
|
||||
* emitted rather than silently converting (the rate isn't reliably known here).
|
||||
*
|
||||
* @param buffer - Raw file buffer
|
||||
* @param filename - Original filename
|
||||
* @param columnOverrides - Optional manual column mapping
|
||||
*/
|
||||
export function parseArticlesFile(
|
||||
buffer: ArrayBuffer,
|
||||
filename: string,
|
||||
columnOverrides?: DetectedArticleColumns,
|
||||
): {
|
||||
filename: string
|
||||
sheet_name: string
|
||||
total_rows: number
|
||||
detected_columns: DetectedArticleColumns
|
||||
headers: string[]
|
||||
preview_rows: string[][]
|
||||
rows: ParsedArticleRow[]
|
||||
warnings: string[]
|
||||
} {
|
||||
const { sheetName, rawData } = readBestSheet(buffer, filename)
|
||||
|
||||
if (rawData.length < 2) {
|
||||
const fallbackColumns: DetectedArticleColumns = columnOverrides ?? {
|
||||
name_col: 0,
|
||||
article_number_col: null,
|
||||
name_en_col: null,
|
||||
type_col: null,
|
||||
unit_col: null,
|
||||
price_col: null,
|
||||
vat_rate_col: null,
|
||||
revenue_account_col: null,
|
||||
cost_price_col: null,
|
||||
ean_col: null,
|
||||
housework_type_col: null,
|
||||
notes_col: null,
|
||||
confidence: 0,
|
||||
}
|
||||
return {
|
||||
filename,
|
||||
sheet_name: sheetName,
|
||||
total_rows: 0,
|
||||
detected_columns: fallbackColumns,
|
||||
headers: rawData[0]?.map((h) => String(h)) || [],
|
||||
preview_rows: [],
|
||||
rows: [],
|
||||
warnings: ['Filen innehåller för få rader.'],
|
||||
}
|
||||
}
|
||||
|
||||
const headers = rawData[0].map((h) => String(h))
|
||||
const dataRows = rawData.slice(1)
|
||||
const columns = columnOverrides || detectArticleColumns(headers)
|
||||
|
||||
const rows: ParsedArticleRow[] = []
|
||||
const warnings: string[] = []
|
||||
const cell = (row: string[], col: number | null): string | null =>
|
||||
col !== null ? cellOrNull(row[col]) : null
|
||||
|
||||
// Surface incl-VAT price columns once for the whole file.
|
||||
if (columns.price_col !== null && INCL_VAT_HEADER_RE.test(headers[columns.price_col] ?? '')) {
|
||||
warnings.push(
|
||||
`Priskolumnen "${headers[columns.price_col]}" verkar vara inkl. moms — priser importeras som exkl. moms. Kontrollera värdena.`,
|
||||
)
|
||||
}
|
||||
|
||||
let vatNoteCount = 0
|
||||
let droppedAccountCount = 0
|
||||
|
||||
for (let i = 0; i < dataRows.length; i++) {
|
||||
const row = dataRows[i]
|
||||
const name = cell(row, columns.name_col)
|
||||
if (!name) continue // skip empty rows silently
|
||||
|
||||
const articleNumber = cell(row, columns.article_number_col)
|
||||
const nameEn = cell(row, columns.name_en_col)
|
||||
const type = normalizeArticleType(cell(row, columns.type_col))
|
||||
const unitRaw = cell(row, columns.unit_col)
|
||||
const unit = unitRaw ?? 'st'
|
||||
|
||||
const priceRaw = cell(row, columns.price_col)
|
||||
const price = priceRaw !== null ? parseAmount(priceRaw) : 0
|
||||
|
||||
const { rate: vatRate, note: vatNote } = normalizeVatRate(cell(row, columns.vat_rate_col))
|
||||
if (vatNote) vatNoteCount++
|
||||
|
||||
// Keep only well-formed BAS class-3 overrides; the execute route validates
|
||||
// them further against the chart of accounts.
|
||||
const revenueRaw = cell(row, columns.revenue_account_col)
|
||||
let revenueAccount: string | null = null
|
||||
if (revenueRaw) {
|
||||
const digits = revenueRaw.replace(/\s/g, '')
|
||||
if (/^3\d{3}$/.test(digits)) revenueAccount = digits
|
||||
else droppedAccountCount++
|
||||
}
|
||||
|
||||
const costRaw = cell(row, columns.cost_price_col)
|
||||
const costPrice = costRaw !== null ? parseAmount(costRaw) : null
|
||||
|
||||
const ean = cell(row, columns.ean_col)
|
||||
const houseworkType = cell(row, columns.housework_type_col)
|
||||
const notes = cell(row, columns.notes_col)
|
||||
|
||||
const validationErrors: string[] = []
|
||||
if (price < 0) validationErrors.push('Priset kan inte vara negativt')
|
||||
if (costPrice !== null && costPrice < 0) validationErrors.push('Inköpspriset kan inte vara negativt')
|
||||
|
||||
rows.push({
|
||||
row_index: i + 2, // 1-based + header
|
||||
name,
|
||||
name_en: nameEn,
|
||||
article_number: articleNumber,
|
||||
type,
|
||||
unit,
|
||||
price_excl_vat: price,
|
||||
vat_rate: vatRate,
|
||||
// A note means the rate was snapped or defaulted — flag it for review.
|
||||
vat_rate_adjusted: vatNote !== null,
|
||||
revenue_account: revenueAccount,
|
||||
cost_price: costPrice,
|
||||
ean,
|
||||
housework_type: houseworkType,
|
||||
notes,
|
||||
is_valid: validationErrors.length === 0,
|
||||
validation_errors: validationErrors,
|
||||
})
|
||||
}
|
||||
|
||||
if (vatNoteCount > 0) {
|
||||
warnings.push(`${vatNoteCount} rad${vatNoteCount === 1 ? '' : 'er'} hade en momssats som avrundades till närmaste giltiga (0/6/12/25 %).`)
|
||||
}
|
||||
if (droppedAccountCount > 0) {
|
||||
warnings.push(`${droppedAccountCount} rad${droppedAccountCount === 1 ? '' : 'er'} hade ett ogiltigt försäljningskonto (måste vara 3xxx) som ignorerades.`)
|
||||
}
|
||||
if (rows.length === 0) {
|
||||
warnings.push('Inga giltiga artiklar hittades. Kontrollera att namn-/benämningskolumnen är korrekt mappad.')
|
||||
}
|
||||
|
||||
return {
|
||||
filename,
|
||||
sheet_name: sheetName,
|
||||
total_rows: rows.length,
|
||||
detected_columns: columns,
|
||||
headers,
|
||||
preview_rows: dataRows.slice(0, 5),
|
||||
rows,
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { ArticleType } from '@/types'
|
||||
|
||||
/** Result of auto-detecting columns in an article register file. */
|
||||
export interface DetectedArticleColumns {
|
||||
name_col: number
|
||||
article_number_col: number | null
|
||||
name_en_col: number | null
|
||||
type_col: number | null
|
||||
unit_col: number | null
|
||||
price_col: number | null
|
||||
vat_rate_col: number | null
|
||||
revenue_account_col: number | null
|
||||
cost_price_col: number | null
|
||||
ean_col: number | null
|
||||
housework_type_col: number | null
|
||||
notes_col: number | null
|
||||
/** 0-1 confidence score for the detection */
|
||||
confidence: number
|
||||
}
|
||||
|
||||
/** A single parsed row from the article register file. */
|
||||
export interface ParsedArticleRow {
|
||||
row_index: number
|
||||
name: string
|
||||
name_en: string | null
|
||||
article_number: string | null
|
||||
type: ArticleType
|
||||
unit: string
|
||||
/** Always stored EXCLUDING VAT. */
|
||||
price_excl_vat: number
|
||||
/** Integer percent, snapped to one of 0 | 6 | 12 | 25. */
|
||||
vat_rate: number
|
||||
/**
|
||||
* True when the VAT rate was inferred (snapped to the nearest statutory rate
|
||||
* or defaulted from an unparseable cell). Drives a "verify this" hint in the
|
||||
* edit step; cleared once the operator confirms the rate. Not persisted.
|
||||
*/
|
||||
vat_rate_adjusted: boolean
|
||||
/** Optional BAS class-3 revenue-account override (validated server-side). */
|
||||
revenue_account: string | null
|
||||
cost_price: number | null
|
||||
ean: string | null
|
||||
housework_type: string | null
|
||||
notes: string | null
|
||||
is_valid: boolean
|
||||
validation_errors: string[]
|
||||
}
|
||||
|
||||
/** Article-row + dedup annotation produced by the parse route. */
|
||||
export interface AnnotatedArticleRow extends ParsedArticleRow {
|
||||
duplicate_match: {
|
||||
article_id: string
|
||||
matched_by: 'article_number' | 'name'
|
||||
existing_name: string
|
||||
} | null
|
||||
}
|
||||
|
||||
/** Full result from parsing an article register file. */
|
||||
export interface ArticleImportParseResult {
|
||||
filename: string
|
||||
sheet_name: string
|
||||
total_rows: number
|
||||
detected_columns: DetectedArticleColumns
|
||||
headers: string[]
|
||||
preview_rows: string[][]
|
||||
rows: AnnotatedArticleRow[]
|
||||
duplicate_count: number
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
/** Input for executing the article import. */
|
||||
export interface ArticleImportExecuteInput {
|
||||
rows: ParsedArticleRow[]
|
||||
update_duplicates: boolean
|
||||
}
|
||||
|
||||
/** Result of executing the article import. */
|
||||
export interface ArticleImportExecuteResult {
|
||||
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). */
|
||||
warnings: string[]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
/**
|
||||
* Shared column-detection helpers for register imports
|
||||
* (customers, suppliers, future: articles).
|
||||
* (customers, suppliers, articles).
|
||||
*/
|
||||
|
||||
export function normalize(header: string): string {
|
||||
|
||||
@@ -109,7 +109,7 @@ function displayLength(value: CellValue, format: ColumnFormat): number {
|
||||
// single type parameter. Per-sheet type safety still applies inside each
|
||||
// `SheetSpec<TRow>` declaration.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars
|
||||
export function reportToWorkbook<_T = unknown>(spec: ReadonlyArray<SheetSpec<any>>): Buffer {
|
||||
export function reportToWorkbook<_T = unknown>(spec: ReadonlyArray<SheetSpec<any>>, options: { bookType?: 'xlsx' | 'csv' } = {}): Buffer {
|
||||
if (spec.length === 0) {
|
||||
throw new Error('reportToWorkbook: at least one sheet spec is required')
|
||||
}
|
||||
@@ -176,11 +176,17 @@ export function reportToWorkbook<_T = unknown>(spec: ReadonlyArray<SheetSpec<any
|
||||
XLSX.utils.book_append_sheet(workbook, worksheet, truncatedName)
|
||||
}
|
||||
|
||||
// `XLSX.write` with `type: 'buffer'` returns a Node Buffer.
|
||||
const out = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' }) as Buffer
|
||||
// `XLSX.write` with `type: 'buffer'` returns a Node Buffer. `bookType: 'csv'`
|
||||
// emits only the first sheet (CSV is single-sheet) — fine for the flat,
|
||||
// single-sheet register exports that use this option.
|
||||
const bookType = options.bookType ?? 'xlsx'
|
||||
const out = XLSX.write(workbook, { type: 'buffer', bookType }) as Buffer
|
||||
return out
|
||||
}
|
||||
|
||||
/** UTF-8 byte-order mark (U+FEFF) so Excel opens CSV exports with åäö intact. */
|
||||
export const UTF8_BOM = '\uFEFF'
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Column helpers — small declarative builders so route files read cleanly.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
@@ -248,3 +254,20 @@ export function xlsxFilename(reportSlug: string, companyName: string, period: st
|
||||
const parts = [reportSlug, companySlug, periodCompact].filter(Boolean)
|
||||
return `${parts.join('-')}.xlsx`
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a download filename `<slug>-<companySlug>-<dateYYYYMMDD>.<ext>`.
|
||||
* Like `xlsxFilename` but with a caller-chosen extension (`'xlsx'` | `'csv'`),
|
||||
* for register exports that offer both formats.
|
||||
*/
|
||||
export function exportFilename(
|
||||
slug: string,
|
||||
companyName: string,
|
||||
date: string,
|
||||
ext: 'xlsx' | 'csv',
|
||||
): string {
|
||||
const companySlug = slugifyCompanyName(companyName)
|
||||
const dateCompact = (date || '').replace(/-/g, '')
|
||||
const parts = [slug, companySlug, dateCompact].filter(Boolean)
|
||||
return `${parts.join('-')}.${ext}`
|
||||
}
|
||||
|
||||
+3
-1
@@ -4067,6 +4067,7 @@
|
||||
"sie_moved_link": "Open SIE export",
|
||||
"download_pdf": "Download PDF",
|
||||
"download_excel": "Download Excel",
|
||||
"download_csv": "Download CSV",
|
||||
"export": "Export",
|
||||
"recent_heading": "Recently opened",
|
||||
"back_to_library": "Reports",
|
||||
@@ -4178,10 +4179,11 @@
|
||||
"bankfile_title": "Bank transactions",
|
||||
"bankfile_description": "Import statements from your bank. Supports most Swedish banks.",
|
||||
"csv_data_title": "Import CSV / Excel data",
|
||||
"csv_data_description": "Import opening balances, customers, or suppliers.",
|
||||
"csv_data_description": "Import opening balances, customers, suppliers, or articles.",
|
||||
"csv_chip_opening_balances": "Opening balances",
|
||||
"csv_chip_customers": "Customers",
|
||||
"csv_chip_suppliers": "Suppliers",
|
||||
"csv_chip_articles": "Articles",
|
||||
"sie_title": "Bookkeeping data (SIE)",
|
||||
"sie_description": "Import journal entries and chart of accounts from another bookkeeping system.",
|
||||
"loading_migration": "Loading migration tool...",
|
||||
|
||||
+3
-1
@@ -4067,6 +4067,7 @@
|
||||
"sie_moved_link": "Öppna SIE-export",
|
||||
"download_pdf": "Ladda ner PDF",
|
||||
"download_excel": "Ladda ner Excel",
|
||||
"download_csv": "Ladda ner CSV",
|
||||
"export": "Exportera",
|
||||
"recent_heading": "Senast öppnade",
|
||||
"back_to_library": "Rapporter",
|
||||
@@ -4178,10 +4179,11 @@
|
||||
"bankfile_title": "Banktransaktioner",
|
||||
"bankfile_description": "Importera kontoutdrag från din bank. Stöder de flesta svenska banker.",
|
||||
"csv_data_title": "Importera CSV/Excel-data",
|
||||
"csv_data_description": "Importera ingående balanser, kunder eller leverantörer.",
|
||||
"csv_data_description": "Importera ingående balanser, kunder, leverantörer eller artiklar.",
|
||||
"csv_chip_opening_balances": "Ingående balanser",
|
||||
"csv_chip_customers": "Kunder",
|
||||
"csv_chip_suppliers": "Leverantörer",
|
||||
"csv_chip_articles": "Artiklar",
|
||||
"sie_title": "Bokföringsdata (SIE)",
|
||||
"sie_description": "Importera verifikationer och kontoplan från ett annat bokföringsprogram.",
|
||||
"loading_migration": "Laddar migreringsverktyg...",
|
||||
|
||||
Reference in New Issue
Block a user