* fix(errors): close remaining raw-message leaks after #1048 (#337) Follow-up to PR #1048. No user-visible toast or response field can now carry a raw engine or DB message; everything maps through getErrorMessage or the structured-errors registry. - get-error-message: only normalize a code-carrying Error instance into the structured path when the registry knows the code; unknown codes (Node system errors, stray third-party codes, Error-wrapped Postgres SQLSTATEs) fall through to pattern match, Swedish check, Postgres map and the status/context/generic fallbacks instead of returning the raw message. New Swedish-detection pattern for "ar last" phrases and a known-pattern row for "already has a journal entry". - structured-errors: add CANNOT_EDIT_NON_DRAFT (409) and MANDATORY_DIMENSION_MISSING (400) rows, plus common Node network codes (ECONNREFUSED, ECONNRESET, ETIMEDOUT, ENOTFOUND, EAI_AGAIN, EPIPE) as retryable 503 transients with a Swedish message. - pending-operations commit + bulk-commit routes: map executor error strings through getErrorMessage before responding (raw stays in logs); Swedish passes through, English falls to status-appropriate Swedish. - pending page: toast via getErrorMessage, fixing raw English toasts and "[object Object]" for structured envelopes on commit/bulk/reject. - transactions book + journal-entries routes: untyped catch and DB list errors no longer return err.message; mapped or static Swedish instead. - invoice send + issue-credit-note: partial_failures reasons are now Swedish (raw provider/DB text logged, never returned). - Tests: new unknown-code/Error-instance suite, registry rows asserted, route tests updated off the pinned raw-English expectations. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(skatteverket): target the räkenskapsår for yearly VAT redovisningsperiod A yearly filer with a broken fiscal year has a Skatteverket period ending in its FY-end month, not December, and the panel's year state is never maintained in yearly mode (the year picker is replaced by the räkenskapsår selector), so calls targeted the wrong period even for calendar-FY companies filing after year end. The selected fiscal period now rides through the whole chain: panel query strings, draft/validate/ submit bodies, buildMomsuppgift (which resolves the FY bounds so the period id and the figures describe the same räkenskapsår), and the staged-commit path. MCP callers without a fiscal period keep the calendar fallback. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(deadlines): group same-day skattekonto deadlines into one card Moms, AGI and preliminärskatt legally share the skattekonto date (den 12:e), so a small monthly-moms employer saw 2-3 near-identical rows per month. Two or more pending system rows of the skattekonto family on the same due date now render as one grouped card with the date block once and each obligation as a sub-row keeping its own confirm-to-complete flow. Presentation only: rows, statuses, ICS feed unchanged. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(deadlines): KU + ROT/RUT + long-tail opt-in deadlines, rolling horizon Follow-ups from the #1028 audit left out of the #1057-#1060 fix stack, each with its own condition modeling: - kontrolluppgifter (KU10/KU20/KU31), due 31 Jan (SFL 24 kap. 1 §): opt-in flag suggested from ledger signals (2898 utdelning, 2393/2893 ägarlån; deliberately not 2091, see DECISIONS.md), AB only, mirroring the #1059 EU-sales suggest-and-confirm pattern. - rot_rut_begaran, due 31 Jan after the payment year (Lag 2009:194 8 §): rows generated only for years with actually PAID ROT/RUT invoices, resolved inside the generator; invoice-derived suggestion. - Long tail, explicit opt-in ('Fler deadlines'): OSS quarterly and IOSS monthly with a skipBankingDayAdjustment config flag (EU-law dates stand on weekends), Intrastat (10th banking day of the following month), punktskatt (ordinary skattedeklaration schedule), and fyllnadsinbetalning (12th of 2nd month over 30k / 3rd of 5th month, SFL 62:8 + 65 kap.). Kvarskatt deferred: needs a slutskattebesked date the app does not hold. - Rolling generation horizon: recurring types ~6 months ahead, annual 12 months, mirrored in the backfill expectation keys so the nightly cron never thrashes; regeneration now preserves manual in_progress status; one-time cleanup migration removes existing far-future rows. Migrations also applied to the staging branch, together with the previously missing 20260717xxxxxx deadline migrations (staging had drifted and lacked dismissed_at). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(arsredovisning): keep narrative editable after year-end close The narrative save endpoint refused writes whenever the fiscal period was closed/locked, but Verkstall bokslut closes the period before the arsredovisning text is ever written, so every legitimate save failed with PERIOD_LOCKED and the PDF fell back to placeholder text. The narrative is arsredovisning document text (ARL 6 kap.), not journal rakenskapsinformation, so the bookkeeping period lock does not apply. Saves are now refused only once a Bolagsverket submission for the period is registrerad (ARSREDOVISNING_REGISTERED, 409); the filed artifact was already frozen separately by the submissions immutability trigger. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(skatteverket): surface dead SKV connections and nudge reconnect Prod has ~70 companies that connected Skatteverket before the post-connect sync fix (#1010) and silently never synced skattekonto: the only reconnect prompt lived in the settings panel nobody revisits. - transactions-page banner when the connection is needs_reconsent or expired without refresh, linking to /settings/tax - pre-connect note in the connect panel: approve ALL behorigheter on Skatteverket's consent page (previously only shown after a failure) - wire the inert skattekonto.connection.expired event to an email nudge to the token owner; one send per consent episode via claim-first dedup in notification_log (type skv_connection_expired, partial unique index in migration 20260720090000, applied to staging) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(archive): per-year behandlingshistorik covers late-booked vouchers + Drive backup disclaimer The per-fiscal-year archive filtered audit rows by created_at within the period, dropping treatment history for bokslut entries, stornos and SIE imports booked after year end (BFNAR 2013:2 kap 8). The year archive now unions the date window with every audit row touching the period's journal entries and lines, deduped by audit id; line rows (company_id NULL by trigger design) are admitted via a scoped OR and reachable on the service-role backup path. ARCHIVE_FORMAT_VERSION 2->3 forces a one-time Drive re-upload so existing archives pick up the complete history. The Drive card on /import Exportera and the LASMIG texts now state the Drive copy is a convenience backup, not the BFL 7 kap legal archive. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(decisions): clarify Arsredovisning narrative save behavior on submission status * feat(invoices): gate payment links behind invoice settings opt-in The payment-link section (manual URL field + Stripe auto-create toggle) was visible on every invoice and auto-created Stripe links on send for any connected company. It is now opt-in per company: - new company_settings.invoice_payment_links_enabled, default false for everyone (no grandfathering of Stripe-connected companies) - invoice editor hides the whole section unless enabled; a draft that already carries a link still shows it so old links stay clearable - enforced server-side in maybeCreatePaymentLinkForInvoice (after the provider lookup, so the extension-free core build never queries), so dashboard, v1, MCP and recurring sends all obey it - new toggle on Settings -> Invoicing, saves instantly; sv/en strings Migration applied to the staging branch; prod gets it on merge. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(tests): add invoice_payment_links_enabled to company settings fixture The makeCompanySettings fixture missed the new required boolean, failing the core-only build's type check of tests/helpers.ts. Default false, matching the migration default. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Signed-off-by: Emil <emilmattsson14@gmail.com> * fix(review): address CodeRabbit, compliance and Swedish review findings Round 2 of PR #1076 review feedback, one change per accepted finding: - pending page: res.json() safe fallback in both commit paths so a non-JSON proxy response cannot surface a raw parser error - bulk-commit: map operation status enums to Swedish display labels in the 'Redan hanterad' skip message - payment-link settings: disable the toggle while a save is in flight to prevent out-of-order PUT responses - deadlines group card: route all UI strings through next-intl (deadlines namespace, sv + en) - archive export: scope the period audit entry lookup to posted/reversed, matching the rest of the export - error tests: assert the exact registry English message for ECONNREFUSED to lock the no-leakage contract - signal routes: log.warn when best-effort lookups swallow a Supabase error (forensics), keep fail-closed behavior - narrative route: document that 'avslutad' submissions deliberately stay editable (never registered at Bolagsverket) - VAT: yearly declarations without an explicit fiscalPeriodId now resolve the räkenskapsår ending in the target year from fiscal_periods instead of assuming a calendar FY (SFL 26 kap 10-11 §§); calendar fallback only when no fiscal period exists - deadlines: IOSS deadline no longer requires vat_registered (Art. 369s has no Swedish VAT registration prerequisite) Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Signed-off-by: Emil <emilmattsson14@gmail.com> --------- Signed-off-by: Emil <emilmattsson14@gmail.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
420 lines
16 KiB
TypeScript
420 lines
16 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { NextResponse } from 'next/server'
|
|
import {
|
|
createMockRequest,
|
|
parseJsonResponse,
|
|
createMockRouteParams,
|
|
createQueuedMockSupabase,
|
|
makeTransaction,
|
|
makeJournalEntry,
|
|
} from '@/tests/helpers'
|
|
import { eventBus } from '@/lib/events'
|
|
|
|
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
|
|
|
const requireAuthMock = vi.fn()
|
|
vi.mock('@/lib/auth/require-auth', () => ({
|
|
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
|
}))
|
|
|
|
vi.mock('@/lib/init', () => ({
|
|
ensureInitialized: vi.fn(),
|
|
}))
|
|
|
|
vi.mock('@/lib/company/context', () => ({
|
|
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
|
}))
|
|
|
|
const requireWriteMock = vi.fn()
|
|
vi.mock('@/lib/auth/require-write', () => ({
|
|
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
|
}))
|
|
|
|
const mockCreateJournalEntry = vi.fn()
|
|
vi.mock('@/lib/bookkeeping/engine', () => ({
|
|
createJournalEntry: (...args: unknown[]) => mockCreateJournalEntry(...args),
|
|
}))
|
|
|
|
// Booking-time duplicate guard: mocked so route tests exercise the WIRING
|
|
// (warn / force / mismatch); the detection query itself is unit-tested in
|
|
// lib/transactions/__tests__/booking-duplicate-detection.test.ts.
|
|
const mockDetectDup = vi.fn()
|
|
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
|
detectBookingDuplicate: (...args: unknown[]) => mockDetectDup(...args),
|
|
}))
|
|
|
|
// Behandlingshistorik append: mocked so we can assert the dismissal is
|
|
// persisted without reaching the service-role client.
|
|
const mockAppendProcessingHistory = vi.fn()
|
|
vi.mock('@/lib/processing-history/append', () => ({
|
|
appendProcessingHistory: (...args: unknown[]) => mockAppendProcessingHistory(...args),
|
|
}))
|
|
|
|
import { POST } from '../route'
|
|
|
|
const VALID_UUID = '550e8400-e29b-41d4-a716-446655440000'
|
|
const SIBLING_UUID = '660e8400-e29b-41d4-a716-446655440111'
|
|
const OTHER_UUID = '770e8400-e29b-41d4-a716-446655440222'
|
|
const VOUCHER_JE_UUID = '880e8400-e29b-41d4-a716-446655440333'
|
|
|
|
describe('POST /api/transactions/[id]/book', () => {
|
|
const mockUser = { id: 'user-1', email: 'test@test.se' }
|
|
const validBody = {
|
|
fiscal_period_id: VALID_UUID,
|
|
entry_date: '2025-01-15',
|
|
description: 'Test booking',
|
|
lines: [
|
|
{ account_number: '6200', debit_amount: 500, credit_amount: 0 },
|
|
{ account_number: '1930', debit_amount: 0, credit_amount: 500 },
|
|
],
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
reset()
|
|
eventBus.clear()
|
|
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
|
|
requireWriteMock.mockResolvedValue({ ok: true })
|
|
// No booking-duplicate by default; guard tests override per-case.
|
|
mockDetectDup.mockResolvedValue(null)
|
|
mockAppendProcessingHistory.mockResolvedValue('evt-1')
|
|
})
|
|
|
|
it('returns 401 when not authenticated', async () => {
|
|
requireAuthMock.mockResolvedValue({
|
|
user: null,
|
|
supabase: mockSupabase,
|
|
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
|
})
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: validBody,
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(401)
|
|
expect(body).toEqual({ error: 'Unauthorized' })
|
|
})
|
|
|
|
it('returns 403 when the caller is a viewer', async () => {
|
|
requireWriteMock.mockResolvedValue({
|
|
ok: false,
|
|
response: NextResponse.json({ error: 'Forbidden' }, { status: 403 }),
|
|
})
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: validBody,
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse(response)
|
|
|
|
expect(status).toBe(403)
|
|
expect(body).toEqual({ error: 'Forbidden' })
|
|
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('returns 400 when missing required fields', async () => {
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: { fiscal_period_id: VALID_UUID },
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(400)
|
|
expect(body.error).toBe('Validation failed')
|
|
})
|
|
|
|
it('returns 404 when transaction not found', async () => {
|
|
enqueue({ data: null, error: { message: 'Not found' } })
|
|
|
|
const request = createMockRequest('/api/transactions/tx-999/book', {
|
|
method: 'POST',
|
|
body: validBody,
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-999' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(404)
|
|
expect(body.error).toBe('Transaction not found')
|
|
})
|
|
|
|
it('returns 409 when transaction already has a journal entry', async () => {
|
|
const tx = makeTransaction({
|
|
id: 'tx-1',
|
|
journal_entry_id: 'je-existing',
|
|
})
|
|
enqueue({ data: tx, error: null })
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: validBody,
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(409)
|
|
expect(body.error).toBe('Transaction already has a journal entry')
|
|
})
|
|
|
|
it('returns 400 when journal entry creation fails (engine error)', async () => {
|
|
const tx = makeTransaction({ id: 'tx-1', journal_entry_id: null })
|
|
enqueue({ data: tx, error: null })
|
|
|
|
mockCreateJournalEntry.mockRejectedValue(new Error('Entry is not balanced'))
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: validBody,
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(400)
|
|
// Untyped engine errors map to the Swedish context fallback; the raw
|
|
// English message must never reach the response field (issue #337).
|
|
expect(body.error).toBe('Kunde inte hantera transaktionen. Försök igen.')
|
|
expect(body.error).not.toContain('not balanced')
|
|
})
|
|
|
|
it('creates journal entry and links to transaction (happy path)', async () => {
|
|
const tx = makeTransaction({
|
|
id: 'tx-1',
|
|
amount: -500,
|
|
journal_entry_id: null,
|
|
})
|
|
const je = makeJournalEntry({ id: 'je-new' })
|
|
|
|
// Fetch transaction
|
|
enqueue({ data: tx, error: null })
|
|
|
|
mockCreateJournalEntry.mockResolvedValue(je)
|
|
|
|
// Update transaction
|
|
enqueue({ data: null, error: null })
|
|
|
|
const emitSpy = vi.spyOn(eventBus, 'emit')
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: validBody,
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{
|
|
success: boolean
|
|
journal_entry_id: string
|
|
data: { id: string }
|
|
}>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.success).toBe(true)
|
|
expect(body.journal_entry_id).toBe('je-new')
|
|
expect(body.data.id).toBe('je-new')
|
|
|
|
expect(mockCreateJournalEntry).toHaveBeenCalledWith(expect.anything(), 'company-1', 'user-1', {
|
|
fiscal_period_id: VALID_UUID,
|
|
entry_date: '2025-01-15',
|
|
description: 'Test booking',
|
|
source_type: 'bank_transaction',
|
|
source_id: 'tx-1',
|
|
lines: validBody.lines,
|
|
})
|
|
|
|
expect(emitSpy).toHaveBeenCalledWith(
|
|
expect.objectContaining({ type: 'transaction.categorized' })
|
|
)
|
|
})
|
|
|
|
it('returns 500 when transaction update fails', async () => {
|
|
const tx = makeTransaction({ id: 'tx-1', journal_entry_id: null })
|
|
const je = makeJournalEntry({ id: 'je-new' })
|
|
|
|
enqueue({ data: tx, error: null })
|
|
mockCreateJournalEntry.mockResolvedValue(je)
|
|
// Update fails
|
|
enqueue({ data: null, error: { message: 'Update failed' } })
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: validBody,
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(500)
|
|
expect(body.error).toBe('Failed to update transaction')
|
|
})
|
|
|
|
// ── Booking-time duplicate guard ──────────────────────────────────────
|
|
|
|
it('returns 409 duplicate warning when a booked sibling shares date+amount', async () => {
|
|
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
|
|
enqueue({ data: tx, error: null }) // fetch
|
|
mockDetectDup.mockResolvedValue({
|
|
transaction_id: SIBLING_UUID,
|
|
journal_entry_id: 'je-existing',
|
|
voucher_label: 'A142',
|
|
entry_date: '2025-01-15',
|
|
description: 'redan bokförd',
|
|
amount: -500,
|
|
})
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', { method: 'POST', body: validBody })
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{
|
|
error: { code: string; details: { candidate: { transaction_id: string; voucher_label: string } } }
|
|
}>(response)
|
|
|
|
expect(status).toBe(409)
|
|
expect(body.error.code).toBe('TRANSACTION_BOOK_POSSIBLE_DUPLICATE')
|
|
expect(body.error.details.candidate.transaction_id).toBe(SIBLING_UUID)
|
|
expect(body.error.details.candidate.voucher_label).toBe('A142')
|
|
// Critically: no verifikat is created when a duplicate is flagged.
|
|
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
|
|
// Blocking a duplicate is not a dismissal: nothing is logged.
|
|
expect(mockAppendProcessingHistory).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('books when force=true and the expected sibling still matches', async () => {
|
|
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
|
|
const je = makeJournalEntry({ id: 'je-new' })
|
|
enqueue({ data: tx, error: null }) // fetch
|
|
enqueue({ data: null, error: null }) // update
|
|
mockDetectDup.mockResolvedValue({
|
|
transaction_id: SIBLING_UUID,
|
|
journal_entry_id: 'je-existing',
|
|
voucher_label: 'A142',
|
|
entry_date: '2025-01-15',
|
|
description: null,
|
|
amount: -500,
|
|
})
|
|
mockCreateJournalEntry.mockResolvedValue(je)
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: { ...validBody, force: true, expected_duplicate_transaction_id: SIBLING_UUID },
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{ success: boolean; journal_entry_id: string }>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.success).toBe(true)
|
|
expect(body.journal_entry_id).toBe('je-new')
|
|
expect(mockCreateJournalEntry).toHaveBeenCalledTimes(1)
|
|
// The dismissal is recorded to behandlingshistorik (BFNAR 2013:2 kap 8).
|
|
expect(mockAppendProcessingHistory).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
eventType: 'BankTransactionDuplicateDismissed',
|
|
aggregateType: 'BankTransaction',
|
|
aggregateId: 'tx-1',
|
|
actor: { type: 'user', id: 'user-1' },
|
|
payload: expect.objectContaining({
|
|
transaction_id: 'tx-1',
|
|
dismissed_transaction_id: SIBLING_UUID,
|
|
}),
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('returns 409 when a ledger-only voucher (no sibling transaction) already books this movement', async () => {
|
|
const tx = makeTransaction({ id: 'tx-1', amount: 98565, journal_entry_id: null })
|
|
enqueue({ data: tx, error: null }) // fetch
|
|
// A voucher-keyed candidate has no transaction_id: it's bound by je id.
|
|
mockDetectDup.mockResolvedValue({
|
|
transaction_id: null,
|
|
journal_entry_id: VOUCHER_JE_UUID,
|
|
voucher_label: 'A2',
|
|
entry_date: '2026-03-30',
|
|
description: 'Inbetalning kundfaktura 2026001',
|
|
amount: 98565,
|
|
})
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', { method: 'POST', body: validBody })
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{
|
|
error: { code: string; details: { candidate: { transaction_id: string | null; journal_entry_id: string } } }
|
|
}>(response)
|
|
|
|
expect(status).toBe(409)
|
|
expect(body.error.code).toBe('TRANSACTION_BOOK_POSSIBLE_DUPLICATE')
|
|
expect(body.error.details.candidate.transaction_id).toBeNull()
|
|
expect(body.error.details.candidate.journal_entry_id).toBe(VOUCHER_JE_UUID)
|
|
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('books a voucher-keyed duplicate when force=true binds the expected journal_entry_id', async () => {
|
|
const tx = makeTransaction({ id: 'tx-1', amount: 98565, journal_entry_id: null })
|
|
const je = makeJournalEntry({ id: 'je-new' })
|
|
enqueue({ data: tx, error: null }) // fetch
|
|
enqueue({ data: null, error: null }) // update
|
|
mockDetectDup.mockResolvedValue({
|
|
transaction_id: null,
|
|
journal_entry_id: VOUCHER_JE_UUID,
|
|
voucher_label: 'A2',
|
|
entry_date: '2026-03-30',
|
|
description: null,
|
|
amount: 98565,
|
|
})
|
|
mockCreateJournalEntry.mockResolvedValue(je)
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: { ...validBody, force: true, expected_duplicate_journal_entry_id: VOUCHER_JE_UUID },
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{ success: boolean; journal_entry_id: string }>(response)
|
|
|
|
expect(status).toBe(200)
|
|
expect(body.success).toBe(true)
|
|
expect(mockCreateJournalEntry).toHaveBeenCalledTimes(1)
|
|
expect(mockAppendProcessingHistory).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
eventType: 'BankTransactionDuplicateDismissed',
|
|
payload: expect.objectContaining({
|
|
dismissed_transaction_id: null,
|
|
dismissed_journal_entry_id: VOUCHER_JE_UUID,
|
|
}),
|
|
}),
|
|
)
|
|
})
|
|
|
|
it('rejects force=true when the expected sibling no longer matches the detected one', async () => {
|
|
const tx = makeTransaction({ id: 'tx-1', amount: -500, journal_entry_id: null })
|
|
enqueue({ data: tx, error: null }) // fetch
|
|
mockDetectDup.mockResolvedValue({
|
|
transaction_id: SIBLING_UUID, // server detects this one…
|
|
journal_entry_id: 'je-existing',
|
|
voucher_label: 'A142',
|
|
entry_date: '2025-01-15',
|
|
description: null,
|
|
amount: -500,
|
|
})
|
|
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: { ...validBody, force: true, expected_duplicate_transaction_id: OTHER_UUID }, // …caller claims another
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
|
|
|
|
expect(status).toBe(409)
|
|
expect(body.error.code).toBe('TRANSACTION_BOOK_FORCE_CANDIDATE_MISMATCH')
|
|
expect(mockCreateJournalEntry).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('returns 400 when force=true is sent without expected_duplicate_transaction_id', async () => {
|
|
const request = createMockRequest('/api/transactions/tx-1/book', {
|
|
method: 'POST',
|
|
body: { ...validBody, force: true },
|
|
})
|
|
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
|
const { status } = await parseJsonResponse<{ error: string }>(response)
|
|
|
|
expect(status).toBe(400)
|
|
})
|
|
})
|