feat: add bank file import as core, move Enable Banking to extension
Replace PSD2 bank integration as the default with file-based bank import (CSV/XML), which better suits Swedish sole traders and small companies. Enable Banking is now an opt-in extension. - Phase 1: Extract generic transaction ingestion service (ingest.ts) with dedup, auto-categorization, and OCR-based invoice matching - Phase 2: Bank file parser library supporting Nordea, SEB, Swedbank, Handelsbanken CSV formats and ISO 20022 camt.053 XML - Phase 3: Database migration adding import_source, reference columns and bank_file_imports tracking table - Phase 4: Import wizard UI (5-step flow) and API routes for parse/execute - Phase 5: Move Enable Banking to extensions/enable-banking/ with commented-out loader entry for opt-in activation - Phase 6: 104 new tests (ingestion + all parser formats), fixing Nordea detection overlap and camt.053 XML tag collision bugs Co-Authored-By: Claude Opus 4.6 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
838dc6b8b5
commit
885f362a29
+343
-139
File diff suppressed because it is too large
Load Diff
@@ -47,17 +47,16 @@ export default async function DashboardPage() {
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('user_id', user.id)
|
||||
|
||||
const { count: bankConnectionCount } = await supabase
|
||||
.from('bank_connections')
|
||||
const { count: transactionCount } = await supabase
|
||||
.from('transactions')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('user_id', user.id)
|
||||
.eq('status', 'active')
|
||||
|
||||
const onboardingProgress: OnboardingProgress = {
|
||||
hasCustomers: (customerCount || 0) > 0,
|
||||
hasInvoices: (invoiceCount || 0) > 0,
|
||||
hasReceipts: (receiptCount || 0) > 0,
|
||||
hasBankConnected: (bankConnectionCount || 0) > 0,
|
||||
hasBankConnected: (transactionCount || 0) > 0,
|
||||
}
|
||||
|
||||
// Fetch current year transactions summary
|
||||
|
||||
@@ -11,7 +11,6 @@ import { Badge } from '@/components/ui/badge'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { getDaysUntilExpiry, isConsentExpiringSoon } from '@/lib/banking/enable-banking'
|
||||
import {
|
||||
Loader2,
|
||||
Building,
|
||||
@@ -25,7 +24,6 @@ import {
|
||||
Calendar,
|
||||
} from 'lucide-react'
|
||||
import type { CompanySettings, BankConnection } from '@/types'
|
||||
import { BankSelector, type Bank } from '@/components/banking/BankSelector'
|
||||
import { NotificationSettings } from '@/extensions/push-notifications/NotificationSettings'
|
||||
import { CalendarFeedSettings } from '@/components/settings/CalendarFeedSettings'
|
||||
|
||||
@@ -41,6 +39,7 @@ export default function SettingsPage() {
|
||||
const [bankConnections, setBankConnections] = useState<BankConnection[]>([])
|
||||
const [isSyncing, setIsSyncing] = useState(false)
|
||||
const [isConnecting, setIsConnecting] = useState(false)
|
||||
const [hasBankingExtension, setHasBankingExtension] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetchData()
|
||||
@@ -85,7 +84,8 @@ export default function SettingsPage() {
|
||||
|
||||
setSettings(settingsData)
|
||||
|
||||
// Fetch bank connections
|
||||
// Check if Enable Banking extension is active by testing for bank connections
|
||||
// If there are active connections, show the banking tab
|
||||
const { data: connections } = await supabase
|
||||
.from('bank_connections')
|
||||
.select('*')
|
||||
@@ -94,6 +94,21 @@ export default function SettingsPage() {
|
||||
|
||||
setBankConnections(connections || [])
|
||||
|
||||
// Check if extension API is available (will return banks list if extension is loaded)
|
||||
try {
|
||||
const bankingCheck = await fetch('/api/extensions/enable-banking/callback', {
|
||||
method: 'HEAD',
|
||||
})
|
||||
// The extension route existing means it's deployed - but we also need
|
||||
// to check if there are existing connections to show the tab
|
||||
setHasBankingExtension(
|
||||
(connections && connections.length > 0) || bankingCheck.status !== 404
|
||||
)
|
||||
} catch {
|
||||
// If the extension routes don't exist, only show tab if there are existing connections
|
||||
setHasBankingExtension((connections && connections.length > 0) || false)
|
||||
}
|
||||
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
@@ -150,14 +165,14 @@ export default function SettingsPage() {
|
||||
setIsSaving(false)
|
||||
}
|
||||
|
||||
async function handleConnectBank(bank: Bank) {
|
||||
async function handleConnectBank(bankName: string, bankCountry: string) {
|
||||
setIsConnecting(true)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/banking/connect', {
|
||||
const response = await fetch('/api/extensions/enable-banking/callback', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ aspsp_name: bank.name, aspsp_country: bank.country }),
|
||||
body: JSON.stringify({ aspsp_name: bankName, aspsp_country: bankCountry }),
|
||||
})
|
||||
|
||||
const data = await response.json()
|
||||
@@ -182,7 +197,7 @@ export default function SettingsPage() {
|
||||
setIsSyncing(true)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/banking/sync', {
|
||||
const response = await fetch('/api/extensions/enable-banking/sync/cron', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ connection_id: connectionId }),
|
||||
@@ -247,6 +262,24 @@ export default function SettingsPage() {
|
||||
|
||||
const activeConnections = bankConnections.filter((c) => c.status === 'active')
|
||||
|
||||
// Helper to calculate days until consent expires
|
||||
function getDaysUntilExpiry(expiresAt: string | null): number | null {
|
||||
if (!expiresAt) return null
|
||||
const expiryDate = new Date(expiresAt)
|
||||
const now = new Date()
|
||||
const diffTime = expiryDate.getTime() - now.getTime()
|
||||
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
|
||||
return Math.max(0, diffDays)
|
||||
}
|
||||
|
||||
function isConsentExpiringSoon(expiresAt: string | null): boolean {
|
||||
if (!expiresAt) return false
|
||||
const expiryDate = new Date(expiresAt)
|
||||
const warningDate = new Date()
|
||||
warningDate.setDate(warningDate.getDate() + 7)
|
||||
return expiryDate <= warningDate
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
@@ -262,10 +295,12 @@ export default function SettingsPage() {
|
||||
<Building className="mr-2 h-4 w-4" />
|
||||
Företag
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="banking">
|
||||
<CreditCard className="mr-2 h-4 w-4" />
|
||||
Bank
|
||||
</TabsTrigger>
|
||||
{hasBankingExtension && (
|
||||
<TabsTrigger value="banking">
|
||||
<CreditCard className="mr-2 h-4 w-4" />
|
||||
Bank (PSD2)
|
||||
</TabsTrigger>
|
||||
)}
|
||||
<TabsTrigger value="notifications">
|
||||
<Bell className="mr-2 h-4 w-4" />
|
||||
Aviseringar
|
||||
@@ -469,93 +504,91 @@ export default function SettingsPage() {
|
||||
</form>
|
||||
</TabsContent>
|
||||
|
||||
{/* Banking settings */}
|
||||
<TabsContent value="banking" className="space-y-6">
|
||||
{/* Connected banks */}
|
||||
{activeConnections.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Anslutna banker</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{activeConnections.map((connection) => {
|
||||
const daysUntilExpiry = getDaysUntilExpiry(connection.consent_expires)
|
||||
const isExpiring = isConsentExpiringSoon(connection.consent_expires)
|
||||
{/* Banking settings (only shown when extension is active or connections exist) */}
|
||||
{hasBankingExtension && (
|
||||
<TabsContent value="banking" className="space-y-6">
|
||||
{/* Connected banks */}
|
||||
{activeConnections.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Anslutna banker</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{activeConnections.map((connection) => {
|
||||
const daysUntilExpiry = getDaysUntilExpiry(connection.consent_expires)
|
||||
const isExpiring = isConsentExpiringSoon(connection.consent_expires)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={connection.id}
|
||||
className="flex items-center justify-between p-4 border rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<CreditCard className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{connection.bank_name}</p>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>
|
||||
Senast synkad: {formatDate(connection.last_synced_at || connection.created_at)}
|
||||
</span>
|
||||
{isExpiring && (
|
||||
<Badge variant="warning" className="flex items-center gap-1">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
{daysUntilExpiry} dagar kvar
|
||||
</Badge>
|
||||
)}
|
||||
return (
|
||||
<div
|
||||
key={connection.id}
|
||||
className="flex items-center justify-between p-4 border rounded-lg"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center">
|
||||
<CreditCard className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">{connection.bank_name}</p>
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>
|
||||
Senast synkad: {formatDate(connection.last_synced_at || connection.created_at)}
|
||||
</span>
|
||||
{isExpiring && (
|
||||
<Badge variant="warning" className="flex items-center gap-1">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
{daysUntilExpiry} dagar kvar
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleSyncTransactions(connection.id)}
|
||||
disabled={isSyncing}
|
||||
>
|
||||
{isSyncing ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDisconnectBank(connection.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleSyncTransactions(connection.id)}
|
||||
disabled={isSyncing}
|
||||
>
|
||||
{isSyncing ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => handleDisconnectBank(connection.id)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
)
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Info about PSD2 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Bankintegration (PSD2)</CardTitle>
|
||||
<CardDescription>
|
||||
Automatisk import av transaktioner via PSD2 open banking.
|
||||
Samtycket gäller i 90 dagar och behöver sedan förnyas.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Vi använder säker bankintegration (PSD2). Vi kan endast läsa transaktioner,
|
||||
aldrig flytta pengar. Du kan också importera transaktioner manuellt via
|
||||
bankfiler på importsidan.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Connect new bank */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Anslut bank</CardTitle>
|
||||
<CardDescription>
|
||||
Koppla din bank för att automatiskt importera transaktioner via PSD2
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<BankSelector
|
||||
onSelect={handleConnectBank}
|
||||
isLoading={isConnecting}
|
||||
country="SE"
|
||||
sandbox={true}
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground mt-4">
|
||||
Vi använder säker bankintegration (PSD2). Vi kan endast läsa transaktioner,
|
||||
aldrig flytta pengar.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
{/* Notification settings */}
|
||||
<TabsContent value="notifications">
|
||||
|
||||
@@ -11,7 +11,8 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, Dialog
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { formatCurrency, formatDate } from '@/lib/utils'
|
||||
import { getCategoryDisplayName } from '@/lib/tax/expense-warnings'
|
||||
import { Plus, Search, ArrowLeftRight, ArrowUpRight, ArrowDownRight, Sparkles, Check, FileText, Link2 } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
import { Plus, Search, ArrowLeftRight, ArrowUpRight, ArrowDownRight, Sparkles, Check, FileText, Link2, Upload } from 'lucide-react'
|
||||
import TransactionForm from '@/components/transactions/TransactionForm'
|
||||
import SwipeCategorizationView from '@/components/transactions/SwipeCategorizationView'
|
||||
import type { Transaction, TransactionCategory, CreateTransactionInput, Invoice, Customer } from '@/types'
|
||||
@@ -408,6 +409,12 @@ export default function TransactionsPage() {
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" asChild>
|
||||
<Link href="/import">
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Importera
|
||||
</Link>
|
||||
</Button>
|
||||
{uncategorizedTransactions.length > 0 && (
|
||||
<Button variant="outline" onClick={openSwipeView} disabled={isLoadingSuggestions}>
|
||||
<Sparkles className="mr-2 h-4 w-4" />
|
||||
@@ -492,13 +499,21 @@ export default function TransactionsPage() {
|
||||
<p className="text-muted-foreground text-center mt-1">
|
||||
{searchTerm
|
||||
? 'Inga transaktioner matchar din sökning'
|
||||
: 'Lägg till din första transaktion eller anslut din bank'}
|
||||
: 'Importera transaktioner från din bank eller lägg till manuellt'}
|
||||
</p>
|
||||
{!searchTerm && (
|
||||
<Button className="mt-4" onClick={() => setIsDialogOpen(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Lägg till transaktion
|
||||
</Button>
|
||||
<div className="flex gap-2 mt-4">
|
||||
<Button asChild>
|
||||
<Link href="/import">
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Importera transaktioner
|
||||
</Link>
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => setIsDialogOpen(true)}>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Lägg till manuellt
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { startAuthorization, getASPSPs, type ASPSP } from '@/lib/banking/enable-banking'
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const aspsps = await getASPSPs('SE')
|
||||
|
||||
// Transform to frontend-friendly format
|
||||
const banks = aspsps.map((aspsp: ASPSP) => ({
|
||||
name: aspsp.name,
|
||||
country: aspsp.country,
|
||||
logo: aspsp.logo,
|
||||
bic: aspsp.bic,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ banks })
|
||||
} catch (error) {
|
||||
console.error('Error fetching banks:', error)
|
||||
// Return fallback list
|
||||
return NextResponse.json({
|
||||
banks: [
|
||||
{ name: 'Nordea', country: 'SE', bic: 'NDEASESS' },
|
||||
{ name: 'SEB', country: 'SE', bic: 'ESSESESS' },
|
||||
{ name: 'Swedbank', country: 'SE', bic: 'SWEDSESS' },
|
||||
{ name: 'Handelsbanken', country: 'SE', bic: 'HANDSESS' },
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { aspsp_name, aspsp_country } = await request.json()
|
||||
|
||||
if (!aspsp_name || !aspsp_country) {
|
||||
return NextResponse.json(
|
||||
{ error: 'aspsp_name and aspsp_country are required' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const redirectUrl = `${process.env.NEXT_PUBLIC_APP_URL}/api/banking/callback`
|
||||
|
||||
// Start the authorization flow with Enable Banking
|
||||
const { url, authorization_id } = await startAuthorization(
|
||||
aspsp_name,
|
||||
aspsp_country,
|
||||
redirectUrl,
|
||||
user.id, // state parameter - returned in callback
|
||||
'personal'
|
||||
)
|
||||
|
||||
// Store pending connection in database with authorization_id
|
||||
// Note: session_id will be set after callback receives the code
|
||||
const { data: connection, error } = await supabase
|
||||
.from('bank_connections')
|
||||
.insert({
|
||||
user_id: user.id,
|
||||
provider: `${aspsp_name.toLowerCase().replace(/\s+/g, '-')}-${aspsp_country.toLowerCase()}`,
|
||||
bank_name: aspsp_name,
|
||||
authorization_id,
|
||||
status: 'pending',
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (error) {
|
||||
console.error('Database error:', error)
|
||||
throw new Error('Failed to store connection')
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
connection_id: connection.id,
|
||||
authorization_url: url,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Bank connection error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : 'Connection failed' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { syncAccountTransactions } from '@/lib/banking/sync-transactions'
|
||||
import type { Transaction } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
interface StoredAccount {
|
||||
uid: string
|
||||
iban?: string
|
||||
name?: string
|
||||
currency: string
|
||||
balance?: number
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { connection_id, days_back = 30 } = await request.json()
|
||||
|
||||
// Get the bank connection
|
||||
const { data: connection, error: connectionError } = await supabase
|
||||
.from('bank_connections')
|
||||
.select('*')
|
||||
.eq('id', connection_id)
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
if (connectionError || !connection) {
|
||||
return NextResponse.json({ error: 'Connection not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
if (connection.status !== 'active') {
|
||||
return NextResponse.json({ error: 'Connection is not active' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
const accounts = (connection.accounts_data as StoredAccount[] || []).map(a => ({ ...a }))
|
||||
|
||||
const toDate = new Date().toISOString().split('T')[0]
|
||||
const fromDate = new Date(Date.now() - days_back * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.split('T')[0]
|
||||
|
||||
let totalImported = 0
|
||||
let totalDuplicates = 0
|
||||
|
||||
for (const account of accounts) {
|
||||
const result = await syncAccountTransactions(
|
||||
supabase,
|
||||
user.id,
|
||||
connection.id,
|
||||
account,
|
||||
fromDate,
|
||||
toDate
|
||||
)
|
||||
|
||||
totalImported += result.imported
|
||||
totalDuplicates += result.duplicates
|
||||
}
|
||||
|
||||
// Update connection with new account balances and sync timestamp
|
||||
const syncedAt = new Date().toISOString()
|
||||
await supabase
|
||||
.from('bank_connections')
|
||||
.update({
|
||||
accounts_data: accounts,
|
||||
last_synced_at: syncedAt,
|
||||
})
|
||||
.eq('id', connection.id)
|
||||
|
||||
// Emit event with newly synced transactions
|
||||
if (totalImported > 0) {
|
||||
const { data: syncedTransactions } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.eq('user_id', user.id)
|
||||
.eq('bank_connection_id', connection.id)
|
||||
.gte('created_at', fromDate)
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(totalImported)
|
||||
|
||||
if (syncedTransactions && syncedTransactions.length > 0) {
|
||||
await eventBus.emit({
|
||||
type: 'transaction.synced',
|
||||
payload: { transactions: syncedTransactions as Transaction[], userId: user.id },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
imported: totalImported,
|
||||
duplicates: totalDuplicates,
|
||||
last_synced_at: syncedAt,
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Sync error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : 'Sync failed' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
+9
-22
@@ -1,28 +1,25 @@
|
||||
import { createServiceClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createSession, getAccountBalance, type AccountInfo } from '@/lib/banking/enable-banking'
|
||||
|
||||
interface StoredAccount {
|
||||
uid: string
|
||||
iban?: string
|
||||
name?: string
|
||||
currency: string
|
||||
balance?: number
|
||||
}
|
||||
import { createSession, getAccountBalance, type AccountInfo } from '@/extensions/enable-banking/lib/api-client'
|
||||
import type { StoredAccount } from '@/extensions/enable-banking/types'
|
||||
|
||||
/**
|
||||
* GET /api/extensions/enable-banking/callback
|
||||
*
|
||||
* OAuth callback for Enable Banking PSD2 authorization.
|
||||
* Must be a real Next.js route (not extension handler) because
|
||||
* banks redirect to this URL directly.
|
||||
*/
|
||||
export async function GET(request: Request) {
|
||||
const { searchParams } = new URL(request.url)
|
||||
|
||||
// Enable Banking returns: ?code=XXX&state=user_id or ?error=XXX&error_description=YYY
|
||||
const code = searchParams.get('code')
|
||||
const state = searchParams.get('state') // This is the user_id we passed during authorization
|
||||
const error = searchParams.get('error')
|
||||
const errorDescription = searchParams.get('error_description')
|
||||
|
||||
// Redirect URL for success/error
|
||||
const baseUrl = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
|
||||
|
||||
// Handle errors from bank authorization
|
||||
if (error) {
|
||||
const errorMessage = errorDescription || error
|
||||
console.error('Bank authorization error:', errorMessage)
|
||||
@@ -38,14 +35,10 @@ export async function GET(request: Request) {
|
||||
const supabase = await createServiceClient()
|
||||
|
||||
try {
|
||||
// Create session from authorization code
|
||||
const sessionData = await createSession(code)
|
||||
|
||||
// Extract data from session response
|
||||
const { session_id, accounts, access, aspsp } = sessionData
|
||||
const consentExpiresAt = access.valid_until
|
||||
|
||||
// Get balances for each account
|
||||
const accountsWithBalances: StoredAccount[] = await Promise.all(
|
||||
accounts.map(async (account: AccountInfo) => {
|
||||
try {
|
||||
@@ -70,8 +63,6 @@ export async function GET(request: Request) {
|
||||
})
|
||||
)
|
||||
|
||||
// Find the pending connection for this user
|
||||
// We match by user_id (state) and status='pending'
|
||||
const { data: pendingConnection, error: findError } = await supabase
|
||||
.from('bank_connections')
|
||||
.select('id')
|
||||
@@ -83,7 +74,6 @@ export async function GET(request: Request) {
|
||||
|
||||
if (findError || !pendingConnection) {
|
||||
console.error('Could not find pending connection:', findError)
|
||||
// Create a new connection if no pending one exists
|
||||
const { error: insertError } = await supabase
|
||||
.from('bank_connections')
|
||||
.insert({
|
||||
@@ -102,7 +92,6 @@ export async function GET(request: Request) {
|
||||
throw new Error('Failed to create connection')
|
||||
}
|
||||
} else {
|
||||
// Update the pending connection with session data
|
||||
const { error: updateError } = await supabase
|
||||
.from('bank_connections')
|
||||
.update({
|
||||
@@ -119,7 +108,6 @@ export async function GET(request: Request) {
|
||||
}
|
||||
}
|
||||
|
||||
// Check if the user has completed onboarding to decide redirect target
|
||||
const { data: userSettings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('onboarding_complete')
|
||||
@@ -134,7 +122,6 @@ export async function GET(request: Request) {
|
||||
} catch (error) {
|
||||
console.error('Bank callback error:', error)
|
||||
|
||||
// Try to update connection status to error
|
||||
try {
|
||||
await supabase
|
||||
.from('bank_connections')
|
||||
+4
-17
@@ -1,18 +1,11 @@
|
||||
import { createClient } from '@supabase/supabase-js'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { syncAccountTransactions } from '@/lib/banking/sync-transactions'
|
||||
import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/lib/banking/enable-banking'
|
||||
|
||||
interface StoredAccount {
|
||||
uid: string
|
||||
iban?: string
|
||||
name?: string
|
||||
currency: string
|
||||
balance?: number
|
||||
}
|
||||
import { syncAccountTransactions } from '@/extensions/enable-banking/lib/sync'
|
||||
import { isConsentExpiringSoon, getDaysUntilExpiry } from '@/extensions/enable-banking/lib/api-client'
|
||||
import type { StoredAccount } from '@/extensions/enable-banking/types'
|
||||
|
||||
/**
|
||||
* GET /api/banking/sync/cron
|
||||
* GET /api/extensions/enable-banking/sync/cron
|
||||
* Automatic daily bank transaction sync
|
||||
* Runs at 05:00 UTC (07:00 Swedish time)
|
||||
*
|
||||
@@ -41,7 +34,6 @@ export async function GET(request: Request) {
|
||||
|
||||
const supabase = createClient(supabaseUrl, supabaseServiceKey)
|
||||
|
||||
// Fetch active bank connections, prioritize least recently synced
|
||||
const { data: connections, error: connError } = await supabase
|
||||
.from('bank_connections')
|
||||
.select('*')
|
||||
@@ -71,12 +63,10 @@ export async function GET(request: Request) {
|
||||
|
||||
for (const connection of connections) {
|
||||
try {
|
||||
// Check consent expiry
|
||||
const daysLeft = getDaysUntilExpiry(connection.consent_expires)
|
||||
const isExpired = daysLeft !== null && daysLeft <= 0
|
||||
|
||||
if (isExpired) {
|
||||
// Mark as expired, skip sync
|
||||
await supabase
|
||||
.from('bank_connections')
|
||||
.update({ status: 'expired' })
|
||||
@@ -97,7 +87,6 @@ export async function GET(request: Request) {
|
||||
|
||||
const expiringSoon = isConsentExpiringSoon(connection.consent_expires)
|
||||
|
||||
// Sync last 7 days (daily cron, with overlap for safety)
|
||||
const toDate = new Date().toISOString().split('T')[0]
|
||||
const fromDate = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
@@ -124,7 +113,6 @@ export async function GET(request: Request) {
|
||||
totalErrors += result.errors
|
||||
}
|
||||
|
||||
// Update connection with new account balances and sync timestamp
|
||||
await supabase
|
||||
.from('bank_connections')
|
||||
.update({
|
||||
@@ -154,7 +142,6 @@ export async function GET(request: Request) {
|
||||
errors: 1,
|
||||
status: 'error',
|
||||
})
|
||||
// Continue with other connections
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { ingestTransactions, type RawTransaction } from '@/lib/transactions/ingest'
|
||||
import { generateExternalId } from '@/lib/import/bank-file/parser'
|
||||
import type { ParsedBankTransaction, BankFileFormatId } from '@/lib/import/bank-file/types'
|
||||
import type { Transaction } from '@/types'
|
||||
|
||||
ensureInitialized()
|
||||
|
||||
interface ExecuteRequest {
|
||||
transactions: ParsedBankTransaction[]
|
||||
format: BankFileFormatId
|
||||
filename: string
|
||||
file_hash: string
|
||||
skip_duplicates: boolean
|
||||
auto_categorize: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/import/bank-file/execute
|
||||
*
|
||||
* Executes the import of confirmed bank transactions.
|
||||
* Records import in bank_file_imports, calls ingestTransactions(),
|
||||
* emits transaction.synced event.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const body: ExecuteRequest = await request.json()
|
||||
const { transactions, format, filename, file_hash, skip_duplicates = true, auto_categorize = true } = body
|
||||
|
||||
if (!transactions || transactions.length === 0) {
|
||||
return NextResponse.json({ error: 'No transactions to import' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
// Create import record
|
||||
const { data: importRecord, error: importError } = await supabase
|
||||
.from('bank_file_imports')
|
||||
.upsert({
|
||||
user_id: user.id,
|
||||
filename,
|
||||
file_hash,
|
||||
file_format: format,
|
||||
transaction_count: transactions.length,
|
||||
status: 'processing',
|
||||
date_from: transactions.map(t => t.date).sort()[0] || null,
|
||||
date_to: transactions.map(t => t.date).sort().reverse()[0] || null,
|
||||
}, {
|
||||
onConflict: 'user_id,file_hash',
|
||||
})
|
||||
.select()
|
||||
.single()
|
||||
|
||||
if (importError) {
|
||||
console.error('Failed to create import record:', importError)
|
||||
return NextResponse.json({ error: 'Failed to create import record' }, { status: 500 })
|
||||
}
|
||||
|
||||
// Convert parsed transactions to RawTransaction format
|
||||
const rawTransactions: RawTransaction[] = transactions.map((tx, index) => ({
|
||||
date: tx.date,
|
||||
description: tx.description,
|
||||
amount: tx.amount,
|
||||
currency: tx.currency || 'SEK',
|
||||
external_id: generateExternalId(tx, format, index),
|
||||
reference: tx.reference || null,
|
||||
import_source: format === 'camt053' ? 'camt053' : `csv_${format}`,
|
||||
}))
|
||||
|
||||
// Run ingestion pipeline
|
||||
const ingestResult = await ingestTransactions(supabase, user.id, rawTransactions)
|
||||
|
||||
// Update import record with results
|
||||
await supabase
|
||||
.from('bank_file_imports')
|
||||
.update({
|
||||
imported_count: ingestResult.imported,
|
||||
duplicate_count: ingestResult.duplicates,
|
||||
matched_count: ingestResult.auto_matched_invoices,
|
||||
status: ingestResult.errors > 0 && ingestResult.imported === 0 ? 'failed' : 'completed',
|
||||
error_message: ingestResult.errors > 0
|
||||
? `${ingestResult.errors} transactions failed to import`
|
||||
: null,
|
||||
})
|
||||
.eq('id', importRecord.id)
|
||||
|
||||
// Emit event with newly imported transactions
|
||||
if (ingestResult.imported > 0 && ingestResult.transaction_ids.length > 0) {
|
||||
try {
|
||||
const { data: importedTransactions } = await supabase
|
||||
.from('transactions')
|
||||
.select('*')
|
||||
.in('id', ingestResult.transaction_ids)
|
||||
|
||||
if (importedTransactions && importedTransactions.length > 0) {
|
||||
await eventBus.emit({
|
||||
type: 'transaction.synced',
|
||||
payload: {
|
||||
transactions: importedTransactions as Transaction[],
|
||||
userId: user.id,
|
||||
},
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
// Non-critical event emission
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
import_id: importRecord.id,
|
||||
...ingestResult,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Bank file execute error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : 'Import failed' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { parseBankFile, generateFileHash, detectFileFormat } from '@/lib/import/bank-file/parser'
|
||||
import { decodeFileContent } from '@/lib/import/bank-file/encoding'
|
||||
import type { BankFileFormatId } from '@/lib/import/bank-file/types'
|
||||
|
||||
/**
|
||||
* POST /api/import/bank-file/parse
|
||||
*
|
||||
* Accepts a bank file (CSV/XML) via FormData, auto-detects format,
|
||||
* returns parsed transactions preview with duplicate detection.
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const supabase = await createClient()
|
||||
|
||||
const { data: { user } } = await supabase.auth.getUser()
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const formData = await request.formData()
|
||||
const file = formData.get('file') as File | null
|
||||
const formatOverride = formData.get('format') as BankFileFormatId | null
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: 'No file provided' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Validate file size (10MB max)
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
return NextResponse.json({ error: 'File too large (max 10MB)' }, { status: 400 })
|
||||
}
|
||||
|
||||
try {
|
||||
// Read and decode file content
|
||||
const arrayBuffer = await file.arrayBuffer()
|
||||
const content = decodeFileContent(arrayBuffer)
|
||||
const fileHash = generateFileHash(content)
|
||||
|
||||
// Check if this exact file has been imported before
|
||||
const { data: existingImport } = await supabase
|
||||
.from('bank_file_imports')
|
||||
.select('id, status, imported_count, created_at')
|
||||
.eq('user_id', user.id)
|
||||
.eq('file_hash', fileHash)
|
||||
.single()
|
||||
|
||||
if (existingImport && existingImport.status === 'completed') {
|
||||
return NextResponse.json({
|
||||
error: 'duplicate',
|
||||
message: `Den här filen har redan importerats (${existingImport.imported_count} transaktioner, ${new Date(existingImport.created_at).toLocaleDateString('sv-SE')})`,
|
||||
}, { status: 409 })
|
||||
}
|
||||
|
||||
// Auto-detect or use specified format
|
||||
const detectedFormat = formatOverride
|
||||
? null
|
||||
: detectFileFormat(content, file.name)
|
||||
|
||||
// Parse the file
|
||||
const parseResult = parseBankFile(content, file.name, formatOverride || undefined)
|
||||
|
||||
// Check for existing transactions (duplicate detection for preview)
|
||||
let existingCount = 0
|
||||
if (parseResult.transactions.length > 0) {
|
||||
// Sample check: look for transactions with matching dates and amounts
|
||||
const { count } = await supabase
|
||||
.from('transactions')
|
||||
.select('*', { count: 'exact', head: true })
|
||||
.eq('user_id', user.id)
|
||||
.gte('date', parseResult.date_from || '1970-01-01')
|
||||
.lte('date', parseResult.date_to || '2099-12-31')
|
||||
|
||||
existingCount = count || 0
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
parse_result: parseResult,
|
||||
detected_format: detectedFormat?.id || formatOverride || null,
|
||||
detected_format_name: detectedFormat?.name || parseResult.format_name,
|
||||
file_hash: fileHash,
|
||||
filename: file.name,
|
||||
existing_transaction_count: existingCount,
|
||||
// Return first row headers for generic CSV column mapping
|
||||
headers: parseResult.format === 'generic_csv'
|
||||
? content.split('\n')[0]?.split(',').map(h => h.trim()) || []
|
||||
: null,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Bank file parse error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: error instanceof Error ? error.message : 'Failed to parse file' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
createInvoicePaymentJournalEntry,
|
||||
createInvoiceCashEntry,
|
||||
} from '@/lib/bookkeeping/invoice-entries'
|
||||
import type { Invoice } from '@/types'
|
||||
import type { EntityType, Invoice } from '@/types'
|
||||
|
||||
/**
|
||||
* POST /api/invoices/[id]/mark-paid
|
||||
@@ -70,11 +70,12 @@ export async function POST(
|
||||
// Fetch accounting method
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('accounting_method')
|
||||
.select('accounting_method, entity_type')
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
const accountingMethod = settings?.accounting_method || 'accrual'
|
||||
const entityType = (settings?.entity_type as EntityType) || 'enskild_firma'
|
||||
|
||||
let journalEntryId: string | null = null
|
||||
|
||||
@@ -92,7 +93,8 @@ export async function POST(
|
||||
const journalEntry = await createInvoiceCashEntry(
|
||||
user.id,
|
||||
invoice as Invoice,
|
||||
paymentDate
|
||||
paymentDate,
|
||||
entityType
|
||||
)
|
||||
journalEntryId = journalEntry?.id ?? null
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createInvoiceJournalEntry } from '@/lib/bookkeeping/invoice-entries'
|
||||
import type { Invoice } from '@/types'
|
||||
import type { EntityType, Invoice } from '@/types'
|
||||
|
||||
/**
|
||||
* POST /api/invoices/[id]/mark-sent
|
||||
@@ -59,7 +59,7 @@ export async function POST(
|
||||
// Fetch accounting method
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('accounting_method')
|
||||
.select('accounting_method, entity_type')
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
@@ -71,7 +71,8 @@ export async function POST(
|
||||
try {
|
||||
const journalEntry = await createInvoiceJournalEntry(
|
||||
user.id,
|
||||
invoice as Invoice
|
||||
invoice as Invoice,
|
||||
(settings?.entity_type as EntityType) || 'enskild_firma'
|
||||
)
|
||||
if (journalEntry) {
|
||||
journalEntryId = journalEntry.id
|
||||
|
||||
@@ -164,7 +164,8 @@ export async function POST(
|
||||
try {
|
||||
const journalEntry = await createInvoiceJournalEntry(
|
||||
user.id,
|
||||
invoice as Invoice
|
||||
invoice as Invoice,
|
||||
(company as CompanySettings).entity_type
|
||||
)
|
||||
if (journalEntry) {
|
||||
await supabase
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createClient } from '@/lib/supabase/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import type { CreateInvoiceInput, Invoice, CreditNote } from '@/types'
|
||||
import type { CreateInvoiceInput, EntityType, Invoice, CreditNote } from '@/types'
|
||||
import { getVatRules, calculateVat, calculateTotal } from '@/lib/invoice/vat-rules'
|
||||
import { fetchExchangeRate, convertToSEK } from '@/lib/currency/riksbanken'
|
||||
import {
|
||||
@@ -292,12 +292,22 @@ async function createCreditNote(
|
||||
.eq('id', creditNote.id)
|
||||
.single()
|
||||
|
||||
// Fetch entity type for correct account mapping
|
||||
const { data: creditNoteSettings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('entity_type')
|
||||
.eq('user_id', userId)
|
||||
.single()
|
||||
|
||||
const entityType = (creditNoteSettings?.entity_type as EntityType) || 'enskild_firma'
|
||||
|
||||
// Create journal entry for the credit note (non-blocking)
|
||||
if (completeCreditNote) {
|
||||
try {
|
||||
const journalEntry = await createCreditNoteJournalEntry(
|
||||
userId,
|
||||
completeCreditNote as Invoice
|
||||
completeCreditNote as Invoice,
|
||||
entityType
|
||||
)
|
||||
if (journalEntry) {
|
||||
await supabase
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
getRevenueAccount,
|
||||
getOutputVatAccount,
|
||||
} from '@/lib/bookkeeping/invoice-entries'
|
||||
import type { Transaction, Invoice, CreateJournalEntryInput, VatTreatment } from '@/types'
|
||||
import type { Transaction, Invoice, CreateJournalEntryInput, EntityType, VatTreatment } from '@/types'
|
||||
|
||||
interface MatchInvoiceRequest {
|
||||
invoice_id: string
|
||||
@@ -139,11 +139,12 @@ export async function POST(
|
||||
// Fetch accounting method
|
||||
const { data: settings } = await supabase
|
||||
.from('company_settings')
|
||||
.select('accounting_method')
|
||||
.select('accounting_method, entity_type')
|
||||
.eq('user_id', user.id)
|
||||
.single()
|
||||
|
||||
const accountingMethod = settings?.accounting_method || 'accrual'
|
||||
const entityType = (settings?.entity_type as EntityType) || 'enskild_firma'
|
||||
|
||||
// Create journal entry for payment receipt (method-aware)
|
||||
let journalEntryId: string | null = null
|
||||
@@ -158,7 +159,7 @@ export async function POST(
|
||||
if (accountingMethod === 'cash') {
|
||||
// Kontantmetoden: combined revenue entry at payment
|
||||
// Debit 1930 Företagskonto, Credit 30xx Försäljning, Credit 26xx Utgående moms
|
||||
const revenueAccount = getRevenueAccount(invoice.vat_treatment as VatTreatment)
|
||||
const revenueAccount = getRevenueAccount(invoice.vat_treatment as VatTreatment, entityType)
|
||||
const lines: CreateJournalEntryInput['lines'] = [
|
||||
{
|
||||
account_number: '1930',
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
export { BankSelector, type Bank } from './BankSelector'
|
||||
export { BankConnectionStatus } from './BankConnectionStatus'
|
||||
@@ -0,0 +1,301 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import { ArrowLeft, ArrowRight, Columns3 } from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { GenericCSVColumnMapping } from '@/lib/import/bank-file/types'
|
||||
|
||||
interface BankFileColumnMappingStepProps {
|
||||
headers: string[]
|
||||
previewRows: string[][]
|
||||
onConfirm: (mapping: GenericCSVColumnMapping) => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export default function BankFileColumnMappingStep({
|
||||
headers,
|
||||
previewRows,
|
||||
onConfirm,
|
||||
onBack,
|
||||
}: BankFileColumnMappingStepProps) {
|
||||
const [dateCol, setDateCol] = useState<number>(-1)
|
||||
const [descCol, setDescCol] = useState<number>(-1)
|
||||
const [amountCol, setAmountCol] = useState<number>(-1)
|
||||
const [referenceCol, setReferenceCol] = useState<number>(-1)
|
||||
const [counterpartyCol, setCounterpartyCol] = useState<number>(-1)
|
||||
const [balanceCol, setBalanceCol] = useState<number>(-1)
|
||||
const [delimiter, setDelimiter] = useState<string>(',')
|
||||
const [decimalSep, setDecimalSep] = useState<',' | '.'>(',')
|
||||
|
||||
const isValid = dateCol >= 0 && descCol >= 0 && amountCol >= 0
|
||||
|
||||
const handleConfirm = () => {
|
||||
const mapping: GenericCSVColumnMapping = {
|
||||
date: dateCol,
|
||||
description: descCol,
|
||||
amount: amountCol,
|
||||
...(referenceCol >= 0 && { reference: referenceCol }),
|
||||
...(counterpartyCol >= 0 && { counterparty: counterpartyCol }),
|
||||
...(balanceCol >= 0 && { balance: balanceCol }),
|
||||
delimiter,
|
||||
decimal_separator: decimalSep,
|
||||
skip_rows: 1, // Skip header
|
||||
date_format: 'YYYY-MM-DD',
|
||||
}
|
||||
onConfirm(mapping)
|
||||
}
|
||||
|
||||
const columnOptions = headers.map((h, i) => ({ label: `${i + 1}: ${h}`, value: i }))
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Columns3 className="h-5 w-5" />
|
||||
Kolumnmappning
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Vi kunde inte identifiera bankformatet automatiskt. Mappa kolumnerna manuellt.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Delimiter and decimal settings */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Avgränsare</Label>
|
||||
<Select value={delimiter} onValueChange={setDelimiter}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value=",">Komma (,)</SelectItem>
|
||||
<SelectItem value=";">Semikolon (;)</SelectItem>
|
||||
<SelectItem value="\t">Tab</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Decimalavgränsare</Label>
|
||||
<Select value={decimalSep} onValueChange={(v) => setDecimalSep(v as ',' | '.')}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value=",">Komma (1 234,56)</SelectItem>
|
||||
<SelectItem value=".">Punkt (1234.56)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Required column mappings */}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium mb-3">Obligatoriska kolumner</h3>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Datum *</Label>
|
||||
<Select
|
||||
value={dateCol >= 0 ? dateCol.toString() : ''}
|
||||
onValueChange={(v) => setDateCol(parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Beskrivning *</Label>
|
||||
<Select
|
||||
value={descCol >= 0 ? descCol.toString() : ''}
|
||||
onValueChange={(v) => setDescCol(parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Belopp *</Label>
|
||||
<Select
|
||||
value={amountCol >= 0 ? amountCol.toString() : ''}
|
||||
onValueChange={(v) => setAmountCol(parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Välj kolumn" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Optional column mappings */}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium mb-3">Valfria kolumner</h3>
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Referens/OCR</Label>
|
||||
<Select
|
||||
value={referenceCol >= 0 ? referenceCol.toString() : 'none'}
|
||||
onValueChange={(v) => setReferenceCol(v === 'none' ? -1 : parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Ingen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">Ingen</SelectItem>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Motpart</Label>
|
||||
<Select
|
||||
value={counterpartyCol >= 0 ? counterpartyCol.toString() : 'none'}
|
||||
onValueChange={(v) => setCounterpartyCol(v === 'none' ? -1 : parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Ingen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">Ingen</SelectItem>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Saldo</Label>
|
||||
<Select
|
||||
value={balanceCol >= 0 ? balanceCol.toString() : 'none'}
|
||||
onValueChange={(v) => setBalanceCol(v === 'none' ? -1 : parseInt(v))}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Ingen" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">Ingen</SelectItem>
|
||||
{columnOptions.map((opt) => (
|
||||
<SelectItem key={opt.value} value={opt.value.toString()}>
|
||||
{opt.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Live preview */}
|
||||
{isValid && previewRows.length > 1 && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Förhandsgranskning</CardTitle>
|
||||
<CardDescription>
|
||||
Så tolkas dina data med den valda mappningen
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border max-h-64 overflow-y-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Datum</TableHead>
|
||||
<TableHead>Beskrivning</TableHead>
|
||||
<TableHead className="text-right">Belopp</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{previewRows.slice(1, 6).map((row, i) => {
|
||||
const amountStr = row[amountCol] || '0'
|
||||
const amount = decimalSep === ','
|
||||
? parseFloat(amountStr.replace(/\s/g, '').replace(',', '.'))
|
||||
: parseFloat(amountStr.replace(/\s/g, ''))
|
||||
|
||||
return (
|
||||
<TableRow key={i}>
|
||||
<TableCell className="font-mono text-sm">{row[dateCol] || '–'}</TableCell>
|
||||
<TableCell className="text-sm">{row[descCol] || '–'}</TableCell>
|
||||
<TableCell
|
||||
className={`text-right font-mono text-sm ${
|
||||
!isNaN(amount) && amount >= 0 ? 'text-green-600' : 'text-red-600'
|
||||
}`}
|
||||
>
|
||||
{!isNaN(amount) ? formatCurrency(amount) : amountStr}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={handleConfirm} disabled={!isValid}>
|
||||
Fortsätt
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Checkbox } from '@/components/ui/checkbox'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Loader2,
|
||||
Play,
|
||||
FileText,
|
||||
AlertTriangle,
|
||||
Link2,
|
||||
Calendar,
|
||||
} from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { BankFileParseResult } from '@/lib/import/bank-file/types'
|
||||
|
||||
interface BankFileConfirmStepProps {
|
||||
parseResult: BankFileParseResult
|
||||
onExecute: (options: { skip_duplicates: boolean; auto_categorize: boolean }) => void
|
||||
onBack: () => void
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
export default function BankFileConfirmStep({
|
||||
parseResult,
|
||||
onExecute,
|
||||
onBack,
|
||||
isLoading,
|
||||
}: BankFileConfirmStepProps) {
|
||||
const [skipDuplicates, setSkipDuplicates] = useState(true)
|
||||
const [autoCategorize, setAutoCategorize] = useState(true)
|
||||
|
||||
const { transactions, stats, date_from, date_to, format_name } = parseResult
|
||||
const refsCount = transactions.filter((t) => t.reference).length
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Summary */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Bekräfta import</CardTitle>
|
||||
<CardDescription>
|
||||
Granska sammanfattningen och importera transaktionerna.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
{/* Stats grid */}
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
|
||||
<div className="p-4 bg-muted/50 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span className="text-xs">Transaktioner</span>
|
||||
</div>
|
||||
<p className="text-xl font-bold">{stats.parsed_rows}</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-muted/50 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Calendar className="h-4 w-4" />
|
||||
<span className="text-xs">Period</span>
|
||||
</div>
|
||||
<p className="text-sm font-medium">
|
||||
{date_from} – {date_to}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-muted/50 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-green-600 mb-1">
|
||||
<span className="text-xs">Inkomster</span>
|
||||
</div>
|
||||
<p className="text-xl font-bold text-green-600">
|
||||
{formatCurrency(stats.total_income)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="p-4 bg-muted/50 rounded-lg">
|
||||
<div className="flex items-center gap-2 text-red-600 mb-1">
|
||||
<span className="text-xs">Utgifter</span>
|
||||
</div>
|
||||
<p className="text-xl font-bold text-red-600">
|
||||
{formatCurrency(stats.total_expenses)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Additional info */}
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge variant="secondary">Format: {format_name}</Badge>
|
||||
{refsCount > 0 && (
|
||||
<Badge variant="outline" className="text-blue-600 border-blue-300">
|
||||
<Link2 className="mr-1 h-3 w-3" />
|
||||
{refsCount} med OCR/referens
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Options */}
|
||||
<div className="border rounded-lg p-4 space-y-4">
|
||||
<h3 className="text-sm font-medium">Importinställningar</h3>
|
||||
|
||||
<div className="flex items-center space-x-3">
|
||||
<Checkbox
|
||||
id="skip-duplicates"
|
||||
checked={skipDuplicates}
|
||||
onCheckedChange={(checked) => setSkipDuplicates(checked === true)}
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="skip-duplicates" className="text-sm font-medium cursor-pointer">
|
||||
Hoppa över dubletter
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Transaktioner som redan finns i systemet importeras inte igen
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-3">
|
||||
<Checkbox
|
||||
id="auto-categorize"
|
||||
checked={autoCategorize}
|
||||
onCheckedChange={(checked) => setAutoCategorize(checked === true)}
|
||||
/>
|
||||
<div>
|
||||
<Label htmlFor="auto-categorize" className="text-sm font-medium cursor-pointer">
|
||||
Auto-kategorisera kända transaktioner
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Skapar automatiskt bokföringsposter för transaktioner med hög konfidens
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Warning note */}
|
||||
<div className="flex gap-3 p-3 bg-yellow-50 dark:bg-yellow-950/20 border border-yellow-200 dark:border-yellow-800 rounded-lg">
|
||||
<AlertTriangle className="h-4 w-4 text-yellow-600 flex-shrink-0 mt-0.5" />
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Importerade transaktioner som inte automatiskt kategoriseras visas som
|
||||
"okategoriserade" på transaktionssidan. Du kan kategorisera dem manuellt
|
||||
efteråt.
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onBack} disabled={isLoading}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => onExecute({
|
||||
skip_duplicates: skipDuplicates,
|
||||
auto_categorize: autoCategorize,
|
||||
})}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Importerar...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="mr-2 h-4 w-4" />
|
||||
Importera {stats.parsed_rows} transaktioner
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
'use client'
|
||||
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from '@/components/ui/table'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
AlertTriangle,
|
||||
Calendar,
|
||||
TrendingUp,
|
||||
TrendingDown,
|
||||
FileText,
|
||||
} from 'lucide-react'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { BankFileParseResult } from '@/lib/import/bank-file/types'
|
||||
|
||||
interface BankFilePreviewStepProps {
|
||||
parseResult: BankFileParseResult
|
||||
existingTransactionCount: number
|
||||
onContinue: () => void
|
||||
onBack: () => void
|
||||
}
|
||||
|
||||
export default function BankFilePreviewStep({
|
||||
parseResult,
|
||||
existingTransactionCount,
|
||||
onContinue,
|
||||
onBack,
|
||||
}: BankFilePreviewStepProps) {
|
||||
const { transactions, stats, issues, date_from, date_to, format_name } = parseResult
|
||||
const hasIssues = issues.filter((i) => i.severity === 'error').length > 0
|
||||
const warnings = issues.filter((i) => i.severity === 'warning')
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Summary cards */}
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span className="text-sm">Transaktioner</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold">{stats.parsed_rows}</p>
|
||||
{stats.skipped_rows > 0 && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
{stats.skipped_rows} rader hoppades över
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Calendar className="h-4 w-4" />
|
||||
<span className="text-sm">Period</span>
|
||||
</div>
|
||||
<p className="text-sm font-medium">
|
||||
{date_from || '–'} till {date_to || '–'}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-green-600 mb-1">
|
||||
<TrendingUp className="h-4 w-4" />
|
||||
<span className="text-sm">Inkomster</span>
|
||||
</div>
|
||||
<p className="text-lg font-bold text-green-600">
|
||||
{formatCurrency(stats.total_income)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-red-600 mb-1">
|
||||
<TrendingDown className="h-4 w-4" />
|
||||
<span className="text-sm">Utgifter</span>
|
||||
</div>
|
||||
<p className="text-lg font-bold text-red-600">
|
||||
{formatCurrency(stats.total_expenses)}
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Format and duplicate info */}
|
||||
<div className="flex items-center gap-4">
|
||||
<Badge variant="secondary">
|
||||
Format: {format_name}
|
||||
</Badge>
|
||||
{existingTransactionCount > 0 && (
|
||||
<Badge variant="outline" className="text-yellow-600 border-yellow-300">
|
||||
<AlertTriangle className="mr-1 h-3 w-3" />
|
||||
{existingTransactionCount} befintliga transaktioner i samma period
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Warnings */}
|
||||
{warnings.length > 0 && (
|
||||
<Card className="border-yellow-300">
|
||||
<CardHeader className="py-3">
|
||||
<CardTitle className="text-sm flex items-center gap-2 text-yellow-600">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{warnings.length} varning{warnings.length !== 1 ? 'ar' : ''}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
<div className="space-y-1 max-h-32 overflow-y-auto">
|
||||
{warnings.slice(0, 10).map((issue, i) => (
|
||||
<p key={i} className="text-xs text-muted-foreground">
|
||||
Rad {issue.row}: {issue.message}
|
||||
</p>
|
||||
))}
|
||||
{warnings.length > 10 && (
|
||||
<p className="text-xs text-muted-foreground font-medium">
|
||||
...och {warnings.length - 10} till
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Transaction preview table */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Transaktioner</CardTitle>
|
||||
<CardDescription>
|
||||
Förhandsgranskning av de {Math.min(transactions.length, 50)} första transaktionerna
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="rounded-md border max-h-96 overflow-y-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-28">Datum</TableHead>
|
||||
<TableHead>Beskrivning</TableHead>
|
||||
<TableHead className="text-right w-32">Belopp</TableHead>
|
||||
{transactions.some((t) => t.balance != null) && (
|
||||
<TableHead className="text-right w-32">Saldo</TableHead>
|
||||
)}
|
||||
{transactions.some((t) => t.reference) && (
|
||||
<TableHead className="w-32">Referens</TableHead>
|
||||
)}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{transactions.slice(0, 50).map((tx, i) => (
|
||||
<TableRow key={i}>
|
||||
<TableCell className="font-mono text-sm">{tx.date}</TableCell>
|
||||
<TableCell className="text-sm">{tx.description}</TableCell>
|
||||
<TableCell
|
||||
className={`text-right font-mono text-sm ${
|
||||
tx.amount >= 0 ? 'text-green-600' : 'text-red-600'
|
||||
}`}
|
||||
>
|
||||
{formatCurrency(tx.amount)}
|
||||
</TableCell>
|
||||
{transactions.some((t) => t.balance != null) && (
|
||||
<TableCell className="text-right font-mono text-sm text-muted-foreground">
|
||||
{tx.balance != null ? formatCurrency(tx.balance) : '–'}
|
||||
</TableCell>
|
||||
)}
|
||||
{transactions.some((t) => t.reference) && (
|
||||
<TableCell className="text-sm">
|
||||
{tx.reference ? (
|
||||
<Badge variant="outline" className="font-mono text-xs">
|
||||
{tx.reference}
|
||||
</Badge>
|
||||
) : (
|
||||
'–'
|
||||
)}
|
||||
</TableCell>
|
||||
)}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
{transactions.length > 50 && (
|
||||
<p className="text-sm text-muted-foreground mt-2 text-center">
|
||||
Visar 50 av {transactions.length} transaktioner
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Navigation */}
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onBack}>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
</Button>
|
||||
<Button onClick={onContinue} disabled={hasIssues || transactions.length === 0}>
|
||||
Fortsätt
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import {
|
||||
CheckCircle,
|
||||
XCircle,
|
||||
FileText,
|
||||
Link2,
|
||||
Sparkles,
|
||||
Copy,
|
||||
ArrowRight,
|
||||
RotateCcw,
|
||||
ExternalLink,
|
||||
} from 'lucide-react'
|
||||
import type { IngestResult } from '@/lib/transactions/ingest'
|
||||
|
||||
interface BankFileResultStepProps {
|
||||
result: IngestResult
|
||||
onNewImport: () => void
|
||||
}
|
||||
|
||||
export default function BankFileResultStep({
|
||||
result,
|
||||
onNewImport,
|
||||
}: BankFileResultStepProps) {
|
||||
const isSuccess = result.imported > 0 || result.duplicates > 0
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Status header */}
|
||||
<Card className={isSuccess ? 'border-green-300' : 'border-destructive/50'}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
{isSuccess ? (
|
||||
<>
|
||||
<CheckCircle className="h-6 w-6 text-green-600" />
|
||||
Import genomförd
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<XCircle className="h-6 w-6 text-destructive" />
|
||||
Import misslyckades
|
||||
</>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{isSuccess
|
||||
? `${result.imported} transaktioner importerades framgångsrikt.`
|
||||
: `${result.errors} fel uppstod under importen.`}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="grid gap-4 md:grid-cols-4">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span className="text-sm">Importerade</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-green-600">{result.imported}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Copy className="h-4 w-4" />
|
||||
<span className="text-sm">Dubletter</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-muted-foreground">{result.duplicates}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
<span className="text-sm">Auto-kategoriserade</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold">{result.auto_categorized}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="flex items-center gap-2 text-muted-foreground mb-1">
|
||||
<Link2 className="h-4 w-4" />
|
||||
<span className="text-sm">Fakturamatchade</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold">{result.auto_matched_invoices}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Next steps */}
|
||||
{isSuccess && (
|
||||
<Card className="bg-muted/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base">Nästa steg</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-sm font-medium flex-shrink-0">
|
||||
1
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Granska okategoriserade transaktioner</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{result.imported - result.auto_categorized > 0
|
||||
? `${result.imported - result.auto_categorized} transaktioner behöver kategoriseras manuellt.`
|
||||
: 'Alla transaktioner kategoriserades automatiskt.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-sm font-medium flex-shrink-0">
|
||||
2
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Bekräfta fakturamatchningar</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{result.auto_matched_invoices > 0
|
||||
? `${result.auto_matched_invoices} transaktioner matchades mot fakturor. Bekräfta dessa på transaktionssidan.`
|
||||
: 'Inga automatiska fakturamatchningar hittades.'}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-sm font-medium flex-shrink-0">
|
||||
3
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Importera fler kontoutdrag</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Importera löpande kontoutdrag för att hålla bokföringen uppdaterad.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex justify-between">
|
||||
<Button variant="outline" onClick={onNewImport}>
|
||||
<RotateCcw className="mr-2 h-4 w-4" />
|
||||
Ny import
|
||||
</Button>
|
||||
<div className="flex gap-2">
|
||||
{isSuccess && (
|
||||
<Button asChild>
|
||||
<Link href="/transactions">
|
||||
Visa transaktioner
|
||||
<ArrowRight className="ml-2 h-4 w-4" />
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useCallback } from 'react'
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Progress } from '@/components/ui/progress'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import {
|
||||
Upload,
|
||||
FileText,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
Building2,
|
||||
HelpCircle,
|
||||
} from 'lucide-react'
|
||||
import type { BankFileFormatId } from '@/lib/import/bank-file/types'
|
||||
|
||||
const FORMAT_NAMES: Record<string, string> = {
|
||||
nordea: 'Nordea',
|
||||
seb: 'SEB',
|
||||
swedbank: 'Swedbank',
|
||||
handelsbanken: 'Handelsbanken',
|
||||
generic_csv: 'CSV (manuell mappning)',
|
||||
camt053: 'ISO 20022 camt.053',
|
||||
}
|
||||
|
||||
interface BankFileUploadStepProps {
|
||||
onFileSelect: (file: File, formatOverride?: BankFileFormatId) => void
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
detectedFormat?: string | null
|
||||
detectedFormatName?: string | null
|
||||
}
|
||||
|
||||
export default function BankFileUploadStep({
|
||||
onFileSelect,
|
||||
isLoading,
|
||||
error,
|
||||
detectedFormat,
|
||||
detectedFormatName,
|
||||
}: BankFileUploadStepProps) {
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [formatOverride, setFormatOverride] = useState<BankFileFormatId | undefined>(undefined)
|
||||
|
||||
const acceptedExtensions = '.csv,.txt,.xml'
|
||||
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(true)
|
||||
}, [])
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
}, [])
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
|
||||
const files = e.dataTransfer.files
|
||||
if (files.length > 0) {
|
||||
const file = files[0]
|
||||
const ext = file.name.toLowerCase()
|
||||
if (ext.endsWith('.csv') || ext.endsWith('.txt') || ext.endsWith('.xml')) {
|
||||
setSelectedFile(file)
|
||||
onFileSelect(file, formatOverride)
|
||||
}
|
||||
}
|
||||
}, [onFileSelect, formatOverride])
|
||||
|
||||
const handleFileInput = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files
|
||||
if (files && files.length > 0) {
|
||||
setSelectedFile(files[0])
|
||||
onFileSelect(files[0], formatOverride)
|
||||
}
|
||||
}, [onFileSelect, formatOverride])
|
||||
|
||||
const handleFormatChange = (value: string) => {
|
||||
const format = value === 'auto' ? undefined : value as BankFileFormatId
|
||||
setFormatOverride(format)
|
||||
if (selectedFile) {
|
||||
onFileSelect(selectedFile, format)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Ladda upp kontoutdrag
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Exportera transaktioner som CSV eller XML från din internetbank och ladda upp filen.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Format override */}
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="text-sm font-medium whitespace-nowrap">Bank/format:</label>
|
||||
<Select
|
||||
value={formatOverride || 'auto'}
|
||||
onValueChange={handleFormatChange}
|
||||
>
|
||||
<SelectTrigger className="w-64">
|
||||
<SelectValue placeholder="Automatisk identifiering" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="auto">Automatisk identifiering</SelectItem>
|
||||
<SelectItem value="nordea">Nordea</SelectItem>
|
||||
<SelectItem value="seb">SEB</SelectItem>
|
||||
<SelectItem value="swedbank">Swedbank</SelectItem>
|
||||
<SelectItem value="handelsbanken">Handelsbanken</SelectItem>
|
||||
<SelectItem value="camt053">ISO 20022 camt.053 (XML)</SelectItem>
|
||||
<SelectItem value="generic_csv">Annan CSV (manuell mappning)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{/* Drop zone */}
|
||||
<div
|
||||
className={`
|
||||
relative border-2 border-dashed rounded-lg p-8 text-center transition-colors
|
||||
${isDragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25'}
|
||||
${error ? 'border-destructive bg-destructive/5' : ''}
|
||||
${isLoading ? 'pointer-events-none opacity-50' : 'cursor-pointer hover:border-primary/50'}
|
||||
`}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
onClick={() => document.getElementById('bank-file-input')?.click()}
|
||||
>
|
||||
<input
|
||||
id="bank-file-input"
|
||||
type="file"
|
||||
accept={acceptedExtensions}
|
||||
className="hidden"
|
||||
onChange={handleFileInput}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
<FileText className="mx-auto h-12 w-12 text-muted-foreground animate-pulse" />
|
||||
<p className="text-muted-foreground">Analyserar fil...</p>
|
||||
<Progress value={33} className="w-48 mx-auto" />
|
||||
</div>
|
||||
) : selectedFile && detectedFormat ? (
|
||||
<div className="space-y-4">
|
||||
<CheckCircle className="mx-auto h-12 w-12 text-green-600" />
|
||||
<div>
|
||||
<p className="font-medium">{selectedFile.name}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{(selectedFile.size / 1024).toFixed(1)} KB
|
||||
</p>
|
||||
<Badge variant="secondary" className="mt-2">
|
||||
<Building2 className="mr-1 h-3 w-3" />
|
||||
{detectedFormatName || FORMAT_NAMES[detectedFormat] || detectedFormat}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
<Upload className="mx-auto h-12 w-12 text-muted-foreground" />
|
||||
<div>
|
||||
<p className="font-medium">Dra och släpp bankfil här</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
CSV, TXT eller XML (max 10 MB)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Error display */}
|
||||
{error && (
|
||||
<div className="p-4 bg-destructive/10 border border-destructive/20 rounded-lg flex gap-3">
|
||||
<AlertCircle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="font-medium text-destructive">Kunde inte läsa filen</p>
|
||||
<p className="text-sm text-muted-foreground">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Bank export instructions */}
|
||||
<Card className="bg-muted/50">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<HelpCircle className="h-4 w-4" />
|
||||
Så exporterar du från din bank
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="text-sm space-y-3">
|
||||
<div>
|
||||
<p className="font-medium">Nordea</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Välj konto → Transaktioner → Exportera (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">SEB</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Kontoutdrag → Hämta som fil (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Swedbank</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Transaktioner → Exportera kontoutdrag (CSV)
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium">Handelsbanken</p>
|
||||
<p className="text-muted-foreground">
|
||||
Logga in → Konton → Transaktioner → Ladda ner (CSV)
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -82,8 +82,8 @@ export default function NewUserChecklist({
|
||||
},
|
||||
{
|
||||
id: 'bank',
|
||||
label: 'Koppla bank',
|
||||
description: 'Se transaktioner automatiskt (valfritt)',
|
||||
label: 'Importera transaktioner',
|
||||
description: 'Importera kontoutdrag från din bank',
|
||||
href: '/import',
|
||||
icon: Building2,
|
||||
completed: hasBankConnected,
|
||||
|
||||
@@ -9,8 +9,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { InfoTooltip } from '@/components/ui/info-tooltip'
|
||||
import { Loader2, ArrowLeft, Landmark, SkipForward, ChevronDown, ChevronUp } from 'lucide-react'
|
||||
import { BankSelector, type Bank } from '@/components/banking/BankSelector'
|
||||
import { Loader2, ArrowLeft, Landmark, SkipForward } from 'lucide-react'
|
||||
|
||||
const manualBankSchema = z.object({
|
||||
bank_name: z.string().optional(),
|
||||
@@ -37,10 +36,6 @@ export default function Step6ConnectBank({
|
||||
onComplete,
|
||||
isSaving,
|
||||
}: Step6Props) {
|
||||
const [isConnecting, setIsConnecting] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [showManual, setShowManual] = useState(false)
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
@@ -55,33 +50,6 @@ export default function Step6ConnectBank({
|
||||
},
|
||||
})
|
||||
|
||||
const handleBankSelect = async (bank: Bank) => {
|
||||
setIsConnecting(true)
|
||||
setError(null)
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/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 || 'Kunde inte ansluta bank')
|
||||
}
|
||||
|
||||
window.location.href = data.authorization_url
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Ett fel uppstod')
|
||||
setIsConnecting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const onManualSubmit = (data: ManualBankData) => {
|
||||
onComplete(data)
|
||||
}
|
||||
@@ -89,9 +57,10 @@ export default function Step6ConnectBank({
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="text-center">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Anslut din bank</h1>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Bankuppgifter</h1>
|
||||
<p className="text-muted-foreground mt-2">
|
||||
Koppla din bank för att automatiskt importera transaktioner via PSD2.
|
||||
Ange dina bankuppgifter så visas de på dina fakturor.
|
||||
Du kan importera transaktioner från din bank efteråt.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -99,159 +68,125 @@ export default function Step6ConnectBank({
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Landmark className="h-5 w-5" />
|
||||
Välj din bank
|
||||
Bankuppgifter för fakturor
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Vi använder säker bankintegration (PSD2) för att hämta dina transaktioner.
|
||||
Vi kan aldrig flytta pengar eller göra ändringar.
|
||||
Dessa uppgifter visas på dina fakturor så att kunder kan betala dig.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<BankSelector
|
||||
onSelect={handleBankSelect}
|
||||
isLoading={isConnecting}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-destructive/10 text-destructive rounded-lg text-sm">
|
||||
{error}
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit(onManualSubmit)} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="bank_name">Bank</Label>
|
||||
<Input
|
||||
id="bank_name"
|
||||
placeholder="t.ex. Nordea, SEB, Swedbank"
|
||||
{...register('bank_name')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-muted/50 rounded-lg p-4">
|
||||
<h4 className="font-medium mb-2">Säker anslutning</h4>
|
||||
<ul className="text-sm text-muted-foreground space-y-1">
|
||||
<li>• Krypterad anslutning via PSD2</li>
|
||||
<li>• Vi kan endast läsa transaktioner</li>
|
||||
<li>• Du kan koppla bort när som helst</li>
|
||||
<li>• Samtycke gäller i 90 dagar</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* Collapsible manual bank details */}
|
||||
<div className="border-t pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowManual(!showManual)}
|
||||
className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors w-full"
|
||||
>
|
||||
{showManual ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
|
||||
<span>Ange bankuppgifter manuellt</span>
|
||||
</button>
|
||||
|
||||
{showManual && (
|
||||
<form onSubmit={handleSubmit(onManualSubmit)} className="space-y-4 mt-4 animate-fade-in">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Dessa uppgifter visas på dina fakturor så att kunder kan betala dig.
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">Vad är clearingnummer?</p>
|
||||
<p>De första 4-5 siffrorna i ditt kontonummer som identifierar din bank.</p>
|
||||
<ul className="text-xs text-muted-foreground space-y-1">
|
||||
<li>Nordea: 3300</li>
|
||||
<li>SEB: 5000</li>
|
||||
<li>Swedbank: 8XXX</li>
|
||||
<li>Handelsbanken: 6XXX</li>
|
||||
<li>Avanza: 9550/9551</li>
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
side="top"
|
||||
>
|
||||
<Label htmlFor="clearing_number">Clearingnummer</Label>
|
||||
</InfoTooltip>
|
||||
<Input
|
||||
id="clearing_number"
|
||||
placeholder="XXXX"
|
||||
{...register('clearing_number')}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="account_number">Kontonummer</Label>
|
||||
<Input
|
||||
id="account_number"
|
||||
placeholder="XXX XXX XXX"
|
||||
{...register('account_number')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t">
|
||||
<h4 className="font-medium mb-4">Internationella betalningar (valfritt)</h4>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="bank_name">Bank</Label>
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">Vad är IBAN?</p>
|
||||
<p>Internationellt bankkontonummer. Svenska IBAN börjar med SE och har 24 tecken totalt.</p>
|
||||
</div>
|
||||
}
|
||||
side="right"
|
||||
>
|
||||
<Label htmlFor="iban">IBAN</Label>
|
||||
</InfoTooltip>
|
||||
<Input
|
||||
id="bank_name"
|
||||
placeholder="t.ex. Nordea, SEB, Swedbank"
|
||||
{...register('bank_name')}
|
||||
id="iban"
|
||||
placeholder="SE00 0000 0000 0000 0000 0000"
|
||||
{...register('iban')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">Vad är clearingnummer?</p>
|
||||
<p>De första 4-5 siffrorna i ditt kontonummer som identifierar din bank.</p>
|
||||
<ul className="text-xs text-muted-foreground space-y-1">
|
||||
<li>Nordea: 3300</li>
|
||||
<li>SEB: 5000</li>
|
||||
<li>Swedbank: 8XXX</li>
|
||||
<li>Handelsbanken: 6XXX</li>
|
||||
<li>Avanza: 9550/9551</li>
|
||||
</ul>
|
||||
</div>
|
||||
}
|
||||
side="top"
|
||||
>
|
||||
<Label htmlFor="clearing_number">Clearingnummer</Label>
|
||||
</InfoTooltip>
|
||||
<Input
|
||||
id="clearing_number"
|
||||
placeholder="XXXX"
|
||||
{...register('clearing_number')}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="account_number">Kontonummer</Label>
|
||||
<Input
|
||||
id="account_number"
|
||||
placeholder="XXX XXX XXX"
|
||||
{...register('account_number')}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">Vad är BIC/SWIFT?</p>
|
||||
<p>Bankens internationella id-kod. Används tillsammans med IBAN för utlandsbetalningar.</p>
|
||||
</div>
|
||||
}
|
||||
side="right"
|
||||
>
|
||||
<Label htmlFor="bic">BIC/SWIFT</Label>
|
||||
</InfoTooltip>
|
||||
<Input
|
||||
id="bic"
|
||||
placeholder="XXXXSESS"
|
||||
{...register('bic')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 border-t">
|
||||
<h4 className="font-medium mb-4">Internationella betalningar (valfritt)</h4>
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">Vad är IBAN?</p>
|
||||
<p>Internationellt bankkontonummer. Svenska IBAN börjar med SE och har 24 tecken totalt.</p>
|
||||
</div>
|
||||
}
|
||||
side="right"
|
||||
>
|
||||
<Label htmlFor="iban">IBAN</Label>
|
||||
</InfoTooltip>
|
||||
<Input
|
||||
id="iban"
|
||||
placeholder="SE00 0000 0000 0000 0000 0000"
|
||||
{...register('iban')}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<InfoTooltip
|
||||
content={
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">Vad är BIC/SWIFT?</p>
|
||||
<p>Bankens internationella id-kod. Används tillsammans med IBAN för utlandsbetalningar.</p>
|
||||
</div>
|
||||
}
|
||||
side="right"
|
||||
>
|
||||
<Label htmlFor="bic">BIC/SWIFT</Label>
|
||||
</InfoTooltip>
|
||||
<Input
|
||||
id="bic"
|
||||
placeholder="XXXXSESS"
|
||||
{...register('bic')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-muted/50 rounded-lg p-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Du kan importera kontoutdrag (CSV, XML) från din bank under <strong>Import</strong>-sidan
|
||||
efter att du slutfört registreringen.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Sparar...
|
||||
</>
|
||||
) : (
|
||||
'Spara bankuppgifter och slutför'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={isSaving}>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Sparar...
|
||||
</>
|
||||
) : (
|
||||
'Spara och slutför'
|
||||
)}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="flex justify-between pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={onBack}
|
||||
disabled={isConnecting}
|
||||
>
|
||||
<ArrowLeft className="mr-2 h-4 w-4" />
|
||||
Tillbaka
|
||||
@@ -260,7 +195,6 @@ export default function Step6ConnectBank({
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onSkip}
|
||||
disabled={isConnecting}
|
||||
>
|
||||
<SkipForward className="mr-2 h-4 w-4" />
|
||||
Hoppa över
|
||||
|
||||
@@ -117,8 +117,8 @@ export function EmptyTransactions() {
|
||||
<EmptyState
|
||||
icon={ArrowLeftRight}
|
||||
title="Inga transaktioner"
|
||||
description="Koppla din bank för att automatiskt importera transaktioner, eller lägg till dem manuellt."
|
||||
actionLabel="Koppla bank"
|
||||
description="Importera kontoutdrag från din bank eller lägg till transaktioner manuellt."
|
||||
actionLabel="Importera transaktioner"
|
||||
actionHref="/import"
|
||||
secondaryActionLabel="Lägg till manuellt"
|
||||
secondaryActionHref="/transactions/new"
|
||||
@@ -152,9 +152,9 @@ export function NoBankConnected() {
|
||||
return (
|
||||
<EmptyState
|
||||
icon={Building2}
|
||||
title="Ingen bank kopplad"
|
||||
description="Koppla din bank för att automatiskt importera transaktioner och få bättre koll på ekonomin."
|
||||
actionLabel="Koppla bank"
|
||||
title="Inga transaktioner importerade"
|
||||
description="Importera kontoutdrag från din bank för att automatiskt bokföra och få bättre koll på ekonomin."
|
||||
actionLabel="Importera transaktioner"
|
||||
actionHref="/import"
|
||||
/>
|
||||
)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,467 @@
|
||||
1/9
|
||||
BAS Förenklat årsbokslut (K1) – Kontoplan 2018
|
||||
Inga ändring eller tillägg har gjorts
|
||||
jämfört med 2017.
|
||||
BAS-konton Rad Underkonton Rad
|
||||
1000 Immateriella
|
||||
anläggningstillgångar
|
||||
B1 1009 Årets avskrivningar på
|
||||
immateriella
|
||||
anläggningstillgångar
|
||||
B1
|
||||
BAS-konton Rad Underkonton Rad
|
||||
1110 Byggnader B2 1119 Ackumulerade avskrivningar på
|
||||
byggnader
|
||||
B2
|
||||
1130 Mark B3
|
||||
1150 Markanläggningar B2 1159 Ackumulerade avskrivningar på
|
||||
markanläggningar
|
||||
B2
|
||||
1180 Pågående nyanläggningar och
|
||||
förskott för byggnader och
|
||||
mark
|
||||
B3
|
||||
Rad Rad
|
||||
1220 Maskiner och inventarier B4 1221 Årets nyanskaffning av
|
||||
maskiner och inventarier
|
||||
B4
|
||||
1222 Årets ersättning för maskiner
|
||||
och inventarier
|
||||
B4
|
||||
1229 Årets avskrivningar på maskiner
|
||||
och inventarier
|
||||
B4
|
||||
1230 Byggnads- och markinventarier B4 1231 Årets nyanskaffning av
|
||||
byggnads- och markinventarier
|
||||
B4
|
||||
1232 Årets ersättning för byggnadsoch markinventarier
|
||||
B4
|
||||
1239 Årets avskrivningar på
|
||||
byggnads- och markinventarier
|
||||
B4
|
||||
1240 Bilar och andra transportmedel B4 1241 Årets nyanskaffning av bilar och
|
||||
andra transportmedel
|
||||
B4
|
||||
1242 Årets ersättning för bilar och
|
||||
andra transportmedel
|
||||
B4
|
||||
1249 Årets avskrivningar på bilar och
|
||||
andra transportmedel
|
||||
B4
|
||||
Rad Rad
|
||||
1300 Andelar B5
|
||||
BAS-konton Rad Rad
|
||||
1 Tillgångar
|
||||
10 Immateriella anläggningstillgångar
|
||||
11 Byggnader och mark
|
||||
12 Maskiner och inventarier
|
||||
14 Lager
|
||||
BAS-konton Underkonton
|
||||
Underkonton
|
||||
13 Övriga anläggningstillgångar
|
||||
BAS-konton Underkonton
|
||||
Kontoplan_K1_2018_ver1
|
||||
2/9
|
||||
1400 Lager B6
|
||||
Rad Rad
|
||||
1500 Kundfordringar B7
|
||||
Rad Rad
|
||||
1600 Övriga fordringar B8
|
||||
1650 Momsfordran B8
|
||||
Rad
|
||||
1700 Förskott till leverantörer B8
|
||||
Rad
|
||||
1910 Kassa B9
|
||||
1920 PlusGiro B9
|
||||
1930 Företagskonto/checkkonto/affär
|
||||
skonto
|
||||
B9
|
||||
1940 Övriga bankkonton B9
|
||||
1970 Särskilda bankkonton B9
|
||||
Rad Rad
|
||||
2010 Eget kapital, delägare 1 B10 2011 Egna varuuttag B10
|
||||
2012 Avräkning för skatter och
|
||||
avgifter (skattekonto)
|
||||
B10
|
||||
2013 Övriga egna uttag B10
|
||||
2014 Uttag förmåner B10
|
||||
2017 Egna insättningar B10
|
||||
2019 Årets resultat, delägare 1 B10
|
||||
2020 Eget kapital, delägare 2 B10 Se delägre 1
|
||||
2030 Eget kapital, delägare 3 B10 Se delägre 1
|
||||
2040 Eget kapital, delägare 4 B10 Se delägre 1
|
||||
2050 Avsättning till expansionsfond U2
|
||||
2060 Ersättningsfond U3
|
||||
2070 Insatsemissioner,
|
||||
avbetalningsplan på skog,
|
||||
skogskonto,
|
||||
upphovsmannakonto
|
||||
U4
|
||||
2080 Periodiseringsfonder U1 2083 Periodiseringsfond vid 2012 års
|
||||
taxering
|
||||
U1
|
||||
BAS-konton
|
||||
16 Övriga fordringar
|
||||
BAS-konton Underkonton
|
||||
BAS-konton Underkonton
|
||||
Underkonton
|
||||
2 EGET KAPITAL OCH SKULDER
|
||||
19 Kassa och bank
|
||||
17 Förskott till leverantörer
|
||||
15 Kundfordringar
|
||||
BAS-konton
|
||||
BAS-konton Underkonton
|
||||
20 Eget kapital
|
||||
Underkonton
|
||||
Kontoplan_K1_2018_ver1
|
||||
3/9
|
||||
2084 Periodiseringsfond vid 2013 års
|
||||
taxering
|
||||
U1
|
||||
2085 Periodiseringsfond 2013 U1
|
||||
2086 Periodiseringsfond 2014 U1
|
||||
2087 Periodiseringsfond 2015 U1
|
||||
2088 Periodiseringsfond 2016 U1
|
||||
2089 Periodiseringsfond 2017 U1
|
||||
2090 Utjämningskonto upplysningar
|
||||
1-4
|
||||
Rad Rad
|
||||
2330 Checkräkningskredit B13
|
||||
2350 Skulder till kreditinstitut B13
|
||||
2390 Övriga låneskulder B13
|
||||
Rad Rad
|
||||
2440 Leverantörsskulder B15
|
||||
Rad Rad
|
||||
2610 Utgående moms, 25 % B14 2611 Utgående moms på försäljning
|
||||
inom Sverige, 25 %
|
||||
B14
|
||||
2612 Utgående moms på egna uttag,
|
||||
25 %
|
||||
B14
|
||||
2613 Utgående moms för uthyrning,
|
||||
25 %
|
||||
B14
|
||||
2614 Utgående moms omvänd
|
||||
skattskyldighet, 25 %
|
||||
B14
|
||||
2615 Utgående moms import av
|
||||
varor, 25 %
|
||||
B14
|
||||
2618 Vilande utgående moms, 25 % B14
|
||||
2620 Utgående moms, 12 % B14 2621 Utgående moms på försäljning
|
||||
inom Sverige, 12 %
|
||||
B14
|
||||
2622 Utgående moms på egna uttag,
|
||||
12 %
|
||||
B14
|
||||
2623 Utgående moms för uthyrning,
|
||||
12 %
|
||||
B14
|
||||
2624 Utgående moms omvänd
|
||||
skattskyldighet, 12 %
|
||||
B14
|
||||
2625 Utgående moms import av
|
||||
varor, 12 %
|
||||
B14
|
||||
2628 Vilande utgående moms, 12 % B14
|
||||
2630 Utgående moms, 6 % B14 2631 Utgående moms på försäljning
|
||||
inom Sverige, 6 %
|
||||
B14
|
||||
2632 Utgående moms på egna uttag,
|
||||
6 %
|
||||
B14
|
||||
BAS-konton Underkonton
|
||||
23 Låneskulder
|
||||
Underkonton
|
||||
BAS-konton Underkonton
|
||||
24 Skulder till leverantörer
|
||||
26 Moms och särskilda punktskatter
|
||||
BAS-konton
|
||||
Kontoplan_K1_2018_ver1
|
||||
4/9
|
||||
2633 Utgående moms för uthyrning,
|
||||
6 %
|
||||
B14
|
||||
2634 Utgående moms omvänd
|
||||
skattskyldighet, 6 %
|
||||
B14
|
||||
2635 Utgående moms import av
|
||||
varor, 6 %
|
||||
B14
|
||||
2638 Vilande utgående moms, 6 % B14
|
||||
2640 Ingående moms B14 2641 Debiterad ingående moms B14
|
||||
2642 Debiterad ingående moms i
|
||||
anslutning till frivillig
|
||||
skattskyldighet
|
||||
B14
|
||||
2645 Beräknad ingående moms på
|
||||
förvärv från utlandet
|
||||
B14
|
||||
2646 Ingående moms på uthyrning B14
|
||||
2648 Vilande ingående moms B14
|
||||
2649 Ingående moms, blandad
|
||||
verksamhet
|
||||
B14
|
||||
2650 Redovisningskonto för moms B14 B14
|
||||
2660 Särskilda punktskatter B14 B14
|
||||
Rad Rad
|
||||
2710 Personalskatt B14
|
||||
2730 Lagstadgade/avtalade sociala
|
||||
avgifter och särskild löneskatt
|
||||
B14
|
||||
Rad Rad
|
||||
2900 Övriga skulder B16
|
||||
Rad Rad
|
||||
3000 Försäljning och utfört arbete
|
||||
samt övriga momspliktiga
|
||||
intäkter
|
||||
R1
|
||||
3100 Momsfria intäkter R2
|
||||
3200 Bil- och bostadsförmån m.m. R3
|
||||
Rad Rad
|
||||
3500 Fakturerade kostnader R1
|
||||
Rad Rad
|
||||
3700 Lämnade rabatter, bonus etc. R1/R2
|
||||
Underkonton
|
||||
35 Fakturerade kostnader
|
||||
37 Intäktskorrigeringar
|
||||
Underkonton
|
||||
BAS-konton
|
||||
Underkonton
|
||||
3 RÖRELSENS INKOMSTER/INTÄKTER
|
||||
30-34 Huvudintäkter
|
||||
BAS-konton Underkonton
|
||||
BAS-konton
|
||||
29 Övriga skulder
|
||||
27 Personalens skatter, avgifter och löneavdrag
|
||||
BAS-konton Underkonton
|
||||
BAS-konton
|
||||
Kontoplan_K1_2018_ver1
|
||||
5/9
|
||||
Rad Rad
|
||||
3900 Övriga rörelseintäkter R1/R2
|
||||
3970 Vinst vid avyttring av
|
||||
immateriella och materiella
|
||||
anläggningstillgångar
|
||||
R2
|
||||
3980 Erhållna bidrag R2
|
||||
Rad Rad
|
||||
4000 Varor R5
|
||||
Rad Rad
|
||||
4600 Legoarbeten och
|
||||
underentreprenader
|
||||
R5
|
||||
Rad Rad
|
||||
4700 Erhållna rabatter, bonus etc. R6
|
||||
Rad Rad
|
||||
4900 Förändring av lager R5
|
||||
Rad Rad
|
||||
5000 Lokalkostnader R6
|
||||
Rad Rad
|
||||
5100 Fastighetskostnader R6
|
||||
Rad Rad
|
||||
5200 Hyra av anläggningstillgångar R6
|
||||
Underkonton
|
||||
Underkonton
|
||||
BAS-konton Underkonton
|
||||
39 Övriga rörelseintäkter
|
||||
Underkonton
|
||||
BAS-konton
|
||||
4 UTGIFTER/KOSTNADER FÖR VAROR, MATERIAL OCH VISSA
|
||||
KÖPTA TJÄNSTER
|
||||
Underkonton
|
||||
47 Reduktion av inköpspriser
|
||||
49 Förändring av lager
|
||||
BAS-konton Underkonton
|
||||
Underkonton
|
||||
BAS-konton Underkonton
|
||||
46 Legoarbeten, underentreprenader
|
||||
BAS-konton
|
||||
BAS-konton
|
||||
BAS-konton
|
||||
40-45 Inköp av varor och material
|
||||
BAS-konton
|
||||
5-6 ÖVRIGA EXTERNA RÖRELSEUTGIFTER/KOSTNADER
|
||||
50 Lokalkostnader
|
||||
51 Fastighetskostnader
|
||||
52 Hyra av anläggningstillgångar
|
||||
54 Förbrukningsinventarier och förbrukningsmaterial
|
||||
Kontoplan_K1_2018_ver1
|
||||
6/9
|
||||
Rad Rad
|
||||
5400 Förbrukningsinventarier och
|
||||
förbrukningsmaterial
|
||||
R6
|
||||
Rad Rad
|
||||
5500 Reparation och underhåll R6
|
||||
Rad Rad
|
||||
5600 Kostnader för transportmedel R6
|
||||
5610 Personbilskostnader R6 5611 Drivmedel för personbilar R6
|
||||
5612 Försäkring och skatt för
|
||||
personbilar
|
||||
R6
|
||||
5613 Reparation och underhåll av
|
||||
personbilar
|
||||
R6
|
||||
5615 Leasing av personbilar R6
|
||||
5618 Schablonmässig milkostnad
|
||||
privat personbil
|
||||
R6
|
||||
5619 Övriga personbilskostnader R6
|
||||
5620 Lastbilskostnader R6
|
||||
Rad Rad
|
||||
5700 Frakter och transporter R6
|
||||
Rad Rad
|
||||
5800 Resekostnader R6
|
||||
Rad Rad
|
||||
5900 Reklam och PR R6
|
||||
Rad Rad
|
||||
6000 Övriga försäljningskostnader
|
||||
R6
|
||||
R6 R6
|
||||
6070 Representation R6 R6 6071 Representation, avdragsgill
|
||||
6072 Representation, ej avdragsgill R6
|
||||
+
|
||||
NE
|
||||
sid.
|
||||
2
|
||||
BAS-konton
|
||||
BAS-konton
|
||||
Underkonton
|
||||
55 Reparation och underhåll
|
||||
56 Kostnader för transportmedel
|
||||
BAS-konton Underkonton
|
||||
Underkonton
|
||||
Underkonton
|
||||
BAS-konton Underkonton
|
||||
57 Frakter och transporter
|
||||
58 Resekostnader
|
||||
59 Reklam och PR
|
||||
60 Övriga försäljningskostnader
|
||||
BAS-konton
|
||||
Underkonton
|
||||
BAS-konton
|
||||
Underkonton
|
||||
BAS-konton
|
||||
Kontoplan_K1_2018_ver1
|
||||
7/9
|
||||
Rad Rad
|
||||
6100 Kontorsmateriel och trycksaker R6
|
||||
Rad Rad
|
||||
6200 Tele och post R6
|
||||
Rad Rad
|
||||
6300 Företagsförsäkringar och
|
||||
övriga riskkostnader
|
||||
R6
|
||||
6310 Företagsförsäkringar R6
|
||||
Rad Rad
|
||||
6500 Övriga externa tjänster R6
|
||||
Rad Rad
|
||||
6800 Inhyrd personal R6
|
||||
Rad Rad
|
||||
6900 Övriga kostnader R6
|
||||
6980 Föreningsavgifter R6
|
||||
Rad Rad
|
||||
7000 Löner till anställda R7
|
||||
Rad Rad
|
||||
7300 Kostnadsersättningar och
|
||||
förmåner
|
||||
R7
|
||||
Rad Rad
|
||||
7400 Pensionskostnader R7
|
||||
74 Pensionskostnader
|
||||
61 Kontorsmateriel och trycksaker
|
||||
62 Tele och post
|
||||
BAS-konton Underkonton
|
||||
BAS-konton Underkonton
|
||||
63 Företagsförsäkringar och övriga riskkostnader
|
||||
Underkonton
|
||||
70 Löner till anställda
|
||||
7 UTGIFTER/KOSTNADER FÖR PERSONAL, AVSKRIVNINGAR
|
||||
BAS-konton
|
||||
68 Inhyrd personal
|
||||
69 Övriga kostnader
|
||||
BAS-konton Underkonton
|
||||
BAS-konton Underkonton
|
||||
BAS-konton Underkonton
|
||||
65 Övriga externa tjänster
|
||||
BAS-konton Underkonton
|
||||
BAS-konton Underkonton
|
||||
73 Kostnadsersättningar och förmåner
|
||||
BAS-konton Underkonton
|
||||
Kontoplan_K1_2018_ver1
|
||||
8/9
|
||||
Rad Rad
|
||||
7500 Sociala och andra avgifter
|
||||
enligt lag och avtal
|
||||
R7
|
||||
Rad Rad
|
||||
7600 Övriga personalkostnader R7 7631 Personalrepresentation,
|
||||
avdragsgill
|
||||
R7
|
||||
7632 Personalrepresentation, ej
|
||||
avdragsgill
|
||||
R7
|
||||
+
|
||||
NE
|
||||
sid.
|
||||
2
|
||||
Rad Rad
|
||||
7700 Nedskrivningar R9
|
||||
alt.
|
||||
R10
|
||||
Rad Rad
|
||||
7810 Avskrivningar på immateriella
|
||||
anläggningstillgångar
|
||||
R10
|
||||
7820 Avskrivningar på byggnader
|
||||
och markanläggningar
|
||||
R9
|
||||
7830 Avskrivningar på maskiner och
|
||||
inventarier
|
||||
R10
|
||||
Rad Rad
|
||||
7970 Förlust vid avyttring av
|
||||
immateriella och materiella
|
||||
anläggningstillgångar
|
||||
R6
|
||||
7980 Ersättningsfonder R9/
|
||||
10
|
||||
Rad Rad
|
||||
8 FINANSIELLA OCH ANDRA INKOMSTER/INTÄKTER OCH
|
||||
UTGIFTER/ KOSTNADER
|
||||
Underkonton
|
||||
BAS-konton Underkonton
|
||||
79 Övriga rörelsekostnader
|
||||
77 Nedskrivningar och återföring av nedskrivningar
|
||||
76 Övriga personalkostnader
|
||||
78 Avskrivningar
|
||||
83 Övriga ränteintäkter och liknande resultatposter
|
||||
BAS-konton Underkonton
|
||||
BAS-konton Underkonton
|
||||
75 Sociala och andra avgifter enligt lag och avtal
|
||||
BAS-konton
|
||||
BAS-konton Underkonton
|
||||
BAS-konton Underkonton
|
||||
Kontoplan_K1_2018_ver1
|
||||
9/9
|
||||
8310 Ränteintäkter och utdelningar R4 8314 Skattefria ränteintäkter R4
|
||||
+
|
||||
NE
|
||||
sid.
|
||||
2
|
||||
8330 Valutakursdifferenser på
|
||||
fordringar och placeringar
|
||||
R4
|
||||
Rad Rad
|
||||
8410 Räntekostnader för skulder R8
|
||||
8430 Valutakursdifferenser på
|
||||
skulder R8
|
||||
Rad Rad
|
||||
8990 Resultat R11 R11 8999 Årets resultat R11
|
||||
84 Räntekostnader och liknande
|
||||
BAS-konton Underkonton
|
||||
BAS-konton Underkonton
|
||||
88 Bokslutsdispositioner
|
||||
89 Årets resultat
|
||||
Kontoplan_K1_2018_ver1
|
||||
@@ -0,0 +1,51 @@
|
||||
ERP-Base: Gap-analys mot svensk bokföringsmarknad
|
||||
|
||||
1. SAKNAS HELT — Kritiska luckor
|
||||
1.1 Leverantörsreskontra
|
||||
Alla etablerade system har fullständig leverantörsreskontra: registrering av inkommande fakturor, förfallodatum, betalningsstatus, automatisk bokföring vid betalning. Ditt system saknar tabeller och flöden för leverantörsfakturor. Detta är ett absolut krav för att kunna kallas bokföringssystem.
|
||||
Behövs: suppliers-tabell, supplier_invoices-tabell, flöde för registrering/betalning/bokföring, leverantörsreskontra-rapport, stöd för både kontant- och fakturametoden.
|
||||
1.2 Kundreskontra (formellt)
|
||||
Du har invoices och customers, men det saknas en explicit kundreskontra-vy som visar utestående fordringar, förfallna fakturor, och avstämning mot konto 1510. Alla konkurrenter har detta som standardfunktion.
|
||||
1.3 Lönehantering
|
||||
salary_payments finns men alla konkurrenter (Fortnox, Bokio, Visma) erbjuder komplett lönehantering: lönespecifikationer, arbetsgivaravgifter, skattetabeller (FOS-förfrågan mot Skatteverket), AGI-rapportering, semesterhantering. Detta är en separat modul som de flesta SME-kunder förväntar sig.
|
||||
Behövs: Skattetabellhantering, lönespec-generering (PDF), arbetsgivaravgiftsberäkning, AGI-rapportering, semesterskuld, förmånsberäkning (bil, etc).
|
||||
1.4 Årsredovisning (K2/K3)
|
||||
Aktiebolag måste lämna årsredovisning till Bolagsverket. Fortnox och Björn Lundén genererar detta. Din plattform har årsbokslut men saknar årsredovisningsgenerering med förvaltningsberättelse, noter, och formell K2/K3-struktur.
|
||||
Behövs: Generering av förvaltningsberättelse, resultaträkning (K2-format), balansräkning (K2-format), noter, digital inlämning till Bolagsverket (XBRL).
|
||||
1.5 Kontantmetod-stöd
|
||||
Många enskilda firmor bokför med kontantmetoden (bokslutsmetoden). Ditt system verkar byggt kring faktureringsmetoden. Båda måste stödjas, med automatisk övergång till fakturametod vid bokslut för kontantmetoden.
|
||||
1.6 Anläggningsregister
|
||||
Inventarier, maskiner, fastigheter — med avskrivningsplaner (linjär/degressiv), restvärden, och automatisk avskrivningsbokföring. Saknas helt. Krävs för AB med tillgångar.
|
||||
1.7 Offert/Order-flöde
|
||||
Fortnox och Visma har offert → order → faktura-kedja. Inte nödvändigt för MVP men förväntat i ett komplett system.
|
||||
|
||||
2. FINNS MEN OTILLRÄCKLIGT — Behöver utökas
|
||||
2.1 Bokföringsmallar / Konteringshjälp
|
||||
Bokio's stora USP är smart konteringshjälp: användaren väljer "IT-tjänst 25% moms" och systemet konterar automatiskt. Du har AI-kategorisering, men saknar troligen ett bibliotek av färdiga bokföringsmallar för vanliga affärshändelser som en nybörjare kan välja mellan.
|
||||
Behövs: 50-100 vanliga transaktionsmallar (kontorsmateriell, IT-tjänst, bensin, representation, etc) med korrekt moms och kontering.
|
||||
2.2 Bankavstämning
|
||||
Du har PSD2-transaktionssynk, men behöver explicit bankavstämning: matcha banktransaktioner mot bokförda poster, markera avstämda, visa differenser. Alla konkurrenter har detta.
|
||||
2.3 Momsdeklaration
|
||||
Du nämner "10 rutor" men verifierar att den genererar korrekt SKV 4820-underlag? Behöver också stödja: EU-handel (omvänd skattskyldighet), import/export-moms, olika momssatser (25/12/6/0%), tröskelbelopp (120 000 SEK från 2025).
|
||||
2.4 SIE-export
|
||||
Du har SIE4-export. Verifiera att SIE-import också fungerar korrekt (ingående balanser, verifikationer, kontoplan) — detta är kritiskt för att kunder ska kunna byta till ditt system från Fortnox/Bokio.
|
||||
2.5 Rapporter
|
||||
Du har saldobalans, resultat, balans, moms. Saknar troligen:
|
||||
Huvudbok (alla transaktioner per konto)
|
||||
Grundbok (verifikationslista i datumordning)
|
||||
Kundreskontra-rapport
|
||||
Leverantörsreskontra-rapport
|
||||
Periodrapporter (jämförelse mellan perioder)
|
||||
Kassaflödesanalys
|
||||
|
||||
3. HYGIEN-FUNKTIONER — Förväntas av alla
|
||||
3.1 Autentisering
|
||||
BankID-inloggning förväntas av svenska användare. Inte nödvändigt dag 1, men e-post + lösenord + 2FA via TOTP är minimum.
|
||||
3.2 Mobilapp / Responsivt
|
||||
Alla konkurrenter har mobilapp eller fullt responsivt gränssnitt. Kvittofotografering från mobil är en hygienfaktor.
|
||||
3.3 Periodlåsning
|
||||
Bokföringslagen kräver att bokföring är "varaktig" — du behöver kunna låsa perioder så att poster inte kan ändras i efterhand utan att det syns. Du har WORM-arkiv, verifiera att periodlåsning är implementerad.
|
||||
3.4 Fleranvändarstöd
|
||||
Roller: ägare, redovisningskonsult (extern), anställd. Behörigheter per modul. Alla konkurrenter har detta. Redovisningskonsult-access är affärskritiskt — byråer är den viktigaste distributionskanalen.
|
||||
3.5 Verifikationskedja
|
||||
Varje verifikation behöver: löpnummer utan luckor, datum, belopp, motkonto, beskrivning, bifogat underlag. Du har detta delvis via WORM + voucher numbering, men verifiera fullständigt BFL-compliance.
|
||||
@@ -52,22 +52,25 @@ export interface CategorizationProvider {
|
||||
// BAS Account + Category Mapping (used in prompt)
|
||||
// ============================================================
|
||||
|
||||
const CATEGORY_ACCOUNT_MAP: Record<string, { account: string; label: string }> = {
|
||||
income_services: { account: '3001', label: 'Tjänsteförsäljning' },
|
||||
income_products: { account: '3001', label: 'Varuförsäljning' },
|
||||
income_other: { account: '3900', label: 'Övriga intäkter' },
|
||||
expense_equipment: { account: '5410', label: 'Förbrukningsinventarier' },
|
||||
expense_software: { account: '5420', label: 'Programvara' },
|
||||
expense_travel: { account: '5800', label: 'Resekostnader' },
|
||||
expense_office: { account: '5010', label: 'Lokalhyra/kontorskostnad' },
|
||||
expense_marketing: { account: '5910', label: 'Annonsering/marknadsföring' },
|
||||
expense_professional_services: { account: '6530', label: 'Redovisning/konsulttjänster' },
|
||||
expense_education: { account: '6991', label: 'Utbildning' },
|
||||
expense_bank_fees: { account: '6570', label: 'Bankavgifter' },
|
||||
expense_card_fees: { account: '6570', label: 'Kortavgifter' },
|
||||
expense_currency_exchange: { account: '7960', label: 'Valutakursförluster' },
|
||||
expense_other: { account: '6991', label: 'Övriga kostnader' },
|
||||
private: { account: '2013', label: 'Privat uttag (EF) / Skuld till ägare (AB)' },
|
||||
function getCategoryAccountMap(entityType: EntityType): Record<string, { account: string; label: string }> {
|
||||
const educationAccount = entityType === 'aktiebolag' ? '7610' : '6991'
|
||||
return {
|
||||
income_services: { account: '3001', label: 'Tjänsteförsäljning' },
|
||||
income_products: { account: '3001', label: 'Varuförsäljning' },
|
||||
income_other: { account: '3900', label: 'Övriga intäkter' },
|
||||
expense_equipment: { account: '5410', label: 'Förbrukningsinventarier' },
|
||||
expense_software: { account: '5420', label: 'Programvara' },
|
||||
expense_travel: { account: '5800', label: 'Resekostnader' },
|
||||
expense_office: { account: '5010', label: 'Lokalhyra/kontorskostnad' },
|
||||
expense_marketing: { account: '5910', label: 'Annonsering/marknadsföring' },
|
||||
expense_professional_services: { account: '6530', label: 'Redovisning/konsulttjänster' },
|
||||
expense_education: { account: educationAccount, label: 'Utbildning' },
|
||||
expense_bank_fees: { account: '6570', label: 'Bankavgifter' },
|
||||
expense_card_fees: { account: '6570', label: 'Kortavgifter' },
|
||||
expense_currency_exchange: { account: '7960', label: 'Valutakursförluster' },
|
||||
expense_other: { account: '6991', label: 'Övriga kostnader' },
|
||||
private: { account: '2013', label: 'Privat uttag (EF) / Skuld till ägare (AB)' },
|
||||
}
|
||||
}
|
||||
|
||||
const NON_DEDUCTIBLE_RULES = `
|
||||
@@ -107,12 +110,13 @@ export class AnthropicCategorizationProvider implements CategorizationProvider {
|
||||
if (batch.length === 0) return []
|
||||
|
||||
const privateAccount = context.entityType === 'aktiebolag' ? '2893' : '2013'
|
||||
const categoryAccountMap = getCategoryAccountMap(context.entityType)
|
||||
|
||||
const systemPrompt = `Du är expert på svensk bokföring och kategorisering av banktransaktioner enligt BAS-kontoplanen.
|
||||
Din uppgift är att kategorisera varje transaktion till rätt kategori och BAS-konto.
|
||||
|
||||
KATEGORIER OCH BAS-KONTON:
|
||||
${Object.entries(CATEGORY_ACCOUNT_MAP)
|
||||
${Object.entries(categoryAccountMap)
|
||||
.map(([cat, info]) => `- ${cat}: ${info.account} (${info.label})`)
|
||||
.join('\n')}
|
||||
|
||||
@@ -209,7 +213,7 @@ Returnera ENDAST JSON-objektet, ingen annan text.`
|
||||
jsonText = jsonText.trim()
|
||||
|
||||
const parsed = JSON.parse(jsonText)
|
||||
return this.validateSuggestions(parsed.suggestions || [], batch)
|
||||
return this.validateSuggestions(parsed.suggestions || [], batch, context.entityType)
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error : new Error('Unknown error')
|
||||
|
||||
@@ -231,12 +235,14 @@ Returnera ENDAST JSON-objektet, ingen annan text.`
|
||||
|
||||
private validateSuggestions(
|
||||
raw: unknown[],
|
||||
transactions: TransactionForCategorization[]
|
||||
transactions: TransactionForCategorization[],
|
||||
entityType: EntityType
|
||||
): CategorizationSuggestion[] {
|
||||
if (!Array.isArray(raw)) return []
|
||||
|
||||
const categoryAccountMap = getCategoryAccountMap(entityType)
|
||||
const validTransactionIds = new Set(transactions.map((t) => t.id))
|
||||
const validCategories = new Set(Object.keys(CATEGORY_ACCOUNT_MAP).concat(['uncategorized']))
|
||||
const validCategories = new Set(Object.keys(categoryAccountMap).concat(['uncategorized']))
|
||||
|
||||
return raw
|
||||
.filter(
|
||||
@@ -249,7 +255,7 @@ Returnera ENDAST JSON-objektet, ingen annan text.`
|
||||
? (s.category as TransactionCategory)
|
||||
: 'expense_other'
|
||||
|
||||
const accountInfo = CATEGORY_ACCOUNT_MAP[category]
|
||||
const accountInfo = categoryAccountMap[category]
|
||||
|
||||
return {
|
||||
transactionId: s.transactionId as string,
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { getDaysUntilExpiry, isConsentExpiringSoon } from '@/lib/banking/enable-banking'
|
||||
import { getDaysUntilExpiry, isConsentExpiringSoon } from '../lib/api-client'
|
||||
import {
|
||||
CreditCard,
|
||||
AlertTriangle,
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user