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
co-authored by Claude Opus 4.6
parent ade4ad5971
commit 7bf7565852
21 changed files with 713 additions and 28 deletions
+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 })
}