Files
accounted/lib/errors/__tests__/get-structured-error.test.ts
T
Jakob Wennberg c74b19df1b Accounted rebrand + swarm-skill cleanup + bank-reconciliation fixes (#643)
* feat(reconciliation): close the bank-feed loop on voucher links and re-tag mis-typed opening balances

Two related fixes to bank reconciliation correctness:

1. Auto-reconcile on voucher link. Linking an invoice or supplier invoice to
   an existing voucher previously advanced only the invoice — the bank
   transaction that paid it kept sitting in the Transactions inbox with a null
   journal_entry_id. linkInvoiceToVoucher / linkSupplierInvoiceToVoucher now
   call autoReconcileTransactionForLinkedVoucher (lib/reconciliation), which
   links the bank transaction to the same verifikat when exactly one unbooked
   line matches it. Best-effort and post-commit: a failure here never fails the
   link. The result surfaces reconciledTransactionId; the inbox row leaves the
   list and the UI shows link_success_tx_reconciled.

2. Re-tag mis-typed opening balances. getReconciliationStatus and the GL-line
   matching RPCs identify a cash account's ingående balans solely by
   journal_entries.source_type='opening_balance'. Companies migrated from other
   systems often booked the bank IB as an ordinary voucher (source_type
   'import' or 'manual'), so it was never excluded and surfaced as a phantom
   reconciliation difference equal to the opening balance. Adds:
   - migration mark_entry_as_opening_balance: a GUC-gated carve-out in the
     immutability trigger plus a SECURITY DEFINER RPC that validates the entry
     (balance-sheet lines only, dated on a fiscal-period boundary), flips the
     source_type, and writes an audit row — no blanket data sweep.
   - POST /api/reconciliation/bank/mark-opening-balance + MarkOpeningBalanceSchema.
   - BankReconciliationView action to trigger it from the IB diff.

The gnubok_create_voucher executor now accepts a typed is_opening_balance flag
and derives source_type='opening_balance' only after validating class 1/2 lines
on the period start, so new IBs land correctly typed.

Covered by lib/reconciliation auto-reconcile tests, voucher-executors tests,
and a mark-entry-as-opening-balance pg-real test.

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

* chore: rebrand gnubok → Accounted and prune swarm agent skills

Product rebrand and skills housekeeping. No runtime behaviour change.

Rebrand: replace user-visible "gnubok" with "Accounted" across docs, READMEs,
in-code comments, doc-site content, MCP skill/resource prose, and the
gnubok-mcp package description. The MCP resource URI scheme is moved gnubok://
→ Accounted:// consistently across resource registrations, the event-type
comment, and the resource/skill tests. Deliberately preserved as stable
identifiers (NOT rebranded): the gnubok-company-id cookie, gnubok_sk_ / gnubok_inv_
token prefixes, the gnubok-mcp npm bridge name, and the AGI <gem:Programnamn>
value (kept 'gnubok' per its source comment — it is the software identifier sent
to Skatteverket and must not churn across visual rebrands).

Skills: remove the 27 swarm-* agent SKILL.md atoms (no longer used; already
absent from the agent_atom_registry in prod), refresh the remaining skill docs,
add the .claude/rules/ path-scoped rule set, and regenerate the
seed_agent_atom_bodies migration + .skill-body-manifest.json via
`npm run skills:generate` so the DB-backed skill bodies match the trimmed set.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 10:52:01 +02:00

87 lines
3.5 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import { getStructuredError } from '../get-structured-error'
describe('getStructuredError', () => {
it('extracts code from structured bookkeeping error', () => {
const result = getStructuredError({
error: {
code: 'JOURNAL_ENTRY_NOT_BALANCED',
message: 'Debits do not match credits',
details: { totalDebit: 100, totalCredit: 90 },
},
})
expect(result.code).toBe('JOURNAL_ENTRY_NOT_BALANCED')
expect(result.message_sv).toContain('balanserar inte')
expect(result.message_en).toContain('Debits')
expect(result.remediation?.description).toContain('Recalculate')
})
it('extracts code from typed error class with code property', () => {
class FakeBookkeepingError extends Error {
readonly code = 'ACCOUNTS_NOT_IN_CHART'
readonly accountNumbers = ['1930', '2641']
constructor() {
super('Accounts not in chart')
}
}
const result = getStructuredError(new FakeBookkeepingError())
expect(result.code).toBe('ACCOUNTS_NOT_IN_CHART')
expect(result.remediation?.resource).toBe('Accounted://chart-of-accounts')
})
it('infers PERIOD_NOT_LOCKED from message text', () => {
const result = getStructuredError(new Error('Period must be locked before closing'))
expect(result.code).toBe('PERIOD_NOT_LOCKED')
expect(result.remediation?.tool).toBe('gnubok_lock_period')
})
it('infers PERIOD_HAS_UNBOOKED_TRANSACTIONS from Swedish lock-error message', () => {
const result = getStructuredError(
new Error('Kan inte låsa period: 3 affärstransaktion(er) saknar bokföring.')
)
expect(result.code).toBe('PERIOD_HAS_UNBOOKED_TRANSACTIONS')
expect(result.remediation?.tool).toBe('gnubok_list_uncategorized_transactions')
})
it('produces INSUFFICIENT_SCOPE remediation with attempted scope', () => {
const result = getStructuredError(
new Error('Insufficient scope: this API key does not have the "bookkeeping:write" scope'),
{ attemptedScope: 'bookkeeping:write' }
)
expect(result.code).toBe('INSUFFICIENT_SCOPE')
expect(result.remediation?.description).toContain('"bookkeeping:write"')
expect(result.remediation?.resource).toBe('Accounted://capabilities')
})
it('infers TRANSACTION_ALREADY_CATEGORIZED', () => {
const result = getStructuredError(new Error('Transaction already has a journal entry'))
expect(result.code).toBe('TRANSACTION_ALREADY_CATEGORIZED')
expect(result.remediation?.tool).toBe('gnubok_uncategorize_transaction')
})
it('falls back to UNKNOWN_ERROR when no code or pattern matches', () => {
const result = getStructuredError(new Error('Something weird happened'))
expect(result.code).toBe('UNKNOWN_ERROR')
expect(result.remediation).toBeUndefined()
})
it('handles plain string errors', () => {
const result = getStructuredError('Period must be locked before closing')
expect(result.code).toBe('PERIOD_NOT_LOCKED')
expect(result.message_en).toBe('Period must be locked before closing')
})
it('handles null/undefined gracefully', () => {
const result = getStructuredError(null)
expect(result.code).toBe('UNKNOWN_ERROR')
expect(result.message_en).toBe('Unknown error')
expect(result.message_sv).toBeTruthy()
})
it('always returns Swedish message even with no match', () => {
const result = getStructuredError(new Error('Random gibberish XYZ'))
expect(result.message_sv).toBeTruthy()
expect(result.message_sv.length).toBeGreaterThan(0)
})
})