Merge remote-tracking branch 'origin/main' into code-quality-improvements

This commit is contained in:
Emil
2026-02-21 16:10:02 +01:00
121 changed files with 12004 additions and 1899 deletions
+218
View File
@@ -0,0 +1,218 @@
'use client'
import { useState, useRef, useEffect, useMemo, useCallback } from 'react'
import { Input } from '@/components/ui/input'
import { getAccountClassName } from '@/lib/bookkeeping/account-descriptions'
import type { BASAccount } from '@/types'
interface AccountComboboxProps {
value: string
accounts: BASAccount[]
onChange: (accountNumber: string) => void
}
const MAX_RESULTS = 50
export default function AccountCombobox({ value, accounts, onChange }: AccountComboboxProps) {
const [search, setSearch] = useState(value)
const [isOpen, setIsOpen] = useState(false)
const [highlightedIndex, setHighlightedIndex] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const inputRef = useRef<HTMLInputElement>(null)
const listRef = useRef<HTMLDivElement>(null)
// Sync external value changes into the search field
useEffect(() => {
setSearch(value)
}, [value])
// Filter accounts based on search input
const filteredAccounts = useMemo(() => {
if (!search) return accounts.slice(0, MAX_RESULTS)
const trimmed = search.trim()
if (!trimmed) return accounts.slice(0, MAX_RESULTS)
const startsWithDigit = /^\d/.test(trimmed)
if (startsWithDigit) {
return accounts
.filter((a) => a.account_number.startsWith(trimmed))
.slice(0, MAX_RESULTS)
}
const lowerSearch = trimmed.toLowerCase()
return accounts
.filter((a) => a.account_name.toLowerCase().includes(lowerSearch))
.slice(0, MAX_RESULTS)
}, [accounts, search])
// Group filtered accounts by class
const groupedAccounts = useMemo(() => {
const groups: { className: string; accounts: BASAccount[] }[] = []
const groupMap = new Map<string, BASAccount[]>()
for (const account of filteredAccounts) {
const className = getAccountClassName(account.account_class)
if (!groupMap.has(className)) {
groupMap.set(className, [])
}
groupMap.get(className)!.push(account)
}
for (const [className, accts] of groupMap) {
groups.push({ className, accounts: accts })
}
return groups
}, [filteredAccounts])
// Flat list for keyboard navigation
const flatList = useMemo(() => filteredAccounts, [filteredAccounts])
// Reset highlight when filtered results change
useEffect(() => {
setHighlightedIndex(0)
}, [filteredAccounts])
// Scroll highlighted item into view
useEffect(() => {
if (!isOpen || !listRef.current) return
const highlighted = listRef.current.querySelector('[data-highlighted="true"]')
if (highlighted) {
highlighted.scrollIntoView({ block: 'nearest' })
}
}, [highlightedIndex, isOpen])
// Close dropdown when clicking outside
useEffect(() => {
function handleClickOutside(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setIsOpen(false)
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [])
const selectAccount = useCallback(
(accountNumber: string) => {
onChange(accountNumber)
setSearch(accountNumber)
setIsOpen(false)
inputRef.current?.blur()
},
[onChange]
)
const handleKeyDown = (e: React.KeyboardEvent) => {
if (!isOpen) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
setIsOpen(true)
e.preventDefault()
}
return
}
switch (e.key) {
case 'ArrowDown':
e.preventDefault()
setHighlightedIndex((prev) => Math.min(prev + 1, flatList.length - 1))
break
case 'ArrowUp':
e.preventDefault()
setHighlightedIndex((prev) => Math.max(prev - 1, 0))
break
case 'Enter':
e.preventDefault()
if (flatList[highlightedIndex]) {
selectAccount(flatList[highlightedIndex].account_number)
}
break
case 'Escape':
e.preventDefault()
setIsOpen(false)
break
}
}
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value
setSearch(newValue)
onChange(newValue)
if (!isOpen) {
setIsOpen(true)
}
}
const handleFocus = () => {
setIsOpen(true)
}
// Find matching account for helper text
const matchedAccount = useMemo(() => {
if (!value || value.length !== 4) return null
return accounts.find((a) => a.account_number === value) || null
}, [value, accounts])
return (
<div ref={containerRef} className="relative">
<Input
ref={inputRef}
value={search}
onChange={handleInputChange}
onFocus={handleFocus}
onKeyDown={handleKeyDown}
placeholder="1930"
className="font-mono h-8"
maxLength={4}
autoComplete="off"
/>
{/* Account name helper text (md+ screens only) */}
{matchedAccount && (
<p className="hidden md:block text-[11px] text-muted-foreground truncate mt-0.5 leading-tight">
{matchedAccount.account_name}
</p>
)}
{/* Dropdown */}
{isOpen && flatList.length > 0 && (
<div
ref={listRef}
className="absolute z-50 top-full left-0 mt-1 w-64 max-h-[300px] overflow-y-auto rounded-md border border-input bg-card shadow-md"
>
{groupedAccounts.map((group) => (
<div key={group.className}>
<div className="sticky top-0 px-2 py-1.5 text-xs font-semibold text-muted-foreground bg-muted border-b border-input">
{group.className}
</div>
{group.accounts.map((account) => {
const flatIndex = flatList.indexOf(account)
const isHighlighted = flatIndex === highlightedIndex
return (
<button
key={account.account_number}
type="button"
data-highlighted={isHighlighted}
className={`w-full text-left px-2 py-1.5 text-sm cursor-pointer flex items-baseline gap-2 ${
isHighlighted ? 'bg-primary/10 text-primary' : 'hover:bg-muted/50'
}`}
onMouseDown={(e) => {
e.preventDefault()
selectAccount(account.account_number)
}}
onMouseEnter={() => setHighlightedIndex(flatIndex)}
>
<span className="font-mono shrink-0">{account.account_number}</span>
<span className="truncate">{account.account_name}</span>
</button>
)
})}
</div>
))}
</div>
)}
</div>
)
}
+225
View File
@@ -0,0 +1,225 @@
'use client'
import { useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Loader2, AlertTriangle } from 'lucide-react'
import { isStandardBASAccount } from '@/lib/bookkeeping/bas-reference'
interface AddAccountDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onCreated: () => void
}
function deriveAccountType(accountNumber: string): { type: string; balance: string } {
const cls = parseInt(accountNumber[0])
switch (cls) {
case 1: return { type: 'asset', balance: 'debit' }
case 2: {
const group = parseInt(accountNumber.substring(0, 2))
if (group <= 20) return { type: 'equity', balance: 'credit' }
return { type: 'liability', balance: 'credit' }
}
case 3: return { type: 'revenue', balance: 'credit' }
case 4: case 5: case 6: case 7: return { type: 'expense', balance: 'debit' }
case 8: {
const group = parseInt(accountNumber.substring(0, 2))
if (group >= 83 && group <= 83) return { type: 'revenue', balance: 'credit' }
if (group >= 84 && group <= 84) return { type: 'expense', balance: 'debit' }
return { type: 'expense', balance: 'debit' }
}
default: return { type: 'expense', balance: 'debit' }
}
}
export function AddAccountDialog({ open, onOpenChange, onCreated }: AddAccountDialogProps) {
const [accountNumber, setAccountNumber] = useState('')
const [accountName, setAccountName] = useState('')
const [description, setDescription] = useState('')
const [defaultVatCode, setDefaultVatCode] = useState('')
const [sruCode, setSruCode] = useState('')
const [normalBalance, setNormalBalance] = useState<'debit' | 'credit'>('debit')
const [isSaving, setIsSaving] = useState(false)
const [error, setError] = useState('')
const isBASMatch = accountNumber.length === 4 && isStandardBASAccount(accountNumber)
const derived = accountNumber.length === 4 ? deriveAccountType(accountNumber) : null
async function handleCreate() {
setError('')
if (!/^\d{4}$/.test(accountNumber)) {
setError('Kontonumret måste vara exakt 4 siffror')
return
}
if (!accountName.trim()) {
setError('Kontonamn krävs')
return
}
setIsSaving(true)
try {
const response = await fetch('/api/bookkeeping/accounts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
account_number: accountNumber,
account_name: accountName.trim(),
account_type: derived?.type || 'expense',
normal_balance: normalBalance,
description: description || null,
default_vat_code: defaultVatCode || null,
sru_code: sruCode || null,
}),
})
if (!response.ok) {
const data = await response.json()
throw new Error(data.error || 'Kunde inte skapa kontot')
}
// Reset form
setAccountNumber('')
setAccountName('')
setDescription('')
setDefaultVatCode('')
setSruCode('')
onCreated()
onOpenChange(false)
} catch (err) {
setError(err instanceof Error ? err.message : 'Något gick fel')
} finally {
setIsSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Lägg till eget konto</DialogTitle>
<DialogDescription>
Skapa ett eget konto utanför BAS-standarden
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-2">
{isBASMatch && (
<div className="flex items-start gap-2 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800 p-3">
<AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" />
<p className="text-sm text-amber-800 dark:text-amber-300">
Kontonummer {accountNumber} finns i BAS-standarden. Använd &quot;BAS-katalog&quot;-fliken för att aktivera standardkonton istället.
</p>
</div>
)}
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Kontonummer</Label>
<Input
value={accountNumber}
onChange={(e) => {
const v = e.target.value.replace(/\D/g, '').slice(0, 4)
setAccountNumber(v)
if (v.length === 4) {
const d = deriveAccountType(v)
setNormalBalance(d.balance as 'debit' | 'credit')
}
}}
placeholder="T.ex. 1935"
maxLength={4}
className="font-mono"
/>
</div>
<div className="space-y-2">
<Label>Normal saldo</Label>
<Select value={normalBalance} onValueChange={(v) => setNormalBalance(v as 'debit' | 'credit')}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="debit">Debet</SelectItem>
<SelectItem value="credit">Kredit</SelectItem>
</SelectContent>
</Select>
</div>
</div>
{derived && (
<p className="text-xs text-muted-foreground">
Auto-detekterad typ:{' '}
<span className="font-medium">
{derived.type === 'asset' ? 'Tillgång' : derived.type === 'liability' ? 'Skuld' : derived.type === 'equity' ? 'Eget kapital' : derived.type === 'revenue' ? 'Intäkt' : 'Kostnad'}
</span>
</p>
)}
<div className="space-y-2">
<Label>Kontonamn</Label>
<Input
value={accountName}
onChange={(e) => setAccountName(e.target.value)}
placeholder="T.ex. Sparkonto företag"
/>
</div>
<div className="space-y-2">
<Label>Beskrivning <span className="text-muted-foreground">(valfritt)</span></Label>
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Kort beskrivning av kontots användning"
rows={2}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Momskod <span className="text-muted-foreground">(valfritt)</span></Label>
<Input
value={defaultVatCode}
onChange={(e) => setDefaultVatCode(e.target.value)}
placeholder="T.ex. MP1"
/>
</div>
<div className="space-y-2">
<Label>SRU-kod <span className="text-muted-foreground">(valfritt)</span></Label>
<Input
value={sruCode}
onChange={(e) => setSruCode(e.target.value)}
placeholder="T.ex. 7201"
/>
</div>
</div>
{error && (
<p className="text-sm text-destructive">{error}</p>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Avbryt
</Button>
<Button onClick={handleCreate} disabled={isSaving || accountNumber.length !== 4 || !accountName.trim()}>
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Skapa konto
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,257 @@
'use client'
import { useState, useCallback, useRef } from 'react'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Upload, FileText, ImageIcon, X, Loader2 } from 'lucide-react'
export interface UploadedFile {
id?: string
file: File
status: 'pending' | 'uploading' | 'uploaded' | 'error'
error?: string
fileName: string
fileSize: number
}
interface DocumentUploadZoneProps {
files: UploadedFile[]
onFilesChange: (files: UploadedFile[]) => void
journalEntryId?: string
maxFiles?: number
disabled?: boolean
compact?: boolean
}
const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB
const ACCEPTED_TYPES = ['application/pdf', 'image/jpeg', 'image/png', 'image/webp']
const ACCEPTED_EXTENSIONS = '.pdf,.jpg,.jpeg,.png,.webp'
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
function isImageType(type: string): boolean {
return type.startsWith('image/')
}
export default function DocumentUploadZone({
files,
onFilesChange,
journalEntryId,
maxFiles = 5,
disabled = false,
compact = false,
}: DocumentUploadZoneProps) {
const [isDragging, setIsDragging] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
const uploadFile = useCallback(async (file: UploadedFile): Promise<UploadedFile> => {
const formData = new FormData()
formData.append('file', file.file)
formData.append('upload_source', 'file_upload')
if (journalEntryId) {
formData.append('journal_entry_id', journalEntryId)
}
try {
const res = await fetch('/api/documents', {
method: 'POST',
body: formData,
})
const result = await res.json()
if (result.error) {
return { ...file, status: 'error', error: result.error }
}
return { ...file, status: 'uploaded', id: result.data?.id }
} catch {
return { ...file, status: 'error', error: 'Uppladdning misslyckades' }
}
}, [journalEntryId])
const handleFiles = useCallback(async (newFiles: File[]) => {
const remaining = maxFiles - files.length
if (remaining <= 0) return
const validFiles: UploadedFile[] = []
for (const file of newFiles.slice(0, remaining)) {
if (!ACCEPTED_TYPES.includes(file.type)) {
validFiles.push({
file,
status: 'error',
error: 'Filtypen stöds inte',
fileName: file.name,
fileSize: file.size,
})
continue
}
if (file.size > MAX_FILE_SIZE) {
validFiles.push({
file,
status: 'error',
error: 'Filen är för stor (max 10 MB)',
fileName: file.name,
fileSize: file.size,
})
continue
}
validFiles.push({
file,
status: 'uploading',
fileName: file.name,
fileSize: file.size,
})
}
let currentFiles = [...files, ...validFiles]
onFilesChange(currentFiles)
// Upload files that passed validation
for (const f of validFiles.filter((f) => f.status === 'uploading')) {
const result = await uploadFile(f)
currentFiles = currentFiles.map((cf) =>
cf.fileName === result.fileName && cf.status === 'uploading' ? result : cf
)
onFilesChange([...currentFiles])
}
}, [files, maxFiles, onFilesChange, uploadFile])
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault()
if (!disabled) setIsDragging(true)
}, [disabled])
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault()
setIsDragging(false)
}, [])
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault()
setIsDragging(false)
if (disabled) return
const droppedFiles = Array.from(e.dataTransfer.files)
handleFiles(droppedFiles)
}, [disabled, handleFiles])
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const selectedFiles = e.target.files
if (selectedFiles) {
handleFiles(Array.from(selectedFiles))
}
// Reset input so the same file can be re-selected
if (inputRef.current) inputRef.current.value = ''
}, [handleFiles])
const removeFile = useCallback((index: number) => {
onFilesChange(files.filter((_, i) => i !== index))
}, [files, onFilesChange])
const isUploading = files.some((f) => f.status === 'uploading')
return (
<div className="space-y-2">
{/* Drop zone */}
<div
className={`
relative border-2 border-dashed rounded-lg text-center transition-colors
${compact ? 'p-3' : 'p-5'}
${isDragging ? 'border-primary bg-primary/5' : 'border-muted-foreground/25'}
${disabled ? 'pointer-events-none opacity-50' : 'cursor-pointer hover:border-primary/50'}
`}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
onClick={() => inputRef.current?.click()}
>
<input
ref={inputRef}
type="file"
multiple
accept={ACCEPTED_EXTENSIONS}
className="hidden"
onChange={handleInputChange}
disabled={disabled}
/>
<div className={compact ? 'flex items-center justify-center gap-2' : 'space-y-2'}>
<Upload className={compact ? 'h-4 w-4 text-muted-foreground' : 'mx-auto h-8 w-8 text-muted-foreground'} />
<div>
<p className={compact ? 'text-sm text-muted-foreground' : 'text-sm font-medium'}>
{compact ? 'Dra och släpp eller klicka' : 'Dra och släpp filer här'}
</p>
{!compact && (
<p className="text-xs text-muted-foreground">
PDF, bilder (max 10 MB)
</p>
)}
</div>
</div>
</div>
{/* File list */}
{files.length > 0 && (
<div className="space-y-1">
{files.map((file, index) => (
<div
key={`${file.fileName}-${index}`}
className="flex items-center gap-2 text-sm py-1.5 px-2 rounded bg-muted/50"
>
{isImageType(file.file.type) ? (
<ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
) : (
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
)}
<span className="truncate flex-1">{file.fileName}</span>
<span className="text-xs text-muted-foreground shrink-0">
{formatFileSize(file.fileSize)}
</span>
{file.status === 'uploading' && (
<Loader2 className="h-3.5 w-3.5 animate-spin text-primary shrink-0" />
)}
{file.status === 'uploaded' && (
<Badge variant="success" className="text-xs px-1.5 py-0">
Uppladdad
</Badge>
)}
{file.status === 'error' && (
<>
<Badge variant="destructive" className="text-xs px-1.5 py-0">
Fel
</Badge>
{file.error && (
<span className="text-xs text-destructive">{file.error}</span>
)}
</>
)}
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0"
onClick={(e) => {
e.stopPropagation()
removeFile(index)
}}
disabled={file.status === 'uploading'}
>
<X className="h-3 w-3" />
</Button>
</div>
))}
</div>
)}
{isUploading && (
<p className="text-xs text-muted-foreground">Laddar upp...</p>
)}
</div>
)
}
@@ -0,0 +1,139 @@
'use client'
import { useState } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Loader2 } from 'lucide-react'
import type { BASAccount } from '@/types'
interface EditAccountDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
account: BASAccount
onSaved: () => void
}
export function EditAccountDialog({ open, onOpenChange, account, onSaved }: EditAccountDialogProps) {
const [accountName, setAccountName] = useState(account.account_name)
const [description, setDescription] = useState(account.description || '')
const [defaultVatCode, setDefaultVatCode] = useState(account.default_vat_code || '')
const [sruCode, setSruCode] = useState(account.sru_code || '')
const [isActive, setIsActive] = useState(account.is_active)
const [isSaving, setIsSaving] = useState(false)
async function handleSave() {
setIsSaving(true)
try {
const response = await fetch(`/api/bookkeeping/accounts/${account.account_number}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
account_name: accountName,
description: description || null,
default_vat_code: defaultVatCode || null,
sru_code: sruCode || null,
is_active: isActive,
}),
})
if (!response.ok) {
const data = await response.json()
throw new Error(data.error || 'Kunde inte uppdatera kontot')
}
onSaved()
onOpenChange(false)
} catch {
// Error handled silently — toast is in parent
} finally {
setIsSaving(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>
Redigera konto {account.account_number}
</DialogTitle>
</DialogHeader>
<div className="space-y-4 py-2">
<div className="space-y-2">
<Label>Kontonamn</Label>
<Input
value={accountName}
onChange={(e) => setAccountName(e.target.value)}
/>
</div>
<div className="space-y-2">
<Label>Beskrivning</Label>
<Textarea
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="Kort beskrivning av kontots användning"
rows={2}
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Standard momskod</Label>
<Input
value={defaultVatCode}
onChange={(e) => setDefaultVatCode(e.target.value)}
placeholder="T.ex. MP1"
/>
</div>
<div className="space-y-2">
<Label>SRU-kod</Label>
<Input
value={sruCode}
onChange={(e) => setSruCode(e.target.value)}
placeholder="T.ex. 7201"
/>
</div>
</div>
<div className="flex items-center justify-between rounded-lg border p-3">
<div>
<p className="text-sm font-medium">Aktivt konto</p>
<p className="text-xs text-muted-foreground">
Inaktiva konton visas inte i bokföringsformulär
</p>
</div>
<Switch checked={isActive} onCheckedChange={setIsActive} />
</div>
{account.is_system_account && (
<p className="text-xs text-muted-foreground bg-muted rounded p-2">
Detta är ett systemkonto och kan inte tas bort.
</p>
)}
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Avbryt
</Button>
<Button onClick={handleSave} disabled={isSaving || !accountName.trim()}>
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Spara
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,209 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { Button } from '@/components/ui/button'
import { FileText, ImageIcon, Download, ChevronDown, ChevronUp, Plus } from 'lucide-react'
import DocumentUploadZone from '@/components/bookkeeping/DocumentUploadZone'
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
interface DocumentRecord {
id: string
file_name: string
file_size_bytes: number
mime_type: string | null
storage_path: string
created_at: string
download_url?: string
}
interface JournalEntryAttachmentsProps {
journalEntryId: string
onCountChange?: (count: number) => void
}
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
}
function isImageType(type: string | null): boolean {
return type?.startsWith('image/') ?? false
}
export default function JournalEntryAttachments({
journalEntryId,
onCountChange,
}: JournalEntryAttachmentsProps) {
const [documents, setDocuments] = useState<DocumentRecord[]>([])
const [loading, setLoading] = useState(true)
const [expandedImage, setExpandedImage] = useState<string | null>(null)
const [showUpload, setShowUpload] = useState(false)
const [uploadFiles, setUploadFiles] = useState<UploadedFile[]>([])
const fetchDocuments = useCallback(async () => {
try {
const res = await fetch(
`/api/documents?journal_entry_id=${journalEntryId}&current_only=true`
)
const { data } = await res.json()
setDocuments(data || [])
onCountChange?.(data?.length || 0)
} catch {
console.error('Failed to fetch documents')
} finally {
setLoading(false)
}
}, [journalEntryId, onCountChange])
useEffect(() => {
fetchDocuments()
}, [fetchDocuments])
// Refresh documents when uploads complete
useEffect(() => {
const allDone = uploadFiles.length > 0 && uploadFiles.every((f) => f.status !== 'uploading')
const hasUploaded = uploadFiles.some((f) => f.status === 'uploaded')
if (allDone && hasUploaded) {
fetchDocuments()
setUploadFiles([])
setShowUpload(false)
}
}, [uploadFiles, fetchDocuments])
const handleDownload = async (docId: string) => {
try {
const res = await fetch(`/api/documents/${docId}`)
const { data } = await res.json()
if (data?.download_url) {
window.open(data.download_url, '_blank')
}
} catch {
console.error('Failed to get download URL')
}
}
const handlePreviewToggle = async (doc: DocumentRecord) => {
if (expandedImage === doc.id) {
setExpandedImage(null)
return
}
// Fetch signed URL for preview if not already loaded
if (!doc.download_url) {
try {
const res = await fetch(`/api/documents/${doc.id}`)
const { data } = await res.json()
if (data?.download_url) {
setDocuments((prev) =>
prev.map((d) => (d.id === doc.id ? { ...d, download_url: data.download_url } : d))
)
}
} catch {
console.error('Failed to get preview URL')
return
}
}
setExpandedImage(doc.id)
}
if (loading) {
return (
<div className="py-2 text-sm text-muted-foreground">
Laddar underlag...
</div>
)
}
return (
<div className="border-t pt-3 mt-3">
<div className="flex items-center justify-between mb-2">
<h4 className="text-sm font-medium">
Underlag {documents.length > 0 && `(${documents.length})`}
</h4>
<Button
variant="outline"
size="sm"
className="h-7 text-xs"
onClick={() => setShowUpload(!showUpload)}
>
<Plus className="h-3 w-3 mr-1" />
Lägg till underlag
</Button>
</div>
{/* Upload zone */}
{showUpload && (
<div className="mb-3">
<DocumentUploadZone
files={uploadFiles}
onFilesChange={setUploadFiles}
journalEntryId={journalEntryId}
compact
/>
</div>
)}
{/* Document list */}
{documents.length === 0 && !showUpload ? (
<p className="text-sm text-muted-foreground py-1">
Inga underlag bifogade.
</p>
) : (
<div className="space-y-1">
{documents.map((doc) => (
<div key={doc.id}>
<div className="flex items-center gap-2 text-sm py-1.5 px-2 rounded bg-muted/50">
{isImageType(doc.mime_type) ? (
<button
onClick={() => handlePreviewToggle(doc)}
className="shrink-0 hover:text-primary transition-colors"
>
{expandedImage === doc.id ? (
<ChevronUp className="h-4 w-4" />
) : (
<ChevronDown className="h-4 w-4" />
)}
</button>
) : (
<FileText className="h-4 w-4 text-muted-foreground shrink-0" />
)}
{isImageType(doc.mime_type) && expandedImage !== doc.id && (
<ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
)}
<span className="truncate flex-1">{doc.file_name}</span>
<span className="text-xs text-muted-foreground shrink-0">
{formatFileSize(doc.file_size_bytes)}
</span>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0"
onClick={() => handleDownload(doc.id)}
title="Ladda ner"
>
<Download className="h-3 w-3" />
</Button>
</div>
{/* Image preview */}
{expandedImage === doc.id && doc.download_url && (
<div className="px-2 py-2">
<img
src={doc.download_url}
alt={doc.file_name}
className="max-h-48 rounded-lg object-contain"
/>
</div>
)}
</div>
))}
</div>
)}
</div>
)
}
+55 -8
View File
@@ -9,7 +9,10 @@ import { useToast } from '@/components/ui/use-toast'
import { Plus, Trash2 } from 'lucide-react'
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
import { JournalEntryReviewContent } from '@/components/bookkeeping/JournalEntryReviewContent'
import type { CreateJournalEntryLineInput, FiscalPeriod } from '@/types'
import DocumentUploadZone from '@/components/bookkeeping/DocumentUploadZone'
import AccountCombobox from '@/components/bookkeeping/AccountCombobox'
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
import type { CreateJournalEntryLineInput, FiscalPeriod, BASAccount } from '@/types'
interface Props {
onCreated?: () => void
@@ -34,9 +37,14 @@ export default function JournalEntryForm({ onCreated }: Props) {
])
const [isSubmitting, setIsSubmitting] = useState(false)
const [showReview, setShowReview] = useState(false)
const [uploadedFiles, setUploadedFiles] = useState<UploadedFile[]>([])
const [accounts, setAccounts] = useState<BASAccount[]>([])
const isUploading = uploadedFiles.some((f) => f.status === 'uploading')
useEffect(() => {
fetchPeriods()
fetchAccounts()
}, [])
async function fetchPeriods() {
@@ -48,6 +56,12 @@ export default function JournalEntryForm({ onCreated }: Props) {
}
}
async function fetchAccounts() {
const res = await fetch('/api/bookkeeping/accounts')
const { data } = await res.json()
setAccounts(data || [])
}
const addLine = () => {
setLines([
...lines,
@@ -116,6 +130,23 @@ export default function JournalEntryForm({ onCreated }: Props) {
variant: 'destructive',
})
} else {
// Link uploaded documents to the new journal entry (non-blocking)
const journalEntryId = result.data?.id
if (journalEntryId) {
const filesToLink = uploadedFiles.filter((f) => f.status === 'uploaded' && f.id)
for (const file of filesToLink) {
try {
await fetch(`/api/documents/${file.id}/link`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ journal_entry_id: journalEntryId }),
})
} catch (linkErr) {
console.error('[JournalEntryForm] Failed to link document:', linkErr)
}
}
}
toast({
title: 'Verifikation skapad',
description: `Verifikation ${result.data?.voucher_series}${result.data?.voucher_number} har skapats.`,
@@ -123,6 +154,7 @@ export default function JournalEntryForm({ onCreated }: Props) {
setShowReview(false)
// Reset form
setDescription('')
setUploadedFiles([])
setLines([
{ account_number: '', debit_amount: '', credit_amount: '', line_description: '' },
{ account_number: '', debit_amount: '', credit_amount: '', line_description: '' },
@@ -188,12 +220,10 @@ export default function JournalEntryForm({ onCreated }: Props) {
{lines.map((line, index) => (
<tr key={index} className="border-b">
<td className="py-1">
<Input
<AccountCombobox
value={line.account_number}
onChange={(e) => updateLine(index, 'account_number', e.target.value)}
placeholder="1930"
className="font-mono h-8"
maxLength={4}
accounts={accounts}
onChange={(num) => updateLine(index, 'account_number', num)}
/>
</td>
<td className="py-1 px-1">
@@ -275,19 +305,35 @@ export default function JournalEntryForm({ onCreated }: Props) {
</Button>
</div>
{/* Document attachments */}
<div>
<Label className="mb-2 block">Underlag</Label>
<DocumentUploadZone
files={uploadedFiles}
onFilesChange={setUploadedFiles}
/>
</div>
{!isBalanced && totalDebit > 0 && (
<p className="text-sm text-red-600">
Differens: {Math.abs(totalDebit - totalCredit).toLocaleString('sv-SE', { minimumFractionDigits: 2 })} kr
</p>
)}
<div className="flex justify-end">
<div className="flex flex-col items-end gap-1">
<Button
onClick={handleReview}
disabled={!isBalanced || !description || !selectedPeriod || isSubmitting}
disabled={!isBalanced || !description || !selectedPeriod || isSubmitting || isUploading}
>
Granska & skapa
</Button>
{(!description || !selectedPeriod || isUploading) && (
<div className="text-xs text-muted-foreground space-y-0.5 text-right">
{!description && <p>Ange en beskrivning</p>}
{!selectedPeriod && <p>Välj en räkenskapsperiod</p>}
{isUploading && <p>Vänta tills filerna laddats upp</p>}
</div>
)}
</div>
<ConfirmationDialog
@@ -305,6 +351,7 @@ export default function JournalEntryForm({ onCreated }: Props) {
lines={lines}
totalDebit={totalDebit}
totalCredit={totalCredit}
attachmentCount={uploadedFiles.filter((f) => f.status === 'uploaded').length}
/>
</ConfirmationDialog>
</CardContent>
+90 -4
View File
@@ -1,13 +1,25 @@
'use client'
import { useState, useEffect } from 'react'
import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { ChevronDown, ChevronRight } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { ChevronDown, ChevronRight, Paperclip, AlertTriangle } from 'lucide-react'
import { AccountNumber } from '@/components/ui/account-number'
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
import type { JournalEntry, JournalEntryLine } from '@/types'
const NEEDS_ATTACHMENT = new Set([
'manual',
'bank_transaction',
'supplier_invoice_registered',
'supplier_invoice_paid',
'supplier_invoice_cash_payment',
'import',
])
interface Props {
periodId?: string
}
@@ -18,8 +30,23 @@ export default function JournalEntryList({ periodId }: Props) {
const [expandedId, setExpandedId] = useState<string | null>(null)
const [count, setCount] = useState(0)
const [page, setPage] = useState(0)
const [attachmentCounts, setAttachmentCounts] = useState<Record<string, number>>({})
const [showMissingOnly, setShowMissingOnly] = useState(false)
const pageSize = 20
const fetchAttachmentCounts = useCallback(async (entryIds: string[]) => {
if (entryIds.length === 0) return
try {
const res = await fetch(
`/api/documents/counts?journal_entry_ids=${entryIds.join(',')}`
)
const { data } = await res.json()
setAttachmentCounts(data || {})
} catch {
console.error('Failed to fetch attachment counts')
}
}, [])
useEffect(() => {
fetchEntries()
}, [periodId, page])
@@ -34,11 +61,20 @@ export default function JournalEntryList({ periodId }: Props) {
const res = await fetch(`/api/bookkeeping/journal-entries?${params}`)
const { data, count: total } = await res.json()
setEntries(data || [])
const loadedEntries = data || []
setEntries(loadedEntries)
setCount(total || 0)
setLoading(false)
// Fetch attachment counts for the loaded entries
const ids = loadedEntries.map((e: JournalEntry) => e.id)
fetchAttachmentCounts(ids)
}
const handleAttachmentCountChange = useCallback((entryId: string, count: number) => {
setAttachmentCounts((prev) => ({ ...prev, [entryId]: count }))
}, [])
const toggleExpand = (id: string) => {
setExpandedId(expandedId === id ? null : id)
}
@@ -66,6 +102,12 @@ export default function JournalEntryList({ periodId }: Props) {
salary_payment: 'Lön',
opening_balance: 'Ingående balans',
year_end: 'Årsbokslut',
supplier_invoice_registered: 'Leverantörsfaktura',
supplier_invoice_paid: 'Leverantörsbetalning',
supplier_invoice_cash_payment: 'Kontant leverantörsbetalning',
import: 'Import',
storno: 'Storno',
correction: 'Korrigering',
}
return labels[source] || source
}
@@ -90,10 +132,36 @@ export default function JournalEntryList({ periodId }: Props) {
)
}
const filteredEntries = showMissingOnly
? entries.filter(
(e) =>
NEEDS_ATTACHMENT.has(e.source_type) &&
!attachmentCounts[e.id] &&
e.status === 'posted'
)
: entries
return (
<div className="space-y-4">
{/* Missing attachment filter */}
<div className="flex items-center gap-2">
<Switch
id="missing-attachments"
checked={showMissingOnly}
onCheckedChange={setShowMissingOnly}
/>
<Label htmlFor="missing-attachments" className="text-sm cursor-pointer">
Visa saknade underlag
</Label>
{showMissingOnly && (
<Badge variant="secondary" className="text-xs">
{filteredEntries.length}
</Badge>
)}
</div>
<div className="space-y-2">
{entries.map((entry) => {
{filteredEntries.map((entry) => {
const isExpanded = expandedId === entry.id
const lines = (entry.lines || []) as JournalEntryLine[]
@@ -116,6 +184,19 @@ export default function JournalEntryList({ periodId }: Props) {
{entry.entry_date}
</span>
<span className="flex-1 truncate">{entry.description}</span>
{/* Attachment indicator */}
{attachmentCounts[entry.id] ? (
<span className="flex items-center gap-0.5 text-muted-foreground mr-1" title={`${attachmentCounts[entry.id]} underlag`}>
<Paperclip className="h-3.5 w-3.5" />
<span className="text-xs">{attachmentCounts[entry.id]}</span>
</span>
) : (
NEEDS_ATTACHMENT.has(entry.source_type) && entry.status === 'posted' && (
<span className="mr-1" title="Underlag saknas">
<AlertTriangle className="h-3.5 w-3.5 text-amber-500" />
</span>
)
)}
<Badge variant="outline" className="text-xs mr-2">
{sourceLabel(entry.source_type)}
</Badge>
@@ -178,6 +259,11 @@ export default function JournalEntryList({ periodId }: Props) {
</tr>
</tfoot>
</table>
<JournalEntryAttachments
journalEntryId={entry.id}
onCountChange={(c) => handleAttachmentCountChange(entry.id, c)}
/>
</CardContent>
)}
</Card>
@@ -2,7 +2,7 @@
import { Badge } from '@/components/ui/badge'
import { AccountNumber } from '@/components/ui/account-number'
import { CheckCircle2 } from 'lucide-react'
import { CheckCircle2, Paperclip } from 'lucide-react'
interface ReviewLine {
account_number: string
@@ -18,6 +18,7 @@ interface JournalEntryReviewContentProps {
lines: ReviewLine[]
totalDebit: number
totalCredit: number
attachmentCount?: number
}
function formatAmount(amount: number): string {
@@ -31,6 +32,7 @@ export function JournalEntryReviewContent({
lines,
totalDebit,
totalCredit,
attachmentCount,
}: JournalEntryReviewContentProps) {
const activeLines = lines.filter(
(l) => l.account_number && (l.debit_amount || l.credit_amount)
@@ -62,6 +64,12 @@ export function JournalEntryReviewContent({
<CheckCircle2 className="h-3 w-3 mr-1" />
Debet = Kredit
</Badge>
{attachmentCount != null && attachmentCount > 0 && (
<Badge variant="outline">
<Paperclip className="h-3 w-3 mr-1" />
{attachmentCount} {attachmentCount === 1 ? 'underlag' : 'underlag'}
</Badge>
)}
</div>
{/* Debit/Credit table */}
+229 -91
View File
@@ -20,9 +20,13 @@ import {
Receipt,
ArrowLeftRight,
ChevronDown,
ChevronUp,
ArrowRight,
Camera,
Users,
Landmark,
CheckCircle2,
ClipboardList,
} from 'lucide-react'
import type { CompanySettings, EntityType, Deadline, ReceiptQueueSummary, OnboardingProgress } from '@/types'
@@ -48,6 +52,7 @@ interface DashboardContentProps {
export default function DashboardContent({ firstName, settings, summary, onboardingProgress }: DashboardContentProps) {
const [showAllAlerts, setShowAllAlerts] = useState(false)
const [showMore, setShowMore] = useState(false)
const entityType = (settings?.entity_type as EntityType) || 'enskild_firma'
const preliminaryTaxMonthly = settings?.preliminary_tax_monthly || 0
@@ -133,7 +138,7 @@ export default function DashboardContent({ firstName, settings, summary, onboard
<div>
<p className="font-medium text-sm">Transaktioner</p>
<p className="text-xs text-muted-foreground mt-0.5">
{summary.uncategorizedCount} okategoriserade
{summary.uncategorizedCount} obokförda
</p>
</div>
</div>
@@ -179,7 +184,7 @@ export default function DashboardContent({ firstName, settings, summary, onboard
{ href: '/invoices/new', icon: Receipt, label: 'Ny faktura', desc: 'Skapa och skicka', accent: true },
{ href: '/receipts/scan', icon: Camera, label: 'Skanna kvitto', desc: 'Fotografera & spara' },
{ href: '/customers', icon: Users, label: 'Ny kund', desc: 'Lägg till kunduppgifter' },
{ href: '/transactions', icon: ArrowLeftRight, label: 'Transaktioner', desc: 'Kategorisera' },
{ href: '/transactions', icon: ArrowLeftRight, label: 'Transaktioner', desc: 'Bokför' },
]
return (
@@ -215,7 +220,7 @@ export default function DashboardContent({ firstName, settings, summary, onboard
todoItems.push({ label: 'förfallna fakturor', href: '/invoices?status=unpaid', count: summary.overdueInvoicesCount, variant: 'destructive' })
}
if (summary.uncategorizedCount > 0) {
todoItems.push({ label: 'okategoriserade', href: '/transactions', count: summary.uncategorizedCount, variant: 'warning' })
todoItems.push({ label: 'obokförda', href: '/transactions', count: summary.uncategorizedCount, variant: 'warning' })
}
if (summary.receiptQueue && summary.receiptQueue.pending_review_count > 0) {
todoItems.push({ label: 'kvitton att granska', href: '/receipts', count: summary.receiptQueue.pending_review_count, variant: 'default' })
@@ -253,12 +258,116 @@ export default function DashboardContent({ firstName, settings, summary, onboard
</section>
)}
{/* Upcoming deadlines */}
{summary.deadlines && summary.deadlines.length > 0 && (
<section className="mb-10">
<UpcomingDeadlinesWidget deadlines={summary.deadlines} maxItems={8} />
</section>
)}
{/* 4 Key Summary Cards */}
{(() => {
const passedDeadlinesCount = summary.deadlines.filter(d => !d.is_completed && new Date(d.due_date) <= new Date()).length
const pendingReceiptsCount = summary.receiptQueue
? summary.receiptQueue.pending_review_count + summary.receiptQueue.unmatched_receipts_count
: 0
const todoCount = summary.uncategorizedCount + summary.overdueInvoicesCount + pendingReceiptsCount + passedDeadlinesCount
return (
<section className="mb-10">
<div className="grid grid-cols-2 md:grid-cols-4 gap-3">
{/* Card 1: Resultat */}
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<TrendingUp className="h-3.5 w-3.5 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Resultat</span>
</div>
<p className={cn(
'font-display text-xl font-medium tabular-nums leading-tight',
summary.mtd.net >= 0 ? 'text-success' : 'text-destructive'
)}>
{formatLargeNumber(summary.mtd.net)}
<span className="text-sm ml-0.5 text-muted-foreground font-normal">kr</span>
</p>
<p className="text-[11px] text-muted-foreground mt-1">
{formatCurrency(summary.ytd.net)} i år
</p>
</CardContent>
</Card>
{/* Card 2: Att få betalt */}
<Link href="/invoices?status=unpaid">
<Card className="h-full hover:border-primary/50 transition-colors">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<Receipt className="h-3.5 w-3.5 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Att få betalt</span>
</div>
<p className="font-display text-xl font-medium tabular-nums leading-tight">
{summary.unpaidInvoicesCount}
<span className="text-sm ml-0.5 text-muted-foreground font-normal">st</span>
</p>
<p className="text-[11px] text-muted-foreground mt-1">
{formatCurrency(summary.unpaidInvoicesTotal)}
</p>
</CardContent>
</Card>
</Link>
{/* Card 3: Banksaldo */}
{summary.bankBalance !== null ? (
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<Landmark className="h-3.5 w-3.5 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Banksaldo</span>
</div>
<p className="font-display text-xl font-medium tabular-nums leading-tight">
{formatLargeNumber(summary.bankBalance)}
<span className="text-sm ml-0.5 text-muted-foreground font-normal">kr</span>
</p>
</CardContent>
</Card>
) : (
<Link href="/import">
<Card className="h-full hover:border-primary/50 transition-colors">
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<Landmark className="h-3.5 w-3.5 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Banksaldo</span>
</div>
<p className="text-sm font-medium text-primary">Koppla bank</p>
<p className="text-[11px] text-muted-foreground mt-1">Importera transaktioner</p>
</CardContent>
</Card>
</Link>
)}
{/* Card 4: Att göra */}
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-2 mb-2">
<ClipboardList className="h-3.5 w-3.5 text-muted-foreground" />
<span className="text-xs text-muted-foreground">Att göra</span>
</div>
{todoCount > 0 ? (
<>
<p className="font-display text-xl font-medium tabular-nums leading-tight text-warning-foreground">
{todoCount}
<span className="text-sm ml-0.5 text-muted-foreground font-normal">st</span>
</p>
<p className="text-[11px] text-muted-foreground mt-1">
Åtgärder att hantera
</p>
</>
) : (
<>
<div className="flex items-center gap-1.5">
<CheckCircle2 className="h-4 w-4 text-success" />
<p className="text-sm font-medium text-success">Allt klart!</p>
</div>
</>
)}
</CardContent>
</Card>
</div>
</section>
)
})()}
{/* Quick actions */}
<section id="quick-actions" className="mb-10">
@@ -294,15 +403,14 @@ export default function DashboardContent({ firstName, settings, summary, onboard
</div>
</section>
{/* F-skatt warning */}
<section id="fskatt-section" className="mb-10">
<FSkattWarningCard
warningStatus={taxWarning}
onAdjustClick={() => { window.location.href = '/settings' }}
/>
</section>
{/* Upcoming deadlines — always visible */}
{summary.deadlines && summary.deadlines.length > 0 && (
<section className="mb-10">
<UpcomingDeadlinesWidget deadlines={summary.deadlines} maxItems={8} />
</section>
)}
{/* Alerts section */}
{/* Alerts section — always visible */}
{alertItems.length > 0 && (
<section id="alerts-section" className="mb-10">
<h2 className="font-display text-lg font-medium mb-4">Att hantera</h2>
@@ -321,82 +429,112 @@ export default function DashboardContent({ firstName, settings, summary, onboard
</section>
)}
{/* Uncategorized transactions warning */}
{summary.uncategorizedCount > 0 && (summary.uncategorizedIncome > 0 || summary.uncategorizedExpenses > 0) && (
<section className="mb-10">
<Link href="/transactions?tab=uncategorized" className="group">
<div className="flex items-start gap-3 px-4 py-3.5 rounded-xl border border-warning/30 bg-warning/[0.03] hover:bg-warning/[0.06] transition-colors">
<ArrowLeftRight className="h-4 w-4 text-warning-foreground flex-shrink-0 mt-0.5" />
<div className="flex-1 min-w-0">
<p className="font-medium text-sm">
{summary.uncategorizedCount} okategoriserade transaktioner
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{summary.uncategorizedIncome > 0 && (
<span>{formatCurrency(summary.uncategorizedIncome)} intäkter</span>
)}
{summary.uncategorizedIncome > 0 && summary.uncategorizedExpenses > 0 && ', '}
{summary.uncategorizedExpenses > 0 && (
<span>{formatCurrency(summary.uncategorizedExpenses)} kostnader</span>
)}
{' '}saknas i resultatet
</p>
</div>
<ArrowRight className="h-3.5 w-3.5 text-muted-foreground/50 group-hover:text-muted-foreground flex-shrink-0 mt-0.5 transition-colors" />
{/* Collapsible details section */}
<button
onClick={() => setShowMore(!showMore)}
className="mb-6 text-sm text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1.5"
>
{showMore ? (
<>
Dölj detaljer
<ChevronUp className="h-3.5 w-3.5" />
</>
) : (
<>
Visa detaljer
<ChevronDown className="h-3.5 w-3.5" />
</>
)}
</button>
{showMore && (
<div>
{/* F-skatt warning */}
<section id="fskatt-section" className="mb-10">
<FSkattWarningCard
warningStatus={taxWarning}
onAdjustClick={() => { window.location.href = '/settings' }}
/>
</section>
{/* Uncategorized transactions warning */}
{summary.uncategorizedCount > 0 && (summary.uncategorizedIncome > 0 || summary.uncategorizedExpenses > 0) && (
<section className="mb-10">
<Link href="/transactions?tab=uncategorized" className="group">
<div className="flex items-start gap-3 px-4 py-3.5 rounded-xl border border-warning/30 bg-warning/[0.03] hover:bg-warning/[0.06] transition-colors">
<ArrowLeftRight className="h-4 w-4 text-warning-foreground flex-shrink-0 mt-0.5" />
<div className="flex-1 min-w-0">
<p className="font-medium text-sm">
{summary.uncategorizedCount} obokförda transaktioner
</p>
<p className="text-xs text-muted-foreground mt-0.5">
{summary.uncategorizedIncome > 0 && (
<span>{formatCurrency(summary.uncategorizedIncome)} intäkter</span>
)}
{summary.uncategorizedIncome > 0 && summary.uncategorizedExpenses > 0 && ', '}
{summary.uncategorizedExpenses > 0 && (
<span>{formatCurrency(summary.uncategorizedExpenses)} kostnader</span>
)}
{' '}saknas i resultatet
</p>
</div>
<ArrowRight className="h-3.5 w-3.5 text-muted-foreground/50 group-hover:text-muted-foreground flex-shrink-0 mt-0.5 transition-colors" />
</div>
</Link>
</section>
)}
{/* Income/Expenses */}
<section className="mb-10">
<h2 className="font-display text-lg font-medium mb-4">Resultat</h2>
<div className="grid md:grid-cols-2 gap-3">
<Card>
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-3">
<TrendingUp className="h-3.5 w-3.5 text-success" />
<span className="text-sm text-muted-foreground">Intäkter</span>
</div>
<div>
<p className="font-display text-2xl font-medium tabular-nums leading-tight">
{formatLargeNumber(summary.mtd.income)}
<span className="text-base ml-1 text-muted-foreground font-normal">kr</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">denna månad</p>
</div>
<div className="mt-4 pt-3 border-t border-border/30">
<div className="flex items-baseline justify-between">
<p className="text-xs text-muted-foreground">I år</p>
<p className="text-sm font-medium tabular-nums">{formatCurrency(summary.ytd.income)}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-3">
<TrendingDown className="h-3.5 w-3.5 text-destructive" />
<span className="text-sm text-muted-foreground">Kostnader</span>
</div>
<div>
<p className="font-display text-2xl font-medium tabular-nums leading-tight">
{formatLargeNumber(summary.mtd.expenses)}
<span className="text-base ml-1 text-muted-foreground font-normal">kr</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">denna månad</p>
</div>
<div className="mt-4 pt-3 border-t border-border/30">
<div className="flex items-baseline justify-between">
<p className="text-xs text-muted-foreground">I år</p>
<p className="text-sm font-medium tabular-nums">{formatCurrency(summary.ytd.expenses)}</p>
</div>
</div>
</CardContent>
</Card>
</div>
</Link>
</section>
)}
{/* Income/Expenses */}
<section className="mb-10">
<h2 className="font-display text-lg font-medium mb-4">Resultat</h2>
<div className="grid md:grid-cols-2 gap-3">
<Card>
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-3">
<TrendingUp className="h-3.5 w-3.5 text-success" />
<span className="text-sm text-muted-foreground">Intäkter</span>
</div>
<div>
<p className="font-display text-2xl font-medium tabular-nums leading-tight">
{formatLargeNumber(summary.mtd.income)}
<span className="text-base ml-1 text-muted-foreground font-normal">kr</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">denna månad</p>
</div>
<div className="mt-4 pt-3 border-t border-border/30">
<div className="flex items-baseline justify-between">
<p className="text-xs text-muted-foreground">I år</p>
<p className="text-sm font-medium tabular-nums">{formatCurrency(summary.ytd.income)}</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-3">
<TrendingDown className="h-3.5 w-3.5 text-destructive" />
<span className="text-sm text-muted-foreground">Kostnader</span>
</div>
<div>
<p className="font-display text-2xl font-medium tabular-nums leading-tight">
{formatLargeNumber(summary.mtd.expenses)}
<span className="text-base ml-1 text-muted-foreground font-normal">kr</span>
</p>
<p className="text-xs text-muted-foreground mt-0.5">denna månad</p>
</div>
<div className="mt-4 pt-3 border-t border-border/30">
<div className="flex items-baseline justify-between">
<p className="text-xs text-muted-foreground">I år</p>
<p className="text-sm font-medium tabular-nums">{formatCurrency(summary.ytd.expenses)}</p>
</div>
</div>
</CardContent>
</Card>
</section>
</div>
</section>
)}
</div>
)
}
+6 -3
View File
@@ -53,8 +53,8 @@ const navItems: NavItem[] = [
{ href: '/supplier-invoices', label: 'Lev.fakturor', icon: FileInput, group: 'finans' },
{ href: '/transactions', label: 'Transaktioner', icon: ArrowLeftRight, group: 'finans' },
{ href: '/bookkeeping', label: 'Bokföring', icon: BookOpen, group: 'finans' },
{ href: '/reports', label: 'Rapporter', icon: BarChart3, group: 'finans' },
{ href: '/import', label: 'Importera', icon: Upload, group: 'övrigt' },
{ href: '/reports', label: 'Rapporter', icon: BarChart3, group: 'övrigt' },
{ href: '/help', label: 'Hjälp', icon: HelpCircle, group: 'övrigt' },
{ href: '/settings', label: 'Inställningar', icon: Settings, group: 'övrigt' },
]
@@ -70,7 +70,10 @@ export default function DashboardNav({ companyName, entityType, enabledExtension
const router = useRouter()
const supabase = createClient()
const [isMobileMenuOpen, setIsMobileMenuOpen] = useState(false)
const [isOvrigtExpanded, setIsOvrigtExpanded] = useState(false)
// Auto-expand Övrigt when the user is on one of its pages, or when manually toggled
const isOnOvrigtPage = ['/import', '/help', '/settings'].some(p => pathname.startsWith(p))
const [manualOvrigtExpanded, setManualOvrigtExpanded] = useState(false)
const isOvrigtExpanded = isOnOvrigtPage || manualOvrigtExpanded
const [isTillaggExpanded, setIsTillaggExpanded] = useState(false)
const [liveExtensions, setLiveExtensions] = useState(enabledExtensions ?? [])
@@ -274,7 +277,7 @@ export default function DashboardNav({ companyName, entityType, enabledExtension
{/* Övrigt group - collapsible */}
<div className="mb-4">
<button
onClick={() => setIsOvrigtExpanded(!isOvrigtExpanded)}
onClick={() => setManualOvrigtExpanded(!isOvrigtExpanded)}
className="w-full flex items-center justify-between px-3 mb-1.5 text-[10px] font-semibold text-muted-foreground/70 uppercase tracking-[0.08em] hover:text-muted-foreground transition-colors"
>
<span>{groupLabels.övrigt}</span>
+1 -22
View File
@@ -30,6 +30,7 @@ import {
} from 'lucide-react'
import type { AccountMapping } from '@/lib/import/types'
import type { BASAccount } from '@/types'
import { getAccountClassName } from '@/lib/bookkeeping/account-descriptions'
interface AccountMappingStepProps {
mappings: AccountMapping[]
@@ -352,25 +353,3 @@ function ConfidenceBadge({
return <Badge variant="outline">Osäker</Badge>
}
function getAccountClassName(accountClass: number): string {
switch (accountClass) {
case 1:
return '1xxx - Tillgångar'
case 2:
return '2xxx - Eget kapital & Skulder'
case 3:
return '3xxx - Intäkter'
case 4:
return '4xxx - Varuinköp'
case 5:
return '5xxx - Externa kostnader'
case 6:
return '6xxx - Övriga externa kostnader'
case 7:
return '7xxx - Personal'
case 8:
return '8xxx - Finansiella poster'
default:
return `${accountClass}xxx - Övrigt`
}
}
+3 -3
View File
@@ -126,7 +126,7 @@ export default function BankFileConfirmStep({
/>
<div>
<Label htmlFor="auto-categorize" className="text-sm font-medium cursor-pointer">
Auto-kategorisera kända transaktioner
Auto-bokför kända transaktioner
</Label>
<p className="text-xs text-muted-foreground">
Skapar automatiskt bokföringsposter för transaktioner med hög konfidens
@@ -139,8 +139,8 @@ export default function BankFileConfirmStep({
<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
&quot;okategoriserade&quot; på transaktionssidan. Du kan kategorisera dem manuellt
Importerade transaktioner som inte automatiskt bokförs visas som
&quot;obokförda&quot; på transaktionssidan. Du kan bokföra dem manuellt
efteråt.
</p>
</div>
+17
View File
@@ -200,6 +200,23 @@ export default function BankFilePreviewStep({
</CardContent>
</Card>
{/* Error blocking continuation */}
{hasIssues && (
<Card className="border-destructive">
<CardContent className="pt-6">
<div className="flex gap-3">
<AlertTriangle className="h-5 w-5 text-destructive flex-shrink-0 mt-0.5" />
<div>
<p className="font-medium text-destructive">Filen innehåller fel som förhindrar import</p>
<p className="text-sm text-muted-foreground mt-1">
Kontrollera felet ovan och försök ladda upp en korrigerad fil.
</p>
</div>
</div>
</CardContent>
</Card>
)}
{/* Navigation */}
<div className="flex justify-between">
<Button variant="outline" onClick={onBack}>
+4 -4
View File
@@ -79,7 +79,7 @@ export default function BankFileResultStep({
<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>
<span className="text-sm">Auto-bokförda</span>
</div>
<p className="text-2xl font-bold">{result.auto_categorized}</p>
</CardContent>
@@ -108,11 +108,11 @@ export default function BankFileResultStep({
1
</div>
<div>
<p className="font-medium">Granska okategoriserade transaktioner</p>
<p className="font-medium">Granska obokförda 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.'}
? `${result.imported - result.auto_categorized} transaktioner behöver bokföras manuellt.`
: 'Alla transaktioner bokfördes automatiskt.'}
</p>
</div>
</div>
+4 -4
View File
@@ -67,13 +67,13 @@ export default function ImportResultStep({ result, onNewImport }: ImportResultSt
<div className="flex items-center gap-2 text-muted-foreground mb-1">
<span className="text-sm">Räkenskapsår</span>
</div>
<p className="text-2xl font-bold">
<div className="text-2xl font-bold">
{result.fiscalPeriodId ? (
<Badge variant="default" className="bg-success">Skapat</Badge>
) : (
<Badge variant="secondary">Befintligt</Badge>
)}
</p>
</div>
</CardContent>
</Card>
@@ -82,13 +82,13 @@ export default function ImportResultStep({ result, onNewImport }: ImportResultSt
<div className="flex items-center gap-2 text-muted-foreground mb-1">
<span className="text-sm">Ingående balanser</span>
</div>
<p className="text-2xl font-bold">
<div className="text-2xl font-bold">
{result.openingBalanceEntryId ? (
<Badge variant="default" className="bg-success">Importerade</Badge>
) : (
<Badge variant="secondary">Inga</Badge>
)}
</p>
</div>
</CardContent>
</Card>
</div>
+40 -4
View File
@@ -11,6 +11,7 @@ interface ReviewItem {
quantity: number
unit: string
unit_price: number
vat_rate?: number
}
interface InvoiceReviewContentProps {
@@ -51,6 +52,24 @@ export function InvoiceReviewContent({
non_eu_business: 'Utanför EU',
}
// Check if items have mixed VAT rates
const hasPerLineVat = items.some((item) => item.vat_rate !== undefined)
const uniqueRates = hasPerLineVat
? new Set(items.map((item) => item.vat_rate ?? vatRate))
: new Set([vatRate])
const showVatColumn = hasPerLineVat && uniqueRates.size > 1
// Calculate per-rate VAT breakdown
const vatByRate = new Map<number, number>()
if (hasPerLineVat) {
for (const item of items) {
const rate = item.vat_rate ?? vatRate
const lineTotal = item.quantity * item.unit_price
const lineVat = Math.round(lineTotal * rate / 100 * 100) / 100
vatByRate.set(rate, (vatByRate.get(rate) || 0) + lineVat)
}
}
return (
<div className="space-y-4">
{/* Customer info */}
@@ -89,6 +108,7 @@ export function InvoiceReviewContent({
<th className="py-2 w-16 text-right">Antal</th>
<th className="py-2 w-16 text-center">Enhet</th>
<th className="py-2 w-24 text-right">À-pris</th>
{showVatColumn && <th className="py-2 w-16 text-right">Moms</th>}
<th className="py-2 w-28 text-right">Belopp</th>
</tr>
</thead>
@@ -99,6 +119,9 @@ export function InvoiceReviewContent({
<td className="py-2 text-right">{item.quantity}</td>
<td className="py-2 text-center">{item.unit}</td>
<td className="py-2 text-right">{formatCurrency(item.unit_price, currency)}</td>
{showVatColumn && (
<td className="py-2 text-right">{item.vat_rate ?? vatRate}%</td>
)}
<td className="py-2 text-right">
{formatCurrency(item.quantity * item.unit_price, currency)}
</td>
@@ -113,10 +136,23 @@ export function InvoiceReviewContent({
<span className="text-muted-foreground">Delsumma</span>
<span>{formatCurrency(subtotal, currency)}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Moms ({vatRate}%)</span>
<span>{formatCurrency(vatAmount, currency)}</span>
</div>
{vatByRate.size > 1 ? (
// Per-rate breakdown
Array.from(vatByRate.entries())
.filter(([, vat]) => vat > 0)
.sort(([a], [b]) => b - a)
.map(([rate, vat]) => (
<div key={rate} className="flex justify-between">
<span className="text-muted-foreground">Moms {rate}%</span>
<span>{formatCurrency(vat, currency)}</span>
</div>
))
) : (
<div className="flex justify-between">
<span className="text-muted-foreground">Moms ({vatRate}%)</span>
<span>{formatCurrency(vatAmount, currency)}</span>
</div>
)}
<Separator />
<div className="flex justify-between font-bold text-2xl">
<span>Totalt</span>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+51
View File
@@ -0,0 +1,51 @@
'use client'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
export interface MonthlyDataPoint {
label: string
income: number
expenses: number
}
interface IncomeExpenseChartProps {
months: MonthlyDataPoint[]
}
export function IncomeExpenseChart({ months }: IncomeExpenseChartProps) {
if (months.length === 0) return null
return (
<Card className="mb-4">
<CardHeader className="pb-2">
<CardTitle className="text-base">Intäkter vs Kostnader per månad</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<BarChart
data={months}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" vertical={false} />
<XAxis dataKey="label" tick={{ fontSize: 12 }} />
<YAxis
tickFormatter={(v) => new Intl.NumberFormat('sv-SE', { notation: 'compact' }).format(v)}
/>
<Tooltip
formatter={(value, name) => [
new Intl.NumberFormat('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(Number(value)) + ' kr',
name === 'income' ? 'Intäkter' : 'Kostnader',
]}
/>
<Legend
formatter={(value) => (value === 'income' ? 'Intäkter' : 'Kostnader')}
/>
<Bar dataKey="income" fill="hsl(var(--chart-1))" radius={[4, 4, 0, 0]} />
<Bar dataKey="expenses" fill="hsl(var(--chart-2))" radius={[4, 4, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
)
}
+69
View File
@@ -0,0 +1,69 @@
'use client'
import { useMemo } from 'react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell } from 'recharts'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import type { TrialBalanceRow } from '@/types'
interface TrialBalanceChartProps {
rows: TrialBalanceRow[]
}
export function TrialBalanceChart({ rows }: TrialBalanceChartProps) {
const chartData = useMemo(() => {
return rows
.map((row) => ({
name: `${row.account_number} ${row.account_name}`,
account: row.account_number,
net: Math.round((row.closing_debit - row.closing_credit) * 100) / 100,
}))
.sort((a, b) => Math.abs(b.net) - Math.abs(a.net))
.slice(0, 10)
}, [rows])
if (chartData.length === 0) return null
return (
<Card className="mb-4">
<CardHeader className="pb-2">
<CardTitle className="text-base">Topp 10 konton (nettosaldo)</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={300}>
<BarChart
data={chartData}
layout="vertical"
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" horizontal={false} />
<XAxis
type="number"
tickFormatter={(v) => new Intl.NumberFormat('sv-SE', { notation: 'compact' }).format(v)}
/>
<YAxis
type="category"
dataKey="account"
width={50}
tick={{ fontSize: 12 }}
/>
<Tooltip
formatter={(value) => [
new Intl.NumberFormat('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(Number(value)) + ' kr',
'Netto',
]}
labelFormatter={(label) => chartData.find((d) => d.account === String(label))?.name || String(label)}
/>
<Bar dataKey="net" radius={[0, 4, 4, 0]}>
{chartData.map((entry) => (
<Cell
key={entry.account}
fill={entry.net >= 0 ? 'hsl(var(--chart-1))' : 'hsl(var(--chart-2))'}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</CardContent>
</Card>
)
}
@@ -0,0 +1,64 @@
'use client'
import { useMemo } from 'react'
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend } from 'recharts'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import type { VatDeclarationRutor } from '@/types'
interface VatCompositionChartProps {
rutor: VatDeclarationRutor
}
const COLORS = [
'hsl(var(--chart-1))',
'hsl(var(--chart-2))',
'hsl(var(--chart-3))',
'hsl(var(--chart-4))',
]
export function VatCompositionChart({ rutor }: VatCompositionChartProps) {
const chartData = useMemo(() => {
const segments = [
{ name: 'Utgående 25%', value: rutor.ruta05 },
{ name: 'Utgående 12%', value: rutor.ruta06 },
{ name: 'Utgående 6%', value: rutor.ruta07 },
{ name: 'Ingående moms', value: rutor.ruta48 },
]
return segments.filter((s) => s.value > 0)
}, [rutor])
if (chartData.length === 0) return null
return (
<Card className="mb-4">
<CardHeader className="pb-2">
<CardTitle className="text-base">Momsfördelning</CardTitle>
</CardHeader>
<CardContent>
<ResponsiveContainer width="100%" height={250}>
<PieChart>
<Pie
data={chartData}
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={90}
paddingAngle={2}
dataKey="value"
>
{chartData.map((_, index) => (
<Cell key={index} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip
formatter={(value) => [
new Intl.NumberFormat('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(Number(value)) + ' kr',
]}
/>
<Legend />
</PieChart>
</ResponsiveContainer>
</CardContent>
</Card>
)
}
@@ -3,13 +3,11 @@
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { AccountNumber } from '@/components/ui/account-number'
import type { Supplier, VatTreatment } from '@/types'
import type { Supplier } from '@/types'
interface ReviewLineItem {
description: string
quantity: number
unit: string
unit_price: number
amount: number
account_number: string
vat_rate: number
}
@@ -22,7 +20,6 @@ interface SupplierInvoiceReviewContentProps {
deliveryDate?: string
currency: string
exchangeRate?: string
vatTreatment: VatTreatment
reverseCharge: boolean
paymentReference?: string
items: ReviewLineItem[]
@@ -35,13 +32,88 @@ function formatAmount(amount: number): string {
return amount.toLocaleString('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
const VAT_TREATMENT_LABELS: Record<VatTreatment, string> = {
standard_25: '25% moms',
reduced_12: '12% moms',
reduced_6: '6% moms',
reverse_charge: 'Omvänd skattskyldighet',
export: 'Export (0%)',
exempt: 'Momsfritt',
interface JournalPreviewLine {
account_number: string
description: string
debit: number
credit: number
}
function buildJournalPreview(
items: ReviewLineItem[],
subtotal: number,
totalVat: number,
total: number,
reverseCharge: boolean,
): JournalPreviewLine[] {
const lines: JournalPreviewLine[] = []
// Aggregate expense amounts by account number
const expenseByAccount = new Map<string, number>()
for (const item of items) {
const current = expenseByAccount.get(item.account_number) || 0
expenseByAccount.set(item.account_number, current + Math.round(item.amount * 100) / 100)
}
// Debit: Expense accounts
for (const [accountNumber, amount] of expenseByAccount) {
lines.push({
account_number: accountNumber,
description: accountNumber,
debit: Math.round(amount * 100) / 100,
credit: 0,
})
}
if (reverseCharge) {
// EU reverse charge: fiktiv moms
const vatRate = 0.25
const fiktivVat = Math.round(subtotal * vatRate * 100) / 100
lines.push({
account_number: '2645',
description: 'Beraknad ingaende moms',
debit: fiktivVat,
credit: 0,
})
lines.push({
account_number: '2614',
description: 'Utgaende moms omvand',
debit: 0,
credit: fiktivVat,
})
// Credit: 2440 at subtotal (no real VAT for reverse charge)
lines.push({
account_number: '2440',
description: 'Leverantorsskulder',
debit: 0,
credit: Math.round(subtotal * 100) / 100,
})
} else {
if (totalVat > 0) {
lines.push({
account_number: '2641',
description: 'Ingaende moms',
debit: Math.round(totalVat * 100) / 100,
credit: 0,
})
}
// Credit: 2440 at total incl. VAT
lines.push({
account_number: '2440',
description: 'Leverantorsskulder',
debit: 0,
credit: Math.round(total * 100) / 100,
})
}
return lines
}
const ACCOUNT_LABELS: Record<string, string> = {
'2440': 'Leverantörsskulder',
'2641': 'Ingående moms',
'2645': 'Beräknad ingående moms',
'2614': 'Utg. moms omvänd skattskyldighet',
}
export function SupplierInvoiceReviewContent({
@@ -52,7 +124,6 @@ export function SupplierInvoiceReviewContent({
deliveryDate,
currency,
exchangeRate,
vatTreatment,
reverseCharge,
paymentReference,
items,
@@ -60,6 +131,10 @@ export function SupplierInvoiceReviewContent({
totalVat,
total,
}: SupplierInvoiceReviewContentProps) {
const journalLines = buildJournalPreview(items, subtotal, totalVat, total, reverseCharge)
const totalDebit = journalLines.reduce((sum, l) => sum + l.debit, 0)
const totalCredit = journalLines.reduce((sum, l) => sum + l.credit, 0)
return (
<div className="space-y-4">
{/* Supplier info */}
@@ -68,24 +143,19 @@ export function SupplierInvoiceReviewContent({
<p className="font-medium text-base">{supplier.name}</p>
<p className="text-sm text-muted-foreground">Fakturanr: {invoiceNumber}</p>
</div>
{reverseCharge && (
<Badge variant="outline" className="border-orange-300 text-orange-700 dark:text-orange-400">
Omvänd skattskyldighet
</Badge>
)}
</div>
{/* VAT + currency badges */}
<div className="flex flex-wrap gap-2">
<Badge className="text-sm px-3 py-1">
{VAT_TREATMENT_LABELS[vatTreatment]}
</Badge>
{currency !== 'SEK' && (
<Badge variant="outline" className="text-sm px-3 py-1">
{currency}
{exchangeRate && ` (kurs ${exchangeRate})`}
</Badge>
)}
<div className="flex gap-2">
{reverseCharge && (
<Badge variant="outline" className="border-orange-300 text-orange-700 dark:text-orange-400">
Omvänd skattskyldighet
</Badge>
)}
{currency !== 'SEK' && (
<Badge variant="outline" className="text-sm">
{currency}
{exchangeRate && ` (kurs ${exchangeRate})`}
</Badge>
)}
</div>
</div>
{/* Dates */}
@@ -110,27 +180,25 @@ export function SupplierInvoiceReviewContent({
<table className="w-full text-sm">
<thead>
<tr className="border-b text-left text-muted-foreground">
<th className="py-2">Beskrivning</th>
<th className="py-2 w-16 text-right">Antal</th>
<th className="py-2 w-24 text-right">À-pris</th>
<th className="py-2 w-20">Konto</th>
<th className="py-2 w-16 text-right">Moms</th>
<th className="py-2">Beskrivning</th>
<th className="py-2 w-28 text-right">Belopp</th>
<th className="py-2 w-16 text-right">Moms%</th>
<th className="py-2 w-24 text-right">Moms</th>
</tr>
</thead>
<tbody>
{items.map((item, index) => {
const lineTotal = Math.round((item.quantity || 0) * (item.unit_price || 0) * 100) / 100
const vatAmount = Math.round(item.amount * item.vat_rate * 100) / 100
return (
<tr key={index} className="border-b last:border-0">
<td className="py-2">{item.description}</td>
<td className="py-2 text-right">{item.quantity} {item.unit}</td>
<td className="py-2 text-right">{formatAmount(item.unit_price)}</td>
<td className="py-2">
<AccountNumber number={item.account_number} size="sm" />
</td>
<td className="py-2">{item.description}</td>
<td className="py-2 text-right font-mono">{formatAmount(item.amount)}</td>
<td className="py-2 text-right">{Math.round(item.vat_rate * 100)}%</td>
<td className="py-2 text-right">{formatAmount(lineTotal)}</td>
<td className="py-2 text-right font-mono">{formatAmount(vatAmount)}</td>
</tr>
)
})}
@@ -160,6 +228,46 @@ export function SupplierInvoiceReviewContent({
)}
</div>
{/* Verifikation preview */}
<div className="bg-muted/50 border rounded-lg p-4 space-y-2">
<p className="text-sm font-semibold text-muted-foreground">Verifikation som bokförs</p>
<table className="w-full text-sm font-mono">
<thead>
<tr className="text-left text-muted-foreground text-xs">
<th className="pb-1 w-16">Konto</th>
<th className="pb-1">Beskrivning</th>
<th className="pb-1 w-24 text-right">Debet</th>
<th className="pb-1 w-24 text-right">Kredit</th>
</tr>
</thead>
<tbody>
{journalLines.map((line, index) => (
<tr key={index} className="border-b border-dashed border-muted-foreground/20 last:border-0">
<td className="py-1">
<AccountNumber number={line.account_number} size="sm" />
</td>
<td className="py-1 text-xs">
{ACCOUNT_LABELS[line.account_number] || line.description}
</td>
<td className="py-1 text-right">
{line.debit > 0 ? formatAmount(line.debit) : ''}
</td>
<td className="py-1 text-right">
{line.credit > 0 ? formatAmount(line.credit) : ''}
</td>
</tr>
))}
</tbody>
<tfoot>
<tr className="border-t font-semibold">
<td className="pt-1" colSpan={2}>SUMMA</td>
<td className="pt-1 text-right">{formatAmount(totalDebit)}</td>
<td className="pt-1 text-right">{formatAmount(totalCredit)}</td>
</tr>
</tfoot>
</table>
</div>
{/* Payment reference */}
{paymentReference && (
<div className="border-t pt-3 text-sm text-muted-foreground">
@@ -0,0 +1,107 @@
'use client'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'
import { Progress } from '@/components/ui/progress'
import type { TransactionCategory } from '@/types'
const expenseCategories: { value: TransactionCategory; label: string }[] = [
{ value: 'expense_equipment', label: 'Utrustning' },
{ value: 'expense_software', label: 'Programvara' },
{ value: 'expense_travel', label: 'Resor' },
{ value: 'expense_office', label: 'Kontor' },
{ value: 'expense_marketing', label: 'Marknadsföring' },
{ value: 'expense_professional_services', label: 'Konsulter' },
{ value: 'expense_education', label: 'Utbildning' },
{ value: 'expense_bank_fees', label: 'Bankavgift' },
{ value: 'expense_card_fees', label: 'Kortavgift' },
{ value: 'expense_currency_exchange', label: 'Valutaväxling' },
{ value: 'expense_other', label: 'Övrigt' },
]
const incomeCategories: { value: TransactionCategory; label: string }[] = [
{ value: 'income_services', label: 'Tjänster' },
{ value: 'income_products', label: 'Produkter' },
{ value: 'income_other', label: 'Övrigt' },
]
interface BatchCategorySelectorProps {
open: boolean
onOpenChange: (open: boolean) => void
selectedCount: number
onSelectCategory: (category: TransactionCategory) => void
progress: { done: number; total: number } | null
}
export default function BatchCategorySelector({
open,
onOpenChange,
selectedCount,
onSelectCategory,
progress,
}: BatchCategorySelectorProps) {
const isProcessing = progress !== null
return (
<Dialog open={open} onOpenChange={isProcessing ? undefined : onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>
{isProcessing
? `Bokför ${progress.done}/${progress.total}...`
: `Bokför ${selectedCount} transaktioner`}
</DialogTitle>
<DialogDescription>
{isProcessing
? 'Vänta medan transaktionerna bokförs'
: 'Välj en kategori som ska tillämpas på alla valda transaktioner'}
</DialogDescription>
</DialogHeader>
{isProcessing ? (
<div className="py-4">
<Progress value={(progress.done / progress.total) * 100} />
<p className="text-sm text-muted-foreground mt-2 text-center">
{progress.done} av {progress.total} klara
</p>
</div>
) : (
<div className="space-y-4 py-2">
<div>
<h4 className="text-sm font-medium text-muted-foreground mb-2">Kostnader</h4>
<div className="grid grid-cols-2 gap-1.5">
{expenseCategories.map((cat) => (
<Button
key={cat.value}
variant="outline"
size="sm"
className="justify-start text-xs"
onClick={() => onSelectCategory(cat.value)}
>
{cat.label}
</Button>
))}
</div>
</div>
<div>
<h4 className="text-sm font-medium text-muted-foreground mb-2">Intäkter</h4>
<div className="grid grid-cols-2 gap-1.5">
{incomeCategories.map((cat) => (
<Button
key={cat.value}
variant="outline"
size="sm"
className="justify-start text-xs"
onClick={() => onSelectCategory(cat.value)}
>
{cat.label}
</Button>
))}
</div>
</div>
</div>
)}
</DialogContent>
</Dialog>
)
}
@@ -112,7 +112,7 @@ export default function SwipeCategorizationView({
if (success) {
moveToNext()
} else {
setError('Kunde inte kategorisera. Tryck "Hoppa över" för att gå vidare.')
setError('Kunde inte bokföra. Tryck "Hoppa över" för att gå vidare.')
}
} catch {
setError('Ett fel uppstod. Tryck "Hoppa över" för att gå vidare.')
@@ -140,7 +140,7 @@ export default function SwipeCategorizationView({
setShowCategorySelect(false)
moveToNext()
} else {
setError('Kunde inte kategorisera. Tryck "Hoppa över" för att gå vidare.')
setError('Kunde inte bokföra. Tryck "Hoppa över" för att gå vidare.')
}
} catch {
setError('Ett fel uppstod. Tryck "Hoppa över" för att gå vidare.')
@@ -186,7 +186,7 @@ export default function SwipeCategorizationView({
</div>
<h2 className="text-2xl font-bold">Klart!</h2>
<p className="text-muted-foreground mt-2">
Alla transaktioner är nu kategoriserade
Alla transaktioner är nu bokförda
</p>
<Button onClick={onClose} className="mt-6">
Tillbaka till transaktioner
@@ -276,7 +276,7 @@ export default function SwipeCategorizationView({
<span>Hoppa över</span>
</div>
<div className="flex items-center gap-2 text-muted-foreground">
<span>Kategorisera</span>
<span>Bokför</span>
<Building className="h-4 w-4" />
<ArrowRight className="h-4 w-4" />
</div>
@@ -457,7 +457,7 @@ export default function SwipeCategorizationView({
disabled={isProcessing}
>
<Building className="mr-2 h-4 w-4" />
Kategorisera
Bokför
</Button>
{/* Skip button - always visible */}
+3
View File
@@ -20,6 +20,7 @@ interface ConfirmationDialogProps {
title: string
warningText?: string
confirmLabel?: string
extraActions?: ReactNode
children: ReactNode
}
@@ -31,6 +32,7 @@ export function ConfirmationDialog({
title,
warningText = 'En verifikation skapas och kan inte ändras efteråt.',
confirmLabel = 'Bekräfta & skapa',
extraActions,
children,
}: ConfirmationDialogProps) {
return (
@@ -66,6 +68,7 @@ export function ConfirmationDialog({
>
Tillbaka
</Button>
{extraActions}
<Button onClick={onConfirm} disabled={isSubmitting}>
{isSubmitting ? (
<>
+1 -1
View File
@@ -131,7 +131,7 @@ export function EmptyReceipts() {
<EmptyState
icon={Camera}
title="Inga kvitton"
description="Ta en bild på ett kvitto för automatisk avläsning och kategorisering. Vi sköter resten!"
description="Ta en bild på ett kvitto för automatisk avläsning och bokföring. Vi sköter resten!"
actionLabel="Skanna kvitto"
actionHref="/receipts/scan"
/>