Files
accounted/app/(dashboard)/import/page.tsx
T
Jakob WennbergandClaude Opus 4.7 a9c98da243 feat(api): Phase 3 — transactions + reconciliation vertical (#464)
* feat(api): Phase 3 — transactions + reconciliation vertical

Closes out Phase 3 of the plan in one PR. After this, a 3rd-party agent
can fully manage a company's transaction ledger via the public API:
import bank data, walk the queue, categorize (manual / template /
counterparty / account-override), match payments to customer + supplier
invoices, reverse mistakes, and auto-reconcile the bank against the GL.

ENDPOINTS (12)

Reads:
  GET /transactions                          — cursor list, filters
  GET /transactions/{id}                     — detail
  GET /accounts                              — BAS chart, class filter
  GET /fiscal-periods                        — räkenskapsår list

Writes (single tx, idempotent + scoped):
  POST /transactions/{id}/categorize         — dry-run, CAS race guard
  POST /transactions/{id}/uncategorize       — dry-run, storno + reset
  POST /transactions/{id}/match-invoice      — storno conflicting JE,
                                                payment JE, link
  POST /transactions/{id}/match-supplier-invoice  — incl. FX diff handling

Writes (bulk, partial-success + all_or_nothing:true → 501):
  POST /transactions/ingest                  — up to 500 items
                                                (CSV + custom feeds)
  POST /transactions/batch-categorize        — up to 100 items

Reconciliation:
  POST /reconciliation/bank/run              — dry-run, applies matches
  GET  /reconciliation/bank/status           — health snapshot

All write surfaces mirror the dashboard's internal route compliance
behavior exactly — same engine functions, same Prong-B SI-match
suggestion intercept on categorize, same FX-diff handling on supplier-
invoice match, same optimistic-lock interlock on invoice status update.
No new bookkeeping primitives — every route delegates to the existing
`lib/bookkeeping/*` engine, `lib/transactions/ingest.ts`, and
`lib/reconciliation/bank-reconciliation.ts`.

SCOPES + ERRORS

Adds 12 entries to lib/auth/scopes.ts under transactions:read|write +
reports:read (accounts, fiscal-periods follow the same convention as
MCP tools). Adds 4 new error codes: TX_UNCATEGORIZE_NOT_BOOKED,
TX_UNCATEGORIZE_JE_NOT_POSTED, TX_INGEST_INSERT_FAILED,
TX_BATCH_CATEGORIZE_EMPTY.

TESTS

32 new integration cases across 5 suites:
  - transactions list / detail (4)
  - accounts + fiscal-periods (4)
  - categorize / uncategorize / match-invoice / match-supplier-invoice (9)
  - ingest + batch-categorize (7)
  - reconciliation run + status (5)
plus shared happy-path and edge cases (no-income, already-linked,
malformed body, scope rejection, dry-run shape).

Full suite green: 3270 passing (234 files). Build + lint clean.

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

* fix(api): address PR #464 review — Phase 3 hardening

Greptile P1 — cursor pagination broken in GET /transactions.
  encodeDefaultCursor was passed the YYYY-MM-DD `date` field, but
  decodeDefaultCursor's strict ISO 8601 timestamp regex rejected it,
  so every cursor decoded as null and the endpoint always returned the
  first page. Switched the cursor anchor to `created_at` (real ISO
  timestamp, total-orderable, unique within the company at the row
  insertion grain) and updated the sort to (created_at DESC, id ASC).
  The `date` column remains in every row + filterable via ?date_from /
  ?date_to. Updated the registry description to reflect the change.

Greptile P1 — JE soft-fall in match-invoice + match-supplier-invoice.
  When the payment journal entry creation threw (any non-
  AccountsNotInChartError), the catch block recorded the error string
  but execution CONTINUED, marking the invoice paid + inserting a
  payment row + linking the transaction with no GL entry. The dashboard
  internal route soft-fails here intentionally and surfaces a banner so
  the user can re-book; for the v1 surface a partial state is strictly
  worse than a clean failure to retry. Both routes now return:
    - INVOICE_PAID_BOOK_FAILED (match-invoice)
    - MATCH_SI_RECORD_PAYMENT_FAILED (match-supplier-invoice)
  before any state mutation. Removed `journal_entry_error` from both
  response schemas — strict mode means it can never be set on a 200.

Greptile P1 — `overdue` supplier invoices fail the optimistic lock.
  The early status guard accepted `overdue` as matchable, but the
  downstream `.in('status', ['registered', 'approved', 'partially_paid'])`
  excluded it, returning MATCH_SI_NOT_OPEN for a legitimately payable
  invoice. Added `overdue` to the optimistic-lock list.

Greptile P1 + Swedish-compliance — CAS-race orphan cancellation.
  Direct `.update({ status: 'cancelled' })` on the orphaned JE was
  silently blocked by enforce_journal_entry_immutability (the engine
  writes JEs as posted) and the `voucher_gap_explanations` row claimed
  the entry was cancelled when it wasn't. BFL 5 kap 5 § requires
  corrections via a reversing entry. Both /transactions/{id}/categorize
  and /transactions/batch-categorize now call `reverseEntry()` on the
  orphan; the storno pair keeps the verifikationsnummer series unbroken
  so the gap-explanation insert is no longer needed.

Greptile P2 + Swedish-compliance — hardcoded category on match-invoice.
  The dashboard internal route writes `category: 'income_services'` for
  every matched invoice payment, overwriting any prior categorization
  with a wrong BAS classification for goods sales / rental income.
  Fixed by preserving the existing transaction.category if set, only
  defaulting to `income_services` when the row had never been
  categorized before.

Compliance Swarm V2.4 — reconciliation date range guard.
  Added a 366-day cap on date_from / date_to via Zod refine. Longer
  reconciliations should be paged.

Greptile P2 — dry-run dedup limitation.
  Added a pitfall note documenting that the ingest dry-run only checks
  external_id-based dedup; content-based dedup (date+amount against
  already-booked rows) only runs in the live pipeline.

Swedish-compliance — BFL chapter typo on fiscal-periods registry.
  "BFL 6 kap" → "BFL 5 kap 2 §" (the löpande bokföring deadline).

Deferred (with rationale documented):
  - OWASP V8.2.1 cross-tenant via path: false positive — wrapper sets
    ctx.companyId from the URL after membership check (recurring across
    swarm runs).
  - OWASP V4.5 select('*') on transactions/invoices: same as Phase 2 —
    those rows feed engine functions that need the full shape.
  - OWASP V2.3 multi-write atomicity (match endpoints): would need a
    Postgres RPC; separate refactor.
  - Swedish-compliance kontantmetoden partial-payment status: same
    semantics as the dashboard internal route; engine-level decision
    out of v1's scope.
  - Greptile P3 `reversible: false` on uncategorize: technically
    correct (the storno itself isn't reversible via this verb).

Tests + build green: 3270 passing, lint clean.

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

* fix(import): distinguish network errors in the SIE upload step

Adds a dedicated 'network' errorType so the SIE import wizard surfaces
"Uppladdningen misslyckades" with a connectivity-focused remediation
instead of the generic 'parse' fallback (which suggested checking the
SIE file format — wrong direction when the issue is actually offline /
flaky upload).

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

* fix(api): address PR #464 swedish-compliance re-run findings

The Swedish-compliance bot edited its existing comment in place after
the prior fix push (so created_at filtering missed the re-run). The
re-run flagged 6 new substantive findings against the post-fix code.

Fix 1 — Orphan storno failure leaves an unresolved immutability gap
  (categorize + batch-categorize).
  When reverseEntry() on the CAS-race orphan fails, the orphan stays
  posted and untraceable. BFL 5 kap 5 § requires every correction be
  traceable. Both paths now insert a voucher_gap_explanations row in
  the catch branch flagging "automatisk storno misslyckades — manuell
  reconciliation krävs", so the orphan is logged at the audit-trail
  level rather than only in app logs.

Fix 2 — Period-lock pre-check (categorize + batch-categorize).
  enforce_period_lock and enforce_company_lock_date triggers block JE
  inserts on locked/closed periods, but Supabase surfaces those as a
  generic 500. Added a new lib/api/v1/check-period-lock.ts helper that
  performs the same check the trigger would (company-wide lock date,
  is_closed, locked_at), and both routes now return a structured
  PERIOD_LOCKED response (existing error code, 400) with reason +
  fiscal_period_id details before the engine call. Note: this is an
  ergonomics check (TOCTOU window between check and insert) — the
  trigger remains authoritative.

Fix 3 — Ingest dry-run now performs content-based dedup too.
  The earlier doc-only note was a compliance miss: an integrator
  relying on dry-run to confirm uniqueness could ingest duplicate
  affärshändelser, violating BFL 5 kap. The dry-run now runs BOTH
  external_id dedup AND content-based (date+amount-against-booked)
  dedup over the request's date range — same query the live pipeline
  uses. Pitfall doc updated accordingly.

Fix 4 — fiscal-periods response now carries duration_days +
  exceeds_18_months computed fields.
  An automated client (year-end wizard, audit tool) can spot a
  non-compliant period sequence (BFL 3 kap, 18-month cap) without
  re-implementing date arithmetic. 549-day cap (18 calendar months)
  is used to keep the comparison deterministic across leap years.
  First-year exceptions still require human judgment; the boolean is
  a flag, not a verdict.

Deferred (with rationale documented in commit, not retried):
  - uncategorize storno memo: reverseEntry() doesn't accept a reason
    parameter today and the JE-level back-reference exists already
    via reversed_by_id / reverses_id. Engine signature change is
    out of v1's scope.
  - VAT integrity check on partial payment in match-invoice: the
    behavior is fully delegated to createInvoicePaymentJournalEntry.
    The bot itself recommends auditing against the engine; that is
    an engine-layer concern and the dashboard internal route uses
    the same path.
  - 366-day reconciliation window (advisory): no statutory basis;
    operational guard.
  - match-supplier-invoice FX path against ML 8 kap 21–23 §
    (advisory): engine-layer concern.

Tests + build green: 3270 passing, lint clean. Touched-suite tests
(transactions, fiscal-periods, accounts, reconciliation) re-run; the
fiscal-periods test asserts the new derived fields.

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

* fix(api): PR #464 round-3 review fixes (re-run after period-lock + dedup)

Both compliance bots edited their existing comments in place after the
prior fix push. New findings against the post-fix code:

Fix — VAT account suppression too broad on account_override.
  categorize/route.ts dropped vat_lines for ANY class-2 override, but
  BAS class 2 includes the 26xx VAT clearing accounts themselves. Result:
  a user override TO a VAT account silently lost the auto-VAT line.
  Tightened to `account_class === 2 && !account_override.startsWith('26')`.
  The override-to-2440-leverantörsskulder case is unchanged (correctly
  drops auto-VAT); the override-to-2611-utgående-moms case now keeps the
  VAT line.

Fix — fiscal-periods 18-month cap uses calendar arithmetic.
  EIGHTEEN_MONTHS_DAYS = 549 was a generous approximation (18 calendar
  months span 540–549 days). Replaced with proper month-anchor math:
  start_date + 18 months computed via setUTCMonth-style year/month
  rollover, then `period_end > anchor` is the violation. Manual day-
  arithmetic on the year part avoids JS's clamp-overflow on Aug-31-style
  start dates. duration_days helper preserved for the response field.

Fix — match-invoice no longer hardcodes 'income_services'.
  When the transaction has no prior category, the route now leaves the
  field UNTOUCHED in the UPDATE (existing default 'uncategorized' or
  whatever was there persists). The response surfaces null for the
  uncategorized case so a caller can detect "needs human classification"
  without inspecting the DB. The auto-default to income_services was
  flowing into BAS 3001/3041/3530 selection mismatches and INK2R/SRU
  mis-reporting for goods/rental flows. Existing-category transactions
  still propagate their value.

Doc — accounts.ts BAS 5/6 description tightened.
  Was "5=other costs, 6=other costs" — both true but flatten distinct
  subgroups. Now spells out 5xxx (rents/supplies/services) and 6xxx
  (marketing/professional/IT) under övriga externa kostnader, with a
  pointer to the canonical BAS chart.

Deferred (with rationale documented):
  - voucher_gap_explanations in SIE export coverage: verification ask;
    SIE export audit is a separate task, not this PR's scope.
  - Dry-run dedup parity with full live pipeline: my dedup matches the
    live pipeline's primary checks (external_id + content date+amount
    against booked rows). Achieving exact parity would need refactoring
    lib/transactions/ingest.ts to expose a shared dedup helper.
  - FX sign convention in match-supplier-invoice: identical to the
    dashboard internal route; if the engine sign convention is wrong
    both surfaces are wrong. Engine-layer audit, not v1 surface.
  - OWASP V8.2.1 cross-tenant via path: recurring false positive — the
    wrapper sets ctx.companyId from the URL only AFTER company_members
    membership check.
  - V2.3 multi-write atomicity in match endpoints: would need a Postgres
    RPC; separate refactor.
  - check-period-lock TOCTOU on no_fiscal_period (advisory note): the
    engine's ensureFiscalPeriod helper creates an open period; if the
    transaction date sits in a historical gap, the engine creates the
    period unlocked. The trigger remains the authoritative gate.

Tests + build green: 3270 passing, lint clean.

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

* fix(api): PR #464 round-4 review fixes (compliance bot re-run)

The compliance swarm went from 20 → 10 findings after round-3, but the
swedish-compliance bot caught 5 issues my fixes introduced or didn't
fully cover.

Fix — VAT account suppression narrowed to BAS 2610–2649.
  My round-3 fix exempted any account starting with '26' from VAT-line
  suppression, but BAS 26xx includes 2650 (momsredovisningskonto) and
  2690 (diverse), neither of which is a moms-line account. Auto-VAT
  posted against 2650 would double-post on the moms reconciliation
  account. Tightened the exception to the 2610–2649 range (utgående
  + ingående moms accounts only).

Fix — exceedsEighteenMonths month-end overflow.
  My round-3 manual month math still passed `startD` raw to Date.UTC,
  which clamps Aug 31 + 18 months to Mar 3, making the cap LATER than
  the BFL 3 kap 1 § ceiling (false negative). Now clamps `startD` to
  the last valid day of the target month using `Date.UTC(year, m+1, 0)`.

Fix — ingest dry-run dedup float-key normalization.
  Built the content-dedup set from `${tx.date}|${tx.amount}` where
  amount is a JS number stringified directly — `-349.5` from JSON vs
  `-349.50` from a Postgres numeric round-trip miss-match. Normalized
  both sides to .toFixed(2). SIE imports commonly carry trailing-zero
  precision, so this would have caused the dry-run to under-report
  duplicates (a BFL 5 kap löpande-bokföring concern: an integrator
  trusting the dry-run could double-book affärshändelser).

Fix — CAS-race voucher_series fallback no longer files under 'A'.
  Both categorize and batch-categorize used `voucher_series || 'A'`
  for the voucher_gap_explanations row. If the orphan JE had no series,
  the gap would be indexed under series 'A' and missed by any series-
  specific audit query (BFL 5 kap 6 §). Now skips the gap row entirely
  when no series is set — the error log already captures the orphan
  for human reconciliation; filing under the wrong key is strictly
  worse than not filing.

Fix — match-invoice rejects kontantmetoden partial payments.
  Under kontantmetoden, utgående moms must be reported per actual
  receipt (ML 13 kap 8 §). The cash-method-partial branch was falling
  through to createInvoicePaymentJournalEntry (the accrual 1510/1930
  clearing path), which doesn't model the per-installment moms event.
  Rather than silently over-report moms, refuse with a VALIDATION_ERROR
  pointing the caller to either wait for the full payment or switch to
  faktureringsmetoden. Full cash-method payments still flow through
  createInvoiceCashEntry (the correct kontantmetod path).

Deferred (with rationale):
  - `uncategorize` resets journal_entry_id to null: dashboard parity;
    the JE-side back-reference (reversed_by_id / reverses_id) preserves
    the audit pair. Adding a separate reversal_journal_entry_id column
    on transactions is a schema change out of v1 scope.
  - OWASP V8.2.1 cross-tenant: recurring false positive.
  - OWASP V2.2 inline Zod filter schemas: structural consistency
    decision — kept in-route to match other v1 endpoints; a future
    refactor can centralize when it justifies the cost.
  - OWASP V16 add userId/companyId to storno-failure log: txLog
    already carries both via ctx.log.child; not changing call-site
    syntax for compliance theatre.
  - Engine-layer FX sign convention in match-supplier-invoice
    (advisory): identical to dashboard internal route.

Tests + build green: 3270 passing.

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

* fix(api): match-supplier-invoice storno conflicting JE before booking

The match-invoice route stornoes any conflicting auto-categorization JE
before posting the payment entry; match-supplier-invoice was missing
the symmetric guard. If a transaction was previously auto-categorized
(e.g. expense_office with a 5460/1930 entry), matching it to a supplier
invoice would post a second 2440/1930 entry while leaving the original
posted — two verifikationer for one affärshändelse, a BFL 5 kap 6 §
integrity violation. Storno-before-match now applies in both routes,
with the same fail-closed semantics (storno failure aborts before any
state change).

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 15:22:57 +02:00

1984 lines
72 KiB
TypeScript

'use client'
import { useState, useCallback, useEffect } from 'react'
import { useSearchParams } from 'next/navigation'
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Progress } from '@/components/ui/progress'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { ArrowLeftRight, ArrowRightLeft, FileText, ArrowLeft, Landmark, Loader2, Info, ChevronRight, FileSpreadsheet } from 'lucide-react'
import { motion } from 'framer-motion'
import { cn } from '@/lib/utils'
import { createClient } from '@/lib/supabase/client'
import { useCompany } from '@/contexts/CompanyContext'
import { BankSelector, type Bank } from '@/extensions/general/enable-banking/components/BankSelector'
import { BankConnectionStatus } from '@/extensions/general/enable-banking/components/BankConnectionStatus'
import { DestructiveConfirmDialog, useDestructiveConfirm } from '@/components/ui/destructive-confirm-dialog'
import type { BankConnection } from '@/types'
// Bank file import components
import BankFileUploadStep from '@/components/import/BankFileUploadStep'
import BankFilePreviewStep from '@/components/import/BankFilePreviewStep'
import BankFileColumnMappingStep from '@/components/import/BankFileColumnMappingStep'
import BankFileConfirmStep from '@/components/import/BankFileConfirmStep'
import BankFileResultStep from '@/components/import/BankFileResultStep'
// Opening balance import components
import OpeningBalanceUploadStep from '@/components/import/OpeningBalanceUploadStep'
import OpeningBalanceColumnMappingStep from '@/components/import/OpeningBalanceColumnMappingStep'
import OpeningBalanceEditStep from '@/components/import/OpeningBalanceEditStep'
import OpeningBalancePeriodStep from '@/components/import/OpeningBalancePeriodStep'
import OpeningBalanceResultStep from '@/components/import/OpeningBalanceResultStep'
import type { OpeningBalanceParseResult, OpeningBalanceExecuteResult, DetectedColumns } from '@/lib/import/opening-balance/types'
// Register import (customers/suppliers) components
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 RegisterResultStep, { type RegisterResult } from '@/components/import/RegisterResultStep'
import type {
CustomerImportParseResult,
AnnotatedCustomerRow,
DetectedCustomerColumns,
} from '@/lib/import/customers/types'
import type {
SupplierImportParseResult,
AnnotatedSupplierRow,
DetectedSupplierColumns,
} from '@/lib/import/suppliers/types'
// SIE import components
import SIEUploadStep from '@/components/import/SIEUploadStep'
import SIEPreviewStep from '@/components/import/SIEPreviewStep'
import AccountMappingStep from '@/components/import/AccountMappingStep'
import ImportReviewStep, { type ImportExecuteOptions } from '@/components/import/ImportReviewStep'
import ImportResultStep from '@/components/import/ImportResultStep'
import { applyMappingOverride } from '@/lib/import/account-mapper'
import type { BankFileParseResult, BankFileFormatId, GenericCSVColumnMapping } from '@/lib/import/bank-file/types'
import type { IngestResult } from '@/lib/transactions/ingest'
import type {
ImportWizardStep,
ParsedSIEFile,
AccountMapping,
ImportPreview,
ImportResult,
ParseIssue,
} from '@/lib/import/types'
import type { BASAccount } from '@/types'
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
import dynamic from 'next/dynamic'
const MigrationWizard = dynamic(
() => import('@/components/extensions/general/ArcimMigrationWorkspace'),
{ ssr: false, loading: () => <div className="flex items-center gap-3 text-muted-foreground p-6"><Loader2 className="h-5 w-5 animate-spin" />Laddar migreringsverktyg...</div> }
)
// ============================================================
// Bank File Import Wizard Steps
// ============================================================
type BankFileStep = 'upload' | 'preview' | 'column_mapping' | 'confirm' | 'result'
const BANK_STEPS: BankFileStep[] = ['upload', 'preview', 'confirm', 'result']
const BANK_STEPS_WITH_MAPPING: BankFileStep[] = ['upload', 'column_mapping', 'confirm', 'result']
const BANK_STEP_LABELS: Record<BankFileStep, string> = {
upload: 'Ladda upp',
preview: 'Förhandsgranskning',
column_mapping: 'Kolumnmappning',
confirm: 'Bekräfta',
result: 'Resultat',
}
function BankFileImportWizard() {
const { toast } = useToast()
const [bankStep, setBankStep] = useState<BankFileStep>('upload')
const [bankIsLoading, setBankIsLoading] = useState(false)
const [bankError, setBankError] = useState<string | null>(null)
// Parse results
const [parseResult, setParseResult] = useState<BankFileParseResult | null>(null)
const [detectedFormat, setDetectedFormat] = useState<string | null>(null)
const [detectedFormatName, setDetectedFormatName] = useState<string | null>(null)
const [fileHash, setFileHash] = useState<string>('')
const [filename, setFilename] = useState<string>('')
const [rawFileContent, setRawFileContent] = useState<string>('')
// Import result
const [ingestResult, setIngestResult] = useState<IngestResult | null>(null)
const steps = parseResult?.format === 'generic_csv' ? BANK_STEPS_WITH_MAPPING : BANK_STEPS
const currentStepIndex = steps.indexOf(bankStep)
const progress = ((currentStepIndex + 1) / steps.length) * 100
const handleFileSelect = useCallback(async (file: File, formatOverride?: BankFileFormatId) => {
setBankError(null)
setBankIsLoading(true)
try {
const formData = new FormData()
formData.append('file', file)
if (formatOverride) {
formData.append('format', formatOverride)
}
const res = await fetch('/api/import/bank-file/parse', {
method: 'POST',
body: formData,
})
const data = await res.json()
if (!res.ok) {
if (data.error === 'duplicate') {
setBankError(data.message)
} else {
setBankError(data.error || 'Kunde inte läsa filen')
}
return
}
setParseResult(data.data.parse_result)
setDetectedFormat(data.data.detected_format)
setDetectedFormatName(data.data.detected_format_name)
setFileHash(data.data.file_hash)
setFilename(data.data.filename)
// Read raw file content for CSV preview
const text = await file.text()
setRawFileContent(text)
const txCount = data.data.parse_result.transactions.length
if (data.data.parse_result.format === 'generic_csv') {
// Auto-detect failed or user picked "Annan CSV" — always route to manual column mapping.
// Default mapping rarely matches, so advance regardless of tx count.
setBankStep('column_mapping')
} else if (txCount > 0) {
setBankStep('preview')
toast({
title: 'Fil analyserad',
description: `${txCount} transaktioner hittades`,
})
} else {
// Format detected but no transactions parsed — parser couldn't extract rows
setBankError('Filen kunde läsas men inga transaktioner hittades. Kontrollera att filen innehåller transaktionsdata och inte bara rubriker.')
}
} catch (err) {
setBankError(err instanceof Error ? err.message : 'Kunde inte läsa filen')
} finally {
setBankIsLoading(false)
}
}, [toast])
const handleColumnMappingConfirm = useCallback(async (mapping: GenericCSVColumnMapping) => {
// Re-parse with mapping via the generic CSV parser
const { parseGenericCSV } = await import('@/lib/import/bank-file/formats/generic-csv')
const result = parseGenericCSV(rawFileContent, mapping)
setParseResult(result)
setBankStep('confirm')
}, [rawFileContent])
const handleExecuteImport = useCallback(async (options: { skip_duplicates: boolean; auto_categorize: boolean; settlement_account?: string }) => {
if (!parseResult) return
setBankIsLoading(true)
setBankError(null)
try {
const res = await fetch('/api/import/bank-file/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
transactions: parseResult.transactions,
format: parseResult.format,
filename,
file_hash: fileHash,
...options,
}),
})
const data = await res.json()
if (!res.ok) {
setBankError(data.error || 'Importen misslyckades')
return
}
setIngestResult(data.data)
setBankStep('result')
toast({
title: 'Import genomförd',
description: `${data.data.imported} transaktioner importerades`,
})
} catch (err) {
setBankError(err instanceof Error ? err.message : 'Importen misslyckades')
} finally {
setBankIsLoading(false)
}
}, [parseResult, filename, fileHash, toast])
const handleNewImport = () => {
setBankStep('upload')
setParseResult(null)
setDetectedFormat(null)
setDetectedFormatName(null)
setFileHash('')
setFilename('')
setIngestResult(null)
setBankError(null)
setRawFileContent('')
}
return (
<div className="space-y-6">
{/* Progress */}
<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}: {BANK_STEP_LABELS[bankStep]}
</span>
{steps.map((s, i) => (
<span
key={s}
className={cn(
'hidden sm:inline',
i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground'
)}
>
{BANK_STEP_LABELS[s]}
</span>
))}
</div>
<Progress value={progress} className="h-2" />
</div>
</CardContent>
</Card>
{/* Step content */}
{bankStep === 'upload' && (
<BankFileUploadStep
onFileSelect={handleFileSelect}
isLoading={bankIsLoading}
error={bankError}
detectedFormat={detectedFormat}
detectedFormatName={detectedFormatName}
/>
)}
{bankStep === 'preview' && parseResult && (
<BankFilePreviewStep
parseResult={parseResult}
onContinue={() => {
if (parseResult.format === 'generic_csv') {
setBankStep('column_mapping')
} else {
setBankStep('confirm')
}
}}
onBack={() => setBankStep('upload')}
/>
)}
{bankStep === 'column_mapping' && (
<BankFileColumnMappingStep
rawFileContent={rawFileContent}
onConfirm={handleColumnMappingConfirm}
onBack={() => setBankStep('upload')}
/>
)}
{bankStep === 'confirm' && parseResult && (
<BankFileConfirmStep
parseResult={parseResult}
onExecute={handleExecuteImport}
onBack={() => {
if (parseResult.format === 'generic_csv') {
setBankStep('column_mapping')
} else {
setBankStep('preview')
}
}}
isLoading={bankIsLoading}
/>
)}
{bankStep === 'result' && ingestResult && (
<BankFileResultStep
result={ingestResult}
onNewImport={handleNewImport}
/>
)}
</div>
)
}
// ============================================================
// SIE Import Wizard (unchanged, extracted into component)
// ============================================================
const SIE_STEP_LABELS: Record<ImportWizardStep, string> = {
upload: 'Ladda upp',
preview: 'Förhandsgranskning',
mapping: 'Kontomappning',
review: 'Bekräfta',
result: 'Resultat',
}
function SIEImportWizard() {
const { toast } = useToast()
const [step, setStep] = useState<ImportWizardStep>('upload')
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [errorType, setErrorType] = useState<'duplicate' | 'duplicate_period' | 'validation' | 'parse' | 'network' | undefined>()
const [validationErrors, setValidationErrors] = useState<string[]>([])
const [validationWarnings, setValidationWarnings] = useState<string[]>([])
const [duplicateImportId, setDuplicateImportId] = useState<string | null>(null)
const [isReplacing, setIsReplacing] = useState(false)
const [file, setFile] = useState<File | null>(null)
const [, setParsed] = useState<ParsedSIEFile | null>(null)
const [mappings, setMappings] = useState<AccountMapping[]>([])
const [basAccounts, setBasAccounts] = useState<BASAccount[]>([])
const [preview, setPreview] = useState<ImportPreview | null>(null)
const [issues, setIssues] = useState<ParseIssue[]>([])
const [importResult, setImportResult] = useState<ImportResult | null>(null)
const [, setSieAccounts] = useState<{ number: string; name: string }[]>([])
const [isCreatingAccounts, setIsCreatingAccounts] = useState(false)
// Skip the mapping step when all accounts are already mapped
const hasUnmapped = mappings.some((m) => !m.targetAccount)
const sieSteps: ImportWizardStep[] = hasUnmapped
? ['upload', 'preview', 'mapping', 'review', 'result']
: ['upload', 'preview', 'review', 'result']
const currentStepIndex = sieSteps.indexOf(step)
const progress = ((currentStepIndex + 1) / sieSteps.length) * 100
const handleFileSelect = useCallback(async (selectedFile: File) => {
setFile(selectedFile)
setError(null)
setErrorType(undefined)
setValidationErrors([])
setValidationWarnings([])
setIsLoading(true)
try {
const formData = new FormData()
formData.append('file', selectedFile)
const res = await fetch('/api/import/sie/parse', {
method: 'POST',
body: formData,
})
const data = await res.json()
if (!res.ok) {
const code = data?.error?.code as string | undefined
const message = getErrorMessage(data)
const details = (data?.error?.details ?? {}) as {
importId?: string
errors?: string[]
warnings?: string[]
}
if (code === 'SIE_DUPLICATE_FILE' || code === 'SIE_DUPLICATE_PERIOD') {
const isPeriod = code === 'SIE_DUPLICATE_PERIOD'
setErrorType(isPeriod ? 'duplicate_period' : 'duplicate')
setError(message)
if (details.importId) {
setDuplicateImportId(details.importId)
}
toast({
title: isPeriod ? 'Överlappande räkenskapsår' : 'Filen har redan importerats',
description: message,
variant: 'destructive',
})
} else if (code === 'SIE_PARSE_VALIDATION_FAILED') {
setErrorType('validation')
setError(message)
setValidationErrors(details.errors || [])
setValidationWarnings(details.warnings || [])
toast({
title: 'Valideringsfel i SIE-filen',
description: `${(details.errors || []).length} fel hittades som måste åtgärdas.`,
variant: 'destructive',
})
} else {
setErrorType('parse')
setError(message)
toast({ title: 'Kunde inte läsa filen', description: message, variant: 'destructive' })
}
return
}
setParsed({
header: data.parsed.header,
accounts: data.parsed.accounts,
openingBalances: [],
closingBalances: [],
resultBalances: [],
vouchers: [],
issues: data.parsed.issues,
stats: data.parsed.stats,
})
setMappings(data.mappings)
setPreview(data.preview)
setIssues(data.parsed.issues)
setSieAccounts(data.parsed.accounts)
const accountsRes = await fetch('/api/bookkeeping/accounts')
if (accountsRes.ok) {
const accountsData = await accountsRes.json()
setBasAccounts(accountsData.data || [])
}
setStep('preview')
toast({
title: 'Fil analyserad',
description: `${data.parsed.stats.totalAccounts} konton och ${data.parsed.stats.totalVouchers} verifikationer hittades`,
})
} catch (err) {
const isNetworkError = err instanceof TypeError && (err.message === 'Failed to fetch' || err.message.includes('NetworkError'))
const message = isNetworkError
? 'Kunde inte nå servern. Kontrollera din internetanslutning och försök igen.'
: err instanceof Error ? err.message : 'Ett oväntat fel uppstod.'
setErrorType(isNetworkError ? 'network' : 'parse')
setError(message)
toast({ title: isNetworkError ? 'Anslutningsfel' : 'Ett fel uppstod', description: message, variant: 'destructive' })
} finally {
setIsLoading(false)
}
}, [toast])
const handleReplace = useCallback(async (importId: string) => {
if (!file) return
setIsReplacing(true)
try {
const res = await fetch(`/api/import/sie/${importId}/replace`, { method: 'POST' })
const data = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte ersätta import', description: getErrorMessage(data), variant: 'destructive' })
return
}
toast({
title: 'Import ersatt',
description: `${data.cancelledEntries} verifikation${data.cancelledEntries === 1 ? '' : 'er'} makulerades. Importerar ny fil...`,
})
// Clear error state and re-trigger the file upload
setError(null)
setErrorType(undefined)
setDuplicateImportId(null)
// Small delay so the user sees the success toast before re-upload starts
await new Promise(resolve => setTimeout(resolve, 500))
handleFileSelect(file)
} catch {
toast({ title: 'Anslutningsfel', description: 'Kunde inte nå servern.', variant: 'destructive' })
} finally {
setIsReplacing(false)
}
}, [file, handleFileSelect, toast])
const handleMappingChange = useCallback((sourceAccount: string, targetAccount: string, targetName: string) => {
setMappings((prev) => applyMappingOverride(prev, sourceAccount, targetAccount, targetName))
setPreview((prev) => {
if (!prev) return prev
const updatedMappings = applyMappingOverride(mappings, sourceAccount, targetAccount, targetName)
const mapped = updatedMappings.filter((m) => m.targetAccount).length
const unmapped = updatedMappings.length - mapped
const lowConfidence = updatedMappings.filter((m) => m.targetAccount && m.confidence < 0.7).length
return {
...prev,
mappingStatus: {
...prev.mappingStatus,
mapped,
unmapped,
lowConfidence,
},
}
})
}, [mappings])
const missingAccounts = mappings
.filter((m) => !m.targetAccount)
.map((m) => ({ number: m.sourceAccount, name: m.sourceName }))
const handleCreateAccounts = useCallback(async () => {
if (missingAccounts.length === 0) return
setIsCreatingAccounts(true)
try {
const res = await fetch('/api/import/sie/create-accounts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accounts: missingAccounts }),
})
const data = await res.json()
if (!res.ok) {
toast({ title: 'Kunde inte skapa konton', description: getErrorMessage(data), variant: 'destructive' })
return
}
toast({ title: 'Konton skapade', description: `${data.created} nya konton har lagts till i din kontoplan` })
// Optimistically update mappings: mark created accounts as self-mapped
const createdSet = new Set(missingAccounts.map(a => a.number))
setMappings(prev => prev.map(m =>
!m.targetAccount && createdSet.has(m.sourceAccount)
? { ...m, targetAccount: m.sourceAccount, targetName: m.sourceName, confidence: 1.0 }
: m
))
setPreview(prev => {
if (!prev) return prev
const newMapped = prev.mappingStatus.mapped + createdSet.size
return {
...prev,
mappingStatus: {
...prev.mappingStatus,
mapped: newMapped,
unmapped: Math.max(0, prev.mappingStatus.unmapped - createdSet.size),
},
}
})
// Also refresh BAS accounts list
const accountsRes = await fetch('/api/bookkeeping/accounts')
if (accountsRes.ok) {
const accountsData = await accountsRes.json()
setBasAccounts(accountsData.data || [])
}
} catch (err) {
toast({ title: 'Kunde inte skapa konton', description: err instanceof Error ? err.message : 'Försök igen.', variant: 'destructive' })
} finally {
setIsCreatingAccounts(false)
}
}, [missingAccounts, toast])
const handleExecuteImport = useCallback(async (options: ImportExecuteOptions) => {
if (!file) { setError('No file selected'); return }
setIsLoading(true)
setError(null)
try {
const formData = new FormData()
formData.append('file', file)
formData.append('mappings', JSON.stringify(mappings))
formData.append('options', JSON.stringify(options))
const res = await fetch('/api/import/sie/execute', { method: 'POST', body: formData })
const data = await res.json()
if (!res.ok) {
if (data.error === 'duplicate') {
setError(data.message || 'Denna fil har redan importerats')
toast({ title: 'Filen har redan importerats', description: data.message, variant: 'destructive' })
return
}
if (data.result) {
setImportResult(data.result)
} else {
const msg = data.message || data.error || 'Importen misslyckades.'
setError(msg)
toast({ title: 'Import misslyckades', description: msg, variant: 'destructive' })
return
}
} else {
setImportResult(data.result)
}
setStep('result')
if (data.result?.success) {
const created = data.result.journalEntriesCreated
const skipped = data.result.details?.skippedVouchers?.total || 0
toast({
title: 'Import genomförd',
description: `${created} verifikationer skapades${skipped > 0 ? ` (${skipped} hoppades över)` : ''}`,
})
} else if (data.result && !data.result.success) {
toast({
title: 'Import slutförd med problem',
description: `${data.result.errors?.length || 0} fel uppstod under importen. Se resultatet för detaljer.`,
variant: 'destructive',
})
}
} catch (err) {
const isNetworkError = err instanceof TypeError && (err.message === 'Failed to fetch' || err.message.includes('NetworkError'))
const msg = isNetworkError
? 'Tappade anslutningen till servern under importen. Kontrollera din internetanslutning och se om importen genomfördes under Bokföring.'
: err instanceof Error ? err.message : 'Ett oväntat fel uppstod.'
setError(msg)
toast({ title: 'Import avbröts', description: msg, variant: 'destructive' })
} finally {
setIsLoading(false)
}
}, [file, mappings, toast])
const goToStep = (targetStep: ImportWizardStep) => { setStep(targetStep); setError(null); setValidationErrors([]); setValidationWarnings([]) }
const goBack = () => { const i = sieSteps.indexOf(step); if (i > 0) setStep(sieSteps[i - 1]) }
const handleNewImport = () => {
setStep('upload'); setFile(null); setParsed(null); setMappings([])
setPreview(null); setIssues([]); setImportResult(null); setError(null); setErrorType(undefined)
setValidationErrors([]); setValidationWarnings([]); setDuplicateImportId(null)
setSieAccounts([]); setIsCreatingAccounts(false)
}
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}/{sieSteps.length}: {SIE_STEP_LABELS[step]}
</span>
{sieSteps.map((s, i) => (
<span key={s} className={cn(
'hidden sm:inline',
i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground'
)}>
{SIE_STEP_LABELS[s]}
</span>
))}
</div>
<Progress value={progress} className="h-2" />
</div>
</CardContent>
</Card>
{step === 'upload' && <SIEUploadStep onFileSelect={handleFileSelect} isLoading={isLoading} error={error} errorType={errorType} validationErrors={validationErrors} validationWarnings={validationWarnings} duplicateImportId={duplicateImportId} onReplace={handleReplace} isReplacing={isReplacing} />}
{step === 'preview' && preview && (
<SIEPreviewStep preview={preview} issues={issues} missingAccounts={missingAccounts}
onCreateAccounts={handleCreateAccounts} isCreatingAccounts={isCreatingAccounts}
onContinue={() => goToStep(hasUnmapped ? 'mapping' : 'review')} onBack={goBack} />
)}
{step === 'mapping' && (
<AccountMappingStep mappings={mappings} basAccounts={basAccounts}
onMappingChange={handleMappingChange} onContinue={() => goToStep('review')} onBack={goBack} />
)}
{step === 'review' && preview && (
<ImportReviewStep preview={preview} mappings={mappings}
onExecute={handleExecuteImport} onBack={goBack} isLoading={isLoading} />
)}
{step === 'result' && importResult && <ImportResultStep result={importResult} onNewImport={handleNewImport} />}
</div>
)
}
// ============================================================
// Opening Balance Flow (entity = "opening_balance" inside CSVDataImportWizard)
// ============================================================
type OpeningBalanceStep = 'upload' | 'column_mapping' | 'edit' | 'period' | 'result'
const OB_STEP_LABELS: Record<OpeningBalanceStep, string> = {
upload: 'Ladda upp',
column_mapping: 'Kolumnmappning',
edit: 'Granska',
period: 'Period',
result: 'Resultat',
}
function OpeningBalanceFlow() {
const { toast } = useToast()
const [obStep, setObStep] = useState<OpeningBalanceStep>('upload')
const [obIsLoading, setObIsLoading] = useState(false)
const [obError, setObError] = useState<string | null>(null)
const [obFile, setObFile] = useState<File | null>(null)
const [parseResult, setParseResult] = useState<OpeningBalanceParseResult | null>(null)
const [editedRows, setEditedRows] = useState<{
id: string; account_number: string; account_name: string
debit_amount: number; credit_amount: number
}[]>([])
const [executeResult, setExecuteResult] = useState<OpeningBalanceExecuteResult | null>(null)
// Determine steps — skip column mapping if confidence >= 0.8
const needsMapping = parseResult && parseResult.detected_columns.confidence < 0.8
const steps: OpeningBalanceStep[] = needsMapping
? ['upload', 'column_mapping', 'edit', 'period', 'result']
: ['upload', 'edit', 'period', 'result']
const currentStepIndex = steps.indexOf(obStep)
const progress = ((currentStepIndex + 1) / steps.length) * 100
const handleFileSelect = useCallback(async (file: File) => {
setObError(null)
setObIsLoading(true)
setObFile(file)
try {
const formData = new FormData()
formData.append('file', file)
const res = await fetch('/api/import/opening-balance/parse', {
method: 'POST',
body: formData,
})
const data = await res.json()
if (!res.ok) {
setObError(data.error || 'Kunde inte läsa filen')
return
}
const result: OpeningBalanceParseResult = data.data
setParseResult(result)
if (result.rows.length === 0) {
setObError('Inga konton med belopp hittades i filen. Kontrollera att filen innehåller kontonummer och belopp.')
return
}
toast({
title: 'Fil analyserad',
description: `${result.rows.length} konton hittades`,
})
// Skip column mapping if confidence >= 0.8
if (result.detected_columns.confidence < 0.8) {
setObStep('column_mapping')
} else {
setObStep('edit')
}
} catch (err) {
setObError(err instanceof Error ? err.message : 'Kunde inte läsa filen')
} finally {
setObIsLoading(false)
}
}, [toast])
const handleColumnMappingConfirm = useCallback(async (columns: DetectedColumns) => {
if (!obFile) return
setObIsLoading(true)
setObError(null)
try {
const formData = new FormData()
formData.append('file', obFile)
formData.append('column_overrides', JSON.stringify(columns))
const res = await fetch('/api/import/opening-balance/parse', {
method: 'POST',
body: formData,
})
const data = await res.json()
if (!res.ok) {
setObError(data.error || 'Kunde inte läsa filen med de valda kolumnerna')
return
}
setParseResult(data.data)
setObStep('edit')
} catch (err) {
setObError(err instanceof Error ? err.message : 'Kunde inte läsa filen')
} finally {
setObIsLoading(false)
}
}, [obFile])
const handleEditContinue = useCallback((rows: typeof editedRows) => {
setEditedRows(rows)
setObStep('period')
}, [])
const handleExecute = useCallback(async (fiscalPeriodId: string) => {
setObIsLoading(true)
setObError(null)
try {
const res = await fetch('/api/import/opening-balance/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
fiscal_period_id: fiscalPeriodId,
lines: editedRows.map((r) => ({
account_number: r.account_number,
debit_amount: r.debit_amount,
credit_amount: r.credit_amount,
})),
}),
})
const data = await res.json()
if (!res.ok) {
if (res.status === 409) {
setObError(data.error || 'Perioden har redan ingående balanser')
} else {
setObError(data.error || 'Importen misslyckades')
}
return
}
setExecuteResult(data.data)
setObStep('result')
if (data.data.success) {
toast({
title: 'Ingående balanser bokförda',
description: `${data.data.lines_created} kontorader skapades`,
})
}
} catch (err) {
setObError(err instanceof Error ? err.message : 'Importen misslyckades')
} finally {
setObIsLoading(false)
}
}, [editedRows, toast])
const handleNewImport = () => {
setObStep('upload')
setObFile(null)
setParseResult(null)
setEditedRows([])
setExecuteResult(null)
setObError(null)
}
return (
<div className="space-y-6">
{/* Progress */}
<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}: {OB_STEP_LABELS[obStep]}
</span>
{steps.map((s, i) => (
<span
key={s}
className={cn(
'hidden sm:inline',
i <= currentStepIndex ? 'text-primary font-medium' : 'text-muted-foreground',
)}
>
{OB_STEP_LABELS[s]}
</span>
))}
</div>
<Progress value={progress} className="h-2" />
</div>
</CardContent>
</Card>
{/* Step content */}
{obStep === 'upload' && (
<OpeningBalanceUploadStep
onFileSelect={handleFileSelect}
isLoading={obIsLoading}
error={obError}
/>
)}
{obStep === 'column_mapping' && parseResult && (
<OpeningBalanceColumnMappingStep
headers={parseResult.headers}
previewRows={parseResult.preview_rows}
detectedColumns={parseResult.detected_columns}
onConfirm={handleColumnMappingConfirm}
onBack={() => setObStep('upload')}
/>
)}
{obStep === 'edit' && parseResult && (
<OpeningBalanceEditStep
rows={parseResult.rows}
onContinue={handleEditContinue}
onBack={() => {
if (needsMapping) {
setObStep('column_mapping')
} else {
setObStep('upload')
}
}}
/>
)}
{obStep === 'period' && (
<OpeningBalancePeriodStep
rows={editedRows}
onExecute={handleExecute}
onBack={() => setObStep('edit')}
isLoading={obIsLoading}
error={obError}
/>
)}
{obStep === 'result' && executeResult && (
<OpeningBalanceResultStep
result={executeResult}
onNewImport={handleNewImport}
/>
)}
</div>
)
}
// ============================================================
// Customers Flow (entity = "customers" inside CSVDataImportWizard)
// ============================================================
type RegisterStep = 'upload' | 'column_mapping' | 'edit' | 'result'
const REGISTER_STEP_LABELS: Record<RegisterStep, string> = {
upload: 'Ladda upp',
column_mapping: 'Kolumnmappning',
edit: 'Granska',
result: 'Resultat',
}
const CUSTOMER_COLUMN_SPECS: RegisterColumnSpec<keyof DetectedCustomerColumns>[] = [
{ key: 'name_col', label: 'Namn', required: true },
{ key: 'org_number_col', label: 'Org-/personnummer', required: false },
{ key: 'customer_type_col', label: 'Kundtyp', required: false },
{ key: 'email_col', label: 'E-post', required: false },
{ key: 'phone_col', label: 'Telefon', required: false },
{ key: 'address_line1_col', label: 'Adress', required: false },
{ key: 'address_line2_col', label: 'Adress rad 2', required: false },
{ key: 'postal_code_col', label: 'Postnummer', required: false },
{ key: 'city_col', label: 'Ort', required: false },
{ key: 'country_col', label: 'Land', required: false },
{ key: 'vat_number_col', label: 'VAT-nummer', required: false },
{ key: 'payment_terms_col', label: 'Betalningsvillkor (dagar)', required: false },
{ key: 'notes_col', label: 'Anteckning', required: false },
]
function columnsToMapping<K extends string>(
cols: { readonly [key: string]: unknown },
specs: RegisterColumnSpec<K>[],
): Record<K, number | null> {
const out = {} as Record<K, number | null>
for (const spec of specs) {
const v = cols[spec.key as string]
out[spec.key] = typeof v === 'number' ? v : null
}
return out
}
function CustomersFlow() {
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<CustomerImportParseResult | 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/customers/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 CustomerImportParseResult
setParseResult(result)
if (result.rows.length === 0) {
setError('Inga giltiga kundrader hittades. Kontrollera att filen innehåller en namnkolumn.')
return
}
toast({
title: 'Fil analyserad',
description: `${result.rows.length} kunder 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 DetectedCustomerColumns, number | null>,
) => {
if (!file) return
setIsLoading(true)
setError(null)
try {
const overrides: DetectedCustomerColumns = {
name_col: mapping.name_col ?? 0,
org_number_col: mapping.org_number_col,
customer_type_col: mapping.customer_type_col,
email_col: mapping.email_col,
phone_col: mapping.phone_col,
address_line1_col: mapping.address_line1_col,
address_line2_col: mapping.address_line2_col,
postal_code_col: mapping.postal_code_col,
city_col: mapping.city_col,
country_col: mapping.country_col,
vat_number_col: mapping.vat_number_col,
payment_terms_col: mapping.payment_terms_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/customers/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: AnnotatedCustomerRow[],
updateDuplicates: boolean,
) => {
setIsLoading(true)
setError(null)
try {
const res = await fetch('/api/import/customers/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
rows: rows.map(({ duplicate_match: _dup, is_valid: _v, validation_errors: _ve, ...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 ? 'Kunder 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 DetectedCustomerColumns>(parseResult.detected_columns as unknown as { [key: string]: unknown }, CUSTOMER_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="customers"
onFileSelect={handleFileSelect}
isLoading={isLoading}
error={error}
/>
)}
{step === 'column_mapping' && parseResult && initialMapping && (
<RegisterColumnMappingStep<keyof DetectedCustomerColumns>
headers={parseResult.headers}
previewRows={parseResult.preview_rows}
specs={CUSTOMER_COLUMN_SPECS}
initial={initialMapping}
onConfirm={handleColumnMappingConfirm}
onBack={() => setStep('upload')}
/>
)}
{step === 'edit' && parseResult && (
<CustomersEditStep
rows={parseResult.rows}
onExecute={handleExecute}
onBack={() => setStep(needsMapping ? 'column_mapping' : 'upload')}
isLoading={isLoading}
error={error}
/>
)}
{step === 'result' && executeResult && (
<RegisterResultStep
entity="customers"
result={executeResult}
onNewImport={handleNewImport}
/>
)}
</div>
)
}
// ============================================================
// Suppliers Flow (entity = "suppliers" inside CSVDataImportWizard)
// ============================================================
const SUPPLIER_COLUMN_SPECS: RegisterColumnSpec<keyof DetectedSupplierColumns>[] = [
{ key: 'name_col', label: 'Namn', required: true },
{ key: 'org_number_col', label: 'Org-/personnummer', required: false },
{ key: 'supplier_type_col', label: 'Leverantörstyp', required: false },
{ key: 'email_col', label: 'E-post', required: false },
{ key: 'phone_col', label: 'Telefon', required: false },
{ key: 'address_line1_col', label: 'Adress', required: false },
{ key: 'address_line2_col', label: 'Adress rad 2', required: false },
{ key: 'postal_code_col', label: 'Postnummer', required: false },
{ key: 'city_col', label: 'Ort', required: false },
{ key: 'country_col', label: 'Land', required: false },
{ key: 'vat_number_col', label: 'VAT-nummer', required: false },
{ key: 'bankgiro_col', label: 'Bankgiro', required: false },
{ key: 'plusgiro_col', label: 'Plusgiro', required: false },
{ key: 'bank_account_col', label: 'Bankkonto', required: false },
{ key: 'iban_col', label: 'IBAN', required: false },
{ key: 'bic_col', label: 'BIC/SWIFT', required: false },
{ key: 'payment_terms_col', label: 'Betalningsvillkor (dagar)', required: false },
{ key: 'default_currency_col', label: 'Valuta', required: false },
{ key: 'notes_col', label: 'Anteckning', required: false },
]
function SuppliersFlow() {
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<SupplierImportParseResult | 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/suppliers/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 SupplierImportParseResult
setParseResult(result)
if (result.rows.length === 0) {
setError('Inga giltiga leverantörsrader hittades. Kontrollera att filen innehåller en namnkolumn.')
return
}
toast({
title: 'Fil analyserad',
description: `${result.rows.length} leverantörer 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 DetectedSupplierColumns, number | null>,
) => {
if (!file) return
setIsLoading(true)
setError(null)
try {
const overrides: DetectedSupplierColumns = {
name_col: mapping.name_col ?? 0,
org_number_col: mapping.org_number_col,
supplier_type_col: mapping.supplier_type_col,
email_col: mapping.email_col,
phone_col: mapping.phone_col,
address_line1_col: mapping.address_line1_col,
address_line2_col: mapping.address_line2_col,
postal_code_col: mapping.postal_code_col,
city_col: mapping.city_col,
country_col: mapping.country_col,
vat_number_col: mapping.vat_number_col,
bankgiro_col: mapping.bankgiro_col,
plusgiro_col: mapping.plusgiro_col,
bank_account_col: mapping.bank_account_col,
iban_col: mapping.iban_col,
bic_col: mapping.bic_col,
payment_terms_col: mapping.payment_terms_col,
default_currency_col: mapping.default_currency_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/suppliers/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')
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: AnnotatedSupplierRow[],
updateDuplicates: boolean,
) => {
setIsLoading(true)
setError(null)
try {
const res = await fetch('/api/import/suppliers/execute', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
rows: rows.map(({ duplicate_match: _dup, is_valid: _v, validation_errors: _ve, ...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 ? 'Leverantörer 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 DetectedSupplierColumns>(parseResult.detected_columns as unknown as { [key: string]: unknown }, SUPPLIER_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="suppliers"
onFileSelect={handleFileSelect}
isLoading={isLoading}
error={error}
/>
)}
{step === 'column_mapping' && parseResult && initialMapping && (
<RegisterColumnMappingStep<keyof DetectedSupplierColumns>
headers={parseResult.headers}
previewRows={parseResult.preview_rows}
specs={SUPPLIER_COLUMN_SPECS}
initial={initialMapping}
onConfirm={handleColumnMappingConfirm}
onBack={() => setStep('upload')}
/>
)}
{step === 'edit' && parseResult && (
<SuppliersEditStep
rows={parseResult.rows}
onExecute={handleExecute}
onBack={() => setStep(needsMapping ? 'column_mapping' : 'upload')}
isLoading={isLoading}
error={error}
/>
)}
{step === 'result' && executeResult && (
<RegisterResultStep
entity="suppliers"
result={executeResult}
onNewImport={handleNewImport}
/>
)}
</div>
)
}
// ============================================================
// CSV/Excel Data Import Wizard — entity selector + sub-flow
// ============================================================
type CSVDataEntity = 'opening_balance' | 'customers' | 'suppliers'
const ENTITY_OPTIONS: { value: CSVDataEntity; label: string }[] = [
{ value: 'opening_balance', label: 'Ingående balanser' },
{ value: 'customers', label: 'Kunder' },
{ value: 'suppliers', label: 'Leverantörer' },
]
function CSVDataImportWizard() {
const [entity, setEntity] = useState<CSVDataEntity | null>('opening_balance')
return (
<div className="space-y-6">
<div className="flex flex-wrap gap-3">
{ENTITY_OPTIONS.map((opt) => {
const selected = entity === opt.value
return (
<div key={opt.value} className="relative">
{selected && (
<svg
aria-hidden
className="pointer-events-none absolute -inset-[3px] h-[calc(100%+6px)] w-[calc(100%+6px)] overflow-visible"
>
<motion.rect
x="1"
y="1"
width="calc(100% - 2px)"
height="calc(100% - 2px)"
rx="8"
ry="8"
fill="none"
stroke="currentColor"
strokeWidth="1.25"
strokeDasharray="3 4"
className="text-foreground/45"
animate={{ strokeDashoffset: [0, -14] }}
transition={{ duration: 1.2, repeat: Infinity, ease: 'linear' }}
/>
</svg>
)}
<button
type="button"
onClick={() => setEntity(opt.value)}
aria-pressed={selected}
className={cn(
'relative h-9 rounded-md border px-4 text-sm font-medium transition-colors',
selected
? 'border-foreground bg-foreground text-background'
: 'border-border bg-card text-foreground hover:border-foreground/30 hover:bg-muted',
)}
>
{opt.label}
</button>
</div>
)
})}
</div>
{entity === 'opening_balance' && <OpeningBalanceFlow key="ob-flow" />}
{entity === 'customers' && <CustomersFlow key="cust-flow" />}
{entity === 'suppliers' && <SuppliersFlow key="supp-flow" />}
</div>
)
}
// ============================================================
// PSD2 Bank Connection (inline, from Enable Banking extension)
// ============================================================
function PSD2ConnectWizard() {
const { toast } = useToast()
const supabase = createClient()
const { dialogProps, confirm } = useDestructiveConfirm()
const { company } = useCompany()
const [bankConnections, setBankConnections] = useState<BankConnection[]>([])
const [syncingConnectionId, setSyncingConnectionId] = useState<string | null>(null)
const [isConnecting, setIsConnecting] = useState(false)
const [connectingBankName, setConnectingBankName] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(true)
useEffect(() => {
fetchConnections()
}, [])
async function fetchConnections() {
setIsLoading(true)
const { data: { user } } = await supabase.auth.getUser()
if (!user) return
if (!company) return
const { data: connections } = await supabase
.from('bank_connections')
.select('*')
.eq('company_id', company.id)
.order('created_at', { ascending: false })
setBankConnections(connections || [])
setIsLoading(false)
}
async function handleConnectBank(bank: Bank) {
setIsConnecting(true)
setConnectingBankName(bank.name)
try {
const response = await fetch('/api/extensions/ext/enable-banking/connect', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ aspsp_name: bank.name, aspsp_country: bank.country }),
})
const data = await response.json()
if (!response.ok) {
throw new Error(data.error)
}
window.location.href = data.authorization_url
} catch (error) {
toast({
title: 'Kunde inte ansluta bank',
description: error instanceof Error ? error.message : 'Försök igen.',
variant: 'destructive',
})
setIsConnecting(false)
setConnectingBankName(null)
}
}
async function handleSyncTransactions(connectionId: string) {
setSyncingConnectionId(connectionId)
try {
const response = await fetch('/api/extensions/ext/enable-banking/sync', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ connection_id: connectionId }),
})
const data = await response.json()
if (!response.ok) {
throw new Error(data.error)
}
toast({
title: 'Synkronisering klar',
description: `${data.imported} nya transaktioner importerade`,
})
fetchConnections()
} catch (error) {
toast({
title: 'Synkronisering misslyckades',
description: error instanceof Error ? error.message : 'Försök igen.',
variant: 'destructive',
})
}
setSyncingConnectionId(null)
}
async function handleDisconnectBank(connectionId: string) {
const ok = await confirm({
title: 'Koppla bort bank?',
description: 'PSD2-samtycket kommer återkallas. Befintliga transaktioner påverkas inte.',
confirmLabel: 'Koppla bort',
variant: 'warning',
})
if (!ok) return
try {
const response = await fetch('/api/extensions/ext/enable-banking/disconnect', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ connection_id: connectionId }),
})
if (!response.ok) {
const data = await response.json()
throw new Error(data.error || 'Disconnect failed')
}
toast({
title: 'Bank bortkopplad',
description: 'Bankanslutningen och PSD2-samtycket har återkallats',
})
fetchConnections()
} catch (error) {
toast({
title: 'Kunde inte koppla bort bank',
description: error instanceof Error ? error.message : 'Försök igen.',
variant: 'destructive',
})
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center h-32">
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
</div>
)
}
const activeConnections = bankConnections.filter((c) => c.status === 'active')
return (
<div className="space-y-6">
<DestructiveConfirmDialog {...dialogProps} />
{/* Connected banks */}
{activeConnections.length > 0 && (
<Card>
<CardHeader>
<CardTitle>Anslutna banker</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{activeConnections.map((connection) => (
<BankConnectionStatus
key={connection.id}
connection={connection}
onSync={handleSyncTransactions}
onDisconnect={handleDisconnectBank}
isSyncing={syncingConnectionId === connection.id}
/>
))}
</CardContent>
</Card>
)}
{/* Connect new bank */}
<Card>
<CardHeader>
<CardTitle>Anslut din bank</CardTitle>
<CardDescription>
Välj din bank nedan för att koppla ditt konto via PSD2. Transaktioner synkas automatiskt varje dag.
</CardDescription>
</CardHeader>
<CardContent>
<BankSelector
onConnect={handleConnectBank}
isConnecting={isConnecting}
connectingBankName={connectingBankName}
/>
</CardContent>
</Card>
</div>
)
}
// ============================================================
// Import Page with Selection Cards
// ============================================================
type ImportMode = null | 'psd2' | 'bank' | 'sie' | 'csv_data' | 'migration'
export default function ImportPage() {
const { company } = useCompany()
const [mode, setMode] = useState<ImportMode>(null)
const [userId, setUserId] = useState('')
const [isSandbox, setIsSandbox] = useState(false)
// Fetch authenticated user ID and sandbox status
useEffect(() => {
const supabase = createClient()
supabase.auth.getUser().then(({ data: { user } }) => {
if (!user) return
setUserId(user.id)
if (!company) return
supabase
.from('company_settings')
.select('is_sandbox')
.eq('company_id', company.id)
.single()
.then(({ data }) => {
if (data?.is_sandbox) setIsSandbox(true)
})
})
}, [])
// Sync mode from URL search params (reacts to client-side navigation changes)
const searchParams = useSearchParams()
useEffect(() => {
if (isSandbox) return
if (searchParams.get('migration')) {
setMode('migration')
} else {
const modeParam = searchParams.get('mode')
if (modeParam && ['psd2', 'bank', 'sie', 'csv_data', 'migration'].includes(modeParam)) {
setMode(modeParam as ImportMode)
}
}
}, [isSandbox, searchParams])
// Extensions are active if compiled in — no runtime toggle check needed
const hasBankingExtension = ENABLED_EXTENSION_IDS.has('enable-banking')
const hasMigrationExtension = ENABLED_EXTENSION_IDS.has('arcim-migration')
return (
<div className="space-y-6">
{/* Header */}
<div>
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">Importera</h1>
<p className="text-muted-foreground">
Importera banktransaktioner eller bokföringsdata till ditt företag
</p>
</div>
{mode === null && (
<>
{isSandbox && (
<div className="flex items-start gap-3 rounded-lg border border-border bg-muted/50 px-4 py-3">
<Info className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
<p className="text-sm text-muted-foreground">
Import är inte tillgängligt i sandlådemiljön. Skapa ett konto för att importera data.
</p>
</div>
)}
<div className="space-y-2">
{/* 1. Koppla bank */}
{hasBankingExtension && (
<div
role="button"
tabIndex={isSandbox ? -1 : 0}
aria-disabled={isSandbox}
className={cn(
'group flex items-start gap-4 rounded-lg border bg-card p-5 transition-all',
isSandbox
? 'opacity-50 cursor-not-allowed'
: 'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
)}
onClick={() => { if (!isSandbox) setMode('psd2') }}
onKeyDown={(e) => { if (!isSandbox && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setMode('psd2') } }}
>
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-foreground/[0.06]">
<Landmark className="h-[18px] w-[18px] text-foreground/60" />
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2.5">
<h3 className="text-[15px] font-semibold leading-tight">Koppla bank</h3>
<span className="text-[11px] font-medium text-success bg-success/10 px-2 py-0.5 rounded-full leading-none">
Rekommenderat
</span>
</div>
<p className="text-sm text-muted-foreground mt-1.5 leading-relaxed max-w-lg">
Anslut ditt bankkonto direkt och synka transaktioner automatiskt via PSD2.
</p>
</div>
<ChevronRight className="h-4 w-4 text-muted-foreground/40 shrink-0 mt-2.5 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-muted-foreground" />
</div>
)}
{/* 2. Hämta från annat system */}
{hasMigrationExtension === true && (
<div
role="button"
tabIndex={isSandbox ? -1 : 0}
aria-disabled={isSandbox}
className={cn(
'group rounded-lg border bg-card p-5 transition-all',
isSandbox
? 'opacity-50 cursor-not-allowed'
: 'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
)}
onClick={() => { if (!isSandbox) setMode('migration') }}
onKeyDown={(e) => { if (!isSandbox && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setMode('migration') } }}
>
<div className="flex items-start gap-4">
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-foreground/[0.06]">
<ArrowRightLeft className="h-[18px] w-[18px] text-foreground/60" />
</div>
<div className="flex-1 min-w-0">
<h3 className="text-[15px] font-semibold leading-tight">Hämta från annat system</h3>
<p className="text-sm mt-1.5 leading-relaxed max-w-lg underline decoration-foreground/20 underline-offset-2 text-muted-foreground">
Inget ändras i ditt befintliga system.
</p>
</div>
<ChevronRight className="h-4 w-4 text-muted-foreground/40 shrink-0 mt-2.5 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-muted-foreground" />
</div>
<div className="flex flex-wrap gap-2 mt-3.5 ml-[52px]">
{([
{ name: 'Fortnox', logo: '/logos/fortnox.svg' },
{ name: 'Visma', logo: '/logos/visma.jpeg' },
{ name: 'Bokio', logo: '/logos/bokio.png' },
{ name: 'Björn Lundén', logo: '/logos/bjornlunden.png' },
{ name: 'Briox', logo: '/logos/Briox_logo.png' },
] as const).map(provider => (
<div key={provider.name} className="flex items-center gap-1.5 rounded border border-border/60 bg-muted/30 px-2 py-1">
<img src={provider.logo} alt={provider.name} className="h-4 w-4 shrink-0 rounded-sm object-contain" />
<span className="text-[11px] font-medium text-muted-foreground">{provider.name}</span>
</div>
))}
</div>
</div>
)}
{/* 3. Banktransaktioner */}
<div
role="button"
tabIndex={isSandbox ? -1 : 0}
aria-disabled={isSandbox}
className={cn(
'group flex items-start gap-4 rounded-lg border bg-card p-5 transition-all',
isSandbox
? 'opacity-50 cursor-not-allowed'
: 'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
)}
onClick={() => { if (!isSandbox) setMode('bank') }}
onKeyDown={(e) => { if (!isSandbox && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setMode('bank') } }}
>
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-foreground/[0.06]">
<ArrowLeftRight className="h-[18px] w-[18px] text-foreground/60" />
</div>
<div className="flex-1 min-w-0">
<h3 className="text-[15px] font-semibold leading-tight">Banktransaktioner</h3>
<p className="text-sm text-muted-foreground mt-1.5 leading-relaxed max-w-lg">
Importera kontoutdrag från din bank. Stöder de flesta svenska banker.
</p>
<div className="flex flex-wrap gap-1.5 mt-2.5">
{['CSV', 'OFX', 'SEB', 'Swedbank', 'Nordea'].map(fmt => (
<span key={fmt} className="text-[11px] text-muted-foreground/80 bg-muted/80 px-1.5 py-0.5 rounded leading-none">
{fmt}
</span>
))}
</div>
</div>
<ChevronRight className="h-4 w-4 text-muted-foreground/40 shrink-0 mt-2.5 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-muted-foreground" />
</div>
{/* 4. CSV/Excel-data (ingående balanser, kunder, leverantörer) */}
<div
role="button"
tabIndex={isSandbox ? -1 : 0}
aria-disabled={isSandbox}
className={cn(
'group flex items-start gap-4 rounded-lg border bg-card p-5 transition-all',
isSandbox
? 'opacity-50 cursor-not-allowed'
: 'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
)}
onClick={() => { if (!isSandbox) setMode('csv_data') }}
onKeyDown={(e) => { if (!isSandbox && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setMode('csv_data') } }}
>
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-foreground/[0.06]">
<FileSpreadsheet className="h-[18px] w-[18px] text-foreground/60" />
</div>
<div className="flex-1 min-w-0">
<h3 className="text-[15px] font-semibold leading-tight">Importera CSV/Excel-data</h3>
<p className="text-sm text-muted-foreground mt-1.5 leading-relaxed max-w-lg">
Importera ingående balanser, kunder eller leverantörer.
</p>
<div className="flex flex-wrap gap-1.5 mt-2.5">
{['XLSX', 'CSV', 'Ingående balanser', 'Kunder', 'Leverantörer'].map(fmt => (
<span key={fmt} className="text-[11px] text-muted-foreground/80 bg-muted/80 px-1.5 py-0.5 rounded leading-none">
{fmt}
</span>
))}
</div>
</div>
<ChevronRight className="h-4 w-4 text-muted-foreground/40 shrink-0 mt-2.5 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-muted-foreground" />
</div>
{/* 5. Bokföringsdata (SIE) */}
<div
role="button"
tabIndex={isSandbox ? -1 : 0}
aria-disabled={isSandbox}
className={cn(
'group flex items-start gap-4 rounded-lg border bg-card p-5 transition-all',
isSandbox
? 'opacity-50 cursor-not-allowed'
: 'cursor-pointer hover:border-foreground/15 hover:shadow-[var(--shadow-sm)] active:scale-[0.998]'
)}
onClick={() => { if (!isSandbox) setMode('sie') }}
onKeyDown={(e) => { if (!isSandbox && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); setMode('sie') } }}
>
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-foreground/[0.06]">
<FileText className="h-[18px] w-[18px] text-foreground/60" />
</div>
<div className="flex-1 min-w-0">
<h3 className="text-[15px] font-semibold leading-tight">Bokföringsdata (SIE)</h3>
<p className="text-sm text-muted-foreground mt-1.5 leading-relaxed max-w-lg">
Importera verifikationer och kontoplan från ett annat bokföringsprogram.
</p>
<div className="flex flex-wrap gap-1.5 mt-2.5">
{['SIE4', '.se', '.si'].map(fmt => (
<span key={fmt} className="text-[11px] text-muted-foreground/80 bg-muted/80 px-1.5 py-0.5 rounded leading-none">
{fmt}
</span>
))}
</div>
</div>
<ChevronRight className="h-4 w-4 text-muted-foreground/40 shrink-0 mt-2.5 transition-transform duration-150 group-hover:translate-x-0.5 group-hover:text-muted-foreground" />
</div>
</div>
</>
)}
{mode !== null && (
<Button variant="ghost" size="sm" onClick={() => setMode(null)}>
<ArrowLeft className="mr-2 h-4 w-4" />
Tillbaka till val
</Button>
)}
{mode === 'psd2' && <PSD2ConnectWizard />}
{mode === 'bank' && <BankFileImportWizard />}
{mode === 'sie' && <SIEImportWizard />}
{mode === 'csv_data' && <CSVDataImportWizard />}
{mode === 'migration' && <MigrationWizard userId={userId} />}
</div>
)
}