feat: delete last voucher, notes field, schema cache fix (#230)

* feat: delete last voucher, notes field, schema cache fix

Address three customer feedback items from William (wigu.se):

1. Delete last voucher per series (Fortnox model):
   - New `delete_last_voucher` RPC with full safety checks (last-in-series,
     open period, no references, owner/admin only)
   - Session variable bypass for immutability/retention/line triggers
   - Full JSONB audit trail (BFNAR 2013:2 behandlingshistorik)
   - DELETE endpoint + UI with confirmation dialogs
   - Storno restoration when deleting a reversal entry

2. Notes/comment field on vouchers:
   - `notes` column on journal_entries (always-editable internal metadata)
   - Immutability trigger updated to allow notes-only updates on posted entries
   - PATCH endpoint, inline-edit UI on detail page, form textarea

3. Schema cache fix:
   - NOTIFY pgrst applied to production (immediate fix)
   - Retroactive migration + CLAUDE.md migration rule added

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

* fix: address Greptile review — tighten trigger, lock voucher sequence

P1: The notes-only exception in enforce_journal_entry_immutability was
too broad — it only checked 7 verifikation fields, allowing silent
mutation of correction_of_id, reverses_id, reversed_by_id, committed_at,
and user_id on posted entries. Now guards all metadata fields; only
notes and updated_at may differ.

P2: Lock voucher_sequences row FOR UPDATE before the MAX(voucher_number)
check in delete_last_voucher to serialise against concurrent
commit_journal_entry calls, preventing voucher number gaps.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-04-13 16:12:03 +02:00
committed by GitHub
parent ade4ad5971
commit 7bf7565852
21 changed files with 713 additions and 28 deletions
+1
View File
@@ -408,6 +408,7 @@ export async function POST(request: Request) {
5. **Never modify existing migrations** — create new ones
6. **Never modify enforcement triggers** (migration 017) — legally required
7. **Apply via Supabase MCP tool**: `mcp__plugin_supabase_supabase__apply_migration`
8. **Always include `NOTIFY pgrst, 'reload schema'`** at the end of migrations that alter table structure (ADD/DROP COLUMN, CREATE TABLE, ALTER TYPE). Without this, PostgREST serves stale schema until next reload.
---
+165 -13
View File
@@ -1,27 +1,39 @@
'use client'
import { useState, useEffect, useCallback, use } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { AccountNumber } from '@/components/ui/account-number'
import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock } from 'lucide-react'
import { Textarea } from '@/components/ui/textarea'
import { Loader2, ArrowLeft, Paperclip, AlertTriangle, Lock, MessageSquare, Pencil, Check, X } from 'lucide-react'
import { useCanWrite } from '@/lib/hooks/use-can-write'
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
import JournalEntryStatusBadge, { sourceTypeLabels } from '@/components/bookkeeping/JournalEntryStatusBadge'
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
import CorrectionChain from '@/components/bookkeeping/CorrectionChain'
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
import { useToast } from '@/components/ui/use-toast'
import type { JournalEntry, JournalEntryLine } from '@/types'
export default function JournalEntryDetailPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params)
const router = useRouter()
const { canWrite } = useCanWrite()
const { toast } = useToast()
const [entry, setEntry] = useState<JournalEntry | null>(null)
const [chain, setChain] = useState<JournalEntry[]>([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [showCorrection, setShowCorrection] = useState(false)
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [isLastInSeries, setIsLastInSeries] = useState(false)
const [attachmentCount, setAttachmentCount] = useState(0)
const [editingNotes, setEditingNotes] = useState(false)
const [notesValue, setNotesValue] = useState('')
const [savingNotes, setSavingNotes] = useState(false)
const fetchData = useCallback(async () => {
setIsLoading(true)
@@ -36,6 +48,7 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
const { data } = await res.json()
setEntry(data.entry)
setChain(data.chain)
setIsLastInSeries(data.is_last_in_series ?? false)
} catch {
setError('Kunde inte hämta verifikation')
} finally {
@@ -43,6 +56,50 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
}
}, [id])
const saveNotes = useCallback(async (value: string) => {
setSavingNotes(true)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${id}/notes`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ notes: value || null }),
})
if (res.ok) {
setEntry(prev => prev ? { ...prev, notes: value || null } : prev)
setEditingNotes(false)
} else {
toast({ title: 'Kunde inte spara anteckning', variant: 'destructive' })
}
} catch {
toast({ title: 'Kunde inte spara anteckning', variant: 'destructive' })
} finally {
setSavingNotes(false)
}
}, [id, toast])
const handleDelete = useCallback(async () => {
setIsDeleting(true)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${id}`, { method: 'DELETE' })
const result = await res.json()
if (res.ok) {
toast({
title: 'Verifikat raderat',
description: `Verifikat ${result.data?.voucher_series ?? ''}${result.data?.voucher_number ?? ''} har raderats.`,
})
router.push('/bookkeeping')
} else {
toast({ title: 'Kunde inte radera', description: result.error, variant: 'destructive' })
setShowDeleteConfirm(false)
}
} catch {
toast({ title: 'Kunde inte radera verifikat', variant: 'destructive' })
setShowDeleteConfirm(false)
} finally {
setIsDeleting(false)
}
}, [id, router, toast])
useEffect(() => {
fetchData()
}, [fetchData])
@@ -120,18 +177,35 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
<p className="text-muted-foreground">{entry.description}</p>
</div>
{canCorrect && (
<Button
variant="outline"
size="sm"
className="w-full sm:w-auto"
onClick={() => setShowCorrection(true)}
disabled={!canWrite}
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
>
{!canWrite && <Lock className="mr-2 h-4 w-4" />}
Skapa ändringsverifikation
</Button>
{entry.status === 'posted' && (
<div className="flex flex-col sm:flex-row gap-2 w-full sm:w-auto">
{isLastInSeries && (
<Button
variant="destructive"
size="sm"
className="w-full sm:w-auto"
onClick={() => setShowDeleteConfirm(true)}
disabled={!canWrite}
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
>
{!canWrite && <Lock className="mr-2 h-4 w-4" />}
Radera verifikat
</Button>
)}
{canCorrect && (
<Button
variant="outline"
size="sm"
className="w-full sm:w-auto"
onClick={() => setShowCorrection(true)}
disabled={!canWrite}
title={!canWrite ? 'Du har endast läsbehörighet i detta företag' : undefined}
>
{!canWrite && <Lock className="mr-2 h-4 w-4" />}
Skapa ändringsverifikation
</Button>
)}
</div>
)}
</div>
@@ -156,6 +230,61 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
<span className="text-muted-foreground">Typ</span>
<span>{sourceTypeLabels[entry.source_type] || entry.source_type}</span>
</div>
{/* Notes — always editable (internal metadata, not BFL verifikation content) */}
<div className="border-t pt-2 mt-2">
<div className="flex items-center justify-between mb-1">
<span className="text-muted-foreground flex items-center gap-1">
<MessageSquare className="h-3.5 w-3.5" />
Anteckning
</span>
{!editingNotes && canWrite && (
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0"
onClick={() => { setNotesValue(entry.notes || ''); setEditingNotes(true) }}
>
<Pencil className="h-3 w-3" />
</Button>
)}
</div>
{editingNotes ? (
<div className="space-y-2">
<Textarea
value={notesValue}
onChange={(e) => setNotesValue(e.target.value)}
placeholder="Intern anteckning..."
className="resize-none text-sm"
rows={3}
maxLength={2000}
autoFocus
/>
<div className="flex gap-1 justify-end">
<Button
variant="ghost"
size="sm"
className="h-7 px-2"
onClick={() => setEditingNotes(false)}
disabled={savingNotes}
>
<X className="h-3.5 w-3.5" />
</Button>
<Button
size="sm"
className="h-7 px-2"
onClick={() => saveNotes(notesValue)}
disabled={savingNotes}
>
{savingNotes ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Check className="h-3.5 w-3.5" />}
</Button>
</div>
</div>
) : (
<p className="text-sm text-muted-foreground italic">
{entry.notes || 'Ingen anteckning'}
</p>
)}
</div>
</CardContent>
</Card>
@@ -374,6 +503,29 @@ export default function JournalEntryDetailPage({ params }: { params: Promise<{ i
}}
/>
)}
{/* Delete confirmation dialog */}
<ConfirmationDialog
open={showDeleteConfirm}
onOpenChange={setShowDeleteConfirm}
onConfirm={handleDelete}
isSubmitting={isDeleting}
title="Radera verifikat"
warningText={`Verifikat ${entry?.voucher_series ?? ''}${entry?.voucher_number ?? ''} raderas permanent. Eventuella kopplade underlag behålls men avlänkas. Denna åtgärd kan inte ångras.`}
confirmLabel="Radera permanent"
>
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4">
<AlertTriangle className="h-5 w-5 text-destructive mt-0.5 shrink-0" />
<div className="text-sm">
<p className="font-medium mb-1">Permanent radering</p>
<p className="text-muted-foreground">
Verifikatet och dess kontorader tas bort. Kopplade transaktioner och
fakturor behåller sina uppgifter men markeras som ej bokförda.
Underlag (kvitton, dokument) behålls men avlänkas.
</p>
</div>
</div>
</ConfirmationDialog>
</div>
)
}
+1 -1
View File
@@ -118,7 +118,7 @@ export default function ExpensesPage() {
return (
<div className="space-y-6">
<PageHeader
title="Utgifter"
title="Leverantörsfakturor"
description="Registrera och hantera dina utgifter"
action={
canWrite ? (
@@ -42,8 +42,9 @@ function buildMockSupabase({
chainFn('or')
chainFn('in')
chainFn('order')
chainFn('limit')
// First call: single entry fetch
// First call: single entry fetch (the main entry)
if (callIndex === 1) {
builder.single = vi.fn().mockResolvedValue({
data: singleResult,
@@ -53,18 +54,29 @@ function buildMockSupabase({
// Second call: reverse lookup for referencing entries
if (callIndex === 2) {
// The or() call resolves the query
builder.or = vi.fn().mockReturnValue({
then: (resolve: (v: unknown) => void) => resolve({ data: referencingIds }),
}) as unknown as ReturnType<typeof vi.fn>
// Make it thenable
const orResult = { data: referencingIds }
builder.or = vi.fn().mockResolvedValue(orResult)
}
// Third+ calls: chain entries fetch
// Third+ calls: chain entries fetch or is_last_in_series check
if (callIndex >= 3) {
builder.order = vi.fn().mockResolvedValue({ data: chainEntries })
builder.order = vi.fn().mockReturnValue(builder)
builder.single = vi.fn().mockResolvedValue({
data: singleResult ? { voucher_number: singleResult.voucher_number } : null,
})
// Also handle when .order resolves directly (chain entries fetch)
const orderResult = { data: chainEntries }
builder.order = vi.fn().mockImplementation(() => {
const obj = { ...builder, ...orderResult }
obj.then = (fn: (v: unknown) => void) => Promise.resolve(fn(orderResult))
// Support both .limit().single() and direct resolution
obj.limit = vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({
data: singleResult ? { voucher_number: singleResult.voucher_number } : null,
}),
})
return obj
})
}
return builder
@@ -109,5 +109,22 @@ export async function GET(
chain = chainEntries || []
}
return NextResponse.json({ data: { entry, chain } })
// Check if entry is the last in its voucher series (enables delete button in UI)
let isLastInSeries = false
if (entry.status === 'posted') {
const { data: maxResult } = await supabase
.from('journal_entries')
.select('voucher_number')
.eq('company_id', companyId)
.eq('fiscal_period_id', entry.fiscal_period_id)
.eq('voucher_series', entry.voucher_series)
.in('status', ['posted', 'reversed'])
.order('voucher_number', { ascending: false })
.limit(1)
.single()
isLastInSeries = maxResult?.voucher_number === entry.voucher_number
}
return NextResponse.json({ data: { entry, chain, is_last_in_series: isLastInSeries } })
}
@@ -0,0 +1,43 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { z } from 'zod'
import { validateBody } from '@/lib/api/validate'
const UpdateNotesSchema = z.object({
notes: z.string().max(2000).nullable(),
})
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
const result = await validateBody(request, UpdateNotesSchema)
if (!result.success) return result.response
const { error } = await supabase
.from('journal_entries')
.update({ notes: result.data.notes })
.eq('id', id)
.eq('company_id', companyId)
if (error) {
return NextResponse.json({ error: error.message }, { status: 400 })
}
return NextResponse.json({ data: { updated: true } })
}
@@ -1,6 +1,11 @@
import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { requireCompanyId } from '@/lib/company/context'
import { requireWritePermission } from '@/lib/auth/require-write'
import { ensureInitialized } from '@/lib/init'
import { eventBus } from '@/lib/events/bus'
ensureInitialized()
export async function GET(
request: Request,
@@ -29,3 +34,46 @@ export async function GET(
return NextResponse.json({ data })
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const writeCheck = await requireWritePermission(supabase, user.id)
if (!writeCheck.ok) return writeCheck.response
const companyId = await requireCompanyId(supabase, user.id)
const { data, error } = await supabase.rpc('delete_last_voucher', {
p_company_id: companyId,
p_entry_id: id,
})
if (error) {
return NextResponse.json(
{ error: error.message },
{ status: 400 }
)
}
await eventBus.emit({
type: 'journal_entry.deleted',
payload: {
entryId: id,
voucherSeries: data.voucher_series,
voucherNumber: data.voucher_number,
userId: user.id,
companyId,
},
})
return NextResponse.json({ data })
}
+19 -1
View File
@@ -4,6 +4,7 @@ import { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { useToast } from '@/components/ui/use-toast'
@@ -45,6 +46,7 @@ interface Props {
initialLines?: FormLine[]
initialDate?: string
initialDescription?: string
initialNotes?: string
sourceType?: JournalEntrySourceType
sourceId?: string
submitUrl?: string
@@ -59,6 +61,7 @@ export default function JournalEntryForm({
initialLines,
initialDate,
initialDescription,
initialNotes,
sourceType,
sourceId,
submitUrl,
@@ -70,6 +73,7 @@ export default function JournalEntryForm({
const [selectedPeriod, setSelectedPeriod] = useState('')
const [entryDate, setEntryDate] = useState(initialDate ?? new Date().toISOString().split('T')[0])
const [description, setDescription] = useState(initialDescription ?? '')
const [notes, setNotes] = useState(initialNotes ?? '')
const [lines, setLines] = useState<FormLine[]>(
initialLines ?? [{ ...BLANK_LINE }, { ...BLANK_LINE }]
)
@@ -90,7 +94,7 @@ export default function JournalEntryForm({
const isUploading = uploadedFiles.some((f) => f.status === 'uploading')
const hasContent = description !== '' ||
const hasContent = description !== '' || notes !== '' ||
lines.some(l => l.account_number !== '' || l.debit_amount !== '' || l.credit_amount !== '') ||
uploadedFiles.length > 0
useUnsavedChanges(hasContent)
@@ -285,6 +289,7 @@ export default function JournalEntryForm({
source_type: sourceType ?? 'manual',
source_id: sourceId,
voucher_series: voucherSeries || 'A',
notes: notes || undefined,
lines: entryLines,
}),
})
@@ -330,6 +335,7 @@ export default function JournalEntryForm({
setShowReview(false)
// Reset form
setDescription('')
setNotes('')
setUploadedFiles([])
setLines([{ ...BLANK_LINE }, { ...BLANK_LINE }])
setEntryCurrency('SEK')
@@ -386,6 +392,17 @@ export default function JournalEntryForm({
placeholder="Verifikationstext..."
/>
</div>
<div className={embedded ? 'hidden' : 'col-span-full'}>
<Label>Intern anteckning <span className="text-muted-foreground font-normal">(valfritt)</span></Label>
<Textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder="T.ex. anledning till bokning, referens till mejl, etc."
className="mt-1 resize-none"
rows={2}
maxLength={2000}
/>
</div>
{!embedded && (
<div>
<Label>Serie</Label>
@@ -720,6 +737,7 @@ export default function JournalEntryForm({
periodName={periods.find((p) => p.id === selectedPeriod)?.name || ''}
entryDate={entryDate}
description={description}
notes={notes || undefined}
voucherSeries={!embedded ? voucherSeries : undefined}
lines={lines}
totalDebit={totalDebit}
+81 -1
View File
@@ -1,6 +1,6 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useState, useEffect, useCallback, useMemo } from 'react'
import Link from 'next/link'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
@@ -13,6 +13,8 @@ import { AccountNumber } from '@/components/ui/account-number'
import { getAccountDescription } from '@/lib/bookkeeping/account-descriptions'
import JournalEntryAttachments from '@/components/bookkeeping/JournalEntryAttachments'
import CorrectionEntryDialog from '@/components/bookkeeping/CorrectionEntryDialog'
import { ConfirmationDialog } from '@/components/ui/confirmation-dialog'
import { useToast } from '@/components/ui/use-toast'
import JournalEntryStatusBadge from '@/components/bookkeeping/JournalEntryStatusBadge'
import type { JournalEntry, JournalEntryLine } from '@/types'
@@ -30,6 +32,7 @@ interface Props {
}
export default function JournalEntryList({ periodId }: Props) {
const { toast } = useToast()
const [entries, setEntries] = useState<JournalEntry[]>([])
const [loading, setLoading] = useState(true)
const [expandedId, setExpandedId] = useState<string | null>(null)
@@ -38,6 +41,8 @@ export default function JournalEntryList({ periodId }: Props) {
const [attachmentCounts, setAttachmentCounts] = useState<Record<string, number>>({})
const [showMissingOnly, setShowMissingOnly] = useState(false)
const [correctionEntry, setCorrectionEntry] = useState<JournalEntry | null>(null)
const [deleteEntry, setDeleteEntry] = useState<JournalEntry | null>(null)
const [isDeleting, setIsDeleting] = useState(false)
const [dateSortDir, setDateSortDir] = useState<'desc' | 'asc'>('desc')
const [dateFrom, setDateFrom] = useState('')
const [dateTo, setDateTo] = useState('')
@@ -134,6 +139,43 @@ export default function JournalEntryList({ periodId }: Props) {
setAttachmentCounts((prev) => ({ ...prev, [entryId]: count }))
}, [])
// Compute which entries are the last in their series (enables delete button)
const lastInSeriesIds = useMemo(() => {
const maxPerSeries = new Map<string, { id: string; num: number }>()
for (const e of entries) {
if (e.status !== 'posted') continue
const key = `${e.fiscal_period_id}:${e.voucher_series}`
const current = maxPerSeries.get(key)
if (!current || e.voucher_number > current.num) {
maxPerSeries.set(key, { id: e.id, num: e.voucher_number })
}
}
return new Set(Array.from(maxPerSeries.values()).map(v => v.id))
}, [entries])
const handleDeleteEntry = useCallback(async () => {
if (!deleteEntry) return
setIsDeleting(true)
try {
const res = await fetch(`/api/bookkeeping/journal-entries/${deleteEntry.id}`, { method: 'DELETE' })
const result = await res.json()
if (res.ok) {
toast({
title: 'Verifikat raderat',
description: `Verifikat ${result.data?.voucher_series ?? ''}${result.data?.voucher_number ?? ''} har raderats.`,
})
setDeleteEntry(null)
fetchEntries()
} else {
toast({ title: 'Kunde inte radera', description: result.error, variant: 'destructive' })
}
} catch {
toast({ title: 'Kunde inte radera verifikat', variant: 'destructive' })
} finally {
setIsDeleting(false)
}
}, [deleteEntry, toast])
const toggleExpand = (id: string) => {
setExpandedId(expandedId === id ? null : id)
}
@@ -420,6 +462,12 @@ export default function JournalEntryList({ periodId }: Props) {
</>
)}
{entry.notes && (
<p className="mt-3 text-xs text-muted-foreground italic px-1">
{entry.notes}
</p>
)}
<JournalEntryAttachments
journalEntryId={entry.id}
onCountChange={(c) => handleAttachmentCountChange(entry.id, c)}
@@ -429,6 +477,16 @@ export default function JournalEntryList({ periodId }: Props) {
<Button variant="outline" size="sm" className="w-full sm:w-auto" asChild>
<Link href={`/bookkeeping/${entry.id}`}>Visa detaljer</Link>
</Button>
{entry.status === 'posted' && lastInSeriesIds.has(entry.id) && (
<Button
variant="destructive"
size="sm"
className="w-full sm:w-auto"
onClick={() => setDeleteEntry(entry)}
>
Radera
</Button>
)}
{entry.status === 'posted' && entry.source_type !== 'storno' && entry.source_type !== 'correction' && (
<Button
variant="outline"
@@ -457,6 +515,28 @@ export default function JournalEntryList({ periodId }: Props) {
/>
)}
{/* Delete confirmation dialog */}
<ConfirmationDialog
open={!!deleteEntry}
onOpenChange={(open) => { if (!open) setDeleteEntry(null) }}
onConfirm={handleDeleteEntry}
isSubmitting={isDeleting}
title="Radera verifikat"
warningText={deleteEntry ? `Verifikat ${deleteEntry.voucher_series}${deleteEntry.voucher_number} raderas permanent. Denna åtgärd kan inte ångras.` : ''}
confirmLabel="Radera permanent"
>
<div className="flex items-start gap-3 rounded-lg border border-destructive/30 bg-destructive/10 p-4">
<AlertTriangle className="h-5 w-5 text-destructive mt-0.5 shrink-0" />
<div className="text-sm">
<p className="font-medium mb-1">Permanent radering</p>
<p className="text-muted-foreground">
Verifikatet och dess kontorader tas bort. Kopplade transaktioner och
fakturor markeras som ej bokförda. Underlag behålls men avlänkas.
</p>
</div>
</div>
</ConfirmationDialog>
{/* Pagination */}
{count > pageSize && (
<div className="flex justify-center gap-2">
@@ -15,6 +15,7 @@ interface JournalEntryReviewContentProps {
periodName: string
entryDate: string
description: string
notes?: string
voucherSeries?: string
lines: ReviewLine[]
totalDebit: number
@@ -32,6 +33,7 @@ export function JournalEntryReviewContent({
periodName,
entryDate,
description,
notes,
voucherSeries,
lines,
totalDebit,
@@ -70,6 +72,12 @@ export function JournalEntryReviewContent({
<span className="text-muted-foreground">Beskrivning</span>
<p className="font-medium">{description}</p>
</div>
{notes && (
<div className="text-sm">
<span className="text-muted-foreground">Intern anteckning</span>
<p className="text-muted-foreground italic">{notes}</p>
</div>
)}
</div>
{/* Balance status */}
+1 -1
View File
@@ -66,7 +66,7 @@ const navItems: NavItem[] = [
{ href: '/invoices', label: 'Fakturor', icon: Receipt, group: 'försäljning' },
{ href: '/customers', label: 'Kunder', icon: Users, group: 'försäljning' },
// AP — Accounts Payable
{ href: '/expenses', label: 'Utgifter', icon: Wallet, group: 'inköp' },
{ href: '/expenses', label: 'Leverantörsfakturor', icon: Wallet, group: 'inköp' },
// Temporarily hidden pending module rework (see feedback #49)
{ href: '/suppliers', label: 'Leverantörer', icon: Building2, group: 'inköp', hidden: true },
{ href: '/supplier-invoices', label: 'Leverantörsfakturor', icon: FileInput, group: 'inköp', hidden: true },
+1 -1
View File
@@ -128,7 +128,7 @@ export default function BankFileConfirmStep({
<div className="p-4 bg-muted/50 rounded-lg">
<div className="flex items-center gap-2 text-muted-foreground mb-1">
<span className="text-xs">Utgifter</span>
<span className="text-xs">Leverantörsfakturor</span>
</div>
<p className="text-xl font-display font-medium tabular-nums">
{formatCurrency(stats.total_expenses)}
+1 -1
View File
@@ -85,7 +85,7 @@ export default function BankFilePreviewStep({
<CardContent className="pt-6">
<div className="flex items-center gap-2 text-muted-foreground mb-1">
<TrendingDown className="h-4 w-4" />
<span className="text-sm">Utgifter</span>
<span className="text-sm">Leverantörsfakturor</span>
</div>
<p className="text-lg font-display font-medium tabular-nums">
{formatCurrency(stats.total_expenses)}
+1
View File
@@ -306,6 +306,7 @@ export const CreateJournalEntrySchema = z.object({
source_type: JournalEntrySourceTypeSchema.default('manual'),
source_id: z.string().optional(),
voucher_series: z.string().regex(/^[A-Z]$/, 'Verifikationsserie måste vara en bokstav AZ').optional(),
notes: z.string().max(2000).optional(),
lines: z.array(CreateJournalEntryLineSchema).min(2, 'At least two lines are required for double-entry'),
})
+1
View File
@@ -187,6 +187,7 @@ export async function createDraftEntry(
description: input.description,
source_type: input.source_type,
source_id: input.source_id || null,
notes: input.notes || null,
status: 'draft',
})
.select()
+1
View File
@@ -21,6 +21,7 @@ export type CoreEvent =
| { type: 'journal_entry.drafted'; payload: { entry: JournalEntry; userId: string; companyId: string } }
| { type: 'journal_entry.committed'; payload: { entry: JournalEntry; userId: string; companyId: string } }
| { type: 'journal_entry.corrected'; payload: { original: JournalEntry; storno: JournalEntry; corrected: JournalEntry; userId: string; companyId: string } }
| { type: 'journal_entry.deleted'; payload: { entryId: string; voucherSeries: string; voucherNumber: number; userId: string; companyId: string } }
// Documents
| { type: 'document.uploaded'; payload: { document: DocumentAttachment; userId: string; companyId: string } }
| { type: 'document.accessed'; payload: { document: { id: string; file_name: string }; userId: string; companyId: string } }
@@ -0,0 +1,4 @@
-- Retroactive schema cache reload after recent ALTER TABLE migrations
-- (trade_name, delivery_date, pays_salaries, etc.) that did not include
-- NOTIFY pgrst. Ensures PostgREST picks up all new columns immediately.
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,73 @@
-- Add optional notes/comment field to journal entries.
-- Notes are internal metadata (not part of BFL verifikation content)
-- and remain editable even after posting, following the Fortnox model.
ALTER TABLE public.journal_entries ADD COLUMN notes text;
-- Update the immutability trigger to allow notes-only updates on posted entries.
-- BFL 5 kap 7§ defines verifikation content (date, description, amount, counterparty,
-- number, underlag refs). Notes are NOT in that list — they are internal metadata.
CREATE OR REPLACE FUNCTION public.enforce_journal_entry_immutability()
RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
-- Session variable bypass for controlled operations (e.g. delete_last_voucher RPC)
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END IF;
IF TG_OP = 'DELETE' THEN
-- No exemption for drafts: varaktighet applies from insertion.
-- Application code uses status='cancelled' instead of DELETE.
RAISE EXCEPTION 'Cannot delete journal entries (id: %, status: %). Use cancelled status instead.',
OLD.id, OLD.status;
END IF;
-- Draft can transition to draft (update fields), posted, or cancelled
IF OLD.status = 'draft' AND NEW.status IN ('draft', 'posted', 'cancelled') THEN
RETURN NEW;
END IF;
-- Posted entries: allow notes-only updates (internal metadata, not verifikation content)
-- BFL 5 kap 7§ mandates immutability for verifikation fields (description, date, amounts,
-- voucher number, etc.). Notes/comments are outside this scope per Fortnox precedent.
IF OLD.status = 'posted' AND NEW.status = 'posted' THEN
IF NEW.description = OLD.description
AND NEW.entry_date = OLD.entry_date
AND NEW.fiscal_period_id = OLD.fiscal_period_id
AND NEW.voucher_number = OLD.voucher_number
AND NEW.voucher_series = OLD.voucher_series
AND NEW.source_type = OLD.source_type
AND COALESCE(NEW.source_id::text, '') = COALESCE(OLD.source_id::text, '')
AND NEW.user_id = OLD.user_id
AND COALESCE(NEW.reversed_by_id::text, '') = COALESCE(OLD.reversed_by_id::text, '')
AND COALESCE(NEW.reverses_id::text, '') = COALESCE(OLD.reverses_id::text, '')
AND COALESCE(NEW.correction_of_id::text, '') = COALESCE(OLD.correction_of_id::text, '')
AND NEW.committed_at IS NOT DISTINCT FROM OLD.committed_at
THEN
RETURN NEW; -- Only notes and updated_at may differ
END IF;
END IF;
-- Posted can transition to reversed (storno) or cancelled (orphaned cleanup)
IF OLD.status = 'posted' AND NEW.status IN ('reversed', 'cancelled') THEN
IF NEW.status = 'reversed' THEN
IF NEW.description != OLD.description OR NEW.entry_date != OLD.entry_date
OR NEW.fiscal_period_id != OLD.fiscal_period_id
OR NEW.voucher_number != OLD.voucher_number THEN
RAISE EXCEPTION 'Cannot modify fields of a posted entry during reversal (id: %)', OLD.id;
END IF;
END IF;
RETURN NEW;
END IF;
-- Reversed entries can transition back to posted (when their storno is deleted)
IF OLD.status = 'reversed' AND NEW.status = 'posted'
AND current_setting('gnubok.allow_delete', true) = 'true' THEN
RETURN NEW;
END IF;
RAISE EXCEPTION 'Cannot modify a % journal entry (id: %). Committed entries are immutable per Bokforingslagen.',
OLD.status, OLD.id;
END; $$;
NOTIFY pgrst, 'reload schema';
@@ -0,0 +1,223 @@
-- Delete last voucher per series (Fortnox model).
-- Allows deleting the highest-numbered posted voucher in a series,
-- maintaining an unbroken voucher number sequence per BFL 5 kap 7§.
--
-- Safeguards:
-- 1. Only the LAST voucher in its (company, fiscal_period, series) can be deleted
-- 2. Fiscal period must not be closed or locked
-- 3. No other entries may reference it (reverses_id, correction_of_id)
-- 4. Calling user must be company owner or admin
-- 5. Full audit trail via write_audit_log() trigger (BFNAR 2013:2 behandlingshistorik)
-- 1. Update line immutability trigger to respect session variable bypass
CREATE OR REPLACE FUNCTION public.enforce_journal_entry_line_immutability()
RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE v_status text;
BEGIN
-- Session variable bypass for controlled operations (delete_last_voucher RPC)
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END IF;
SELECT status INTO v_status FROM public.journal_entries
WHERE id = COALESCE(OLD.journal_entry_id, NEW.journal_entry_id);
-- Draft entries: all operations allowed
IF v_status = 'draft' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END IF;
-- Cancelled entries: only DELETE for cleanup
IF v_status = 'cancelled' THEN
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RAISE EXCEPTION 'Cannot % lines of a cancelled journal entry.', TG_OP;
END IF;
RAISE EXCEPTION 'Cannot % lines of a % journal entry.', TG_OP, v_status;
END; $$;
-- 2. Update retention trigger to respect session variable bypass
CREATE OR REPLACE FUNCTION public.enforce_retention_journal_entries()
RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER AS $$
DECLARE
v_retention_expires date;
BEGIN
-- Session variable bypass for controlled operations (delete_last_voucher RPC)
IF current_setting('gnubok.allow_delete', true) = 'true' THEN
RETURN OLD;
END IF;
SELECT fp.retention_expires_at INTO v_retention_expires
FROM public.fiscal_periods fp
WHERE fp.id = OLD.fiscal_period_id;
IF v_retention_expires IS NOT NULL AND v_retention_expires > CURRENT_DATE THEN
INSERT INTO public.audit_log (user_id, action, table_name, record_id, description)
VALUES (OLD.user_id, 'RETENTION_BLOCK', 'journal_entries', OLD.id,
'Attempted deletion within retention period (expires ' || v_retention_expires || ')');
RAISE EXCEPTION 'Cannot delete journal entry within 7-year retention period (expires %)',
v_retention_expires;
END IF;
RETURN OLD;
END; $$;
-- 3. Create the delete_last_voucher RPC
CREATE OR REPLACE FUNCTION public.delete_last_voucher(
p_company_id uuid,
p_entry_id uuid
)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_entry record;
v_period record;
v_max_voucher integer;
v_ref_count integer;
v_caller_role text;
v_snapshot jsonb;
v_lines_snapshot jsonb;
BEGIN
-- 1. Verify calling user is company owner or admin
SELECT cm.role INTO v_caller_role
FROM company_members cm
WHERE cm.company_id = p_company_id
AND cm.user_id = auth.uid();
IF v_caller_role IS NULL OR v_caller_role NOT IN ('owner', 'admin') THEN
RAISE EXCEPTION 'Only company owners and admins can delete vouchers';
END IF;
-- 2. Lock and fetch the target entry
SELECT * INTO v_entry
FROM journal_entries
WHERE id = p_entry_id
AND company_id = p_company_id
FOR UPDATE;
IF v_entry IS NULL THEN
RAISE EXCEPTION 'Journal entry not found';
END IF;
IF v_entry.status != 'posted' THEN
RAISE EXCEPTION 'Only posted entries can be deleted (current status: %)', v_entry.status;
END IF;
-- 3. Verify fiscal period is open
SELECT * INTO v_period
FROM fiscal_periods
WHERE id = v_entry.fiscal_period_id
FOR UPDATE;
IF v_period.is_closed THEN
RAISE EXCEPTION 'Cannot delete voucher in a closed fiscal period';
END IF;
IF v_period.locked_at IS NOT NULL THEN
RAISE EXCEPTION 'Cannot delete voucher in a locked fiscal period';
END IF;
-- 4. Lock voucher_sequences row to serialise against concurrent commit_journal_entry.
-- Without this, a concurrent commit could assign a new voucher number between
-- our MAX check and the DELETE, producing a gap (violating BFL 5 kap 7§).
PERFORM 1 FROM voucher_sequences
WHERE company_id = p_company_id
AND fiscal_period_id = v_entry.fiscal_period_id
AND voucher_series = v_entry.voucher_series
FOR UPDATE;
-- Verify it is the LAST voucher in its series
SELECT MAX(voucher_number) INTO v_max_voucher
FROM journal_entries
WHERE company_id = p_company_id
AND fiscal_period_id = v_entry.fiscal_period_id
AND voucher_series = v_entry.voucher_series
AND status NOT IN ('cancelled', 'draft');
IF v_entry.voucher_number != v_max_voucher THEN
RAISE EXCEPTION 'Kan bara radera det sista verifikatet i serien. % har nummer % men senaste är %',
v_entry.voucher_series, v_entry.voucher_number, v_max_voucher;
END IF;
-- 5. Verify no other entries reference this one
SELECT COUNT(*) INTO v_ref_count
FROM journal_entries
WHERE company_id = p_company_id
AND status != 'cancelled'
AND (reverses_id = p_entry_id OR correction_of_id = p_entry_id);
IF v_ref_count > 0 THEN
RAISE EXCEPTION 'Cannot delete: other entries reference this voucher (% references)',
v_ref_count;
END IF;
-- 6. Capture snapshot for audit trail (BFNAR 2013:2 behandlingshistorik)
-- The write_audit_log() AFTER trigger also captures old_state, but we
-- include lines here for complete traceability.
SELECT jsonb_agg(to_jsonb(l)) INTO v_lines_snapshot
FROM journal_entry_lines l
WHERE l.journal_entry_id = p_entry_id;
v_snapshot := to_jsonb(v_entry) || jsonb_build_object('lines', COALESCE(v_lines_snapshot, '[]'::jsonb));
-- 7. If this entry is a storno (reverses another entry), restore the original
IF v_entry.reverses_id IS NOT NULL THEN
-- Use session variable to allow reversed → posted transition
PERFORM set_config('gnubok.allow_delete', 'true', true);
UPDATE journal_entries
SET status = 'posted', reversed_by_id = NULL
WHERE id = v_entry.reverses_id
AND company_id = p_company_id;
END IF;
-- 8. Enable session variable bypass for deletion triggers
PERFORM set_config('gnubok.allow_delete', 'true', true);
-- 9. Unlink document attachments (FK is RESTRICT, must clear before delete)
UPDATE document_attachments
SET journal_entry_id = NULL
WHERE journal_entry_id = p_entry_id;
-- 10. Delete the journal entry
-- journal_entry_lines: ON DELETE CASCADE (auto-deleted)
-- transactions: ON DELETE SET NULL (auto-nullified)
-- supplier_invoices: ON DELETE SET NULL (auto-nullified)
-- supplier_invoice_payments: ON DELETE SET NULL (auto-nullified)
-- invoice_payments: ON DELETE SET NULL (auto-nullified)
DELETE FROM journal_entries WHERE id = p_entry_id;
-- 11. Decrement voucher sequence
UPDATE voucher_sequences
SET last_number = GREATEST(last_number - 1, 0)
WHERE company_id = p_company_id
AND fiscal_period_id = v_entry.fiscal_period_id
AND voucher_series = v_entry.voucher_series;
-- 12. Insert explicit audit entry with full snapshot including lines
INSERT INTO audit_log (user_id, action, table_name, record_id, actor_id, old_state, description)
VALUES (
v_entry.user_id,
'DELETE',
'journal_entries',
p_entry_id,
auth.uid(),
v_snapshot,
'Deleted voucher ' || v_entry.voucher_series || v_entry.voucher_number ||
' (delete_last_voucher RPC, caller: ' || auth.uid() || ')'
);
RETURN jsonb_build_object(
'deleted', true,
'voucher_series', v_entry.voucher_series,
'voucher_number', v_entry.voucher_number
);
END;
$$;
NOTIFY pgrst, 'reload schema';
+1
View File
@@ -239,6 +239,7 @@ export function makeJournalEntry(overrides: Partial<JournalEntry> = {}): Journal
reverses_id: null,
correction_of_id: null,
attachment_urls: null,
notes: null,
created_at: '2024-06-15T14:30:00Z',
updated_at: '2024-06-15T14:30:00Z',
...overrides,
+2
View File
@@ -938,6 +938,7 @@ export interface JournalEntry {
reverses_id: string | null
correction_of_id: string | null
attachment_urls: string[] | null
notes: string | null
created_at: string
updated_at: string
// Relations
@@ -1136,6 +1137,7 @@ export interface CreateJournalEntryInput {
source_type: JournalEntrySourceType
source_id?: string
voucher_series?: string
notes?: string
lines: CreateJournalEntryLineInput[]
}