Files
accounted/components/bookkeeping/DocumentUploadZone.tsx
T
Jakob Wennberg 91e2c1705a feat: per-line VAT, invoice document types, ledger-based VAT declaration, bank reconciliation, and pagination
Per-line VAT rates:
- Add generatePerRateLines() to group invoice items by vat_rate with separate
  revenue + VAT lines per rate group (invoice-entries.ts)
- Add getAvailableVatRates() and getVatTreatmentForRate() (vat-rules.ts)
- PDF template shows per-line VAT column and per-rate totals for mixed-rate invoices
- Invoice create/review UI supports per-line rate selection
- Types: add vat_rate/vat_amount to InvoiceItem, vat_rate to CreateInvoiceItemInput

Invoice document types (proforma, delivery note):
- Add InvoiceDocumentType, document_type and converted_from_id to Invoice type
- PDF hides prices for delivery notes, adds proforma notice
- Email templates support all document types
- mark-paid skips journal entries for non-invoice document types
- Migration 031: invoice_document_type

Accounting method support:
- Add AccountingMethod type (accrual/cash)
- Migration 032: add_accounting_method column to company_settings

VAT declaration rewrite:
- Rewrite to read directly from general ledger (26xx/3xxx account lines)
  instead of aggregating invoices/transactions/receipts
- ACCOUNT_RUTA mapping drives momsdeklaration boxes from GL balances

Bank reconciliation:
- Transaction ingest now pre-fetches unlinked GL lines and attempts
  auto-reconciliation during import
- Add transaction.reconciled event type
- Add ReconciliationMethod type and reconciliation_method on Transaction
- Migration 030: bank_reconciliation
- New reconciliation engine, API routes, and BankReconciliationView component

Pagination (fetchAllRows):
- New lib/supabase/fetch-all.ts overcomes PostgREST 1000-row limit
- Adopted in all report generators, SIE/SRU export, account list APIs

Fiscal period validation:
- New validate-period-duration.ts enforces max 18 months per BFL 3 kap.
- Applied in period-service.ts and fiscal-periods API

Account mapper simplification:
- Remove Levenshtein/fuzzy matching, use exact account number match only

Swedbank parser improvements:
- Support abbreviated headers (Clnr, Bokfdag, Radnr)
- Use Referens column as counterparty

Chart of accounts management:
- Add DELETE endpoint with system account and usage protection
- PUT uses partial updates
- New AccountCombobox, AddAccountDialog, EditAccountDialog, ChartOfAccountsManager

Tax deadline corrections:
- Rewrite inkomstdeklaration_ab using Skatteverket lookup table
- Rewrite arsredovisning deadline to 7 months after FY end per ÅRL 8:3

Onboarding first fiscal year:
- Add first fiscal year toggle with date pickers and 18-month validation

UI terminology:
- Change "okategoriserad/kategorisera" to "obokförd/bokföra" throughout

Report column fix:
- Fix start_date/end_date to period_start/period_end in report queries

Supplier invoice input:
- CreateSupplierInvoiceItemInput uses amount field (legacy quantity/unit_price kept)

Misc:
- SIE import uses upsert for idempotent account creation
- account-descriptions.ts falls back to BAS reference data
- Add invoice_default_notes to CompanySettings
- Update CLAUDE.md to reflect current project state

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-21 14:57:15 +01:00

258 lines
7.8 KiB
TypeScript

'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>
)
}