Files
accounted/lib/bookkeeping/__tests__/voucher-atomicity.test.ts
T
Jakob WennbergandClaude Opus 4.7 adf58a51c0 Prompt to activate missing BAS accounts at commit (#308)
* feat: prompt to activate missing BAS accounts at commit

Booking to an account not in the active chart previously threw a
generic 400 "Account(s) not found: 5010" and the user had to leave
the form to enable the account via /bookkeeping > BAS-katalog.

- New AccountsNotInChartError thrown from resolveAccountIds in the
  engine (and the parallel resolver in core/storno-service). The
  query also now filters on is_active=true, so deactivated accounts
  are treated the same as never-added ones.
- API routes that call the engine (journal-entries, reverse, correct,
  transactions/book + match-invoice + match-supplier-invoice +
  uncategorize, invoices/mark-paid, supplier-invoices + mark-paid +
  credit, salary/runs/correct, import/opening-balance/execute,
  pending-operations/commit) catch the typed error and return a
  structured 400: { error: { code: ACCOUNTS_NOT_IN_CHART,
  account_numbers, message } }.
- /api/bookkeeping/accounts/activate now also reactivates rows that
  already exist but are is_active=false, not only INSERTs. Returns
  { activated, reactivated, skipped, unknown }.
- New GET /api/bookkeeping/accounts/bas-lookup?numbers=... resolves
  BAS names client-side so the dialog can show "5010 · Lokalhyra"
  without bundling the full 1,276-account catalog.
- ActivateAccountsDialog lists the missing accounts (BAS names + any
  unknown non-BAS numbers) and confirms with a single action.
- useSubmitWithAccountActivation wraps an async submit: on
  ACCOUNTS_NOT_IN_CHART it opens the dialog, activates on confirm,
  then retries the original submit so the user never re-enters data.
- AccountCombobox accepts any 4-digit numeric value, not just items
  from the active chart — the activation dialog handles the rest.
- JournalEntryForm wired to the hook + dialog. Other submit surfaces
  now surface a clear Swedish message ("Följande konton behöver
  aktiveras: …") via getErrorMessage; wiring the dialog into those
  is an additive follow-up.

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

* docs: sync CLAUDE.md with current codebase state

Catch-up on growth since the last CLAUDE.md revision:
- Integrations list now includes AWS Bedrock, Upstash Redis,
  Google Drive, Recharts, PDF.js, @react-pdf/renderer, xlsx,
  fuse.js, ics.
- Extension table reflects cloud-backup enabled; adds
  inbox-smart-match and example-logger; reorders to match current
  extensions.config.json.
- Updated counts: 36 event types (was 30+), 35 MCP tools (was 26),
  ~60 tables (was ~47), 118 migrations (was 93), 19 report
  endpoints (was 16), 20 report generators (was 17).
- lib/ directory table now covers salary, providers,
  company-lookup, processing-history, support.ts; removes the
  deleted settings/ subdir.
- App routes table adds /salary/*, /help, /settings/salary,
  /settings/backup.
- API endpoints table adds /api/salary/*, /api/support/contact,
  /api/account/delete, /api/audit-trail/*, /api/log,
  /api/currency/rate, top-level extension routes.
- Tables section adds Salary, Third-party providers, Inbox &
  Migration groups; removes salary_payments (replaced by
  salary_runs + salary_line_items).
- Skills list updated to enumerate the Swedish domain skills by
  name instead of the old single /swedish-bookkeeping.

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

* fix: address PR review feedback on account activation

Seven fixes based on Greptile + Swedish compliance review on #308.

- ActivateAccountsDialog: disable the confirm button when any
  entered number isn't a valid BAS account. Previously activation
  would succeed for the knowns and the retry would immediately
  fail again on the unknowns, giving a confusing double-toast UX.
- pending-operations/commit: revert commitSendInvoice and
  commitMarkInvoiceSent to swallow AccountsNotInChartError
  silently. The prior PR upgrade made these blocking, which
  regressed invoice delivery for users whose AR accounts are
  inactive — and since the activation dialog isn't wired into
  those flows yet, there's no one-click recovery. The silent
  catches now append an InvoiceJournalEntrySkipped event to
  processing_history so the missing verifikation is actionable
  in audit trails rather than silently understating the
  momsdeklaration (revenue / utgående moms unposted).
- engine.reverseEntry: resolve account IDs with includeInactive=true
  so storno of an already-committed entry goes through even when
  the user has since deactivated one of its accounts. Blocking
  the reversal would leave the original entry uncorrected in
  violation of BFL 5 kap 5§ (rättelse must be documented). The
  default (includeInactive=false) still applies to createDraftEntry
  so new bookings to inactive accounts continue to trigger the
  activation dialog.
- supplier-invoices POST + credit: roll back the just-inserted
  supplier_invoices row (items cascade-delete) on any JE failure,
  not only AccountsNotInChartError. An orphan supplier_invoices
  row without a registration / credit JE leaves leverantörsskuld
  (2440) and ingående moms (2641) unposted — a silent
  understatement / overstatement in the momsdeklaration (ML
  2023:200 / BFL 5 kap). The catch now returns a clear Swedish
  error message for non-activation failures (typically period
  lock or DB error) instead of silently logging.

Test mocks for chart_of_accounts updated for the new query chain
(eq.in.eq instead of eq.eq.in after the is_active conditional).

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-22 09:58:54 +02:00

332 lines
11 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { JournalEntryStatus } from '@/types'
// Mock event bus
vi.mock('@/lib/events', () => ({
eventBus: { emit: vi.fn().mockResolvedValue([]) },
}))
import { commitEntry, getNextVoucherNumber, createJournalEntry } from '../engine'
describe('voucher number atomicity', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('getNextVoucherNumber returns incrementing numbers from RPC', async () => {
let callCount = 0
const supabase = {
rpc: vi.fn().mockImplementation(() => {
callCount++
return Promise.resolve({ data: callCount, error: null })
}),
}
const n1 = await getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'A')
const n2 = await getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'A')
const n3 = await getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'A')
expect(n1).toBe(1)
expect(n2).toBe(2)
expect(n3).toBe(3)
expect(supabase.rpc).toHaveBeenCalledTimes(3)
})
it('getNextVoucherNumber throws on RPC error', async () => {
const supabase = {
rpc: vi.fn().mockResolvedValue({ data: null, error: { message: 'connection lost' } }),
}
await expect(
getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'A')
).rejects.toThrow('Failed to get next voucher number: connection lost')
})
/**
* commitEntry uses the atomic commit_journal_entry RPC which increments the
* voucher sequence and updates the entry status in one transaction.
* If the RPC fails (e.g., balance trigger rejection), the sequence increment
* rolls back — no burned number, no gap.
*/
it('commitEntry RPC failure does not burn a sequence number', async () => {
const supabase = {
from: vi.fn(),
rpc: vi.fn().mockResolvedValue({
data: null,
error: { message: 'Journal entry is not balanced: debit=1000 credit=500' },
}),
}
await expect(
commitEntry(supabase as never, 'co-1', 'user-1', 'entry-1')
).rejects.toThrow('Failed to commit journal entry: Journal entry is not balanced')
// The atomic RPC was called — it failed, rolling back both the
// sequence increment and the status update. No burned number.
expect(supabase.rpc).toHaveBeenCalledWith('commit_journal_entry', {
p_company_id: 'co-1',
p_entry_id: 'entry-1',
p_commit_method: null,
p_rubric_version: null,
})
// from() was never called — the RPC handles everything atomically
expect(supabase.from).not.toHaveBeenCalled()
})
it('commitEntry succeeds via atomic RPC and returns posted entry', async () => {
const postedEntry = {
id: 'entry-1',
company_id: 'co-1',
fiscal_period_id: 'fp-1',
voucher_series: 'A',
voucher_number: 3,
status: 'posted' as JournalEntryStatus,
lines: [],
}
const supabase = {
from: vi.fn().mockImplementation(() => ({
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({ data: postedEntry, error: null }),
}),
}),
})),
// Atomic RPC returns the assigned voucher number
rpc: vi.fn().mockResolvedValue({ data: [{ voucher_number: 3 }], error: null }),
}
const result = await commitEntry(supabase as never, 'co-1', 'user-1', 'entry-1')
expect(result.voucher_number).toBe(3)
expect(result.status).toBe('posted')
expect(supabase.rpc).toHaveBeenCalledWith('commit_journal_entry', {
p_company_id: 'co-1',
p_entry_id: 'entry-1',
p_commit_method: null,
p_rubric_version: null,
})
// from() called once to fetch the complete entry with lines
expect(supabase.from).toHaveBeenCalledWith('journal_entries')
})
/**
* getNextVoucherNumber is still used by reverseEntry and storno-service.
* Those flows INSERT a new entry (not UPDATE a draft), so the atomic
* commit_journal_entry RPC doesn't apply. Burned numbers can still occur
* in reversal/correction flows if the INSERT fails after the counter
* increments. This is documented and expected.
*/
it('getNextVoucherNumber remains available for reversal/storno flows', async () => {
const supabase = {
rpc: vi.fn().mockResolvedValue({ data: 7, error: null }),
}
const num = await getNextVoucherNumber(supabase as never, 'co-1', 'fp-1', 'B')
expect(num).toBe(7)
expect(supabase.rpc).toHaveBeenCalledWith('next_voucher_number', {
p_company_id: 'co-1',
p_fiscal_period_id: 'fp-1',
p_series: 'B',
})
})
})
describe('createJournalEntry orphan draft cleanup', () => {
beforeEach(() => {
vi.clearAllMocks()
})
/**
* Regression test for #292: when commit_journal_entry RPC fails (e.g. overload
* ambiguity, balance trigger, period lock), the draft created by createDraftEntry
* must be cancelled so it doesn't linger as an undeletable stuck draft.
*/
it('cancels the draft when commit RPC fails', async () => {
const draftId = 'entry-1'
const cancelUpdate = vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockResolvedValue({ error: null }),
}),
})
const supabase = {
from: vi.fn().mockImplementation((table: string) => {
if (table === 'fiscal_periods') {
return {
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({
data: { name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
error: null,
}),
}),
}),
}),
}
}
if (table === 'chart_of_accounts') {
return {
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
in: vi.fn().mockReturnValue({
eq: vi.fn().mockResolvedValue({
data: [
{ account_number: '1930', id: 'acc-1930' },
{ account_number: '1510', id: 'acc-1510' },
],
error: null,
}),
}),
}),
}),
}
}
if (table === 'journal_entries') {
return {
insert: vi.fn().mockReturnValue({
select: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({
data: { id: draftId, status: 'draft' as JournalEntryStatus },
error: null,
}),
}),
}),
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({
data: { id: draftId, status: 'draft', lines: [] },
error: null,
}),
}),
}),
update: cancelUpdate,
}
}
if (table === 'journal_entry_lines') {
return {
insert: vi.fn().mockResolvedValue({ error: null }),
}
}
return {}
}),
// commit_journal_entry RPC fails — simulates overload ambiguity or balance error
rpc: vi.fn().mockResolvedValue({
data: null,
error: { message: 'Could not choose the best candidate function' },
}),
}
await expect(
createJournalEntry(supabase as never, 'co-1', 'user-1', {
fiscal_period_id: 'fp-1',
entry_date: '2025-06-15',
description: 'Payment',
source_type: 'invoice_paid',
lines: [
{ account_number: '1930', debit_amount: 1000, credit_amount: 0 },
{ account_number: '1510', debit_amount: 0, credit_amount: 1000 },
],
})
).rejects.toThrow('Failed to commit journal entry')
// The orphan draft must have been cancelled with CAS guard (status='draft')
expect(cancelUpdate).toHaveBeenCalledWith({ status: 'cancelled' })
const firstEq = cancelUpdate.mock.results[0].value.eq
expect(firstEq).toHaveBeenCalledWith('id', draftId)
const secondEq = firstEq.mock.results[0].value.eq
expect(secondEq).toHaveBeenCalledWith('status', 'draft')
})
it('surfaces original commit error even if cleanup update fails', async () => {
const draftId = 'entry-1'
const supabase = {
from: vi.fn().mockImplementation((table: string) => {
if (table === 'fiscal_periods') {
return {
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({
data: { name: 'FY 2025', period_start: '2025-01-01', period_end: '2025-12-31' },
error: null,
}),
}),
}),
}),
}
}
if (table === 'chart_of_accounts') {
return {
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
in: vi.fn().mockReturnValue({
eq: vi.fn().mockResolvedValue({
data: [
{ account_number: '1930', id: 'acc-1930' },
{ account_number: '1510', id: 'acc-1510' },
],
error: null,
}),
}),
}),
}),
}
}
if (table === 'journal_entries') {
return {
insert: vi.fn().mockReturnValue({
select: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({
data: { id: draftId, status: 'draft' as JournalEntryStatus },
error: null,
}),
}),
}),
select: vi.fn().mockReturnValue({
eq: vi.fn().mockReturnValue({
single: vi.fn().mockResolvedValue({
data: { id: draftId, status: 'draft', lines: [] },
error: null,
}),
}),
}),
// Cleanup throws — original error should still propagate
update: vi.fn().mockImplementation(() => {
throw new Error('Network error during rollback')
}),
}
}
if (table === 'journal_entry_lines') {
return {
insert: vi.fn().mockResolvedValue({ error: null }),
}
}
return {}
}),
rpc: vi.fn().mockResolvedValue({
data: null,
error: { message: 'Period is locked' },
}),
}
await expect(
createJournalEntry(supabase as never, 'co-1', 'user-1', {
fiscal_period_id: 'fp-1',
entry_date: '2025-06-15',
description: 'Payment',
source_type: 'invoice_paid',
lines: [
{ account_number: '1930', debit_amount: 1000, credit_amount: 0 },
{ account_number: '1510', debit_amount: 0, credit_amount: 1000 },
],
})
// Original commit error surfaces, not the cleanup error
).rejects.toThrow('Period is locked')
})
})