feat(bookkeeping): guarded fiscal-year reset + findable Angra import (#1883) (#1897)

* feat(bookkeeping): guarded fiscal-year reset + findable Angra import (#1883)

Two deliverables from the community report where a bad SIE test import
left no way out short of deleting the company:

A) Discoverability: the voucher list shows one attn line linking to
   /import?history=sie whenever the page contains import-sourced
   vouchers, and /import?history=sie deep-links straight into the
   fold-open SIE import history where per-import Angra already lives.

B) Reset of an UNLOCKED fiscal year regardless of how the entries
   arrived: new reset_fiscal_year RPC (same gnubok.allow_delete escape
   hatch as undo_sie_import; no enforcement trigger touched) behind
   GET/POST /api/bookkeeping/fiscal-periods/[id]/reset and a typed
   type-the-year-name confirmation dialog on the fiscal years settings
   list. Refuses on: locked/closed year, company lock date over any part
   of the year, executed year-end, arsredovisning state, later year
   depending on this year's UB, VAT-declared evidence (vat_settlement
   verifikat, SKV lock/submit audit rows, extension workflow keys, fail
   closed) and AGI-declared months. Entries referenced by RESTRICT/NO
   ACTION FKs abort the whole reset (all-or-nothing). Documents are
   detached, never deleted (BFL 7 kap); every delete is audit-logged
   plus one behandlingshistorik summary row.

