Fix/chrome pdf preview csp (#572)

* feat: add option to exclude year-end closing entries in SIE export and related reports

* delete docs

* fix: allow Chrome's PDF viewer in verifikat document preview

The /api/documents/:id/inline route shipped with
`object-src 'none'` in its CSP, which blocked Chrome's built-in PDF
viewer (it renders inline PDFs via an internal <embed>). Users on
Chrome saw "Det här innehållet har blockerats" when expanding a PDF
attachment in the bookkeeping view; Firefox (PDF.js) and Edge (own
viewer) were unaffected, and JPGs worked because <img> isn't subject
to object-src.

Drops the CSP for this route to the minimum needed for embeddability:
`frame-ancestors 'self'`. X-Content-Type-Options: nosniff plus the
fixed Content-Type from the handler already block MIME confusion;
X-Frame-Options: SAMEORIGIN + frame-ancestors still block clickjacking.

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

* feat(auth): add webmail deep link to email confirmation screens

Mirrors Stripe's signup UX: after asking the user to verify their email,
detect their webmail provider from the domain and show a button that
opens the inbox in a new tab. Gmail gets a from:<sender> search
pre-populated; Outlook/Yahoo/iCloud/Proton open the inbox directly.
Unknown / custom domains fall back to the existing copy.

Sender address is configurable via NEXT_PUBLIC_BRANDING_AUTH_EMAIL_FROM
(default noreply@gnubok.se) so white-label installs can match their
Supabase Auth SMTP config.

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

* fix(auth): unblock first-time password set for BankID users with MFA

Supabase rejects updateUser({password}) and mfa.unenroll with "AAL2 session
is required" whenever a TOTP factor is enrolled. BankID magic-link logins
produce AAL1, and middleware skips MFA enforcement for bankid_linked users,
so they had no path to AAL2 — leaving them unable to set a backup password
or disable MFA without going through the email-recovery escape hatch.

- /api/account/password: branch on app_metadata.has_password. First-time set
  writes via service.auth.admin.updateUserById (no existing credential to
  protect, AAL2 guard does not apply). Change-password keeps the user-session
  updateUser so AAL2 still fires for credential rotation.
- /mfa/verify: accept a safeReturnTo query param and route there after
  successful verify, so step-up flows can land back where they came from.
- SecuritySettings: detect the AAL2 error from both change-password and
  mfa.unenroll and redirect through /mfa/verify?returnTo=/settings/account
  instead of toasting a dead-end error.

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

* Add tests and rounding utility for öre precision in bokslut calculations

- Implemented `roundOre` function for rounding SEK amounts to two decimal places, ensuring consistent monetary calculations.
- Introduced `ORE_TOLERANCE` constant for comparing rounded amounts, facilitating invariant checks in financial entries.
- Created comprehensive tests for `roundOre`, covering typical cases, edge cases, and idempotency.
- Added year-end invariants tests to verify database-level guarantees for closing entries, ensuring they balance to the öre and reject discrepancies.
- Developed end-to-end tests for the dispositions chain, validating the correctness of calculations across various scenarios.

* fix: update PDF rendering to remove Swish QR code generation and set default to disable Swish visibility

* fix: enhance security by rejecting data URIs in safeReturnTo function tests

* fix: improve rounding logic in roundOre function and add customer_type migration

* fix: add customer_type column to customers and enforce CHECK constraint

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-05-26 22:29:41 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent 0087b7be3f
commit 32d9978f1b
207 changed files with 24187 additions and 1052 deletions
+198 -32
View File
@@ -1,14 +1,28 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslations } from 'next-intl'
import { ExternalLink, FileText, ImageIcon, Paperclip } from 'lucide-react'
import {
Sheet,
SheetContent,
SheetHeader,
SheetTitle,
} from '@/components/ui/sheet'
AlertTriangle,
ExternalLink,
FileText,
ImageIcon,
Loader2,
Lock,
Paperclip,
RefreshCw,
Trash2,
} from 'lucide-react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { Skeleton } from '@/components/ui/skeleton'
interface DocumentRecord {
@@ -47,9 +61,16 @@ export default function AttachmentPreviewSheet({
onOpenChange,
}: AttachmentPreviewSheetProps) {
const t = useTranslations('attachment_preview_sheet')
const tj = useTranslations('journal_attachments')
const { toast } = useToast()
const [documents, setDocuments] = useState<DocumentRecord[]>([])
const [loading, setLoading] = useState(false)
const [blockedDoc, setBlockedDoc] = useState<DocumentRecord | null>(null)
const [replacingDocId, setReplacingDocId] = useState<string | null>(null)
const replaceFileInputRef = useRef<HTMLInputElement | null>(null)
const replaceTargetIdRef = useRef<string | null>(null)
const fetchAttachments = useCallback(async (id: string) => {
setLoading(true)
try {
@@ -87,20 +108,64 @@ export default function AttachmentPreviewSheet({
if (open && entryId) {
fetchAttachments(entryId)
} else if (!open) {
// Reset state when closed so the next open starts fresh
setDocuments([])
setBlockedDoc(null)
}
}, [open, entryId, fetchAttachments])
const handleOpenReplacePicker = (docId: string) => {
replaceTargetIdRef.current = docId
replaceFileInputRef.current?.click()
}
const handleReplaceFileSelected = async (file: File | null) => {
const docId = replaceTargetIdRef.current
replaceTargetIdRef.current = null
if (replaceFileInputRef.current) {
replaceFileInputRef.current.value = ''
}
if (!file || !docId || !entryId) return
setReplacingDocId(docId)
try {
const fd = new FormData()
fd.append('file', file)
const res = await fetch(`/api/documents/${docId}/versions`, {
method: 'POST',
body: fd,
})
if (!res.ok) {
const { error } = await res.json().catch(() => ({ error: undefined }))
toast({
title: tj('replace_failed'),
description: error || undefined,
variant: 'destructive',
})
} else {
await fetchAttachments(entryId)
setBlockedDoc(null)
}
} catch {
toast({ title: tj('replace_failed'), variant: 'destructive' })
} finally {
setReplacingDocId(null)
}
}
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
side="right"
className="w-full overflow-y-auto sm:max-w-[560px]"
>
<SheetHeader>
<SheetTitle>{t('title')}</SheetTitle>
</SheetHeader>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90vh] w-[95vw] max-w-4xl overflow-y-auto">
<DialogHeader>
<DialogTitle>{t('title')}</DialogTitle>
</DialogHeader>
<input
ref={replaceFileInputRef}
type="file"
accept="application/pdf,image/jpeg,image/png,image/webp"
className="hidden"
onChange={(e) => handleReplaceFileSelected(e.target.files?.[0] ?? null)}
/>
{loading ? (
<div className="space-y-3">
@@ -119,6 +184,7 @@ export default function AttachmentPreviewSheet({
{documents.map((doc) => {
const inlineSrc = `/api/documents/${doc.id}/inline`
const previewable = isImageType(doc.mime_type) || isPdfType(doc.mime_type)
const isReplacing = replacingDocId === doc.id
return (
<div key={doc.id} className="space-y-2">
<div className="flex items-start justify-between gap-3">
@@ -137,25 +203,76 @@ export default function AttachmentPreviewSheet({
</p>
</div>
</div>
{doc.download_url && (
<a
href={doc.download_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex shrink-0 items-center gap-1 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
<div className="flex shrink-0 items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
onClick={() => handleOpenReplacePicker(doc.id)}
disabled={isReplacing}
title={t('replace')}
aria-label={t('replace')}
>
<ExternalLink className="h-3.5 w-3.5" />
{t('open_in_new_tab')}
</a>
)}
{isReplacing ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
<RefreshCw className="h-3.5 w-3.5" />
)}
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
onClick={() => setBlockedDoc(doc)}
title={t('remove')}
aria-label={t('remove')}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
{doc.download_url && (
<a
href={doc.download_url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 px-2 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
>
<ExternalLink className="h-3.5 w-3.5" />
{t('open_in_new_tab')}
</a>
)}
</div>
</div>
{isPdfType(doc.mime_type) && (
<iframe
src={inlineSrc}
title={doc.file_name}
// <object> + type="application/pdf" invokes Chrome's PDF
// plugin directly. <iframe> went through Chrome's frame
// pipeline first and intermittently surfaced
// "Det här innehållet har blockerats" even with a
// permissive CSP. Firefox/Edge handled both fine; Chrome
// is the odd one. See crbug.com/271452.
<object
data={inlineSrc}
type="application/pdf"
aria-label={doc.file_name}
className="h-[70vh] w-full rounded-lg border border-border"
/>
>
<div className="flex h-[70vh] w-full items-center justify-center rounded-lg border border-border bg-muted/30 p-4 text-center text-sm text-muted-foreground">
{t('not_previewable')}
{doc.download_url && (
<>
{' — '}
<a
href={doc.download_url}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
{t('open_in_new_tab')}
</a>
</>
)}
</div>
</object>
)}
{isImageType(doc.mime_type) && (
@@ -178,7 +295,56 @@ export default function AttachmentPreviewSheet({
})}
</div>
)}
</SheetContent>
</Sheet>
<Dialog
open={blockedDoc !== null}
onOpenChange={(o) => {
if (!o) setBlockedDoc(null)
}}
>
<DialogContent>
<DialogHeader>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-warning/15 shrink-0">
<Lock className="h-5 w-5 text-warning-foreground" />
</div>
<DialogTitle>{tj('remove_blocked_title')}</DialogTitle>
</div>
<DialogDescription className="pt-3 text-sm text-muted-foreground">
{tj('remove_blocked_body')}
</DialogDescription>
</DialogHeader>
<div className="rounded-lg border border-border bg-muted/30 p-3 text-sm">
<div className="flex items-start gap-2">
<AlertTriangle className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
<p className="text-muted-foreground">{tj('remove_blocked_hint')}</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setBlockedDoc(null)}>
{tj('remove_blocked_cancel_cta')}
</Button>
<Button
onClick={() => {
if (blockedDoc) handleOpenReplacePicker(blockedDoc.id)
}}
disabled={blockedDoc !== null && replacingDocId === blockedDoc.id}
>
{blockedDoc !== null && replacingDocId === blockedDoc.id ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{tj('replace_uploading')}
</>
) : (
tj('remove_blocked_replace_cta')
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</DialogContent>
</Dialog>
)
}
+2 -1
View File
@@ -6,6 +6,7 @@ import { Badge } from '@/components/ui/badge'
import { Info } from 'lucide-react'
import JournalEntryStatusBadge from '@/components/bookkeeping/JournalEntryStatusBadge'
import { formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import type { JournalEntry, JournalEntryLine } from '@/types'
interface Props {
@@ -73,7 +74,7 @@ export default function CorrectionChain({ currentEntryId, chain }: Props) {
<div className="flex items-center gap-2 flex-wrap">
<span className="text-xs font-medium text-muted-foreground">{role.label}</span>
<span className="font-mono text-sm">
{entry.voucher_series}{entry.voucher_number}
{formatVoucher(entry)}
</span>
<span className="text-sm text-muted-foreground tabular-nums">{formatDate(entry.entry_date)}</span>
<JournalEntryStatusBadge entry={entry} showStatus={false} />
@@ -18,6 +18,7 @@ import { useToast } from '@/components/ui/use-toast'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { Plus, Trash2 } from 'lucide-react'
import { formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import type { JournalEntry, JournalEntryLine, BASAccount } from '@/types'
interface CorrectionLine {
@@ -165,7 +166,7 @@ export default function CorrectionEntryDialog({ entry, open, onOpenChange, onCor
{/* Original entry (read-only) */}
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<span className="font-mono">{entry.voucher_series}{entry.voucher_number}</span>
<span className="font-mono">{formatVoucher(entry)}</span>
<span className="tabular-nums">{formatDate(entry.entry_date)}</span>
<Badge variant="outline" className="text-xs">Original</Badge>
</div>
@@ -3,7 +3,28 @@
import { useState, useEffect, useCallback, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { FileText, ImageIcon, Download, ChevronDown, ChevronUp, Plus } from 'lucide-react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogDescription,
DialogFooter,
} from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import {
FileText,
ImageIcon,
Download,
ChevronDown,
ChevronUp,
Plus,
Trash2,
RefreshCw,
Loader2,
Lock,
AlertTriangle,
} from 'lucide-react'
import DocumentUploadZone from '@/components/bookkeeping/DocumentUploadZone'
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
@@ -45,12 +66,22 @@ export default function JournalEntryAttachments({
onCountChange,
}: JournalEntryAttachmentsProps) {
const t = useTranslations('journal_attachments')
const { toast } = useToast()
const [documents, setDocuments] = useState<DocumentRecord[]>([])
const [loading, setLoading] = useState(true)
const [expandedDoc, setExpandedDoc] = useState<string | null>(null)
const [showUpload, setShowUpload] = useState(false)
const [uploadFiles, setUploadFiles] = useState<UploadedFile[]>([])
// Docs listed here are filtered by journal_entry_id, so every row is bound
// to a verifikation — BFL 7 kap 2§ blocks deletion. "Ta bort" therefore
// surfaces the educational modal; "Ersätt" goes through createNewVersion()
// so the original stays in the version chain.
const [blockedDoc, setBlockedDoc] = useState<DocumentRecord | null>(null)
const [replacingDocId, setReplacingDocId] = useState<string | null>(null)
const replaceFileInputRef = useRef<HTMLInputElement | null>(null)
const replaceTargetIdRef = useRef<string | null>(null)
const onCountChangeRef = useRef(onCountChange)
onCountChangeRef.current = onCountChange
@@ -102,7 +133,6 @@ export default function JournalEntryAttachments({
return
}
// Fetch signed URL for preview if not already loaded
if (!doc.download_url) {
try {
const res = await fetch(`/api/documents/${doc.id}`)
@@ -113,7 +143,6 @@ export default function JournalEntryAttachments({
)
}
} catch {
// Non-critical — silently ignore
return
}
}
@@ -121,6 +150,49 @@ export default function JournalEntryAttachments({
setExpandedDoc(doc.id)
}
const handleRequestRemove = (doc: DocumentRecord) => {
setBlockedDoc(doc)
}
const handleOpenReplacePicker = (docId: string) => {
replaceTargetIdRef.current = docId
replaceFileInputRef.current?.click()
}
const handleReplaceFileSelected = async (file: File | null) => {
const docId = replaceTargetIdRef.current
replaceTargetIdRef.current = null
if (replaceFileInputRef.current) {
replaceFileInputRef.current.value = ''
}
if (!file || !docId) return
setReplacingDocId(docId)
try {
const fd = new FormData()
fd.append('file', file)
const res = await fetch(`/api/documents/${docId}/versions`, {
method: 'POST',
body: fd,
})
if (!res.ok) {
const { error } = await res.json().catch(() => ({ error: undefined }))
toast({
title: t('replace_failed'),
description: error || undefined,
variant: 'destructive',
})
} else {
await fetchDocuments()
setBlockedDoc(null)
}
} catch {
toast({ title: t('replace_failed'), variant: 'destructive' })
} finally {
setReplacingDocId(null)
}
}
if (loading) {
return (
<div className="py-2 text-sm text-muted-foreground">
@@ -131,6 +203,14 @@ export default function JournalEntryAttachments({
return (
<div className="border-t pt-3 mt-3">
<input
ref={replaceFileInputRef}
type="file"
accept="application/pdf,image/jpeg,image/png,image/webp"
className="hidden"
onChange={(e) => handleReplaceFileSelected(e.target.files?.[0] ?? null)}
/>
<div className="flex items-center justify-between mb-2">
<h4 className="text-sm font-medium">
{t('title')} {documents.length > 0 && `(${documents.length})`}
@@ -146,7 +226,6 @@ export default function JournalEntryAttachments({
</Button>
</div>
{/* Upload zone */}
{showUpload && (
<div className="mb-3">
<DocumentUploadZone
@@ -158,80 +237,157 @@ export default function JournalEntryAttachments({
</div>
)}
{/* Document list */}
{documents.length === 0 && !showUpload ? (
<p className="text-sm text-muted-foreground py-1">
{t('empty')}
</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">
{isPreviewable(doc.mime_type) ? (
<button
onClick={() => handlePreviewToggle(doc)}
className="shrink-0 hover:text-primary transition-colors"
>
{expandedDoc === 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" />
)}
{isPreviewable(doc.mime_type) && expandedDoc !== doc.id && (
isImageType(doc.mime_type) ? (
<ImageIcon className="h-4 w-4 text-muted-foreground shrink-0" />
{documents.map((doc) => {
const isReplacing = replacingDocId === doc.id
return (
<div key={doc.id}>
<div className="flex items-center gap-2 text-sm py-1.5 px-2 rounded bg-muted/50">
{isPreviewable(doc.mime_type) ? (
<button
onClick={() => handlePreviewToggle(doc)}
className="shrink-0 hover:text-primary transition-colors"
>
{expandedDoc === 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" />
)
)}
{isPreviewable(doc.mime_type) && expandedDoc !== doc.id && (
isImageType(doc.mime_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">{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 min-h-[44px] min-w-[44px]"
onClick={() => handleOpenReplacePicker(doc.id)}
disabled={isReplacing}
title={t('replace')}
aria-label={t('replace')}
>
{isReplacing ? (
<Loader2 className="h-3 w-3 animate-spin" />
) : (
<RefreshCw className="h-3 w-3" />
)}
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleRequestRemove(doc)}
title={t('remove')}
aria-label={t('remove')}
>
<Trash2 className="h-3 w-3" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 shrink-0 min-h-[44px] min-w-[44px]"
onClick={() => handleDownload(doc.id)}
title={t('download')}
aria-label={t('download')}
>
<Download className="h-3 w-3" />
</Button>
</div>
{expandedDoc === doc.id && doc.download_url && isImageType(doc.mime_type) && (
<div className="px-2 py-2">
<img
src={`/api/documents/${doc.id}/inline`}
alt={doc.file_name}
className="max-h-48 rounded-lg object-contain"
/>
</div>
)}
<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 min-h-[44px] min-w-[44px]"
onClick={() => handleDownload(doc.id)}
title={t('download')}
>
<Download className="h-3 w-3" />
</Button>
{expandedDoc === doc.id && doc.download_url && isPdfType(doc.mime_type) && (
<div className="px-2 py-2">
<iframe
src={`/api/documents/${doc.id}/inline`}
title={doc.file_name}
className="w-full h-[60vh] rounded-lg border"
/>
</div>
)}
</div>
{/* Image preview */}
{expandedDoc === doc.id && doc.download_url && isImageType(doc.mime_type) && (
<div className="px-2 py-2">
<img
src={`/api/documents/${doc.id}/inline`}
alt={doc.file_name}
className="max-h-48 rounded-lg object-contain"
/>
</div>
)}
{/* PDF preview */}
{expandedDoc === doc.id && doc.download_url && isPdfType(doc.mime_type) && (
<div className="px-2 py-2">
<iframe
src={`/api/documents/${doc.id}/inline`}
title={doc.file_name}
className="w-full h-[60vh] rounded-lg border"
/>
</div>
)}
</div>
))}
)
})}
</div>
)}
<Dialog
open={blockedDoc !== null}
onOpenChange={(o) => {
if (!o) setBlockedDoc(null)
}}
>
<DialogContent>
<DialogHeader>
<div className="flex items-center gap-3">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-warning/15 shrink-0">
<Lock className="h-5 w-5 text-warning-foreground" />
</div>
<DialogTitle>{t('remove_blocked_title')}</DialogTitle>
</div>
<DialogDescription className="pt-3 text-sm text-muted-foreground">
{t('remove_blocked_body')}
</DialogDescription>
</DialogHeader>
<div className="rounded-lg border border-border bg-muted/30 p-3 text-sm">
<div className="flex items-start gap-2">
<AlertTriangle className="h-4 w-4 text-muted-foreground mt-0.5 shrink-0" />
<p className="text-muted-foreground">{t('remove_blocked_hint')}</p>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setBlockedDoc(null)}>
{t('remove_blocked_cancel_cta')}
</Button>
<Button
onClick={() => {
if (blockedDoc) handleOpenReplacePicker(blockedDoc.id)
}}
disabled={blockedDoc !== null && replacingDocId === blockedDoc.id}
>
{blockedDoc !== null && replacingDocId === blockedDoc.id ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
{t('replace_uploading')}
</>
) : (
t('remove_blocked_replace_cta')
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
)
}
+15 -5
View File
@@ -25,6 +25,7 @@ import {
} from '@/lib/hooks/use-submit-with-account-activation'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { formatCurrency } from '@/lib/utils'
import { formatVoucher, resolveDefaultSeriesForSource } from '@/lib/bookkeeping/voucher-series-resolver'
import { useUnsavedChanges } from '@/lib/hooks/use-unsaved-changes'
import { useCompany } from '@/contexts/CompanyContext'
import type { UploadedFile } from '@/components/bookkeeping/DocumentUploadZone'
@@ -144,13 +145,22 @@ export default function JournalEntryForm({
useEffect(() => {
fetchPeriods()
fetchAccounts()
// Fetch default voucher series from company settings
// Fetch default voucher series from company settings — prefer the
// per-source-type mapping when present; fall back to the legacy
// default_voucher_series, then to 'A'.
if (!embedded) {
fetch('/api/settings').then(r => r.json()).then(({ data }) => {
if (data?.default_voucher_series) setVoucherSeries(data.default_voucher_series)
if (!data) return
const effectiveSourceType = sourceType ?? 'manual'
const perSource = resolveDefaultSeriesForSource(
data as { default_voucher_series_per_source_type?: Record<string, string> | null } | null,
effectiveSourceType,
)
const fallback = data.default_voucher_series || 'A'
setVoucherSeries(perSource !== 'A' ? perSource : fallback)
}).catch(() => {/* keep 'A' */})
}
}, [])
}, [embedded, sourceType])
// Auto-select period when entry date changes
useEffect(() => {
@@ -464,7 +474,7 @@ export default function JournalEntryForm({
toast({
title: t('toast_created_title'),
description: t('toast_created_description', { voucher: `${result.data?.voucher_series ?? ''}${result.data?.voucher_number ?? ''}` }),
description: t('toast_created_description', { voucher: formatVoucher(result.data ?? {}) }),
})
setShowReview(false)
setDescription('')
@@ -996,7 +1006,7 @@ export default function JournalEntryForm({
isSubmitting={isSubmitting}
title={
!embedded && nextVoucherNumber != null
? t('review_title_with_voucher', { voucher: `${voucherSeries}${nextVoucherNumber}` })
? t('review_title_with_voucher', { voucher: formatVoucher({ voucher_series: voucherSeries, voucher_number: nextVoucherNumber }) })
: t('review_title')
}
warningText={embedded ? '' : t('review_warning')}
+23 -4
View File
@@ -12,6 +12,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
import { Switch } from '@/components/ui/switch'
import { ChevronDown, ChevronRight, Paperclip, AlertTriangle, Loader2, BookOpen, X, Copy, Lock } from 'lucide-react'
import { formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { Input } from '@/components/ui/input'
import { AccountNumber } from '@/components/ui/account-number'
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
@@ -57,6 +58,7 @@ export default function JournalEntryList({ periodId }: Props) {
const [dateTo, setDateTo] = useState('')
const [dateFromInput, setDateFromInput] = useState('')
const [dateToInput, setDateToInput] = useState('')
const [seriesFilter, setSeriesFilter] = useState<string>('all')
const pageSize = 20
const normalizeDate = (v: string): string | null => {
@@ -123,6 +125,7 @@ export default function JournalEntryList({ periodId }: Props) {
if (periodId) params.set('period_id', periodId)
if (dateFrom) params.set('date_from', dateFrom)
if (dateTo) params.set('date_to', dateTo)
if (seriesFilter !== 'all') params.set('series', seriesFilter)
const res = await fetch(`/api/bookkeeping/journal-entries?${params}`)
if (!res.ok) {
@@ -142,7 +145,7 @@ export default function JournalEntryList({ periodId }: Props) {
useEffect(() => {
fetchEntries()
}, [periodId, page, sortBy, dateFrom, dateTo])
}, [periodId, page, sortBy, dateFrom, dateTo, seriesFilter])
const handleAttachmentCountChange = useCallback((entryId: string, count: number) => {
setAttachmentCounts((prev) => ({ ...prev, [entryId]: count }))
@@ -161,7 +164,7 @@ export default function JournalEntryList({ periodId }: Props) {
const posted = result.data
toast({
title: t('toast_posted_title'),
description: t('toast_posted_description', { voucher: `${posted?.voucher_series ?? ''}${posted?.voucher_number ?? ''}` }),
description: t('toast_posted_description', { voucher: formatVoucher(posted ?? {}) }),
})
await fetchEntries()
} else {
@@ -242,6 +245,22 @@ export default function JournalEntryList({ periodId }: Props) {
<SelectItem value="voucher_desc">{t('sort_voucher_desc')}</SelectItem>
</SelectContent>
</Select>
<Select value={seriesFilter} onValueChange={(v) => { setSeriesFilter(v); setPage(0) }}>
<SelectTrigger
className="h-8 w-auto gap-1.5 text-xs sm:w-[120px] font-mono"
aria-label="Verifikationsserie"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="all" className="text-xs">Alla serier</SelectItem>
{'ABCDEFG'.split('').map((letter) => (
<SelectItem key={letter} value={letter} className="font-mono text-xs">
Serie {letter}
</SelectItem>
))}
</SelectContent>
</Select>
<div className="flex items-center gap-1.5">
<Input
type="text"
@@ -326,7 +345,7 @@ export default function JournalEntryList({ periodId }: Props) {
className="font-mono text-sm text-primary hover:underline w-16"
onClick={(e) => e.stopPropagation()}
>
{entry.voucher_series}{entry.voucher_number}
{formatVoucher(entry)}
</Link>
<span className="text-sm text-muted-foreground tabular-nums w-24">
{formatDate(entry.entry_date)}
@@ -396,7 +415,7 @@ export default function JournalEntryList({ periodId }: Props) {
className="font-mono text-sm text-primary hover:underline"
onClick={(e) => e.stopPropagation()}
>
{entry.voucher_series}{entry.voucher_number}
{formatVoucher(entry)}
</Link>
<span className="text-sm text-muted-foreground tabular-nums">
{formatDate(entry.entry_date)}
@@ -35,6 +35,7 @@ const SOURCE_TYPES = [
'supplier_invoice_paid',
'supplier_invoice_cash_payment',
'currency_revaluation',
'reminder_fee',
] as const
/**
@@ -1,6 +1,6 @@
'use client'
import { useState } from 'react'
import { useMemo, useState } from 'react'
import {
Dialog,
DialogContent,
@@ -18,9 +18,11 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Loader2 } from 'lucide-react'
import { Loader2, Plus, X } from 'lucide-react'
import { useToast } from '@/components/ui/use-toast'
import type { AssetCategory } from '@/types'
import { useCompanyOptional } from '@/contexts/CompanyContext'
import { formatCurrency } from '@/lib/utils'
import type { AssetCategory, DepreciationMethod, K3Component } from '@/types'
interface CreateAssetDialogProps {
open: boolean
@@ -28,6 +30,28 @@ interface CreateAssetDialogProps {
onCreated: () => void
}
/** Editor row state — strings so the user can clear inputs without zeroing
* out the component immediately. Converted to numbers at submit time. */
interface ComponentRow {
id: string
name: string
cost: string
useful_life_months: string
salvage_value: string
}
let componentRowCounter = 0
function newComponentRow(): ComponentRow {
componentRowCounter += 1
return {
id: `cmp-${componentRowCounter}`,
name: '',
cost: '',
useful_life_months: '',
salvage_value: '',
}
}
// Defaults are K2-redovisning (BFNAR 2016:10) schablon, NOT skattemässig
// avskrivning. Building / markanläggning values are conservative — IL 19/20
// kap may allow longer (50 yr) or shorter (10 yr) depending on byggnadstyp.
@@ -42,8 +66,36 @@ const CATEGORY_OPTIONS: { value: AssetCategory; label: string; defaultYears: num
{ value: 'other_tangible', label: 'Övrig materiell tillgång', defaultYears: 5 },
]
const DEPRECIATION_METHOD_OPTIONS: { value: DepreciationMethod; label: string; hint: string }[] = [
{
value: 'linear',
label: 'Linjär',
hint: 'Planenlig raklinje över nyttjandeperioden (ÅRL 4 kap 4§).',
},
{
value: 'declining_balance_30',
label: 'Räkenskapsenlig 30 %',
hint: 'Huvudregeln (IL 18 kap 13§) — 30 % degressivt på avskrivningsunderlaget.',
},
{
value: 'declining_balance_20',
label: 'Räkenskapsenlig 20 %',
hint: 'Kompletteringsregeln (IL 18 kap 17§) — 20 % degressivt. Vanlig för byggnader.',
},
{
value: 'restvardesavskrivning_25',
label: 'Restvärdeavskrivning 25 %',
hint: 'IL 18 kap 13§ st.3 — 25 % degressivt ner till angivet restvärde.',
},
]
export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAssetDialogProps) {
const { toast } = useToast()
// useCompanyOptional so the dialog still works in tests / storyboards
// that don't wrap it in CompanyProvider. K3 features simply hide.
const companyCtx = useCompanyOptional()
const isK3 = companyCtx?.company?.accounting_framework === 'k3'
const [name, setName] = useState('')
const [category, setCategory] = useState<AssetCategory>('equipment')
const [acquisitionDate, setAcquisitionDate] = useState(
@@ -51,6 +103,12 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
)
const [acquisitionCost, setAcquisitionCost] = useState('')
const [usefulLifeYears, setUsefulLifeYears] = useState('5')
const [depreciationMethod, setDepreciationMethod] = useState<DepreciationMethod>('linear')
const [restvardeTarget, setRestvardeTarget] = useState('')
// K3 component depreciation. `useComponents` toggles the advanced section;
// null when disabled, an array (possibly empty during editing) when enabled.
const [useComponents, setUseComponents] = useState(false)
const [componentRows, setComponentRows] = useState<ComponentRow[]>([])
const [submitting, setSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -60,6 +118,40 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
if (option) setUsefulLifeYears(option.defaultYears.toString())
}
const isRestvarde = depreciationMethod === 'restvardesavskrivning_25'
const methodHint =
DEPRECIATION_METHOD_OPTIONS.find((o) => o.value === depreciationMethod)?.hint ?? ''
const totalComponentCost = useMemo(() => {
return componentRows.reduce((sum, row) => {
const v = parseFloat(row.cost)
return Number.isFinite(v) ? sum + v : sum
}, 0)
}, [componentRows])
const parsedAcquisitionCost = parseFloat(acquisitionCost)
const componentMismatch =
useComponents
&& componentRows.length > 0
&& Number.isFinite(parsedAcquisitionCost)
&& Math.abs(totalComponentCost - parsedAcquisitionCost) > 1
const addComponentRow = () => {
setComponentRows((rows) => [...rows, newComponentRow()])
}
const removeComponentRow = (id: string) => {
setComponentRows((rows) => rows.filter((r) => r.id !== id))
}
const updateComponentRow = (id: string, patch: Partial<ComponentRow>) => {
setComponentRows((rows) => rows.map((r) => (r.id === id ? { ...r, ...patch } : r)))
}
const toggleUseComponents = (next: boolean) => {
setUseComponents(next)
if (next && componentRows.length === 0) {
setComponentRows([newComponentRow()])
}
}
const handleSubmit = async () => {
setError(null)
const cost = parseFloat(acquisitionCost)
@@ -68,6 +160,73 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
setError('Fyll i namn, anskaffningsvärde och avskrivningstid.')
return
}
let restvardeTargetNumber: number | null = null
if (isRestvarde) {
const parsed = parseFloat(restvardeTarget)
if (!Number.isFinite(parsed) || parsed < 0) {
setError('Ange ett restvärde (0 kr eller högre).')
return
}
if (parsed >= cost) {
setError('Restvärdet måste vara lägre än anskaffningsvärdet.')
return
}
restvardeTargetNumber = parsed
}
// K3 components — only when both the framework permits (gate at API)
// and the user opted into the section. Empty array is invalid (the
// validator rejects it) so the dialog also flips back to "off" when
// every row is removed.
let componentsPayload: K3Component[] | null = null
if (useComponents && isK3) {
if (componentRows.length === 0) {
setError('Lägg till minst en komponent eller stäng av komponentuppdelningen.')
return
}
const parsed: K3Component[] = []
for (const [index, row] of componentRows.entries()) {
const componentCost = parseFloat(row.cost)
const months = parseInt(row.useful_life_months, 10)
const salvageRaw = row.salvage_value.trim()
const salvage = salvageRaw === '' ? undefined : parseFloat(salvageRaw)
const trimmedName = row.name.trim()
if (!trimmedName) {
setError(`Komponent ${index + 1}: ange ett namn.`)
return
}
if (!Number.isFinite(componentCost) || componentCost <= 0) {
setError(`${trimmedName}: anskaffningsvärdet måste vara större än 0.`)
return
}
if (!Number.isFinite(months) || months <= 0) {
setError(`${trimmedName}: ange ett positivt heltal månader.`)
return
}
if (salvage !== undefined && (!Number.isFinite(salvage) || salvage < 0)) {
setError(`${trimmedName}: restvärdet får inte vara negativt.`)
return
}
if (salvage !== undefined && salvage > componentCost) {
setError(`${trimmedName}: restvärdet får inte överstiga anskaffningsvärdet.`)
return
}
parsed.push({
name: trimmedName,
cost: componentCost,
useful_life_months: months,
...(salvage !== undefined ? { salvage_value: salvage } : {}),
})
}
const sum = parsed.reduce((s, c) => s + c.cost, 0)
if (Math.abs(sum - cost) > 1) {
setError(
`Komponenter summerar till ${formatCurrency(sum)} men anskaffningsvärdet är ${formatCurrency(cost)}.`,
)
return
}
componentsPayload = parsed
}
setSubmitting(true)
try {
const res = await fetch('/api/assets', {
@@ -79,7 +238,11 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
acquisition_date: acquisitionDate,
acquisition_cost: cost,
useful_life_months: years * 12,
depreciation_method: 'linear',
depreciation_method: depreciationMethod,
...(restvardeTargetNumber !== null
? { restvarde_target: restvardeTargetNumber }
: {}),
...(componentsPayload !== null ? { k3_components: componentsPayload } : {}),
}),
})
const body = await res.json()
@@ -91,6 +254,10 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
// Reset form for next entry
setName('')
setAcquisitionCost('')
setDepreciationMethod('linear')
setRestvardeTarget('')
setUseComponents(false)
setComponentRows([])
onCreated()
} catch (err) {
setError(err instanceof Error ? err.message : 'Okänt fel')
@@ -101,7 +268,7 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md">
<DialogContent className={isK3 ? 'sm:max-w-2xl' : 'sm:max-w-md'}>
<DialogHeader>
<DialogTitle>Ny anläggningstillgång</DialogTitle>
</DialogHeader>
@@ -172,6 +339,196 @@ export function CreateAssetDialog({ open, onOpenChange, onCreated }: CreateAsset
För skattemässig avskrivning kan annan livslängd gälla (IL 18–20 kap).
</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="asset-method">Avskrivningsmetod</Label>
<Select
value={depreciationMethod}
onValueChange={(v) => setDepreciationMethod(v as DepreciationMethod)}
>
<SelectTrigger id="asset-method">
<SelectValue />
</SelectTrigger>
<SelectContent>
{DEPRECIATION_METHOD_OPTIONS.map((o) => (
<SelectItem key={o.value} value={o.value}>
{o.label}
</SelectItem>
))}
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">{methodHint}</p>
</div>
{isRestvarde && (
<div className="space-y-1.5">
<Label htmlFor="asset-restvarde">Restvärde (kr)</Label>
<Input
id="asset-restvarde"
type="number"
min="0"
step="1"
value={restvardeTarget}
onChange={(e) => setRestvardeTarget(e.target.value)}
placeholder="t.ex. 5000"
className="tabular-nums"
/>
<p className="text-xs text-muted-foreground">
Avskrivningen stannar när bokfört värde når restvärdet. Restvärdet
måste vara lägre än anskaffningsvärdet.
</p>
</div>
)}
{isK3 && (
<div className="space-y-3 rounded-md border border-border bg-muted/20 p-4">
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<Label className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Avancerat — komponentuppdelning
</Label>
<p className="text-xs text-muted-foreground">
K3 (BFNAR 2012:1 17.4) — när väsentliga komponenter har olika nyttjandeperiod
skrivs varje komponent av för sig. Typisk för fastigheter (tak, fasad, stomme,
installationer).
</p>
</div>
<Button
type="button"
variant={useComponents ? 'default' : 'outline'}
size="sm"
onClick={() => toggleUseComponents(!useComponents)}
>
{useComponents ? 'Aktiverad' : 'Aktivera'}
</Button>
</div>
{useComponents && (
<div className="space-y-2">
{componentRows.map((row, idx) => (
<div
key={row.id}
className="grid grid-cols-12 items-end gap-2 rounded-md border border-border bg-background p-2"
>
<div className="col-span-12 sm:col-span-4 space-y-1">
<Label
htmlFor={`cmp-name-${row.id}`}
className="text-xs text-muted-foreground"
>
Komponent
</Label>
<Input
id={`cmp-name-${row.id}`}
value={row.name}
onChange={(e) =>
updateComponentRow(row.id, { name: e.target.value })
}
placeholder={idx === 0 ? 't.ex. Stomme' : 'Namn'}
/>
</div>
<div className="col-span-6 sm:col-span-3 space-y-1">
<Label
htmlFor={`cmp-cost-${row.id}`}
className="text-xs text-muted-foreground"
>
Kostnad (kr)
</Label>
<Input
id={`cmp-cost-${row.id}`}
type="number"
min="0"
step="1"
value={row.cost}
onChange={(e) =>
updateComponentRow(row.id, { cost: e.target.value })
}
className="tabular-nums"
/>
</div>
<div className="col-span-6 sm:col-span-2 space-y-1">
<Label
htmlFor={`cmp-life-${row.id}`}
className="text-xs text-muted-foreground"
>
Liv (mån)
</Label>
<Input
id={`cmp-life-${row.id}`}
type="number"
min="1"
step="1"
value={row.useful_life_months}
onChange={(e) =>
updateComponentRow(row.id, { useful_life_months: e.target.value })
}
className="tabular-nums"
/>
</div>
<div className="col-span-9 sm:col-span-2 space-y-1">
<Label
htmlFor={`cmp-salvage-${row.id}`}
className="text-xs text-muted-foreground"
>
Restvärde
</Label>
<Input
id={`cmp-salvage-${row.id}`}
type="number"
min="0"
step="1"
value={row.salvage_value}
onChange={(e) =>
updateComponentRow(row.id, { salvage_value: e.target.value })
}
placeholder="0"
className="tabular-nums"
/>
</div>
<div className="col-span-3 sm:col-span-1 flex justify-end">
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => removeComponentRow(row.id)}
aria-label="Ta bort komponent"
disabled={componentRows.length === 1}
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
))}
<div className="flex items-center justify-between gap-3">
<Button
type="button"
variant="outline"
size="sm"
onClick={addComponentRow}
>
<Plus className="mr-1 h-4 w-4" /> Lägg till komponent
</Button>
<div className="text-xs tabular-nums text-muted-foreground">
Summa komponenter:{' '}
<span
className={
componentMismatch
? 'text-destructive font-medium'
: 'text-foreground'
}
>
{formatCurrency(totalComponentCost)}
</span>
</div>
</div>
{componentMismatch && (
<p className="text-xs text-destructive">
Komponenter summerar inte till anskaffningsvärdet (
{formatCurrency(parsedAcquisitionCost)}).
</p>
)}
</div>
)}
</div>
)}
<div className="rounded-md border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
<strong className="text-foreground">Tips:</strong> Anskaffningen måste redan vara
bokförd (debet på 1xxx-kontot mot t.ex. 1930/2440) — registret bokför inte
@@ -391,6 +391,10 @@ function buildPostItems(proposal: DispositionsProposal, ui: UiState): PostItem[]
additionalAmount: sel.overrideAmount ?? p.amount,
})
break
case 'uppskjuten_skatt':
// K3 only — server recomputes the amount; client just signals intent.
items.push({ kind: 'uppskjuten_skatt' })
break
}
}
if (Object.keys(ateforingReturns).length > 0) {
@@ -1,101 +1,211 @@
'use client'
import { useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { FileDown, Info } from 'lucide-react'
import { Skeleton } from '@/components/ui/skeleton'
import { AlertTriangle, FileDown, Info } from 'lucide-react'
import { formatCurrency } from '@/lib/utils'
import { calculateEgenavgifter, type EgenavgiftCategory } from '@/lib/bokslut/enskild-firma/egenavgifter-calculator'
import { calculateRantefordelning } from '@/lib/bokslut/enskild-firma/rantefordelning-calculator'
import { proposeEfPfondAvsattning } from '@/lib/bokslut/enskild-firma/periodiseringsfond-ef'
import { calculateExpansionsfondChange } from '@/lib/bokslut/enskild-firma/expansionsfond-calculator'
import type { EgenavgiftCategory } from '@/lib/bokslut/enskild-firma/egenavgifter-calculator'
import type { EfDeclarationItem } from '@/lib/bokslut/enskild-firma/types'
interface EfDeclarationSectionProps {
fiscalPeriodId: string
/** Bokfört resultat (income statement net_result) — used as the default
* surplus base for the calculators. */
/** Bokfört resultat (income statement net_result) — shown as the surplus
* base in the wizard header. Server recomputes from the trial balance. */
bookedSurplus: number
/** Closing year of the fiscal period (for periodiseringsfond cohort). */
fiscalYear: number
}
interface EfOverrideInputs {
category: EgenavgiftCategory
kapitalunderlag: string
priorSchablon: string
priorActual: string
pfondDesired: string
expansionsfondBalance: string
expansionsfondChange: string
}
interface EfPreviewResponse {
fiscalPeriod: {
id: string
name: string
period_start: string
period_end: string
}
bookedSurplus: number
items: EfDeclarationItem[]
postedEntryCount: number
inputWarnings: string[]
}
const DEFAULT_OVERRIDES: EfOverrideInputs = {
category: 'full',
kapitalunderlag: '',
priorSchablon: '',
priorActual: '',
pfondDesired: '',
expansionsfondBalance: '',
expansionsfondChange: '',
}
/**
* Read-only EF declaration computation. All values are skattemässiga
* justeringar that are filed in NE-bilaga / INK1 — never booked. The card
* runs calculators in the browser as the user adjusts inputs and shows the
* NE-bilaga ruta where each number lands.
* EF declaration step — fetches the four calculator outputs (egenavgifter,
* räntefördelning, periodiseringsfond-EF, expansionsfond) from the server
* so the same source-of-truth (computeEfDeclarationPreview) is used by
* wizard, MCP tool and NE-bilaga.
*
* EF tax mechanisms are declaration-only — they NEVER produce journal
* entries. The banner makes that BFL distinction visible.
*
* Override inputs persist to localStorage scoped by fiscal period id, so
* re-entering the wizard recalls them without round-tripping a write.
*/
export function EfDeclarationSection({
fiscalPeriodId,
bookedSurplus,
fiscalYear,
}: EfDeclarationSectionProps) {
const [category, setCategory] = useState<EgenavgiftCategory>('full')
const [priorSchablon, setPriorSchablon] = useState('')
const [priorActual, setPriorActual] = useState('')
const [kapitalunderlag, setKapitalunderlag] = useState('')
const [pfondDesired, setPfondDesired] = useState('')
const [expansionsfondBalance, setExpansionsfondBalance] = useState('')
const [expansionsfondChange, setExpansionsfondChange] = useState('')
const storageKey = `ef-declaration-overrides:${fiscalPeriodId}`
const items: EfDeclarationItem[] = useMemo(() => {
const list: EfDeclarationItem[] = []
const eg = calculateEgenavgifter({
surplusBeforeEgenavgifter: bookedSurplus,
category,
priorYearSchablonavdrag: parseFloat(priorSchablon) || 0,
priorYearActualCharged: parseFloat(priorActual) || 0,
})
list.push(eg)
const [overrides, setOverrides] = useState<EfOverrideInputs>(DEFAULT_OVERRIDES)
const [preview, setPreview] = useState<EfPreviewResponse | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const kap = parseFloat(kapitalunderlag) || 0
const r = calculateRantefordelning({ kapitalunderlag: kap })
if (r) list.push(r)
const surplusAfterEg = bookedSurplus - eg.amount
const pfond = proposeEfPfondAvsattning({
surplus: surplusAfterEg,
fiscalYear,
desiredAmount: pfondDesired === '' ? undefined : parseFloat(pfondDesired),
})
if (pfond) list.push(pfond)
const expChange = parseFloat(expansionsfondChange) || 0
if (expChange !== 0) {
const exp = calculateExpansionsfondChange({
kapitalunderlag: kap,
existingBalance: parseFloat(expansionsfondBalance) || 0,
desiredChange: expChange,
})
if (exp) list.push(exp)
// Restore overrides from localStorage on mount.
useEffect(() => {
if (typeof window === 'undefined') return
try {
const raw = window.localStorage.getItem(storageKey)
if (raw) {
const parsed = JSON.parse(raw) as Partial<EfOverrideInputs>
setOverrides({ ...DEFAULT_OVERRIDES, ...parsed })
}
} catch {
// Ignore — start with defaults.
}
return list
}, [
bookedSurplus,
category,
priorSchablon,
priorActual,
kapitalunderlag,
pfondDesired,
expansionsfondBalance,
expansionsfondChange,
fiscalYear,
])
}, [storageKey])
// Persist overrides on change.
useEffect(() => {
if (typeof window === 'undefined') return
try {
window.localStorage.setItem(storageKey, JSON.stringify(overrides))
} catch {
// Quota exceeded or disabled — non-fatal.
}
}, [storageKey, overrides])
const queryString = useMemo(() => {
const params = new URLSearchParams()
params.set('category', overrides.category)
const kap = parseFloat(overrides.kapitalunderlag)
if (Number.isFinite(kap)) params.set('kapitalunderlag', String(kap))
const ps = parseFloat(overrides.priorSchablon)
if (Number.isFinite(ps)) params.set('priorYearSchablonavdrag', String(ps))
const pa = parseFloat(overrides.priorActual)
if (Number.isFinite(pa)) params.set('priorYearActualCharged', String(pa))
const pf = parseFloat(overrides.pfondDesired)
if (Number.isFinite(pf)) params.set('pfondDesiredAmount', String(pf))
const eb = parseFloat(overrides.expansionsfondBalance)
if (Number.isFinite(eb)) params.set('expansionsfondExistingBalance', String(eb))
const ec = parseFloat(overrides.expansionsfondChange)
if (Number.isFinite(ec) && ec !== 0) params.set('expansionsfondDesiredChange', String(ec))
return params.toString()
}, [overrides])
const loadPreview = useCallback(async () => {
setLoading(true)
setError(null)
try {
const res = await fetch(
`/api/bookkeeping/fiscal-periods/${fiscalPeriodId}/ef-declaration?${queryString}`,
)
const body = await res.json()
if (!res.ok) {
setError(body?.error?.message ?? 'Kunde inte ladda EF-deklaration')
setPreview(null)
return
}
setPreview(body.data as EfPreviewResponse)
} catch {
setError('Kunde inte ladda EF-deklaration')
setPreview(null)
} finally {
setLoading(false)
}
}, [fiscalPeriodId, queryString])
// Debounce refetch so each keystroke doesn't slam the API. 350 ms feels
// responsive without being noisy.
useEffect(() => {
const handle = setTimeout(() => {
void loadPreview()
}, 350)
return () => clearTimeout(handle)
}, [loadPreview])
const update = useCallback(
<K extends keyof EfOverrideInputs>(field: K, value: EfOverrideInputs[K]) => {
setOverrides((prev) => ({ ...prev, [field]: value }))
},
[],
)
const items = preview?.items ?? []
const inputWarnings = preview?.inputWarnings ?? []
const noPostedEntries = preview ? preview.postedEntryCount === 0 : false
return (
<div className="space-y-6">
{/* BFL distinction banner — EF values are declaration-only, never booked. */}
<Card className="border-border bg-secondary/40">
<CardContent className="p-4 flex items-start gap-3">
<Info className="h-4 w-4 mt-0.5 text-muted-foreground shrink-0" />
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
Skattemässiga justeringar — NE-bilaga
</span>
<br />
För enskild firma bokförs varken skatt, egenavgifter, fonder eller räntefördelning.
Värdena nedan visar vad du fyller i på NE-bilagan när du deklarerar. Inga verifikat skapas.
</p>
</CardContent>
</Card>
{/* "No journal entries posted" banner — surfaced when the period has
zero posted vouchers, so the user knows the surplus is 0 because
nothing's booked yet, not because the calculators failed. */}
{noPostedEntries && (
<Card className="border-border">
<CardContent className="p-4 flex items-start gap-3">
<AlertTriangle className="h-4 w-4 mt-0.5 text-warning-foreground shrink-0" />
<p className="text-sm">
<span className="font-medium">Inga verifikat bokförda i perioden.</span>{' '}
Värdena nedan baseras enbart på NE-bilagans räkenskapsschema (intäkter och
kostnader hittills). Bokför löpande verifikat först för att få ett realistiskt
överskott.
</p>
</CardContent>
</Card>
)}
{/* Input form */}
<Card>
<CardHeader>
<CardTitle className="text-base">Skattemässiga justeringar — NE-bilaga</CardTitle>
<CardTitle className="text-base">Indata</CardTitle>
<p className="text-sm text-muted-foreground">
För enskild firma bokförs inte skatt, egenavgifter, fonder eller
räntefördelning. Beräkningarna nedan visar vad du fyller i på NE-bilagan
när du deklarerar.
Bokfört överskott:{' '}
<span className="tabular-nums font-medium text-foreground">
{formatCurrency(preview?.bookedSurplus ?? bookedSurplus)}
</span>
</p>
</CardHeader>
<CardContent className="space-y-4">
@@ -104,8 +214,8 @@ export function EfDeclarationSection({
<Label className="text-xs">Egenavgifter — kategori</Label>
<select
className="border border-border rounded-md h-9 text-sm px-2 w-full bg-background"
value={category}
onChange={(e) => setCategory(e.target.value as EgenavgiftCategory)}
value={overrides.category}
onChange={(e) => update('category', e.target.value as EgenavgiftCategory)}
>
<option value="full">Aktiv, full sats (28,97 %)</option>
<option value="pensioner">Pensionär (10,21 %)</option>
@@ -117,8 +227,8 @@ export function EfDeclarationSection({
<Input
type="number"
step="1"
value={kapitalunderlag}
onChange={(e) => setKapitalunderlag(e.target.value)}
value={overrides.kapitalunderlag}
onChange={(e) => update('kapitalunderlag', e.target.value)}
placeholder="0"
className="tabular-nums h-9"
/>
@@ -128,8 +238,8 @@ export function EfDeclarationSection({
<Input
type="number"
step="1"
value={priorSchablon}
onChange={(e) => setPriorSchablon(e.target.value)}
value={overrides.priorSchablon}
onChange={(e) => update('priorSchablon', e.target.value)}
placeholder="0"
className="tabular-nums h-9"
/>
@@ -139,8 +249,8 @@ export function EfDeclarationSection({
<Input
type="number"
step="1"
value={priorActual}
onChange={(e) => setPriorActual(e.target.value)}
value={overrides.priorActual}
onChange={(e) => update('priorActual', e.target.value)}
placeholder="0"
className="tabular-nums h-9"
/>
@@ -150,8 +260,8 @@ export function EfDeclarationSection({
<Input
type="number"
step="1"
value={pfondDesired}
onChange={(e) => setPfondDesired(e.target.value)}
value={overrides.pfondDesired}
onChange={(e) => update('pfondDesired', e.target.value)}
placeholder="0"
className="tabular-nums h-9"
/>
@@ -161,8 +271,8 @@ export function EfDeclarationSection({
<Input
type="number"
step="1"
value={expansionsfondBalance}
onChange={(e) => setExpansionsfondBalance(e.target.value)}
value={overrides.expansionsfondBalance}
onChange={(e) => update('expansionsfondBalance', e.target.value)}
placeholder="0"
className="tabular-nums h-9"
/>
@@ -174,8 +284,8 @@ export function EfDeclarationSection({
<Input
type="number"
step="1"
value={expansionsfondChange}
onChange={(e) => setExpansionsfondChange(e.target.value)}
value={overrides.expansionsfondChange}
onChange={(e) => update('expansionsfondChange', e.target.value)}
placeholder="0"
className="tabular-nums h-9"
/>
@@ -184,6 +294,32 @@ export function EfDeclarationSection({
</CardContent>
</Card>
{/* Top-level input warnings (e.g. missing kapitalunderlag) */}
{inputWarnings.map((w, i) => (
<Card key={i} className="border-border">
<CardContent className="p-4 flex items-start gap-3">
<AlertTriangle className="h-4 w-4 mt-0.5 text-warning-foreground shrink-0" />
<p className="text-sm">{w}</p>
</CardContent>
</Card>
))}
{/* Loading / error / items */}
{error && (
<Card>
<CardContent className="p-4 text-sm text-destructive">{error}</CardContent>
</Card>
)}
{loading && !preview && (
<Card>
<CardContent className="p-6 space-y-3">
<Skeleton className="h-6 w-1/3" />
<Skeleton className="h-20 w-full" />
</CardContent>
</Card>
)}
{items.map((item) => (
<Card key={item.kind}>
<CardHeader>
@@ -210,6 +346,7 @@ export function EfDeclarationSection({
</Card>
))}
{/* NE-bilaga download */}
<Card>
<CardHeader>
<CardTitle className="text-base flex items-center gap-2">
@@ -217,8 +354,8 @@ export function EfDeclarationSection({
NE-bilaga räkenskapsschema (R1–R11)
</CardTitle>
<p className="text-sm text-muted-foreground">
Räkenskapsschema-delen genereras automatiskt från bokföringen. Ladda ner
SRU-filen och ladda upp den i Skatteverkets e-tjänst för Inkomstdeklaration 1.
Räkenskapsschema-delen genereras automatiskt från bokföringen för räkenskapsåret {fiscalYear}.
Ladda ner SRU-filen och ladda upp den i Skatteverkets e-tjänst för Inkomstdeklaration 1.
</p>
</CardHeader>
<CardContent>
+196 -20
View File
@@ -1,16 +1,39 @@
'use client'
import { useMemo, useState } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { CheckCircle2 } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from '@/components/ui/table'
import { CheckCircle2, AlertTriangle } from 'lucide-react'
import Link from 'next/link'
import type { YearEndResult } from '@/types'
import type { YearEndResult, ContinuityDiscrepancy } from '@/types'
import { formatCurrency } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
interface ResultStepProps {
result: YearEndResult
}
const ORE_TOLERANCE = 0.005
export function ResultStep({ result }: ResultStepProps) {
const [acknowledged, setAcknowledged] = useState(false)
const continuity = result.continuity
const discrepancies = continuity?.discrepancies ?? []
// If the wizard reached ResultStep, executeYearEndClosing already enforced
// that no per-account diff exceeded ORE_TOLERANCE — but surface a panel
// grouped by BAS class so the user can confirm visually before leaving.
return (
<div className="space-y-6">
<Card>
@@ -32,40 +55,82 @@ export function ResultStep({ result }: ResultStepProps) {
<CardContent className="space-y-3 text-sm">
<ResultRow
label="Bokslutsverifikation"
value={`${result.closingEntry.voucher_series}${result.closingEntry.voucher_number}`}
value={formatVoucher(result.closingEntry)}
href={`/bookkeeping/${result.closingEntry.id}`}
/>
{result.revaluationEntry && (
<ResultRow
label="Kursrevaluering"
value={`${result.revaluationEntry.voucher_series}${result.revaluationEntry.voucher_number}`}
value={formatVoucher(result.revaluationEntry)}
href={`/bookkeeping/${result.revaluationEntry.id}`}
/>
)}
<ResultRow
label="Ingående balanser i ny period"
value={`${result.openingBalanceEntry.voucher_series}${result.openingBalanceEntry.voucher_number}`}
value={formatVoucher(result.openingBalanceEntry)}
href={`/bookkeeping/${result.openingBalanceEntry.id}`}
/>
<ResultRow label="Ny räkenskapsperiod" value={result.nextPeriod.name} />
</CardContent>
</Card>
<div className="flex flex-col sm:flex-row gap-3 sm:justify-end">
<Button variant="outline" asChild>
<Link href="/bookkeeping">Till bokföringen</Link>
</Button>
<Button variant="outline" asChild>
<Link href="/reports">Generera rapporter</Link>
</Button>
<Button asChild>
<Link
href={`/bookkeeping/year-end/arsredovisning?period=${result.closingEntry.fiscal_period_id}`}
>
Skapa årsredovisning
</Link>
</Button>
</div>
{continuity && (
<ContinuityPanel
discrepancies={discrepancies}
checkedAccounts={continuity.checked_accounts}
/>
)}
<Card>
<CardContent className="p-6 space-y-4">
<label className="flex items-start gap-3 cursor-pointer">
<Checkbox
checked={acknowledged}
onCheckedChange={(v) => setAcknowledged(v === true)}
className="mt-0.5"
aria-label="Bekräfta bokslut"
/>
<span className="text-sm leading-relaxed">
Jag har granskat bokslutet och IB/UB-kontinuiteten ovan, och
bekräftar att alla balanskonton stämmer mot föregående periods
utgående balans.
</span>
</label>
<div className="flex flex-col sm:flex-row gap-3 sm:justify-end">
<Button variant="outline" asChild disabled={!acknowledged}>
<Link
href="/bookkeeping"
aria-disabled={!acknowledged}
tabIndex={acknowledged ? undefined : -1}
className={!acknowledged ? 'pointer-events-none opacity-50' : ''}
>
Till bokföringen
</Link>
</Button>
<Button variant="outline" asChild disabled={!acknowledged}>
<Link
href="/reports"
aria-disabled={!acknowledged}
tabIndex={acknowledged ? undefined : -1}
className={!acknowledged ? 'pointer-events-none opacity-50' : ''}
>
Generera rapporter
</Link>
</Button>
<Button asChild disabled={!acknowledged}>
<Link
href={`/bookkeeping/year-end/arsredovisning?period=${result.closingEntry.fiscal_period_id}`}
aria-disabled={!acknowledged}
tabIndex={acknowledged ? undefined : -1}
className={!acknowledged ? 'pointer-events-none opacity-50' : ''}
>
Skapa årsredovisning
</Link>
</Button>
</div>
</CardContent>
</Card>
</div>
)
}
@@ -84,3 +149,114 @@ function ResultRow({ label, value, href }: { label: string; value: string; href?
</div>
)
}
interface ContinuityPanelProps {
discrepancies: ContinuityDiscrepancy[]
checkedAccounts: number
}
function ContinuityPanel({ discrepancies, checkedAccounts }: ContinuityPanelProps) {
const grouped = useMemo(() => {
const byClass = new Map<number, ContinuityDiscrepancy[]>()
for (const d of discrepancies) {
const klass = parseInt(d.account_number[0]) || 0
if (klass !== 1 && klass !== 2) continue
const list = byClass.get(klass) ?? []
list.push(d)
byClass.set(klass, list)
}
return byClass
}, [discrepancies])
const hasIssues = discrepancies.some(
(d) => Math.abs(d.difference) > ORE_TOLERANCE
)
return (
<Card>
<CardHeader className="flex flex-row items-center justify-between space-y-0">
<CardTitle className="text-base">IB/UB-avstämning</CardTitle>
{hasIssues ? (
<Badge variant="destructive" className="gap-1">
<AlertTriangle className="h-3 w-3" />
Avvikelser
</Badge>
) : (
<Badge variant="success" className="gap-1">
<CheckCircle2 className="h-3 w-3" />
Stämmer
</Badge>
)}
</CardHeader>
<CardContent className="space-y-4">
<p className="text-sm text-muted-foreground">
{checkedAccounts} balanskonto(n) jämförda mellan utgående balans i
stängd period och ingående balans i ny period.
</p>
{discrepancies.length === 0 ? (
<p className="text-sm">
Inga avvikelser. Alla balanskonton i klass 1 och 2 matchar inom
tolerans (±0,005 SEK).
</p>
) : (
<div className="space-y-6">
{[1, 2].map((klass) => {
const rows = grouped.get(klass) ?? []
if (rows.length === 0) return null
return (
<div key={klass}>
<h3 className="text-sm font-medium uppercase tracking-wider text-muted-foreground mb-2">
Klass {klass} – {klass === 1 ? 'Tillgångar' : 'Skulder & eget kapital'}
</h3>
<Table>
<TableHeader>
<TableRow>
<TableHead>Konto</TableHead>
<TableHead className="text-right">UB (föregående)</TableHead>
<TableHead className="text-right">IB (ny period)</TableHead>
<TableHead className="text-right">Diff</TableHead>
<TableHead className="text-right">Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{rows.map((d) => {
const overTol = Math.abs(d.difference) > ORE_TOLERANCE
return (
<TableRow key={d.account_number}>
<TableCell className="font-medium tabular-nums">
{d.account_number}
<span className="ml-2 font-normal text-muted-foreground">
{d.account_name}
</span>
</TableCell>
<TableCell className="text-right tabular-nums">
{formatCurrency(d.previous_ub_net)}
</TableCell>
<TableCell className="text-right tabular-nums">
{formatCurrency(d.current_ib_net)}
</TableCell>
<TableCell className="text-right tabular-nums">
{formatCurrency(d.difference)}
</TableCell>
<TableCell className="text-right">
{overTol ? (
<Badge variant="destructive">Avviker</Badge>
) : (
<Badge variant="success">OK</Badge>
)}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</div>
)
})}
</div>
)}
</CardContent>
</Card>
)
}