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