Files
accounted/app/api/transactions/[id]/__tests__/route.test.ts
T
Jakob WennbergandClaude Opus 4.8 b5c3c3ec04 fix(reconciliation): surface bank tx + match to existing verifikat, delete UX, DPA links (#623)
* fix(reconciliation): surface bank transactions via robust cash_account_id scoping

The per-account reconciliation scoping silently returned zero transactions for
companies whose rows were NULL or mis-assigned mid-backfill (e.g. Arcim: 138
transactions, 101 unbooked, yet Bankavstämning showed "0 kr" while the 1930 GL
movement and a large difference still displayed). Two causes, both fixed:

- scopeTransactionsToAccount used a fragile nested or(...,and(is.null,...))
  PostgREST filter. Replace it with a flat, reliable
  `currency = X AND (cash_account_id = id OR cash_account_id IS NULL)` and share
  the one implementation with /api/transactions so the status card and the lists
  can never drift.
- The original best-effort backfill only touched NULL rows and an earlier
  revision mis-assigned cash_account_id (the since-fixed min(uuid) bug), which
  migrations cannot self-correct. Add an idempotent repair migration that
  re-seeds the default 1930 account and re-derives cash_account_id (correcting
  non-NULL mis-assignments) for booked rows and single-account companies.

Also localise manualLink's user-facing errors to Swedish. Adds unit coverage for
the new filter shape and pg-real coverage for the repair (incl. the Arcim
single-account reproduction).

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

* feat(transactions): match a bank transaction to an existing verifikat

Adds a "Matcha mot befintlig verifikation" action to the Transactions inbox so a
bank line that is already booked elsewhere (a salary run, a Fortnox/manual
voucher, an invoice paid from the invoice page) can be linked to that existing
verifikat with no new bokföring — the capability previously lived only in
Reports → Bankavstämning.

- Extract the searchable MatchVerifikationPicker into a shared client component.
- New MatchVoucherDialog: resolves the tx's cash account, fetches candidates
  ranked server-side by reconciliation confidence, links via
  /api/reconciliation/bank/link (so the link is undoable in Bankavstämning).
- unmatched-entries route gains an optional transaction_id that ranks candidates
  (ranking stays server-side; the recon lib is not client-safe).
- Inbox row's overflow (⋯) menu gains the new action.

Also fixes the Bankavstämning view: editing the date no longer auto-reloads
(applies on Filtrera / account change only) and Datum till defaults to today.

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

* fix(transactions): actionable Swedish errors when a bank tx cannot be deleted

The delete route returned a hardcoded English 409 that getErrorMessage mapped to
the misleading generic "En konflikt uppstod. Ladda om sidan...". Return
structured bilingual envelopes instead:

- TRANSACTION_DELETE_BOOKED (409) for a booked/linked row — steers the user to
  unlink in Bankavstämning or storna the voucher.
- TRANSACTION_DELETE_HAS_AUDIT_TRAIL (409) for the real, common case where an
  unbooked row carries payment_match_log rows: the cascade hits the
  audit-immutability trigger (P0001), previously surfaced as a bare 500. Steers
  the user to match-to-voucher or ignore instead.

Updates the DELETE test suite and adds the P0001 case.

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

* feat(settings): surface DPA and privacy policy links

The /dpa page (personuppgiftsbiträdesavtal, GDPR Art. 28) was complete but
linked from nowhere. Add a "Sekretess och avtal" card on Inställningar → Konto
linking to /privacy and /dpa, and a reciprocal link to the DPA from the privacy
policy's sub-processor section. (The DPA already links back to /privacy.)

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

* fix(review): address PR #623 feedback

- unmatched-entries: when transaction_id is supplied but resolves to no row in
  the caller's company, return an empty candidate list instead of silently
  falling back to the full unranked list (Compliance Swarm V8.2.1, high).
- MatchVoucherDialog: preserve a manually-picked voucher when the candidate
  list reloads (e.g. "Visa alla datum") instead of discarding it (Greptile P2).
- DELETE /api/transactions/[id]: return the 404 as the structured
  { error: { code, message, message_en } } envelope like the handler's other
  errors, for a uniform contract (Greptile P2). Test updated.

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

* feat(bookkeeping): allow editing notes on a committed journal entry

Saving a note on a posted verifikation failed with "Committed entries are
immutable": enforce_journal_entry_immutability() had no posted→posted path, so a
notes-only UPDATE fell through to the final RAISE. `notes` is internal annotation
metadata (not verifikation content under BFL 5 kap. / BFNAR 2013:2), so add a
narrow carve-out that permits a notes-only change on a committed entry — verified
with a whole-row to_jsonb() diff so any other field change still raises, and only
when status is unchanged. Period-lock enforcement is unaffected.

CREATE OR REPLACE in a new migration (same pattern as
20260428160000_fix_journal_entry_immutability_delete_bypass); the migration-017
protections are extended, never weakened. Covered by a pg-real test asserting a
notes edit succeeds while amount/description/account edits still fail.

(Already applied to production; committing the file + test for repo consistency.)

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

* fix(sandbox): make pre-staged pending operations executor-complete

The seeded pending_operations existed only as display previews — approving them
failed because commit executors in lib/pending-operations/commit.ts validate
required fields on "Godkänn". Seed a backing invoice_inbox_items row and fill the
supplier-invoice and categorize params with every field the executors require
(inbox_item_id, full items array; real uncategorized transaction_id + category),
so the sandbox approval queue is actually approvable end to end.

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-01 21:08:06 +02:00

308 lines
11 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
makeTransaction,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createClient: () => Promise.resolve(mockSupabase),
}))
vi.mock('@/lib/company/context', () => ({
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
}))
vi.mock('@/lib/auth/require-write', () => ({
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
}))
// PATCH (edit title) goes through withRouteContext → requireAuth.
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: vi.fn(),
}))
vi.mock('@/lib/sandbox/guard', () => ({
guardSandbox: vi.fn(),
}))
import { DELETE, PATCH } from '../route'
import { requireAuth } from '@/lib/auth/require-auth'
import { guardSandbox } from '@/lib/sandbox/guard'
import { NextResponse } from 'next/server'
describe('DELETE /api/transactions/[id]', () => {
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
})
it('returns 401 when not authenticated', async () => {
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(401)
expect(body).toEqual({ error: 'Unauthorized' })
})
it('returns 404 when transaction not found', async () => {
enqueue({ data: null, error: { message: 'Not found' } })
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(404)
expect((body as { error: { code: string } }).error.code).toBe('TRANSACTION_NOT_FOUND')
})
it('returns 409 with an actionable code when transaction has a journal entry', async () => {
const tx = makeTransaction({ journal_entry_id: 'je-1', bank_connection_id: null, import_source: null })
enqueue({ data: tx, error: null })
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_DELETE_BOOKED')
// Swedish, actionable — not the generic "Ladda om sidan" 409 fallback.
expect(body.error.message).toMatch(/Bankavstämning|storna/)
})
it('allows deleting unbooked bank-synced transactions', async () => {
const tx = makeTransaction({ bank_connection_id: 'bc-1', journal_entry_id: null, import_source: null })
enqueue({ data: tx, error: null }) // fetch
enqueue({ data: null, error: null }) // delete
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(body).toEqual({ success: true })
})
it('allows deleting unbooked imported transactions', async () => {
const tx = makeTransaction({ import_source: 'csv_nordea', journal_entry_id: null, bank_connection_id: null })
enqueue({ data: tx, error: null }) // fetch
enqueue({ data: null, error: null }) // delete
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(body).toEqual({ success: true })
})
it('deletes a manually added unbooked transaction', async () => {
const tx = makeTransaction({ journal_entry_id: null, bank_connection_id: null, import_source: null })
enqueue({ data: tx, error: null }) // fetch
enqueue({ data: null, error: null }) // delete
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(response)
expect(status).toBe(200)
expect(body).toEqual({ success: true })
})
it('returns 500 with a structured code when deletion fails', async () => {
const tx = makeTransaction({ journal_entry_id: null, bank_connection_id: null, import_source: null })
enqueue({ data: tx, error: null }) // fetch
enqueue({ data: null, error: { message: 'DB error' } }) // delete fails
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(response)
expect(status).toBe(500)
expect(body.error.code).toBe('TRANSACTION_DELETE_FAILED')
})
it('returns 409 with an audit-trail code when the immutability trigger blocks the delete', async () => {
// An unbooked row with payment_match_log rows: the cascade hits the
// audit_log_immutable trigger (P0001), not a clean FK error.
const tx = makeTransaction({ journal_entry_id: null, bank_connection_id: 'bc-1', import_source: null })
enqueue({ data: tx, error: null }) // fetch
enqueue({
data: null,
error: { code: 'P0001', message: 'Audit log entries cannot be modified or deleted' },
}) // delete blocked by trigger
const request = new Request('http://localhost/api/transactions/tx-1', { method: 'DELETE' })
const response = await DELETE(request, createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(response)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_DELETE_HAS_AUDIT_TRAIL')
expect(body.error.message).toMatch(/matchningshistorik|Bankavstämning/)
})
})
describe('PATCH /api/transactions/[id] (edit title)', () => {
const mockUser = { id: 'user-1', email: 'test@test.se' }
function patchReq(body: unknown) {
return new Request('http://localhost/api/transactions/tx-1', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
})
}
beforeEach(() => {
vi.clearAllMocks()
reset()
vi.mocked(requireAuth).mockResolvedValue({
user: mockUser as never,
supabase: mockSupabase as never,
error: null,
})
vi.mocked(guardSandbox).mockResolvedValue(null)
})
it('returns 401 when not authenticated', async () => {
vi.mocked(requireAuth).mockResolvedValue({
user: null as never,
supabase: mockSupabase as never,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await PATCH(patchReq({ description: 'Ny titel' }), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(401)
})
it('returns 400 when the title is empty / whitespace-only', async () => {
const res = await PATCH(patchReq({ description: ' ' }), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 404 when the transaction is not found', async () => {
enqueue({ data: null, error: { message: 'Not found' } })
const res = await PATCH(patchReq({ description: 'Ny titel' }), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('returns 409 when the transaction is booked', async () => {
enqueue({
data: {
id: 'tx-1',
description: 'X',
original_description: 'X',
journal_entry_id: 'je-1',
invoice_id: null,
supplier_invoice_id: null,
},
error: null,
})
const res = await PATCH(patchReq({ description: 'Ny titel' }), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_TITLE_LOCKED')
})
it('returns 409 when matched to an invoice even if journal_entry_id is null', async () => {
enqueue({
data: {
id: 'tx-1',
description: 'X',
original_description: 'X',
journal_entry_id: null,
invoice_id: 'inv-1',
supplier_invoice_id: null,
},
error: null,
})
const res = await PATCH(patchReq({ description: 'Ny titel' }), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(409)
})
it('updates the title for an editable (unbooked, unmatched) transaction', async () => {
enqueue({
data: {
id: 'tx-1',
description: 'ICA',
original_description: 'ICA',
journal_entry_id: null,
invoice_id: null,
supplier_invoice_id: null,
},
error: null,
}) // fetch
enqueue({
data: { id: 'tx-1', description: 'Lunch med kund', title_edited_at: '2026-06-01T10:00:00Z' },
error: null,
}) // update
const res = await PATCH(
patchReq({ description: 'Lunch med kund' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { description: string } }>(res)
expect(status).toBe(200)
expect(body.data.description).toBe('Lunch med kund')
})
it('restores the original title (200) when the new title equals original_description', async () => {
enqueue({
data: {
id: 'tx-1',
description: 'Lunch med kund',
original_description: 'ICA MAXI',
journal_entry_id: null,
invoice_id: null,
supplier_invoice_id: null,
},
error: null,
}) // fetch
enqueue({
data: { id: 'tx-1', description: 'ICA MAXI', title_edited_at: null },
error: null,
}) // update
const res = await PATCH(patchReq({ description: 'ICA MAXI' }), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ data: { title_edited_at: string | null } }>(res)
expect(status).toBe(200)
expect(body.data.title_edited_at).toBeNull()
})
it('returns 409 when the row is matched/booked between read and write (optimistic-lock miss)', async () => {
enqueue({
data: {
id: 'tx-1',
description: 'ICA',
original_description: 'ICA',
journal_entry_id: null,
invoice_id: null,
supplier_invoice_id: null,
},
error: null,
}) // fetch passes the read gate
enqueue({ data: null, error: null }) // UPDATE affects 0 rows (gate re-assert failed)
const res = await PATCH(patchReq({ description: 'Ny titel' }), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('TRANSACTION_TITLE_LOCKED')
})
})