Fixes #1883

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(bookkeeping): harden fiscal-year reset after skeptic review (#1883)

Blocking skeptic findings on PR #1897, one consolidated pass:

- New snapshot blocker cross_year_reference: an entry outside the year whose
  correction_of_id / reverses_id / reversed_by_id points into the year made
  the delete crash with an uncaught P0001 (immutability trigger refusing the
  ON DELETE SET NULL referential UPDATE) after an eligible:true preview, and
  silently severed draft chains. 12 such chains exist in prod today.
- New snapshot blocker rot_rut_state: a begaran om utbetalning that reached
  Skatteverket (submitted/paid/partially_paid/rejected) was silently
  unlinked via SET NULL, erasing the bokforing behind a filed and possibly
  decided myndighetsarende.
- Rakenskapsinformation preservation (BFL 7 kap): line-level trigger audit
  rows carry no company_id and header rows no amounts, so a reset destroyed
  konton/belopp with no company-readable trace. The RPC now archives the
  full content of every verifikat in company-scoped RESET_SNAPSHOT audit
  rows before deleting (action added to audit_log_action_check, NOT VALID),
  and behandlingshistorik renders them.
- Dimension registry lockstep on reset (mirrors undo_sie_import): flipped
  imports can never be undone again, so their dimensions/values would have
  been orphaned forever.
- EXCEPTION WHEN raise_exception now returns a typed
  FISCAL_YEAR_RESET_LINKED_ENTRIES envelope instead of a bare 500;
  gnubok.allow_delete is cleared before leaving the guarded block.
- Voucher-list attn line fires only for source_type 'import':
  opening_balance is also written by year-end closing and the manual IB
  flows, which mislabelled every year-2+ company as SIE-imported.
- /import?history=sie now scrolls the SIE history into view.
- Reset dialog copy (sv+en) discloses that linked invoices, payments and
  bank transactions become unbooked; new blocker strings in both locales.
- pg fixture fix: document_attachments seeded without company_id (23502);
  new pg tests for both blockers, RESET_SNAPSHOT rows and the lockstep.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-08-25 14:36:18 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 77cacdcf34
commit 79013cf092
17 changed files with 2359 additions and 2 deletions
+15
View File
@@ -3754,6 +3754,21 @@ export const CompanyMigrationResetSchema = z.object({
}),
})
/**
* POST /api/bookkeeping/fiscal-periods/[id]/reset
*
* Typed confirmation for the destructive fiscal-year reset: the caller must
* restate the year's label (fiscal_periods.name) exactly. The RPC repeats
* the match server-side, so this only provides early Swedish feedback.
*/
export const FiscalYearResetSchema = z.object({
confirm_name: z
.string()
.trim()
.min(1, 'Ange räkenskapsårets namn exakt som det visas')
.max(200, 'Räkenskapsårets namn får vara högst 200 tecken'),
})
/**
* POST /api/notices/dismiss
*
@@ -0,0 +1,167 @@
/**
* Unit tests for the fiscal-year-reset service wrapper.
*
* The guards themselves live in the reset_fiscal_year RPC and are pinned by
* tests/pg/reset-fiscal-year.pg.test.ts against real Postgres; these tests
* pin the envelope mapping (RPC jsonb -> typed outcomes), the fail-closed
* default code, and that the execution escalates through
* rpcClientForBulkDelete with an explicit p_user_id.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
getFiscalYearResetEligibility,
resetFiscalYear,
} from '@/lib/core/bookkeeping/fiscal-year-reset'
import type { SupabaseClient } from '@supabase/supabase-js'
const bulkRpcMock = vi.fn()
const bulkClient = { rpc: bulkRpcMock } as unknown as SupabaseClient
vi.mock('@/lib/import/sie-import', () => ({
rpcClientForBulkDelete: vi.fn(async () => bulkClient),
}))
function sessionClient(rpcResult: { data?: unknown; error?: unknown }): SupabaseClient {
return { rpc: vi.fn(async () => rpcResult) } as unknown as SupabaseClient
}
const SNAPSHOT = {
ok: true,
eligible: true,
blockers: [],
period: {
id: 'period-1',
name: '2026',
period_start: '2026-01-01',
period_end: '2026-12-31',
},
counts: { vouchers: 7, documents_to_detach: 2 },
}
describe('getFiscalYearResetEligibility', () => {
beforeEach(() => vi.clearAllMocks())
it('maps the RPC snapshot to a typed eligibility', async () => {
const supabase = sessionClient({ data: SNAPSHOT, error: null })
const result = await getFiscalYearResetEligibility(supabase, 'company-1', 'period-1')
expect(result).toEqual({
ok: true,
eligibility: {
eligible: true,
blockers: [],
period: SNAPSHOT.period,
counts: SNAPSHOT.counts,
},
})
expect(supabase.rpc).toHaveBeenCalledWith('get_fiscal_year_reset_eligibility', {
p_company_id: 'company-1',
p_period_id: 'period-1',
})
})
it('passes through blockers for an ineligible year', async () => {
const supabase = sessionClient({
data: {
...SNAPSHOT,
eligible: false,
blockers: [{ code: 'period_locked' }, { code: 'vat_declared', count: 1 }],
},
error: null,
})
const result = await getFiscalYearResetEligibility(supabase, 'company-1', 'period-1')
expect(result.ok).toBe(true)
if (result.ok) {
expect(result.eligibility.eligible).toBe(false)
expect(result.eligibility.blockers).toEqual([
{ code: 'period_locked' },
{ code: 'vat_declared', count: 1 },
])
}
})
it('returns the RPC error code when the RPC refuses', async () => {
const supabase = sessionClient({
data: { ok: false, code: 'FISCAL_YEAR_RESET_FORBIDDEN' },
error: null,
})
const result = await getFiscalYearResetEligibility(supabase, 'company-1', 'period-1')
expect(result).toEqual({ ok: false, code: 'FISCAL_YEAR_RESET_FORBIDDEN' })
})
it('fails closed on a transport error', async () => {
const supabase = sessionClient({ data: null, error: { message: 'boom' } })
const result = await getFiscalYearResetEligibility(supabase, 'company-1', 'period-1')
expect(result).toEqual({ ok: false, code: 'FISCAL_YEAR_RESET_FAILED' })
})
it('fails closed on a null RPC payload', async () => {
const supabase = sessionClient({ data: null, error: null })
const result = await getFiscalYearResetEligibility(supabase, 'company-1', 'period-1')
expect(result).toEqual({ ok: false, code: 'FISCAL_YEAR_RESET_FAILED' })
})
})
describe('resetFiscalYear', () => {
beforeEach(() => vi.clearAllMocks())
it('executes through the bulk-delete client with an explicit user id', async () => {
bulkRpcMock.mockResolvedValue({
data: { ok: true, deleted: 7, detached_documents: 2, period_name: '2026' },
error: null,
})
const supabase = sessionClient({ data: null, error: null })
const result = await resetFiscalYear(supabase, 'company-1', 'period-1', 'user-1', '2026')
expect(result).toEqual({
ok: true,
deleted: 7,
detachedDocuments: 2,
periodName: '2026',
})
expect(bulkRpcMock).toHaveBeenCalledWith('reset_fiscal_year', {
p_company_id: 'company-1',
p_period_id: 'period-1',
p_confirmed_name: '2026',
p_user_id: 'user-1',
})
})
it('passes through refusal codes and blockers', async () => {
bulkRpcMock.mockResolvedValue({
data: {
ok: false,
code: 'FISCAL_YEAR_RESET_INELIGIBLE',
blockers: [{ code: 'company_lock_date', date: '2026-06-30' }],
},
error: null,
})
const supabase = sessionClient({ data: null, error: null })
const result = await resetFiscalYear(supabase, 'company-1', 'period-1', 'user-1', '2026')
expect(result).toEqual({
ok: false,
code: 'FISCAL_YEAR_RESET_INELIGIBLE',
blockers: [{ code: 'company_lock_date', date: '2026-06-30' }],
})
})
it('fails closed on a transport error', async () => {
bulkRpcMock.mockResolvedValue({ data: null, error: { message: 'boom' } })
const supabase = sessionClient({ data: null, error: null })
const result = await resetFiscalYear(supabase, 'company-1', 'period-1', 'user-1', '2026')
expect(result).toEqual({ ok: false, code: 'FISCAL_YEAR_RESET_FAILED' })
})
})
+105
View File
@@ -0,0 +1,105 @@
import type { SupabaseClient } from '@supabase/supabase-js'
import { rpcClientForBulkDelete } from '@/lib/import/sie-import'
import type { FiscalYearResetEligibility, FiscalYearResetRpcResult } from '@/types'
/**
* Fiscal-year reset (issue #1883): guarded hard-delete of ALL vouchers in one
* OPEN fiscal year, regardless of how they arrived (SIE import, manual,
* agent). The heavy lifting and every guard live in the `reset_fiscal_year`
* RPC (migration 20260825150000), which reuses the same
* `gnubok.allow_delete` escape hatch as `undo_sie_import`: this module is a
* thin typed wrapper.
*
* The RPC refuses whenever any reliance state exists: locked/closed year,
* company lock date over the year, year-end/arsredovisning state, a later
* year depending on this year's UB, VAT/AGI declared evidence, or entries
* referenced by other records (assets, accruals, salary runs). Documents are
* detached, never deleted (BFL 7 kap).
*/
export type FiscalYearResetOutcome =
| { ok: true; deleted: number; detachedDocuments: number; periodName: string }
| { ok: false; code: string; blockers?: FiscalYearResetEligibility['blockers'] }
export type FiscalYearResetEligibilityOutcome =
| { ok: true; eligibility: FiscalYearResetEligibility }
| { ok: false; code: string }
/**
* Owner/admin-only eligibility preview. Runs on the caller's session client
* (auth.uid() present), so no explicit user id is needed. The execution RPC
* rechecks every condition; this response is informational only.
*/
export async function getFiscalYearResetEligibility(
supabase: SupabaseClient,
companyId: string,
periodId: string,
): Promise<FiscalYearResetEligibilityOutcome> {
const { data, error } = await supabase.rpc('get_fiscal_year_reset_eligibility', {
p_company_id: companyId,
p_period_id: periodId,
})
if (error) {
return { ok: false, code: 'FISCAL_YEAR_RESET_FAILED' }
}
const result = data as FiscalYearResetRpcResult | null
if (!result?.ok) {
return { ok: false, code: result?.code ?? 'FISCAL_YEAR_RESET_FAILED' }
}
return {
ok: true,
eligibility: {
eligible: result.eligible === true,
blockers: result.blockers ?? [],
period: result.period!,
counts: result.counts ?? { vouchers: 0, documents_to_detach: 0 },
},
}
}
/**
* Execute the reset. Runs on the service client when available (the
* authenticated role's 8s statement_timeout cannot fit a year-sized delete;
* see rpcClientForBulkDelete), passing the authorising user explicitly: on
* the service client auth.uid() is NULL and the RPC resolves its owner/admin
* gate from p_user_id instead. `confirmedName` must restate the year's label
* exactly (typed confirmation, verified again inside the RPC).
*/
export async function resetFiscalYear(
supabase: SupabaseClient,
companyId: string,
periodId: string,
userId: string,
confirmedName: string,
): Promise<FiscalYearResetOutcome> {
const rpcClient = await rpcClientForBulkDelete(supabase)
const { data, error } = await rpcClient.rpc('reset_fiscal_year', {
p_company_id: companyId,
p_period_id: periodId,
p_confirmed_name: confirmedName,
p_user_id: userId,
})
if (error) {
return { ok: false, code: 'FISCAL_YEAR_RESET_FAILED' }
}
const result = data as FiscalYearResetRpcResult | null
if (!result?.ok) {
return {
ok: false,
code: result?.code ?? 'FISCAL_YEAR_RESET_FAILED',
blockers: result?.blockers,
}
}
return {
ok: true,
deleted: result.deleted ?? 0,
detachedDocuments: result.detached_documents ?? 0,
periodName: result.period_name ?? '',
}
}
+32
View File
@@ -1526,6 +1526,38 @@ const PERIOD: Record<string, StructuredErrorEntry> = {
message_sv: 'Ett stängt räkenskapsår kan inte låsas upp.',
message_en: 'A closed fiscal year cannot be unlocked.',
},
FISCAL_YEAR_RESET_NOT_FOUND: {
httpStatus: 404,
message_sv: 'Räkenskapsåret kunde inte hittas.',
message_en: 'Fiscal year not found.',
},
FISCAL_YEAR_RESET_FORBIDDEN: {
httpStatus: 403,
message_sv: 'Endast företagets ägare eller administratörer kan nollställa ett räkenskapsår.',
message_en: 'Only company owners and admins can reset a fiscal year.',
},
FISCAL_YEAR_RESET_INELIGIBLE: {
httpStatus: 409,
message_sv: 'Räkenskapsåret kan inte nollställas i sitt nuvarande läge.',
message_en: 'The fiscal year cannot be reset in its current state.',
},
FISCAL_YEAR_RESET_CONFIRMATION_MISMATCH: {
httpStatus: 400,
message_sv: 'Räkenskapsårets namn stämmer inte överens.',
message_en: 'The fiscal year name does not match.',
},
FISCAL_YEAR_RESET_LINKED_ENTRIES: {
httpStatus: 409,
message_sv:
'Räkenskapsåret innehåller verifikat som är kopplade till andra poster (t.ex. anläggningstillgångar, periodiseringar eller lönekörningar). Ta bort eller ångra de kopplade flödena först. Inga ändringar har sparats.',
message_en:
'The fiscal year contains vouchers linked to other records (e.g. assets, accrual schedules or salary runs). Undo those flows first. No changes were saved.',
},
FISCAL_YEAR_RESET_FAILED: {
httpStatus: 500,
message_sv: 'Räkenskapsåret kunde inte nollställas. Inga ändringar har sparats.',
message_en: 'Failed to reset the fiscal year. No changes were saved.',
},
// Retired 2026-07-26: PERIOD_CREATE_BLOCKED_BY_OPEN_PERIODS. Creating the
// next räkenskapsår while a prior one is still fully open is no longer an
// error at all: BFL 5 kap 2 § forces the new year's affärshändelser to be
+23
View File
@@ -702,6 +702,29 @@ function journalEntryAuditEvent(
object,
details: [`Datum: ${fmtValue(oldState?.entry_date)}`, `Text: ${fmtValue(oldState?.description)}`],
})
case 'RESET_SNAPSHOT': {
// reset_fiscal_year archives the full verifikat content (accounts,
// amounts, line text) in a company-scoped row before deleting; the
// trigger's DELETE row that follows carries only the header.
const rawLines = oldState?.lines
const lineDetails = Array.isArray(rawLines)
? rawLines.map((raw) => {
const line = raw as Record<string, unknown>
return `${str(line.account_number) ?? '?'}: debet ${fmtValue(line.debit_amount)}, kredit ${fmtValue(line.credit_amount)}`
})
: []
return auditEvent(row, {
category: 'verifikation',
code: 'journal_entry.reset_snapshot',
event: 'Verifikationsinnehåll arkiverat inför nollställning',
object,
details: [
`Datum: ${fmtValue(oldState?.entry_date)}`,
`Text: ${fmtValue(oldState?.description)}`,
...lineDetails,
],
})
}
case 'COMMITTED_AT_OVERRIDE':
return auditEvent(row, {
category: 'verifikation',