Files
accounted/app/api/bookkeeping/journal-entries/[id]/chain/route.ts
T
Jakob WennbergandClaude Opus 4.6 7bf7565852 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>
2026-04-13 16:12:03 +02:00

131 lines
4.0 KiB
TypeScript

import { createClient } from '@/lib/supabase/server'
import { NextResponse } from 'next/server'
import { requireCompanyId } from '@/lib/company/context'
export async function GET(
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 companyId = await requireCompanyId(supabase, user.id)
// Fetch the requested entry with lines
const { data: entry, error } = await supabase
.from('journal_entries')
.select('*, lines:journal_entry_lines(*)')
.eq('id', id)
.eq('company_id', companyId)
.single()
if (error || !entry) {
return NextResponse.json({ error: 'Entry not found' }, { status: 404 })
}
// Collect all related entry IDs by following FK links iteratively
const visited = new Set<string>([id])
const toVisit = new Set<string>()
// Seed with direct FK references from this entry
for (const fk of [entry.reverses_id, entry.reversed_by_id, entry.correction_of_id]) {
if (fk && !visited.has(fk)) toVisit.add(fk)
}
// Also find entries that reference this entry (reverse lookup)
const { data: referencing } = await supabase
.from('journal_entries')
.select('id')
.eq('company_id', companyId)
.or(`reverses_id.eq.${id},reversed_by_id.eq.${id},correction_of_id.eq.${id}`)
if (referencing) {
for (const r of referencing) {
if (!visited.has(r.id)) toVisit.add(r.id)
}
}
// Iteratively expand (bounded) to handle multi-level correction chains
const MAX_ITERATIONS = 10
for (let i = 0; i < MAX_ITERATIONS && toVisit.size > 0; i++) {
const batch = Array.from(toVisit)
toVisit.clear()
for (const bid of batch) visited.add(bid)
const { data: batchEntries } = await supabase
.from('journal_entries')
.select('id, reverses_id, reversed_by_id, correction_of_id')
.eq('company_id', companyId)
.in('id', batch)
if (!batchEntries) continue
// Collect FK references from forward links
for (const e of batchEntries) {
for (const fk of [e.reverses_id, e.reversed_by_id, e.correction_of_id]) {
if (fk && !visited.has(fk)) toVisit.add(fk)
}
}
// Single reverse-lookup for the whole batch instead of one per entry
const batchOr = batch
.flatMap(bid => [
`reverses_id.eq.${bid}`,
`reversed_by_id.eq.${bid}`,
`correction_of_id.eq.${bid}`,
])
.join(',')
const { data: refs } = await supabase
.from('journal_entries')
.select('id')
.eq('company_id', companyId)
.or(batchOr)
if (refs) {
for (const r of refs) {
if (!visited.has(r.id)) toVisit.add(r.id)
}
}
}
// Fetch all chain entries (excluding the main entry itself) with lines
const chainIds = Array.from(visited).filter((cid) => cid !== id)
let chain: typeof entry[] = []
if (chainIds.length > 0) {
const { data: chainEntries } = await supabase
.from('journal_entries')
.select('*, lines:journal_entry_lines(*)')
.eq('company_id', companyId)
.in('id', chainIds)
.order('created_at', { ascending: true })
chain = chainEntries || []
}
// 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 } })
}