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>
)
}
@@ -1098,9 +1098,9 @@ function FiscalYearResult({ result, index }: { result: ImportResult; index: numb
{' · '}{d.skippedVouchers.total} hoppade över
</span>
)}
{result.replacedPriorImport && result.replacedPriorImport.cancelledEntries > 0 && (
{result.replacedPriorImport && result.replacedPriorImport.deletedEntries > 0 && (
<span>
{' · '}ersatte {result.replacedPriorImport.cancelledEntries.toLocaleString('sv-SE')} tidigare importerade verifikationer
{' · '}ersatte {result.replacedPriorImport.deletedEntries.toLocaleString('sv-SE')} tidigare importerade verifikationer
</span>
)}
</p>
@@ -1868,7 +1868,7 @@ export default function ArcimMigrationWorkspace(_props: WorkspaceComponentProps)
// Send every file to the engine. The Fortnox endpoint runs in
// replace-mode, so a year that already has a completed import
// gets its prior import marked 'replaced' (imported entries
// cancelled, user-created entries untouched) before the new
// deleted, user-created entries untouched) before the new
// SIE is loaded. The per-file result reports replacedPriorImport.
const filesToImport = sieData.rawContent.map((content, i) => ({
content,
@@ -24,6 +24,7 @@ import {
throwOnStructuredError,
} from '@/lib/hooks/use-submit-with-account-activation'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import type { BASAccount, FiscalPeriod, InvoiceExtractionResult } from '@/types'
interface InboxItem {
@@ -341,7 +342,7 @@ export default function BookDirectlyDialog({ open, onOpenChange, item, onSuccess
toast({
title: 'Bokfört',
description: voucher
? `Verifikation ${voucher.voucher_series}${voucher.voucher_number} skapad.`
? `Verifikation ${formatVoucher(voucher)} skapad.`
: 'Verifikation skapad.',
})
await onSuccess()
@@ -8,6 +8,7 @@ import { Badge } from '@/components/ui/badge'
import { AccountNumber } from '@/components/ui/account-number'
import { AlertCircle, ChevronDown, ChevronRight, Link2, Unlink, Play, Eye } from 'lucide-react'
import { formatCurrency, formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { CashAccountSelector } from '@/components/common/CashAccountSelector'
function formatAmount(amount: number): string {
@@ -411,7 +412,7 @@ export function BankReconciliationView() {
<td className="py-2 text-right font-mono">{formatAmount(m.transaction_amount)}</td>
<td className="py-2 text-center text-muted-foreground">&harr;</td>
<td className="py-2">
<span className="font-mono text-xs">{m.voucher_series}{m.voucher_number}</span>
<span className="font-mono text-xs">{formatVoucher(m)}</span>
<span className="ml-2 text-muted-foreground truncate">{m.entry_description}</span>
</td>
<td className="py-2 tabular-nums">{formatDate(m.entry_date)}</td>
@@ -478,7 +479,7 @@ export function BankReconciliationView() {
const lineAmount = line.debit_amount > 0 ? line.debit_amount : -line.credit_amount
return (
<option key={line.line_id} value={line.journal_entry_id}>
{line.voucher_series}{line.voucher_number} | {formatDate(line.entry_date)} | {formatCurrency(lineAmount)} | {line.entry_description}
{formatVoucher(line)} | {formatDate(line.entry_date)} | {formatCurrency(lineAmount)} | {line.entry_description}
</option>
)
})}
@@ -528,7 +529,7 @@ export function BankReconciliationView() {
return (
<tr key={line.line_id} className="border-b last:border-0">
<td className="py-2 font-mono text-xs">
{line.voucher_series}{line.voucher_number}
{formatVoucher(line)}
</td>
<td className="py-2 tabular-nums">{formatDate(line.entry_date)}</td>
<td className="py-2 truncate max-w-[300px]">
+307
View File
@@ -0,0 +1,307 @@
'use client'
import React, { useState, useCallback, useMemo } from 'react'
import Link from 'next/link'
import { ChevronDown, ChevronRight, AlertCircle } from 'lucide-react'
import { Skeleton } from '@/components/ui/skeleton'
import { formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import {
createSourceLoader,
type ReportSourceLine,
type ReportSourceFetcher,
} from '@/lib/reports/source-lines'
interface ReportRowExpansionProps {
/** Lazy fetcher invoked the first time the row is expanded. */
fetcher: ReportSourceFetcher
/** Column span used by the inline expansion `<tr>`. */
colSpan: number
/** Stable id used as the toggle's aria-controls reference. */
rowId: string
}
interface UseSourceLinesResult {
lines: ReportSourceLine[] | null
loading: boolean
error: string | null
load: () => Promise<void>
}
/**
* Hook owning the lazy fetch + caching of source lines. Thin wrapper on top
* of `createSourceLoader` from `lib/reports/source-lines` so the loading
* semantics can be unit-tested in node without DOM.
*
* The cache lives per-instance — reopening the same row never refetches.
*/
export function useSourceLines(fetcher: ReportSourceFetcher): UseSourceLinesResult {
const [lines, setLines] = useState<ReportSourceLine[] | null>(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
// The loader is stable for the lifetime of the fetcher reference; callers
// are expected to memoise their fetcher with `useMemo` (every callsite in
// `reports/page.tsx` does).
const loader = useMemo(
() =>
createSourceLoader(fetcher, (s) => {
setLines(s.lines)
setLoading(s.loading)
setError(s.error)
}),
[fetcher]
)
const load = useCallback(() => loader.load(), [loader])
return { lines, loading, error, load }
}
/**
* Drilldown affordance for aggregated report rows.
*
* Renders two cells (the chevron-toggle is placed in the calling row; the
* expansion itself is rendered as a sibling `<tr>` only when expanded).
* The caller is responsible for placing `<ReportRowExpansion.Toggle>` inside
* the aggregated row and `<ReportRowExpansion.Panel>` immediately below.
*
* Usage:
* const expansion = useReportRowExpansion(fetcher)
* <tr><td><expansion.Toggle /></td>...</tr>
* {expansion.expanded && <expansion.Panel colSpan={6} />}
*
* Or use the all-in-one component below where the caller owns the
* surrounding `<tr>` and just plugs the expansion in.
*/
export function ReportRowExpansion({
fetcher,
colSpan,
rowId,
}: ReportRowExpansionProps) {
const [expanded, setExpanded] = useState(false)
const { lines, loading, error, load } = useSourceLines(fetcher)
const toggle = useCallback(() => {
const next = !expanded
setExpanded(next)
if (next) load()
}, [expanded, load])
return (
<>
<td className="py-2 w-8">
<button
type="button"
onClick={toggle}
aria-expanded={expanded}
aria-controls={`expansion-${rowId}`}
aria-label={expanded ? 'Dölj verifikat' : 'Visa verifikat'}
className="inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors"
>
{expanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</button>
</td>
{expanded && (
<ExpansionPanel
colSpan={colSpan}
loading={loading}
error={error}
lines={lines}
rowId={rowId}
/>
)}
</>
)
}
/**
* Variant where the toggle and the expansion are placed by the caller. The
* caller renders `<Toggle />` inside the aggregated `<tr>`, then below
* conditionally renders `<Panel />` as a sibling `<tr>` so its `<td
* colSpan={n}>` lines up with the rest of the table.
*/
export function useReportRowExpansion(fetcher: ReportSourceFetcher, rowId: string) {
const [expanded, setExpanded] = useState(false)
const { lines, loading, error, load } = useSourceLines(fetcher)
const toggle = useCallback(() => {
const next = !expanded
setExpanded(next)
if (next) load()
}, [expanded, load])
const Toggle = () => (
<button
type="button"
onClick={toggle}
aria-expanded={expanded}
aria-controls={`expansion-${rowId}`}
aria-label={expanded ? 'Dölj verifikat' : 'Visa verifikat'}
className="inline-flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:text-foreground hover:bg-muted/60 transition-colors"
>
{expanded ? (
<ChevronDown className="h-4 w-4" />
) : (
<ChevronRight className="h-4 w-4" />
)}
</button>
)
const Panel = ({ colSpan }: { colSpan: number }) =>
expanded ? (
<ExpansionPanelRow
colSpan={colSpan}
loading={loading}
error={error}
lines={lines}
rowId={rowId}
/>
) : null
return { expanded, Toggle, Panel }
}
/**
* Body of the expansion when the wrapping `<td>` colSpan is provided —
* renders inline (used by ReportRowExpansion).
*/
function ExpansionPanel({
colSpan,
loading,
error,
lines,
rowId,
}: {
colSpan: number
loading: boolean
error: string | null
lines: ReportSourceLine[] | null
rowId: string
}) {
return (
<td colSpan={colSpan} id={`expansion-${rowId}`} className="bg-muted/20 p-0">
<ExpansionContent loading={loading} error={error} lines={lines} />
</td>
)
}
/**
* Body of the expansion when used in a sibling `<tr>` (used by
* `useReportRowExpansion`'s Panel).
*/
function ExpansionPanelRow({
colSpan,
loading,
error,
lines,
rowId,
}: {
colSpan: number
loading: boolean
error: string | null
lines: ReportSourceLine[] | null
rowId: string
}) {
return (
<tr className="bg-muted/20">
<td colSpan={colSpan} id={`expansion-${rowId}`} className="p-0">
<ExpansionContent loading={loading} error={error} lines={lines} />
</td>
</tr>
)
}
function ExpansionContent({
loading,
error,
lines,
}: {
loading: boolean
error: string | null
lines: ReportSourceLine[] | null
}) {
if (loading) {
return (
<div className="px-4 py-3 space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-5/6" />
<Skeleton className="h-4 w-2/3" />
</div>
)
}
if (error) {
return (
<div className="px-4 py-3 flex items-center gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4" />
{error}
</div>
)
}
if (!lines || lines.length === 0) {
return (
<div className="px-4 py-3 text-sm text-muted-foreground">
Inga underliggande verifikat.
</div>
)
}
return (
<div className="px-4 py-2">
<table className="w-full text-xs">
<thead className="[&_th]:font-medium [&_th]:text-[10px] [&_th]:uppercase [&_th]:tracking-wider [&_th]:text-muted-foreground">
<tr className="text-left">
<th className="py-1 w-24">Verifikat</th>
<th className="py-1 w-24">Datum</th>
<th className="py-1">Beskrivning</th>
<th className="py-1 w-24 text-right">Debet</th>
<th className="py-1 w-24 text-right">Kredit</th>
</tr>
</thead>
<tbody>
{lines.map((line) => (
<tr key={`${line.voucher_series}-${line.voucher_number}-${line.journal_entry_id}`} className="border-t border-border/40">
<td className="py-1.5">
{line.journal_entry_id ? (
<Link
href={`/bookkeeping/${line.journal_entry_id}`}
className="font-mono text-foreground hover:underline underline-offset-4"
>
{formatVoucher(line)}
</Link>
) : (
<span className="font-mono text-muted-foreground">—</span>
)}
</td>
<td className="py-1.5 tabular-nums text-muted-foreground">
{line.date ? formatDate(line.date) : ''}
</td>
<td className="py-1.5 truncate max-w-md" title={line.description}>
{line.description}
</td>
<td className="py-1.5 text-right tabular-nums">
{line.debit > 0 ? formatAmount(line.debit) : ''}
</td>
<td className="py-1.5 text-right tabular-nums">
{line.credit > 0 ? formatAmount(line.credit) : ''}
</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
function formatAmount(amount: number): string {
return amount.toLocaleString('sv-SE', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
}
+2
View File
@@ -38,6 +38,8 @@ const CATEGORIES: ReportCategory[] = [
items: [
{ value: 'income-statement', labelKey: 'name_income_statement' },
{ value: 'balance-sheet', labelKey: 'name_balance_sheet' },
{ value: 'kassaflodesanalys', labelKey: 'name_kassaflodesanalys' },
{ value: 'arsredovisning', labelKey: 'name_arsredovisning', entityType: 'aktiebolag' },
],
},
{
@@ -0,0 +1,179 @@
'use client'
import { useState } from 'react'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { useToast } from '@/components/ui/use-toast'
import type { AccountingFramework } from '@/types'
import { Loader2 } from 'lucide-react'
interface AccountingFrameworkFormProps {
/** Current framework on the company row. */
current: AccountingFramework
/** Bubble up after a successful save so parent state can refresh. */
onSaved?: (next: AccountingFramework) => void
}
/**
* K2/K3 selector for AB. Lives on the bookkeeping settings page. Renders nothing
* for non-AB entities — the parent gates this component by entity_type.
*
* UX rules (regulatory area — kept in Swedish):
* - Default is K2 (matches the column default and BFNAR 2016:10 baseline).
* - Switching K2 → K3 fires a confirmation dialog. The recommendation per
* BFN is that the choice is permanent for the company once made; we
* surface that as a warning, not a block, so the user can still revert.
* - The save is its own request (PATCH /api/company/current) — separate
* from /api/settings because the column lives on companies, not on
* company_settings.
*/
export function AccountingFrameworkForm({ current, onSaved }: AccountingFrameworkFormProps) {
const { toast } = useToast()
const [selected, setSelected] = useState<AccountingFramework>(current)
const [pending, setPending] = useState<AccountingFramework | null>(null)
const [saving, setSaving] = useState(false)
async function persist(next: AccountingFramework) {
setSaving(true)
try {
const res = await fetch('/api/company/current', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ accounting_framework: next }),
})
const body = await res.json()
if (!res.ok) {
toast({
title: 'Kunde inte spara',
description: body?.error ?? 'Försök igen.',
variant: 'destructive',
})
setSelected(current)
return
}
toast({
title: 'Sparat',
description:
next === 'k3'
? 'Bolaget redovisar nu enligt K3 (BFNAR 2012:1).'
: 'Bolaget redovisar nu enligt K2 (BFNAR 2016:10).',
})
onSaved?.(next)
} catch {
toast({
title: 'Kunde inte spara',
description: 'Försök igen.',
variant: 'destructive',
})
setSelected(current)
} finally {
setSaving(false)
setPending(null)
}
}
function handleChange(next: string) {
const value = next as AccountingFramework
if (value === selected) return
// K2 → K3 is the consequential direction: confirm before persisting.
if (selected === 'k2' && value === 'k3') {
setPending(value)
return
}
setSelected(value)
void persist(value)
}
return (
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Redovisningsregelverk
</h2>
<div className="space-y-2">
<Label htmlFor="accounting_framework">Regelverk</Label>
<Select
value={selected}
onValueChange={handleChange}
disabled={saving}
>
<SelectTrigger id="accounting_framework" className="w-full max-w-sm">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="k2">K2 (BFNAR 2016:10) — mindre företag</SelectItem>
<SelectItem value="k3">K3 (BFNAR 2012:1) — större företag</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
K2 är standard för mindre bolag och innebär förenklade regler. K3 krävs när
bolaget når två av tre tröskelvärden (nettoomsättning &gt; 80 MSEK, tillgångar
&gt; 40 MSEK, eller fler än 50 anställda). K3 ställer högre krav: kassaflödesanalys,
komponentavskrivning på materiella anläggningstillgångar och redovisning av
uppskjuten skatt på obeskattade reserver (79,4 % eget kapital / 20,6 % skuld).
</p>
</div>
<Dialog
open={pending !== null}
onOpenChange={(open) => {
if (!open) setPending(null)
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Byta till K3?</DialogTitle>
<DialogDescription className="space-y-2 pt-2">
<span className="block">
K3 medför löpande att kassaflödesanalys upprättas, komponentavskrivning
används och uppskjuten skatt redovisas separat (konto 2240 / 8940).
</span>
<span className="block">
Bytet är permanent enligt rekommendation. Fortsätt?
</span>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
variant="outline"
onClick={() => setPending(null)}
disabled={saving}
>
Avbryt
</Button>
<Button
onClick={() => {
if (!pending) return
setSelected(pending)
void persist(pending)
}}
disabled={saving}
>
{saving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" /> Sparar…
</>
) : (
'Byt till K3'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</section>
)
}
+123 -1
View File
@@ -2,6 +2,7 @@
import { useTranslations } from 'next-intl'
import { useState, useCallback } from 'react'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
@@ -18,6 +19,15 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
const { toast } = useToast()
const [lateFeeText, setLateFeeText] = useState(settings.invoice_late_fee_text || '')
const [creditTermsText, setCreditTermsText] = useState(settings.invoice_credit_terms_text || '')
const [reminderFeeAmount, setReminderFeeAmount] = useState(
String(settings.reminder_fee_amount ?? 60),
)
// Display override as a percentage (the DB stores a decimal). Empty = no override.
const [interestRatePercent, setInterestRatePercent] = useState(
settings.reminder_interest_rate_override != null
? String(settings.reminder_interest_rate_override * 100)
: '',
)
const saveToggle = useCallback(async (field: string, value: boolean) => {
try {
@@ -61,6 +71,62 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
}
}, [onUpdate, toast, t])
const saveReminderFeeAmount = useCallback(async (raw: string) => {
const parsed = parseFloat(raw.replace(',', '.'))
if (Number.isNaN(parsed) || parsed < 0) {
toast({ title: 'Ogiltigt belopp', variant: 'destructive' })
return
}
// Lag 1981:739: maxgräns 60 kr för lagstadgad påminnelseavgift.
const clamped = Math.min(parsed, 60)
try {
const response = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reminder_fee_amount: clamped }),
})
if (!response.ok) throw new Error()
onUpdate({ reminder_fee_amount: clamped })
setReminderFeeAmount(String(clamped))
} catch {
toast({ title: t('toast_save_failed'), variant: 'destructive' })
}
}, [onUpdate, toast, t])
const saveInterestOverride = useCallback(async (raw: string) => {
if (raw.trim() === '') {
try {
const response = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reminder_interest_rate_override: null }),
})
if (!response.ok) throw new Error()
onUpdate({ reminder_interest_rate_override: null })
} catch {
toast({ title: t('toast_save_failed'), variant: 'destructive' })
}
return
}
const percent = parseFloat(raw.replace(',', '.'))
if (Number.isNaN(percent) || percent < 0 || percent >= 100) {
toast({ title: 'Ogiltig räntesats (0–99%)', variant: 'destructive' })
return
}
const decimal = Math.round((percent / 100) * 10_000) / 10_000
try {
const response = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ reminder_interest_rate_override: decimal }),
})
if (!response.ok) throw new Error()
onUpdate({ reminder_interest_rate_override: decimal })
} catch {
toast({ title: t('toast_save_failed'), variant: 'destructive' })
}
}, [onUpdate, toast, t])
return (
<section className="space-y-6">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
@@ -118,7 +184,7 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
<p className="text-xs text-muted-foreground">{t('show_swish_help')}</p>
</div>
<Switch
checked={settings.invoice_show_swish ?? true}
checked={settings.invoice_show_swish ?? false}
onCheckedChange={(v) => saveToggle('invoice_show_swish', v)}
/>
</div>
@@ -221,6 +287,62 @@ export function PdfPrintSettings({ settings, onUpdate }: PdfPrintSettingsProps)
onCheckedChange={(v) => saveToggle('send_invoice_reminders', v)}
/>
</div>
<div className="flex items-center justify-between">
<div>
<Label>Aktivera påminnelseavgift</Label>
<p className="text-xs text-muted-foreground">
Debitera lagstadgad påminnelseavgift (Lag 1981:739, max 60 kr) på varje påminnelse.
Avgiften bokförs automatiskt (1510 / 3990) och adderas till kundens fordran.
</p>
</div>
<Switch
checked={settings.reminder_fee_enabled ?? true}
onCheckedChange={(v) => saveToggle('reminder_fee_enabled', v)}
/>
</div>
{(settings.reminder_fee_enabled ?? true) && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pl-0">
<div className="space-y-2">
<Label htmlFor="reminder_fee_amount">Påminnelseavgift (kr)</Label>
<Input
id="reminder_fee_amount"
type="number"
min={0}
max={60}
step={1}
value={reminderFeeAmount}
onChange={(e) => setReminderFeeAmount(e.target.value)}
onBlur={() => saveReminderFeeAmount(reminderFeeAmount)}
/>
<p className="text-xs text-muted-foreground">
Standardvärde 60 kr. Maxgräns enligt Lag 1981:739.
</p>
</div>
</div>
)}
<div className="space-y-2">
<Label htmlFor="reminder_interest_rate_override">
Räntesats för dröjsmålsränta (% per år)
</Label>
<Input
id="reminder_interest_rate_override"
type="number"
min={0}
max={99}
step={0.1}
placeholder="Lämna tom för Räntelagen §6 (referensränta + 8 procentenheter)"
value={interestRatePercent}
onChange={(e) => setInterestRatePercent(e.target.value)}
onBlur={() => saveInterestOverride(interestRatePercent)}
/>
<p className="text-xs text-muted-foreground">
Om tom används lagstadgad dröjsmålsränta (Räntelagen §6 = Riksbankens
referensränta + 8 procentenheter). Räntan visas i påminnelsen men bokförs inte.
</p>
</div>
</div>
</section>
)
@@ -0,0 +1,108 @@
'use client'
import { useCallback, useSyncExternalStore } from 'react'
import Link from 'next/link'
import { ExternalLink } from 'lucide-react'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
/**
* Per-user toggle for the periodisering wizard's auto-detection step.
*
* Backed by localStorage (key: `periodisering_autodetect_enabled`) because
* the company_settings table does not yet have a dedicated column for this
* preference, and the task description explicitly allows the persistence to
* be UI-local. A future migration can promote this to a real
* `company_settings.periodisering_autodetect_enabled boolean` column and
* the wizard's auto-detect step will read either source.
*
* Default: enabled. The wizard's auto-detect step renders regardless — the
* toggle merely controls whether the GET response includes `autoDetected`
* on subsequent fetches. (Today the API always returns it; the wizard step
* can early-out based on this setting locally.)
*/
const STORAGE_KEY = 'periodisering_autodetect_enabled'
function readStored(): boolean {
if (typeof window === 'undefined') return true
try {
const stored = window.localStorage.getItem(STORAGE_KEY)
return stored === null ? true : stored !== 'false'
} catch {
return true
}
}
/** Subscribe to localStorage changes from OTHER tabs. Same-tab updates are
* picked up via the explicit re-render after `setItem` — see
* `notifyChange` below. */
function subscribe(callback: () => void): () => void {
if (typeof window === 'undefined') return () => {}
const handler = (e: StorageEvent) => {
if (e.key === STORAGE_KEY || e.key === null) callback()
}
const customHandler = () => callback()
window.addEventListener('storage', handler)
window.addEventListener('gnubok-periodisering-toggle', customHandler)
return () => {
window.removeEventListener('storage', handler)
window.removeEventListener('gnubok-periodisering-toggle', customHandler)
}
}
/** Fire a same-tab notification so useSyncExternalStore re-subscribers
* see the change without a manual setState. */
function notifyChange() {
if (typeof window === 'undefined') return
window.dispatchEvent(new Event('gnubok-periodisering-toggle'))
}
export function PeriodiseringAutoDetectToggle() {
const enabled = useSyncExternalStore(
subscribe,
readStored,
// Server snapshot: default to enabled. Matches the client default so
// hydration is identical.
() => true,
)
const handleChange = useCallback((value: boolean) => {
try {
window.localStorage.setItem(STORAGE_KEY, String(value))
} catch {
// No-op; if storage is blocked the toggle simply won't persist.
}
notifyChange()
}, [])
return (
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Periodisering
</h2>
<div className="flex items-start justify-between gap-4">
<div className="space-y-1">
<Label htmlFor="periodisering-autodetect" className="text-sm">
Aktivera automatisk periodiseringsdetektering
</Label>
<p className="text-xs text-muted-foreground max-w-md">
Skannar fakturor i bokslutet efter datumintervall som sträcker sig
in i nästa räkenskapsår och föreslår periodiseringar i bokslut-wizarden.
</p>
</div>
<Switch
id="periodisering-autodetect"
checked={enabled}
onCheckedChange={handleChange}
/>
</div>
<Link
href="/bookkeeping/year-end/periodisering"
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ExternalLink className="h-3.5 w-3.5" />
Öppna periodiserings-wizarden
</Link>
</section>
)
}
+17
View File
@@ -88,6 +88,15 @@ export function SecuritySettings() {
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string }
// Supabase rejects updateUser({password}) with this exact message when
// the user has a TOTP factor enrolled but is at AAL1. Send them through
// /mfa/verify to step up; on return they land back here and can retry.
if (body.error?.includes('AAL2')) {
router.push(
`/mfa/verify?returnTo=${encodeURIComponent('/settings/account')}`,
)
return
}
toast({
title: t('toast_update_failed_title'),
description: body.error || t('toast_update_failed_description'),
@@ -122,6 +131,14 @@ export function SecuritySettings() {
const { error } = await supabase.auth.mfa.unenroll({ factorId: mfaFactorId })
if (error) {
// mfa.unenroll requires AAL2 — for BankID-linked users at AAL1 (the
// shouldEnforceMfa skip path), this is the only way to step up.
if (error.message?.includes('AAL2')) {
router.push(
`/mfa/verify?returnTo=${encodeURIComponent('/settings/account')}`,
)
return
}
toast({
title: t('toast_unenroll_failed_title'),
description: error.message,
+1
View File
@@ -35,6 +35,7 @@ export function SettingsNav({ isSandbox }: { isSandbox?: boolean }) {
{ href: '/settings/skatteverket', label: t('skatteverket'), show: hasCompany && !isSandbox && hasSkatteverketExtension },
{ href: '/settings/salary', label: t('salary'), show: hasCompany && company?.entity_type === 'aktiebolag' },
{ href: '/settings/templates', label: t('templates'), show: hasCompany },
{ href: '/settings/approval-rules', label: t('approval_rules'), show: hasCompany },
{ href: '/settings/account', label: t('account'), show: true },
{ href: '/settings/api', label: t('api'), show: hasCompany && hasMcpExtension },
].filter(item => item.show)
@@ -0,0 +1,168 @@
'use client'
import { useState } from 'react'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { useToast } from '@/components/ui/use-toast'
import { Loader2 } from 'lucide-react'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import type { CompanySettings, JournalEntrySourceType } from '@/types'
const SERIES_OPTIONS = 'ABCDEFG'.split('')
// Subset of source_types presented to the user. The DB column accepts every
// JournalEntrySourceType, but several values (storno, correction, etc.) are
// derived from the original entry's series and would surprise the user if
// surfaced as configurable. We expose only the user-relevant subset; the
// engine still falls back to 'A' for the keys we hide.
const VISIBLE_SOURCE_TYPES: Array<{ key: JournalEntrySourceType; labelKey: string }> = [
{ key: 'manual', labelKey: 'manual' },
{ key: 'invoice_created', labelKey: 'invoice_created' },
{ key: 'invoice_paid', labelKey: 'invoice_paid' },
{ key: 'supplier_invoice_registered', labelKey: 'supplier_invoice_registered' },
{ key: 'supplier_invoice_paid', labelKey: 'supplier_invoice_paid' },
{ key: 'salary_payment', labelKey: 'salary_payment' },
{ key: 'bank_transaction', labelKey: 'bank_transaction' },
{ key: 'reminder_fee', labelKey: 'reminder_fee' },
{ key: 'opening_balance', labelKey: 'opening_balance' },
{ key: 'year_end', labelKey: 'year_end' },
]
// Swedish labels. Kept inline so this component is self-contained — these
// labels are bookkeeping-domain terms that intentionally stay Swedish across
// locales (see CLAUDE.md i18n table).
const SV_LABELS: Record<string, string> = {
manual: 'Manuella verifikat',
invoice_created: 'Kundfakturor (skapande)',
invoice_paid: 'Kundfakturor (betalning)',
supplier_invoice_registered: 'Leverantörsfakturor (registrering)',
supplier_invoice_paid: 'Leverantörsfakturor (betalning)',
salary_payment: 'Lön',
bank_transaction: 'Banktransaktioner',
reminder_fee: 'Påminnelseavgifter',
opening_balance: 'Ingående balanser',
year_end: 'Bokslut',
}
interface Props {
settings: CompanySettings
onSettingsUpdated: (settings: Partial<CompanySettings>) => void
}
export function VoucherSeriesPerSourceTypeForm({ settings, onSettingsUpdated }: Props) {
const { toast } = useToast()
const initialMap = settings.default_voucher_series_per_source_type || {}
const [draft, setDraft] = useState<Partial<Record<JournalEntrySourceType, string>>>(
initialMap as Partial<Record<JournalEntrySourceType, string>>,
)
const [isSaving, setIsSaving] = useState(false)
const handleChange = (sourceType: JournalEntrySourceType, value: string) => {
setDraft((prev) => ({ ...prev, [sourceType]: value }))
}
const hasChanges =
JSON.stringify(draft) !== JSON.stringify(initialMap)
const handleSave = async () => {
setIsSaving(true)
try {
const res = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
default_voucher_series_per_source_type: draft,
}),
})
const json = await res.json()
if (!res.ok) {
toast({
title: 'Kunde inte spara',
description: getErrorMessage(json, { context: 'settings', statusCode: res.status }),
variant: 'destructive',
})
return
}
onSettingsUpdated({
default_voucher_series_per_source_type: draft as Record<JournalEntrySourceType, string>,
})
toast({
title: 'Verifikationsserier sparade',
description: 'Nya verifikat använder de uppdaterade serierna.',
})
} catch (err) {
toast({
title: 'Kunde inte spara',
description: getErrorMessage(err, { context: 'settings' }),
variant: 'destructive',
})
} finally {
setIsSaving(false)
}
}
return (
<section className="space-y-4">
<div className="space-y-1">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
Verifikationsserier per typ
</h2>
<p className="text-xs text-muted-foreground">
Tilldela en standardserie per typ av verifikat. Vanlig svensk
praxis: leverantörsfakturor på serie B, löner på serie C, övrigt på
serie A. Kan alltid ändras per verifikat när du bokför.
</p>
</div>
<div className="grid gap-3 sm:grid-cols-2">
{VISIBLE_SOURCE_TYPES.map(({ key, labelKey }) => (
<div key={key} className="flex items-center justify-between gap-3">
<Label
htmlFor={`series-${key}`}
className="text-sm text-foreground flex-1 cursor-pointer"
>
{SV_LABELS[labelKey] ?? key}
</Label>
<Select
value={(draft[key] as string | undefined) || 'A'}
onValueChange={(v) => handleChange(key, v)}
>
<SelectTrigger
id={`series-${key}`}
className="w-16 font-mono"
aria-label={SV_LABELS[labelKey] ?? key}
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{SERIES_OPTIONS.map((letter) => (
<SelectItem key={letter} value={letter} className="font-mono">
{letter}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
))}
</div>
<div className="flex justify-end pt-2">
<Button
type="button"
onClick={handleSave}
disabled={!hasChanges || isSaving}
>
{isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Spara serier
</Button>
</div>
</section>
)
}
@@ -22,6 +22,7 @@ import {
} from '@/components/ui/table'
import { useToast } from '@/components/ui/use-toast'
import { formatCurrency } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import type { StoredSkattekontoTransaction } from '@/types/skatteverket'
interface MatchCandidate {
@@ -177,9 +178,7 @@ export function SkattekontoMatchDialog({
<TableRow key={c.journal_entry_id}>
<TableCell className="tabular-nums">{c.entry_date}</TableCell>
<TableCell className="tabular-nums">
{c.voucher_series && c.voucher_number
? `${c.voucher_series}${c.voucher_number}`
: '–'}
{formatVoucher(c)}
</TableCell>
<TableCell className="max-w-[260px] truncate">
{c.description}
@@ -11,6 +11,7 @@ import {
DataListMetaSeparator,
} from '@/components/ui/data-list'
import { cn, formatCurrency, formatDate } from '@/lib/utils'
import { formatVoucher } from '@/lib/bookkeeping/voucher-series-resolver'
import { AlertCircle, ArrowUpRight, ArrowDownRight, Landmark, Link2, Loader2 } from 'lucide-react'
import type {
SkattekontoMatchSuggestion,
@@ -46,7 +47,10 @@ export default function SkattekontoInboxCard({
const duplicateLabel =
matchSuggestion?.voucher_series && matchSuggestion?.voucher_number
? t('duplicate_title_with_voucher', {
label: `${matchSuggestion.voucher_series}${matchSuggestion.voucher_number}`,
label: formatVoucher({
voucher_series: matchSuggestion.voucher_series,
voucher_number: matchSuggestion.voucher_number,
}),
})
: t('duplicate_title_draft')