Files
accounted/app/api/transactions/[id]/attach-document/__tests__/route.test.ts
T
MattssonandClaude Fable 5 8d56219c31 fix(inbox): booked items no longer strand in Att gora as matched-forever (#1547)
* fix(inbox): booked items no longer strand in Att gora as matched-forever

A matched inbox item only left the active inbox when
created_journal_entry_id was stamped, and only categorizeTransactionCore
stamped it. Booking the matched transaction through any other path (the
/book dialog route, bulk-book, link-to-existing-voucher) or matching a
receipt to an already-booked transaction (receipt hunt approvals,
attach-document, match-transaction) left the item "linked" forever,
pointing at a transaction that had already left the transactions work
list. Todays hunt fix (#1524) turned this July-old gap into a visible
flood of stuck items.

Two-part fix, because stamps alone cannot cover the reported case:
created_journal_entry_id is UNIQUE (20260515090000), so on a bulk-book
samlingsverifikat only one of N matched items can ever carry it.

Write side: lib/transactions/inbox-underlag.ts is the shared
implementation all paths now call. It links matched items' documents to
the anchoring verifikat (BFL 5 kap 6-7 kap: underlag on the
verifikation) and stamps created_journal_entry_id best-effort (CAS on
null, unique_violation tolerated). Wired into categorize-core (replacing
its inline block), /book, bulk-book, linkTransactionToJournalEntry, both
attach paths (REST + pending-operation), and the inbox match-transaction
handler. The attach paths and the doc-conflict guard also resolve
bulk-booked transactions through transaction_voucher_links, which they
previously treated as unbooked.

Read side: GET /items (and /items/:id) enrich matched-but-unstamped
items with matched_transaction_journal_entry_id, and the workspace
derives "booked" from it. This is what clears the stuck rows already in
prod without a status backfill, and what covers the N-1 samlingsverifikat
items the UNIQUE constraint refuses to stamp. Bulk-book selection
filters exclude such items so "Bokfor valda" no longer offers 409 fodder.

scripts/backfill-inbox-booked-underlag.ts (dry-run by default) repairs
the historical document->verifikat links the old paths never made.

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

* fix(inbox): stamp only settled underlag, and give the backfill behandlingshistorik

Both from the Swedish accounting compliance review.

The consumed-stamp is now conditional on the underlag actually
referencing a verifikat: stamping over a failed document link hid the
item from the .is('created_journal_entry_id', null) query forever,
leaving a posted verifikation without its underlag reference
(BFL 5 kap 6-7 kap) and nothing left to surface or repair it. A failed
link now leaves the item unstamped so re-runs and the backfill can
finish the job; a document preserved on another verifikat still counts
as settled.

The backfill script now appends an InboxUnderlagBackfilled event per
repaired transaction to processing_history (BFNAR 2013:2 kap 8): a mass
repair touching underlag-to-verifikat linkage leaves a changelog trail
distinguishing it from the original booking action.

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

* refactor(inbox): backfill writes behandlingshistorik through the shared appender

From the Swedish accounting compliance review round 2: a hand-rolled
processing_history insert in the backfill script could drift from the
shared row shape and skip the PII validation. appendProcessingHistory
now delegates to appendProcessingHistoryWithClient, which takes a
caller-supplied service-role client, so standalone scripts write
behandlingshistorik through the exact same code path as the app
(BFNAR 2013:2 kap 8: one reconcilable change log across writers).

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

* fix(inbox): leave the item unstamped when its document belongs to another verifikat

Swedish accounting review round 3: refusing to steal the document was
right, but stamping the item consumed anyway hid the fact that the
transaction's own verifikat ended up with no underlag reference from it
(BFL 5 kap 6-7 kap). The anchored-elsewhere case now leaves
created_journal_entry_id null so the mismatch keeps surfacing for
reconciliation, same posture as a failed link.

Also documents in the backfill script header why its writes cannot land
in locked periods: linkToJournalEntry's UPDATE is guarded by the
enforce_period_lock DB trigger, which fires for service-role writes too.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-13 00:49:20 +02:00

347 lines
17 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import {
parseJsonResponse,
createMockRouteParams,
createQueuedMockSupabase,
} from '@/tests/helpers'
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
const requireAuthMock = vi.fn()
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
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),
}))
vi.mock('@/lib/init', () => ({
ensureInitialized: vi.fn(),
}))
import { POST, DELETE } from '../route'
const mockUser = { id: 'user-1', email: 'test@test.se' }
beforeEach(() => {
vi.clearAllMocks()
reset()
requireAuthMock.mockResolvedValue({ user: mockUser, supabase: mockSupabase })
requireWriteMock.mockResolvedValue({ ok: true })
})
function makeReq(body: unknown, method: 'POST' | 'DELETE' = 'POST') {
return new Request('http://localhost/api/transactions/tx-1/attach-document', {
method,
headers: { 'Content-Type': 'application/json' },
body: method === 'POST' ? JSON.stringify(body) : undefined,
})
}
describe('POST /api/transactions/[id]/attach-document', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await POST(makeReq({ document_id: 'doc-1' }), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(res)
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 res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(403)
expect(body).toEqual({ error: 'Forbidden' })
})
it('returns 400 when document_id missing', async () => {
const res = await POST(makeReq({}), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(400)
})
it('returns 404 when transaction not in company', async () => {
enqueue({ data: null, error: null }) // tx fetch
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(body).toEqual({ error: 'Transaction not found' })
})
it('returns 404 when document not in company', async () => {
enqueue({ data: { id: 'tx-1' }, error: null }) // tx fetch
enqueue({ data: null, error: null }) // doc fetch
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(body).toEqual({ error: 'Document not found' })
})
it('attaches when both rows exist', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: [], error: null }) // completion: voucher-link resolution (not bulk-booked)
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { transaction_id: string; document_id: string; journal_entry_id: string | null } }>(res)
expect(status).toBe(200)
expect(body.data.transaction_id).toBe('tx-1')
expect(body.data.document_id).toBe('11111111-1111-4111-8111-111111111111')
expect(body.data.journal_entry_id).toBeNull()
// Unbooked tx: document_attachments is only read (doc fetch), never
// written: no journal entry to propagate to.
const fromCalls = mockSupabase.from.mock.calls.map((c) => c[0])
expect(fromCalls.filter((t) => t === 'document_attachments')).toHaveLength(1)
})
it('propagates the link onto the verifikation when the transaction is booked', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: null, error: null }) // document_attachments propagation
enqueue({ data: [], error: null }) // completion: matched inbox items (none)
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { journal_entry_id: string } }>(res)
expect(status).toBe(200)
expect(body.data.journal_entry_id).toBe('je-1')
// doc fetch + propagation write
const fromCalls = mockSupabase.from.mock.calls.map((c) => c[0])
expect(fromCalls.filter((t) => t === 'document_attachments')).toHaveLength(2)
})
it('skips propagation when the doc already points at the same verifikation (idempotent re-attach)', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-1' }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: [], error: null }) // completion: matched inbox items (none)
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
// No propagation write: only the doc fetch touched document_attachments.
const fromCalls = mockSupabase.from.mock.calls.map((c) => c[0])
expect(fromCalls.filter((t) => t === 'document_attachments')).toHaveLength(1)
})
it('returns 409 when the document already belongs to a different verifikation', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: 'je-OTHER' }, error: null }) // doc fetch
enqueue({ data: [], error: null }) // voucher-link check: je-OTHER anchors nothing here
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('annan verifikation')
})
it('completes the matched inbox item when the tx is anchored via a bulk-book samlingsverifikat', async () => {
// A bulk-booked tx keeps transactions.journal_entry_id null: the
// verifikat hangs off transaction_voucher_links. Attaching a receipt to
// it must link the underlag to that verifikat and stamp the matched
// inbox item, or the item strands as "linked" (the 2026-08-12 report).
const DOC = '11111111-1111-4111-8111-111111111111'
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: DOC, journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: [{ transaction_id: 'tx-1', journal_entry_id: 'je-9' }], error: null }) // voucher links
enqueue({ data: [{ id: 'inbox-1', document_id: DOC }], error: null }) // matched inbox items
enqueue({ data: { journal_entry_id: null }, error: null }) // doc anchor check: free
enqueue({ data: { id: 'je-9' }, error: null }) // linkToJournalEntry: JE ownership check
enqueue({ data: { id: DOC, journal_entry_id: 'je-9' }, error: null }) // linkToJournalEntry: doc update
enqueue({ data: null, error: null }) // created_journal_entry_id stamp
const res = await POST(makeReq({ document_id: DOC }), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ data: { journal_entry_id: string } }>(res)
expect(status).toBe(200)
// The response reports the samlingsverifikat the attach completed against.
expect(body.data.journal_entry_id).toBe('je-9')
})
it('returns 409 when the verifikation period is locked during propagation', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: null, error: { message: 'cannot link document in a locked/closed fiscal period' } }) // propagation blocked
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('låst')
})
it('returns 500 with the idempotent-retry message when propagation fails', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: 'je-1' }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link best-effort update
enqueue({ data: null, error: { message: 'boom' } }) // propagation fails
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(500)
expect(body.error).toContain('idempotent')
spy.mockRestore()
})
it('returns 404 when the update matches no row (concurrent delete)', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: null, error: null }) // transactions update returns no row
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status } = await parseJsonResponse(res)
expect(status).toBe(404)
})
it('attempts to update invoice_inbox_items.matched_transaction_id after successful attach', async () => {
// The side effect lets the inbox UI flip an item from "needs action" to
// "Kopplad till transaktion" without an extra round-trip.
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: null }) // inbox-link update
enqueue({ data: [], error: null }) // completion: voucher-link resolution (not bulk-booked)
await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
// Verify the inbox_items table was touched.
const fromCalls = mockSupabase.from.mock.calls.map((c) => c[0])
expect(fromCalls).toContain('invoice_inbox_items')
})
it('tolerates a failing inbox-link update: the document attach is the primary effect', async () => {
enqueue({ data: { id: 'tx-1', journal_entry_id: null }, error: null }) // tx fetch
enqueue({ data: { id: 'doc-1', journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // transactions update (RETURNING)
enqueue({ data: null, error: { message: 'rls denied' } }) // inbox-link fails
enqueue({ data: [], error: null }) // completion: voucher-link resolution (not bulk-booked)
const spy = vi.spyOn(console, 'error').mockImplementation(() => {})
const res = await POST(
makeReq({ document_id: '11111111-1111-4111-8111-111111111111' }),
createMockRouteParams({ id: 'tx-1' }),
)
const { status, body } = await parseJsonResponse<{ data: { transaction_id: string } }>(res)
// Side-effect failure must not roll back the (compliant) document attach.
expect(status).toBe(200)
expect(body.data.transaction_id).toBe('tx-1')
// The Supabase client resolves with { error } rather than rejecting, so
// we additionally assert that the error was actually inspected and logged
// (not silently dropped by a try/catch that never fires).
expect(spy).toHaveBeenCalledWith(
'[attach-document] Failed to link inbox item:',
expect.objectContaining({ message: 'rls denied' }),
)
spy.mockRestore()
})
})
describe('DELETE /api/transactions/[id]/attach-document', () => {
it('returns 401 when not authenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase: mockSupabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(res)
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 res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(403)
expect(body).toEqual({ error: 'Forbidden' })
})
it('returns 404 when transaction not in company', async () => {
enqueue({ data: null, error: null }) // tx fetch
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse(res)
expect(status).toBe(404)
expect(body).toEqual({ error: 'Transaction not found' })
})
it('returns 409 when document is already on a journal entry', async () => {
enqueue({ data: { id: 'tx-1', document_id: 'doc-1' }, error: null }) // tx fetch
enqueue({ data: { journal_entry_id: 'je-1' }, error: null }) // doc fetch
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ error: string }>(res)
expect(status).toBe(409)
expect(body.error).toContain('verifikation')
})
it('clears document_id when no journal entry link', async () => {
enqueue({ data: { id: 'tx-1', document_id: 'doc-1' }, error: null }) // tx fetch
enqueue({ data: { journal_entry_id: null }, error: null }) // doc fetch
enqueue({ data: null, error: null }) // update
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status, body } = await parseJsonResponse<{ data: { document_id: string | null } }>(res)
expect(status).toBe(200)
expect(body.data.document_id).toBeNull()
})
it('clears document_id when no doc was attached', async () => {
enqueue({ data: { id: 'tx-1', document_id: null }, error: null }) // tx fetch
enqueue({ data: null, error: null }) // update
const res = await DELETE(makeReq(null, 'DELETE'), createMockRouteParams({ id: 'tx-1' }))
const { status } = await parseJsonResponse(res)
expect(status).toBe(200)
})
})