feat(transactions): steer private marking in locked periods to ignore, with v1 and MCP ignore verbs (#1661) (#2031)
Decision (option a): a private marking stays a real booking (eget uttag/insattning), so it remains blocked in a locked or closed period; the legal escape for rows that are not affarshandelser is ignore. Private + locked now returns TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED with remediation naming the ignore paths instead of a bare PERIOD_LOCKED, on all four categorize surfaces and the bulk driver. New v1 POST/DELETE /transactions/{id}/ignore (isTransactionBooked-based 409, idempotent) and a staged MCP gnubok_ignore_transaction (+ accounted_ alias, search visibility to respect the tools/list payload ceiling) with operation_type ignore_transaction; the CHECK pair 20260831070000/070001 rebuilds the constraint from main's newest list plus the new value. Dashboard toast gains an Ignorera i stallet action. Closes #1661
This commit is contained in:
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1803,6 +1803,29 @@ export default function TransactionsPage() {
|
||||
setProcessingId(null)
|
||||
return { ok: false, journalEntryId: null }
|
||||
}
|
||||
if (result?.error?.code === 'TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED') {
|
||||
// Issue #1661: a private marking is a real booking (eget uttag /
|
||||
// insättning), so a locked period refuses it. The row being cleared
|
||||
// is usually no affärshändelse at all: offer Ignorera (no verifikat,
|
||||
// allowed in a locked period) on the toast. Interactive escalation,
|
||||
// so it shows for batch rows too: it is the only way forward.
|
||||
const lockedTx = transactions.find((t) => t.id === id)
|
||||
toast({
|
||||
title: t('private_locked_title'),
|
||||
description: getErrorMessage(result, { context: 'transaction', statusCode: response.status }),
|
||||
variant: 'destructive',
|
||||
action: lockedTx ? (
|
||||
<ToastAction
|
||||
altText={t('private_locked_ignore_action')}
|
||||
onClick={() => void handleIgnoreTransaction(lockedTx)}
|
||||
>
|
||||
{t('private_locked_ignore_action')}
|
||||
</ToastAction>
|
||||
) : undefined,
|
||||
})
|
||||
setProcessingId(null)
|
||||
return { ok: false, journalEntryId: null }
|
||||
}
|
||||
if (!silent) {
|
||||
toast({
|
||||
title: 'Kategorisering misslyckades',
|
||||
|
||||
@@ -685,6 +685,36 @@ describe('POST /api/transactions/[id]/categorize', () => {
|
||||
expect(mockSaveUserMappingRule).not.toHaveBeenCalled()
|
||||
expect(mockReverseOrphanedJournalEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED (suggested_action ignore) for a private marking in a locked period (issue #1661)', async () => {
|
||||
// A private marking books eget uttag/insättning, so the lock applies,
|
||||
// but the row is usually no affärshändelse: the pre-check answers with
|
||||
// the ignore-steering code before the engine is asked to book anything.
|
||||
enqueueUpToEngine()
|
||||
mockCheckPeriodLock.mockResolvedValue({
|
||||
locked: true,
|
||||
reason: 'period_locked_at_set',
|
||||
fiscal_period_id: 'fp-2024',
|
||||
})
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-1/categorize', {
|
||||
method: 'POST',
|
||||
body: { is_business: false },
|
||||
})
|
||||
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
error: { code: string; message: string; details?: { reason?: string; suggested_action?: string } }
|
||||
}>(response)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED')
|
||||
expect(body.error.message).toContain('Ignorera')
|
||||
expect(body.error.details?.reason).toBe('period_locked_at_set')
|
||||
expect(body.error.details?.suggested_action).toBe('ignore')
|
||||
expect(mockCreateTransactionJournalEntry).not.toHaveBeenCalled()
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
expect(mockReverseOrphanedJournalEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 500 when transaction update fails', async () => {
|
||||
|
||||
@@ -805,6 +805,27 @@ export const POST = withRouteContext(
|
||||
|
||||
await ensureFiscalPeriod(supabase, user.id, companyId, transaction.date, fiscalYearStartMonth, txLog)
|
||||
|
||||
// Issue #1661: a private marking books eget uttag/insättning, so a locked
|
||||
// period refuses it like any verifikat. Pre-check only for private rows:
|
||||
// the trigger path below would answer with a bare locked-period cause,
|
||||
// while the row the user wants to clear (a duplicate, a PSD2 ghost) is
|
||||
// usually no affärshändelse at all and should be ignored instead. The
|
||||
// response carries suggested_action: 'ignore' for the one-click toast.
|
||||
if (!is_business) {
|
||||
const privateLock = await checkPeriodLock(supabase, companyId, transaction.date)
|
||||
if (privateLock.locked) {
|
||||
return errorResponseFromCode('TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED', txLog, {
|
||||
requestId,
|
||||
details: {
|
||||
transaction_date: transaction.date,
|
||||
reason: privateLock.reason,
|
||||
fiscal_period_id: privateLock.fiscal_period_id,
|
||||
suggested_action: 'ignore',
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let journalEntryCreated = false
|
||||
let journalEntryId: string | null = null
|
||||
let documentLinkWarning: string | null = null
|
||||
@@ -863,14 +884,19 @@ export const POST = withRouteContext(
|
||||
if (!journalEntryId) {
|
||||
const periodLock = await checkPeriodLock(supabase, companyId, transaction.date)
|
||||
if (periodLock.locked) {
|
||||
return errorResponseFromCode('PERIOD_LOCKED', txLog, {
|
||||
requestId,
|
||||
details: {
|
||||
transaction_date: transaction.date,
|
||||
reason: periodLock.reason,
|
||||
fiscal_period_id: periodLock.fiscal_period_id,
|
||||
return errorResponseFromCode(
|
||||
is_business ? 'PERIOD_LOCKED' : 'TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED',
|
||||
txLog,
|
||||
{
|
||||
requestId,
|
||||
details: {
|
||||
transaction_date: transaction.date,
|
||||
reason: periodLock.reason,
|
||||
fiscal_period_id: periodLock.fiscal_period_id,
|
||||
...(is_business ? {} : { suggested_action: 'ignore' }),
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
}
|
||||
return errorResponseFromCode('NO_OPEN_PERIOD_FOR_DATE', txLog, {
|
||||
requestId,
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
const { supabase: mockSupabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
@@ -28,6 +28,13 @@ import { POST, DELETE } from '../route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
/** The three junction lookups the shared core runs for an unbooked row. */
|
||||
function enqueueNoAnchors() {
|
||||
enqueue({ data: [], error: null }) // transaction_voucher_links
|
||||
enqueue({ data: [], error: null }) // invoice_payments
|
||||
enqueue({ data: [], error: null }) // supplier_invoice_payments
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
@@ -68,7 +75,7 @@ describe('POST /api/transactions/[id]/ignore', () => {
|
||||
})
|
||||
|
||||
it('returns 404 when transaction not found', async () => {
|
||||
enqueue({ data: null, error: { message: 'Not found' } })
|
||||
enqueue({ data: null, error: null }) // maybeSingle: no row
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-999/ignore', { method: 'POST' })
|
||||
const response = await POST(request, createMockRouteParams({ id: 'tx-999' }))
|
||||
@@ -87,10 +94,29 @@ describe('POST /api/transactions/[id]/ignore', () => {
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toContain('redan bokförd')
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('returns 409 for a bulk-booked row whose verifikat lives in transaction_voucher_links (issue #1661)', async () => {
|
||||
// journal_entry_id stays NULL for N>1 bulk bookings: the old bare check
|
||||
// would have let this row be ignored while a verifikat still carries it.
|
||||
enqueue({ data: { id: 'tx-1', journal_entry_id: null, is_ignored: false }, error: null })
|
||||
enqueue({ data: [{ transaction_id: 'tx-1' }], error: null }) // transaction_voucher_links
|
||||
enqueue({ data: [], error: null })
|
||||
enqueue({ data: [], error: null })
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-1/ignore', { method: 'POST' })
|
||||
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
|
||||
expect(status).toBe(409)
|
||||
expect(body.error).toContain('redan bokförd')
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('is idempotent when the transaction is already ignored', async () => {
|
||||
enqueue({ data: { id: 'tx-1', journal_entry_id: null, is_ignored: true }, error: null })
|
||||
enqueueNoAnchors()
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-1/ignore', { method: 'POST' })
|
||||
const response = await POST(request, createMockRouteParams({ id: 'tx-1' }))
|
||||
@@ -98,10 +124,12 @@ describe('POST /api/transactions/[id]/ignore', () => {
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body).toEqual({ success: true, already_ignored: true })
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('marks the transaction ignored (happy path)', async () => {
|
||||
enqueue({ data: { id: 'tx-1', journal_entry_id: null, is_ignored: false }, error: null }) // fetch
|
||||
enqueueNoAnchors()
|
||||
enqueue({ data: null, error: null }) // update
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-1/ignore', { method: 'POST' })
|
||||
@@ -110,10 +138,12 @@ describe('POST /api/transactions/[id]/ignore', () => {
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body).toEqual({ success: true })
|
||||
expect(findCalls('transactions', 'update')).toEqual([[{ is_ignored: true }]])
|
||||
})
|
||||
|
||||
it('returns 500 when the update fails', async () => {
|
||||
enqueue({ data: { id: 'tx-1', journal_entry_id: null, is_ignored: false }, error: null }) // fetch
|
||||
enqueueNoAnchors()
|
||||
enqueue({ data: null, error: { message: 'db down' } }) // update fails
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-1/ignore', { method: 'POST' })
|
||||
@@ -155,7 +185,19 @@ describe('DELETE /api/transactions/[id]/ignore', () => {
|
||||
expect(body).toEqual({ error: 'Forbidden' })
|
||||
})
|
||||
|
||||
it('returns 404 when transaction not found', async () => {
|
||||
enqueue({ data: null, error: null })
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-999/ignore', { method: 'DELETE' })
|
||||
const response = await DELETE(request, createMockRouteParams({ id: 'tx-999' }))
|
||||
const { status, body } = await parseJsonResponse(response)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body).toEqual({ error: 'Transaction not found' })
|
||||
})
|
||||
|
||||
it('clears the ignore flag (happy path)', async () => {
|
||||
enqueue({ data: { id: 'tx-1', journal_entry_id: null, is_ignored: true }, error: null }) // fetch
|
||||
enqueue({ data: null, error: null }) // update
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-1/ignore', { method: 'DELETE' })
|
||||
@@ -164,9 +206,11 @@ describe('DELETE /api/transactions/[id]/ignore', () => {
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body).toEqual({ success: true })
|
||||
expect(findCalls('transactions', 'update')).toEqual([[{ is_ignored: false }]])
|
||||
})
|
||||
|
||||
it('returns 500 when the update fails', async () => {
|
||||
enqueue({ data: { id: 'tx-1', journal_entry_id: null, is_ignored: true }, error: null }) // fetch
|
||||
enqueue({ data: null, error: { message: 'db down' } }) // update fails
|
||||
|
||||
const request = createMockRequest('/api/transactions/tx-1/ignore', { method: 'DELETE' })
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { getErrorEntry } from '@/lib/errors/structured-errors'
|
||||
import { setTransactionIgnored } from '@/lib/transactions/ignore'
|
||||
|
||||
/**
|
||||
* POST /api/transactions/[id]/ignore
|
||||
@@ -8,50 +10,37 @@ import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-m
|
||||
* Mark a bank transaction as ignored so it stops surfacing in the bank
|
||||
* reconciliation view (and other "to book" funnels) without creating a
|
||||
* verifikation. Use case: tiny ränteintäkter, rounding noise, opening-balance
|
||||
* artefacts: anything the user wants off the unmatched list but doesn't want
|
||||
* to fabricate a journal entry for.
|
||||
* artefacts, PSD2 ghost rows: anything the user wants off the unmatched list
|
||||
* but doesn't want to fabricate a journal entry for. No verifikat is written,
|
||||
* so a locked or closed period does not block it (issue #1661).
|
||||
*
|
||||
* Refuses when the transaction is already booked; once a verifikation exists,
|
||||
* the proper way to revisit it is /uncategorize (storno).
|
||||
* Refuses when the transaction is already booked (directly or through a
|
||||
* payment allocation / voucher link: lib/transactions/is-booked.ts); once a
|
||||
* verifikation exists, the proper way to revisit it is /uncategorize (storno).
|
||||
*/
|
||||
export const POST = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
'transaction.ignore',
|
||||
async (_request, { supabase, companyId }, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
const { data: transaction, error: fetchError } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, journal_entry_id, is_ignored')
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
|
||||
if (fetchError || !transaction) {
|
||||
return NextResponse.json({ error: 'Transaction not found' }, { status: 404 })
|
||||
try {
|
||||
const outcome = await setTransactionIgnored(supabase, companyId, id, true)
|
||||
if (!outcome.ok) {
|
||||
if (outcome.status === 404) {
|
||||
return NextResponse.json({ error: 'Transaction not found' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: getErrorEntry(outcome.code)?.message_sv ?? 'Transaktionen är redan bokförd.' },
|
||||
{ status: outcome.status },
|
||||
)
|
||||
}
|
||||
if (!outcome.changed) {
|
||||
return NextResponse.json({ success: true, already_ignored: true })
|
||||
}
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
|
||||
if (transaction.journal_entry_id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Transaktionen är redan bokförd: använd Avmatcha eller backa verifikationen för att ändra status.' },
|
||||
{ status: 409 }
|
||||
)
|
||||
}
|
||||
|
||||
if (transaction.is_ignored) {
|
||||
return NextResponse.json({ success: true, already_ignored: true })
|
||||
}
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('transactions')
|
||||
.update({ is_ignored: true })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (updateError) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(updateError) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -68,17 +57,15 @@ export const DELETE = withRouteContext<{ params: Promise<{ id: string }> }>(
|
||||
async (_request, { supabase, companyId }, { params }) => {
|
||||
const { id } = await params
|
||||
|
||||
const { error: updateError } = await supabase
|
||||
.from('transactions')
|
||||
.update({ is_ignored: false })
|
||||
.eq('id', id)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (updateError) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(updateError) }, { status: 500 })
|
||||
try {
|
||||
const outcome = await setTransactionIgnored(supabase, companyId, id, false)
|
||||
if (!outcome.ok) {
|
||||
return NextResponse.json({ error: 'Transaction not found' }, { status: 404 })
|
||||
}
|
||||
return NextResponse.json({ success: true })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
|
||||
@@ -451,3 +451,62 @@ describe('POST /api/v1/.../transactions/{id}/categorize orphaned counter-account
|
||||
expect(createTxJE).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/v1/.../transactions/{id}/categorize private marking in a locked period (issue #1661)', () => {
|
||||
function lockedPeriodSupabase() {
|
||||
return makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
transactions: {
|
||||
data: {
|
||||
id: TX_ID,
|
||||
company_id: COMPANY_ID,
|
||||
date: '2025-11-12',
|
||||
amount: -349.5,
|
||||
currency: 'SEK',
|
||||
merchant_name: 'SWISH DUBBLETT',
|
||||
cash_account_id: null,
|
||||
journal_entry_id: null,
|
||||
},
|
||||
error: null,
|
||||
},
|
||||
company_settings: { data: { entity_type: 'enskild_firma' }, error: null },
|
||||
fiscal_periods: { data: { id: 'period-2025', is_closed: false, locked_at: '2026-01-31T00:00:00Z' }, error: null },
|
||||
})
|
||||
}
|
||||
|
||||
it('answers is_business: false with TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED and suggested_action ignore', async () => {
|
||||
const { supabase, updates } = lockedPeriodSupabase()
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest({ is_business: false }), routeParams())
|
||||
const body = await res.json()
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED')
|
||||
expect(body.error.details).toMatchObject({
|
||||
transaction_date: '2025-11-12',
|
||||
reason: 'period_locked_at_set',
|
||||
fiscal_period_id: 'period-2025',
|
||||
suggested_action: 'ignore',
|
||||
})
|
||||
expect(createTxJE).not.toHaveBeenCalled()
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps PERIOD_LOCKED (no suggested_action) for a business categorization', async () => {
|
||||
const { supabase, updates } = lockedPeriodSupabase()
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(
|
||||
makeRequest({ is_business: true, category: 'expense_office' }),
|
||||
routeParams(),
|
||||
)
|
||||
const body = await res.json()
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('PERIOD_LOCKED')
|
||||
expect(body.error.details.suggested_action).toBeUndefined()
|
||||
expect(createTxJE).not.toHaveBeenCalled()
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -397,14 +397,23 @@ export const POST = withApiV1<{ params: Promise<{ companyId: string; id: string
|
||||
transaction.date,
|
||||
)
|
||||
if (periodLock.locked) {
|
||||
return v1ErrorResponseFromCode('PERIOD_LOCKED', txLog, {
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
transaction_date: transaction.date,
|
||||
reason: periodLock.reason,
|
||||
fiscal_period_id: periodLock.fiscal_period_id,
|
||||
// Issue #1661: a private marking is a real booking (eget uttag /
|
||||
// insättning), so the lock applies, but a row that is not a business
|
||||
// event should be ignored, not booked: answer with the code whose
|
||||
// remediation names the ignore verb instead of unlock.
|
||||
return v1ErrorResponseFromCode(
|
||||
is_business ? 'PERIOD_LOCKED' : 'TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED',
|
||||
txLog,
|
||||
{
|
||||
requestId: ctx.requestId,
|
||||
details: {
|
||||
transaction_date: transaction.date,
|
||||
reason: periodLock.reason,
|
||||
fiscal_period_id: periodLock.fiscal_period_id,
|
||||
...(is_business ? {} : { suggested_action: 'ignore' }),
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
// Live path: create the journal entry. The internal route runs a
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
/**
|
||||
* Tests for the v1 ignore verb (issue #1661):
|
||||
*
|
||||
* POST /api/v1/companies/{companyId}/transactions/{id}/ignore
|
||||
* DELETE /api/v1/companies/{companyId}/transactions/{id}/ignore
|
||||
*
|
||||
* Proxy-backed Supabase mock with per-table response queues (same pattern as
|
||||
* the sibling categorize route test). The booked check is the shared core's
|
||||
* (lib/transactions/ignore.ts): a junction-anchored row with journal_entry_id
|
||||
* NULL must be refused like a directly booked one.
|
||||
*/
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
beforeAll(() => {
|
||||
if (process.env.NODE_ENV !== 'test') throw new Error('NODE_ENV=test required')
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL ||= 'http://localhost:54321'
|
||||
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||= 'test-anon-key'
|
||||
})
|
||||
|
||||
vi.mock('@/lib/auth/api-keys', async () => {
|
||||
const actual = await vi.importActual<typeof import('@/lib/auth/api-keys')>('@/lib/auth/api-keys')
|
||||
return { ...actual, validateApiKey: vi.fn(), createServiceClientNoCookies: vi.fn() }
|
||||
})
|
||||
vi.mock('@supabase/supabase-js', async () => {
|
||||
const actual = await vi.importActual<typeof import('@supabase/supabase-js')>('@supabase/supabase-js')
|
||||
return { ...actual, createClient: vi.fn().mockReturnValue({}) }
|
||||
})
|
||||
|
||||
import { validateApiKey, createServiceClientNoCookies } from '@/lib/auth/api-keys'
|
||||
import { POST, DELETE } from '../route'
|
||||
|
||||
const mockValidate = validateApiKey as ReturnType<typeof vi.fn>
|
||||
const mockServiceClient = createServiceClientNoCookies as ReturnType<typeof vi.fn>
|
||||
|
||||
type MockResult = { data?: unknown; error?: unknown }
|
||||
function makeFlexibleSupabase(byTable: Record<string, MockResult | MockResult[]>) {
|
||||
const queues = new Map<string, MockResult[]>()
|
||||
for (const [t, val] of Object.entries(byTable)) {
|
||||
queues.set(t, Array.isArray(val) ? [...val] : [val])
|
||||
}
|
||||
const updates: Record<string, unknown[]> = {}
|
||||
const buildChain = (table: string): unknown => {
|
||||
const handler: ProxyHandler<object> = {
|
||||
get(_target, prop) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: (v: unknown) => void) => {
|
||||
const q = queues.get(table)
|
||||
const next = q && q.length > 1 ? q.shift()! : (q?.[0] ?? { data: null, error: null })
|
||||
resolve(next)
|
||||
}
|
||||
}
|
||||
return (...args: unknown[]) => {
|
||||
if (prop === 'update') (updates[table] ??= []).push(args[0])
|
||||
return buildChain(table)
|
||||
}
|
||||
},
|
||||
}
|
||||
return new Proxy({}, handler)
|
||||
}
|
||||
return { supabase: { from: vi.fn((table: string) => buildChain(table)) }, updates }
|
||||
}
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const TX_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
const URL = `https://x.test/api/v1/companies/${COMPANY_ID}/transactions/${TX_ID}/ignore`
|
||||
|
||||
function makeRequest(method: 'POST' | 'DELETE', opts: { url?: string; idempotencyKey?: string | null } = {}): Request {
|
||||
const headers: Record<string, string> = {
|
||||
Authorization: 'Bearer test-fixture-not-a-real-key',
|
||||
}
|
||||
if (opts.idempotencyKey !== null) {
|
||||
headers['Idempotency-Key'] = opts.idempotencyKey ?? 'idem1234-aaaa-4abc-8def-1234567890ab'
|
||||
}
|
||||
return new Request(opts.url ?? URL, { method, headers })
|
||||
}
|
||||
function routeParams(id: string = TX_ID) {
|
||||
return { params: Promise.resolve({ companyId: COMPANY_ID, id }) }
|
||||
}
|
||||
|
||||
function unbookedSupabase(transactionOverrides: Record<string, unknown> = {}) {
|
||||
return makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
transactions: [
|
||||
{ data: { id: TX_ID, journal_entry_id: null, is_ignored: false, ...transactionOverrides }, error: null },
|
||||
{ data: null, error: null }, // update
|
||||
],
|
||||
transaction_voucher_links: { data: [], error: null },
|
||||
invoice_payments: { data: [], error: null },
|
||||
supplier_invoice_payments: { data: [], error: null },
|
||||
idempotency_keys: { data: null, error: null },
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
scopes: ['transactions:write'],
|
||||
mode: 'live',
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/v1/.../transactions/{id}/ignore', () => {
|
||||
it('returns 401 without a valid bearer token', async () => {
|
||||
mockValidate.mockResolvedValue({ error: 'Invalid API key', status: 401 })
|
||||
mockServiceClient.mockReturnValue(unbookedSupabase().supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST'), routeParams())
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects keys without transactions:write scope', async () => {
|
||||
mockValidate.mockResolvedValue({
|
||||
userId: 'user-1',
|
||||
companyId: COMPANY_ID,
|
||||
apiKeyId: 'ak_1',
|
||||
scopes: ['transactions:read'],
|
||||
mode: 'live',
|
||||
})
|
||||
mockServiceClient.mockReturnValue(unbookedSupabase().supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST'), routeParams())
|
||||
expect(res.status).toBe(403)
|
||||
})
|
||||
|
||||
it('requires an Idempotency-Key (400)', async () => {
|
||||
const { supabase, updates } = unbookedSupabase()
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST', { idempotencyKey: null }), routeParams())
|
||||
expect(res.status).toBe(400)
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('rejects a non-UUID transaction id with 400 VALIDATION_ERROR', async () => {
|
||||
mockServiceClient.mockReturnValue(unbookedSupabase().supabase)
|
||||
|
||||
const res = await POST(
|
||||
makeRequest('POST', { url: `https://x.test/api/v1/companies/${COMPANY_ID}/transactions/not-a-uuid/ignore` }),
|
||||
routeParams('not-a-uuid'),
|
||||
)
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(400)
|
||||
expect(body.error.code).toBe('VALIDATION_ERROR')
|
||||
})
|
||||
|
||||
it('returns 404 TX_CATEGORIZE_TX_NOT_FOUND when the row is not in this company', async () => {
|
||||
const { supabase, updates } = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
transactions: { data: null, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(404)
|
||||
expect(body.error.code).toBe('TX_CATEGORIZE_TX_NOT_FOUND')
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns 409 TX_IGNORE_ALREADY_BOOKED for a directly booked row', async () => {
|
||||
const { supabase, updates } = unbookedSupabase({ journal_entry_id: 'je-1' })
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(409)
|
||||
expect(body.error.code).toBe('TX_IGNORE_ALREADY_BOOKED')
|
||||
expect(body.error.details.transaction_id).toBe(TX_ID)
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns 409 for a bulk-booked row anchored only through transaction_voucher_links', async () => {
|
||||
const { supabase, updates } = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
transactions: { data: { id: TX_ID, journal_entry_id: null, is_ignored: false }, error: null },
|
||||
transaction_voucher_links: { data: [{ transaction_id: TX_ID }], error: null },
|
||||
invoice_payments: { data: [], error: null },
|
||||
supplier_invoice_payments: { data: [], error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(409)
|
||||
expect(body.error.code).toBe('TX_IGNORE_ALREADY_BOOKED')
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns 409 for a multi-allocated row anchored only through invoice_payments', async () => {
|
||||
const { supabase } = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
transactions: { data: { id: TX_ID, journal_entry_id: null, is_ignored: false }, error: null },
|
||||
transaction_voucher_links: { data: [], error: null },
|
||||
invoice_payments: { data: [{ transaction_id: TX_ID }], error: null },
|
||||
supplier_invoice_payments: { data: [], error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(409)
|
||||
expect(body.error.code).toBe('TX_IGNORE_ALREADY_BOOKED')
|
||||
})
|
||||
|
||||
it('is idempotent: an already-ignored row returns already_ignored=true without writing', async () => {
|
||||
const { supabase, updates } = unbookedSupabase({ is_ignored: true })
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data).toEqual({
|
||||
success: true,
|
||||
transaction_id: TX_ID,
|
||||
is_ignored: true,
|
||||
already_ignored: true,
|
||||
})
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('ignores an unbooked row (happy path)', async () => {
|
||||
const { supabase, updates } = unbookedSupabase()
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data).toEqual({
|
||||
success: true,
|
||||
transaction_id: TX_ID,
|
||||
is_ignored: true,
|
||||
already_ignored: false,
|
||||
})
|
||||
expect(updates.transactions).toEqual([{ is_ignored: true }])
|
||||
})
|
||||
|
||||
it('dry-run previews without writing', async () => {
|
||||
const { supabase, updates } = unbookedSupabase()
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(makeRequest('POST', { url: `${URL}?dry_run=true` }), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data.dry_run).toBe(true)
|
||||
expect(body.data.preview).toEqual({
|
||||
transaction_id: TX_ID,
|
||||
would_set_ignored: true,
|
||||
already_ignored: false,
|
||||
})
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE /api/v1/.../transactions/{id}/ignore', () => {
|
||||
it('returns 401 without a valid bearer token', async () => {
|
||||
mockValidate.mockResolvedValue({ error: 'Invalid API key', status: 401 })
|
||||
mockServiceClient.mockReturnValue(unbookedSupabase().supabase)
|
||||
|
||||
const res = await DELETE(makeRequest('DELETE'), routeParams())
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when the row is not in this company', async () => {
|
||||
const { supabase } = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
transactions: { data: null, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await DELETE(makeRequest('DELETE'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(404)
|
||||
expect(body.error.code).toBe('TX_CATEGORIZE_TX_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('restores an ignored row (happy path)', async () => {
|
||||
const { supabase, updates } = unbookedSupabase({ is_ignored: true })
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await DELETE(makeRequest('DELETE'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data).toEqual({
|
||||
success: true,
|
||||
transaction_id: TX_ID,
|
||||
is_ignored: false,
|
||||
was_ignored: true,
|
||||
})
|
||||
expect(updates.transactions).toEqual([{ is_ignored: false }])
|
||||
})
|
||||
|
||||
it('is idempotent: restoring a row that is not ignored returns was_ignored=false without writing', async () => {
|
||||
const { supabase, updates } = unbookedSupabase()
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await DELETE(makeRequest('DELETE'), routeParams())
|
||||
const body = await res.json()
|
||||
expect(res.status).toBe(200)
|
||||
expect(body.data.was_ignored).toBe(false)
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
+52
@@ -237,6 +237,58 @@ describe('POST batch-categorize', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('answers a private marking in a locked period with TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED, a business one with PERIOD_LOCKED (issue #1661)', async () => {
|
||||
const { supabase, updates } = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
transactions: {
|
||||
data: {
|
||||
id: TX_A,
|
||||
company_id: COMPANY_ID,
|
||||
date: '2025-11-12',
|
||||
amount: -349.5,
|
||||
currency: 'SEK',
|
||||
merchant_name: 'SWISH DUBBLETT',
|
||||
journal_entry_id: null,
|
||||
},
|
||||
error: null,
|
||||
},
|
||||
company_settings: { data: { entity_type: 'enskild_firma' }, error: null },
|
||||
fiscal_periods: { data: { id: 'period-2025', is_closed: true, locked_at: null }, error: null },
|
||||
})
|
||||
mockServiceClient.mockReturnValue(supabase)
|
||||
|
||||
const res = await POST(
|
||||
makeRequest(
|
||||
`https://x.test/api/v1/companies/${COMPANY_ID}/transactions/batch-categorize`,
|
||||
{
|
||||
items: [
|
||||
{ transaction_id: TX_A, categorization: { is_business: false } },
|
||||
{ transaction_id: TX_B, categorization: { is_business: true, category: 'expense_office' } },
|
||||
],
|
||||
},
|
||||
),
|
||||
batchParams(),
|
||||
)
|
||||
|
||||
const body = await res.json()
|
||||
expect(body.data.results[0].ok).toBe(false)
|
||||
expect(body.data.results[0].error.code).toBe('TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED')
|
||||
expect(body.data.results[0].error.message).toContain('Ignorera')
|
||||
expect(body.data.results[0].error.details).toMatchObject({
|
||||
transaction_date: '2025-11-12',
|
||||
reason: 'period_is_closed',
|
||||
fiscal_period_id: 'period-2025',
|
||||
suggested_action: 'ignore',
|
||||
})
|
||||
expect(body.data.results[1].ok).toBe(false)
|
||||
expect(body.data.results[1].error.code).toBe('PERIOD_LOCKED')
|
||||
expect(body.data.results[1].error.details.suggested_action).toBeUndefined()
|
||||
expect(body.data.summary).toEqual({ total: 2, succeeded: 0, failed: 2 })
|
||||
// Neither item reached the engine or the CAS write.
|
||||
expect(createTxJE).not.toHaveBeenCalled()
|
||||
expect(updates.transactions).toBeUndefined()
|
||||
})
|
||||
|
||||
it('returns a per-item NO_OPEN_PERIOD_FOR_DATE and writes nothing when the engine finds no covering period', async () => {
|
||||
const { supabase, updates } = makeFlexibleSupabase({
|
||||
company_members: { data: { company_id: COMPANY_ID, role: 'owner' }, error: null },
|
||||
|
||||
@@ -323,6 +323,30 @@ async function categorizeOne(
|
||||
// than a generic INTERNAL_ERROR from the trigger exception.
|
||||
const periodLock = await checkPeriodLock(supabase, companyId, transaction.date)
|
||||
if (periodLock.locked) {
|
||||
// Issue #1661: a private marking is a real booking (eget uttag /
|
||||
// insättning), so the lock applies, but the row the caller wants to
|
||||
// clear is usually not a business event at all. Name the ignore path
|
||||
// instead of a bare PERIOD_LOCKED so an agent clearing PSD2 ghost rows
|
||||
// out of a closed period is not steered to unlock it.
|
||||
if (!is_business) {
|
||||
return {
|
||||
ok: false,
|
||||
request_index: index,
|
||||
transaction_id: transactionId,
|
||||
error: {
|
||||
code: 'TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED',
|
||||
message:
|
||||
getErrorEntry('TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED')?.message_sv ??
|
||||
'Perioden är låst. Ignorera raden i stället om den inte är en affärshändelse.',
|
||||
details: {
|
||||
transaction_date: transaction.date,
|
||||
reason: periodLock.reason,
|
||||
fiscal_period_id: periodLock.fiscal_period_id,
|
||||
suggested_action: 'ignore',
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
return {
|
||||
ok: false,
|
||||
request_index: index,
|
||||
|
||||
@@ -47,6 +47,7 @@ export const OPERATION_LABEL_KEYS: Record<string, string> = {
|
||||
link_supplier_invoice_voucher: 'type_link_supplier_invoice_voucher',
|
||||
link_transaction_journal_entry: 'type_link_transaction_journal_entry',
|
||||
uncategorize_transaction: 'type_uncategorize_transaction',
|
||||
ignore_transaction: 'type_ignore_transaction',
|
||||
retag_line_dimensions: 'type_retag_line_dimensions',
|
||||
set_voucher_note: 'type_set_voucher_note',
|
||||
// Bulk booking / allocation
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
/**
|
||||
* Unit tests for gnubok_ignore_transaction (issue #1661): registration,
|
||||
* scope/risk/catalog wiring, the booked-row refusal through the shared core,
|
||||
* and staging (dry run + persisted). Executor-side coverage
|
||||
* (commitIgnoreTransaction) lives in
|
||||
* lib/pending-operations/__tests__/ignore-transaction-executor.test.ts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { tools, isDefaultCatalogTool } from '../server'
|
||||
import { RECOMMENDED_WORKFLOW_LOADOUTS } from '../recommended-tools'
|
||||
import { TOOL_SCOPE_MAP } from '@/lib/auth/api-keys'
|
||||
import { OPERATION_RISK_TIERS } from '@/lib/pending-operations/risk-tiers'
|
||||
|
||||
const tool = tools.find((t) => t.name === 'gnubok_ignore_transaction')!
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000aa'
|
||||
const TX_ROW = {
|
||||
id: TX_ID,
|
||||
description: 'SWISH DUBBLETT',
|
||||
merchant_name: null,
|
||||
amount: -250,
|
||||
currency: 'SEK',
|
||||
date: '2025-11-15',
|
||||
is_ignored: false,
|
||||
}
|
||||
const CORE_ROW = { id: TX_ID, journal_entry_id: null, is_ignored: false }
|
||||
|
||||
const noopSupabase = { from: vi.fn() } as never
|
||||
|
||||
/** Tool fetch + shared-core fetch + the three junction lookups. */
|
||||
function enqueueUnbooked(
|
||||
enqueue: (r: { data?: unknown; error?: unknown }) => void,
|
||||
overrides: { tool?: Record<string, unknown>; core?: Record<string, unknown> } = {},
|
||||
) {
|
||||
enqueue({ data: { ...TX_ROW, ...overrides.tool } })
|
||||
enqueue({ data: { ...CORE_ROW, ...overrides.core } })
|
||||
enqueue({ data: [] }) // transaction_voucher_links
|
||||
enqueue({ data: [] }) // invoice_payments
|
||||
enqueue({ data: [] }) // supplier_invoice_payments
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('gnubok_ignore_transaction: registration', () => {
|
||||
it('is registered in the DEFAULT catalog (a search-only write is uncallable on Claude.ai)', () => {
|
||||
expect(tool).toBeDefined()
|
||||
expect(isDefaultCatalogTool(tool)).toBe(true)
|
||||
expect((tool.inputSchema as { additionalProperties?: boolean }).additionalProperties).toBe(false)
|
||||
expect((tool.inputSchema as { required?: string[] }).required).toEqual(['transaction_id'])
|
||||
const out = tool.outputSchema as { properties?: Record<string, unknown>; required?: string[] }
|
||||
expect(out?.required).toContain('staged')
|
||||
expect(tool.description).toMatch(/TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED/)
|
||||
})
|
||||
|
||||
it('is mapped to transactions:write and the low risk tier', () => {
|
||||
expect(TOOL_SCOPE_MAP.gnubok_ignore_transaction).toBe('transactions:write')
|
||||
expect(OPERATION_RISK_TIERS.ignore_transaction).toBe('low')
|
||||
})
|
||||
|
||||
it('is part of the categorize, close-period and reconcile loadouts', () => {
|
||||
const byWorkflow = new Map(RECOMMENDED_WORKFLOW_LOADOUTS.map((l) => [l.workflow, l.tools]))
|
||||
for (const workflow of ['categorize_month', 'close_period', 'reconcile_month']) {
|
||||
expect(byWorkflow.get(workflow), workflow).toContain('gnubok_ignore_transaction')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('gnubok_ignore_transaction: validation gates', () => {
|
||||
it('rejects a missing transaction_id before any DB call', async () => {
|
||||
await expect(
|
||||
tool.execute({ transaction_id: '' }, 'company-1', 'user-1', noopSupabase),
|
||||
).rejects.toThrow(/transaction_id/)
|
||||
expect((noopSupabase as { from: ReturnType<typeof vi.fn> }).from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects when the transaction does not exist in this company', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null })
|
||||
await expect(
|
||||
tool.execute({ transaction_id: TX_ID }, 'company-1', 'user-1', supabase as never),
|
||||
).rejects.toThrow(/not found/i)
|
||||
})
|
||||
|
||||
it('refuses a directly booked row with TX_IGNORE_ALREADY_BOOKED', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: TX_ROW })
|
||||
enqueue({ data: { ...CORE_ROW, journal_entry_id: 'je-1' } })
|
||||
await expect(
|
||||
tool.execute({ transaction_id: TX_ID }, 'company-1', 'user-1', supabase as never),
|
||||
).rejects.toThrow(/TX_IGNORE_ALREADY_BOOKED/)
|
||||
expect(findCalls('pending_operations', 'insert')).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses a bulk-booked row anchored only through transaction_voucher_links', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: TX_ROW })
|
||||
enqueue({ data: CORE_ROW })
|
||||
enqueue({ data: [{ transaction_id: TX_ID }] }) // voucher links
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] })
|
||||
await expect(
|
||||
tool.execute({ transaction_id: TX_ID }, 'company-1', 'user-1', supabase as never),
|
||||
).rejects.toThrow(/TX_IGNORE_ALREADY_BOOKED/)
|
||||
expect(findCalls('pending_operations', 'insert')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('gnubok_ignore_transaction: staging', () => {
|
||||
it('dry run previews the flip, marks period lock as not applicable, and writes nothing', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueueUnbooked(enqueue)
|
||||
enqueue({ data: null }) // resolvePeriodStatusForDate: company_settings
|
||||
enqueue({ data: null }) // resolvePeriodStatusForDate: fiscal_periods
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ transaction_id: TX_ID, dry_run: true },
|
||||
'company-1', 'user-1', supabase as never, { type: 'user' },
|
||||
)) as { staged: boolean; dry_run?: boolean; risk_level: string; preview: Record<string, unknown> }
|
||||
|
||||
expect(result.staged).toBe(false)
|
||||
expect(result.dry_run).toBe(true)
|
||||
expect(result.risk_level).toBe('low')
|
||||
expect(result.preview).toMatchObject({
|
||||
transaction_id: TX_ID,
|
||||
transaction_description: 'SWISH DUBBLETT',
|
||||
amount: -250,
|
||||
currently_ignored: false,
|
||||
will_be_ignored: true,
|
||||
already_in_state: false,
|
||||
writes_verifikat: false,
|
||||
period_lock_applies: false,
|
||||
})
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
expect(findCalls('pending_operations', 'insert')).toEqual([])
|
||||
})
|
||||
|
||||
it('stages an ignore_transaction operation with { transaction_id, ignored: true } params', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueueUnbooked(enqueue)
|
||||
enqueue({ data: null }) // company_settings
|
||||
enqueue({ data: null }) // fiscal_periods
|
||||
enqueue({ data: { id: 'op-1' }, error: null }) // pending_operations insert
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ transaction_id: TX_ID },
|
||||
'company-1', 'user-1', supabase as never, { type: 'user' },
|
||||
)) as { staged: boolean; operation_id?: string; next?: { tool: string } }
|
||||
|
||||
expect(result.staged).toBe(true)
|
||||
expect(result.operation_id).toBe('op-1')
|
||||
expect(result.next?.tool).toBe('gnubok_list_uncategorized_transactions')
|
||||
const inserts = findCalls('pending_operations', 'insert')
|
||||
expect(inserts).toHaveLength(1)
|
||||
expect(inserts[0][0]).toMatchObject({
|
||||
operation_type: 'ignore_transaction',
|
||||
title: 'Ignorera transaktion: SWISH DUBBLETT',
|
||||
params: { transaction_id: TX_ID, ignored: true },
|
||||
})
|
||||
// Staging never flips the flag itself: that is the executor's job.
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('restore: true stages ignored: false without the booked check and points back at categorize', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { ...TX_ROW, is_ignored: true } }) // tool fetch
|
||||
enqueue({ data: { ...CORE_ROW, is_ignored: true } }) // core fetch (no junction lookups on restore)
|
||||
enqueue({ data: null }) // company_settings
|
||||
enqueue({ data: null }) // fiscal_periods
|
||||
enqueue({ data: { id: 'op-2' }, error: null }) // insert
|
||||
|
||||
const result = (await tool.execute(
|
||||
{ transaction_id: TX_ID, restore: true },
|
||||
'company-1', 'user-1', supabase as never, { type: 'user' },
|
||||
)) as { staged: boolean; preview: Record<string, unknown>; next?: { tool: string } }
|
||||
|
||||
expect(result.staged).toBe(true)
|
||||
expect(result.preview).toMatchObject({ currently_ignored: true, will_be_ignored: false })
|
||||
expect(result.next?.tool).toBe('gnubok_categorize_transaction')
|
||||
expect(findCalls('transaction_voucher_links', 'select')).toEqual([])
|
||||
expect(findCalls('pending_operations', 'insert')[0][0]).toMatchObject({
|
||||
title: 'Återställ ignorerad transaktion: SWISH DUBBLETT',
|
||||
params: { transaction_id: TX_ID, ignored: false },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -295,12 +295,21 @@ describe('tools/list payload size guard', () => {
|
||||
// deliberately: picking which read to demote needs prod usage data
|
||||
// (MCP usage profile), not a guess inside a payroll PR: do that
|
||||
// demotion as its own change and ratchet this ceiling back down.
|
||||
// * 64.4K to 65K with gnubok_ignore_transaction in the default catalog
|
||||
// (issue #1661: private marking in a locked period). Same reason as
|
||||
// set_run_salary: a search-only WRITE is uncallable on Claude.ai, and
|
||||
// the TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED remediation, three loadouts
|
||||
// and the reconcile-month skill instruct agents to CALL it. Measured
|
||||
// 64 863 on the accounted projection (+548: a 4-property schema plus
|
||||
// the staging envelope; the description is one sentence per fact).
|
||||
// Same deliberate skip of the read-demotion rule as the entry above:
|
||||
// the demotion needs prod usage data, not a guess inside this PR.
|
||||
// Long-term answer to growth is no longer a ceiling bump. gnubok_call_tool
|
||||
// makes `catalogVisibility: 'search'` usable for READ tools on hosts that
|
||||
// can only invoke what tools/list showed them, which is the constraint that
|
||||
// forced gnubok_reconcile_match back into the default catalog on
|
||||
// 2026-08-26. Demote a read to search-only before proposing a bump.
|
||||
expect(approxTokens).toBeLessThan(64_400)
|
||||
expect(approxTokens).toBeLessThan(65_000)
|
||||
})
|
||||
|
||||
it('keeps the accounted_* namespace as the measured worst case', () => {
|
||||
|
||||
@@ -49,6 +49,10 @@ export const RECOMMENDED_WORKFLOW_LOADOUTS: readonly WorkflowLoadout[] = [
|
||||
// verifikat: links without creating new bookkeeping. Categorizing such a
|
||||
// transaction would double-book it.
|
||||
'gnubok_link_transaction_to_journal_entry',
|
||||
// Rows that are not business events (PSD2 ghost rows, duplicates):
|
||||
// ignore writes no verifikat and is allowed in a locked period, the
|
||||
// answer to TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED (issue #1661).
|
||||
'gnubok_ignore_transaction',
|
||||
// Tagging: check the registry before writing dimensions bags on
|
||||
// categorize calls (resolve-don't-select needs real codes/names).
|
||||
'gnubok_list_dimensions',
|
||||
@@ -63,6 +67,9 @@ export const RECOMMENDED_WORKFLOW_LOADOUTS: readonly WorkflowLoadout[] = [
|
||||
tools: [
|
||||
'gnubok_list_fiscal_periods',
|
||||
'gnubok_list_uncategorized_transactions',
|
||||
// Clears non-business rows out of the period without a verifikat; the
|
||||
// lock guard counts untriaged rows, ignored ones no longer block it.
|
||||
'gnubok_ignore_transaction',
|
||||
'gnubok_get_reconciliation_status',
|
||||
// Account-keyed reconciliation: the rows behind the bridge and the
|
||||
// staged link (bank accounts and skattekonto alike).
|
||||
@@ -92,6 +99,8 @@ export const RECOMMENDED_WORKFLOW_LOADOUTS: readonly WorkflowLoadout[] = [
|
||||
// verifikat that already holds the affärshändelse.
|
||||
'gnubok_categorize_transaction',
|
||||
'gnubok_link_transaction_to_journal_entry',
|
||||
// A row that will never be booked (duplicate, noise line): ignore it.
|
||||
'gnubok_ignore_transaction',
|
||||
'gnubok_reconcile_signoff',
|
||||
'gnubok_approve_pending_operation',
|
||||
],
|
||||
|
||||
@@ -54,6 +54,7 @@ import { resolveSettlementAccount } from '@/lib/bookkeeping/settlement-account'
|
||||
import { buildTransactionEntryLines, createTransactionJournalEntry } from '@/lib/bookkeeping/transaction-entries'
|
||||
import { upsertCounterpartyTemplate, findCounterpartyTemplatesBatch, formatCounterpartyName } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import { formatVoucherLabel, hasLiveJournalEntryLink } from '@/lib/transactions/link-journal-entry'
|
||||
import { setTransactionIgnored } from '@/lib/transactions/ignore'
|
||||
import { canApproveSupplierInvoice } from '@/lib/supplier-invoices/lifecycle'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import { getVatRules, getPermittedVatRates, getArticleVatRateAdoptionSet } from '@/lib/invoices/vat-rules'
|
||||
@@ -15770,6 +15771,93 @@ export const tools: McpTool[] = [
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_ignore_transaction',
|
||||
title: 'Ignore Transaction (Ignorera)',
|
||||
description: 'Stage ignoring an unbooked bank transaction that is no business event (PSD2 ghost row, duplicate). No verifikat is written, so a locked period does not block it: the answer to TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED. restore: true un-ignores; booked rows are refused.',
|
||||
// Default catalog: gnubok_call_tool only bridges READ tools, so a
|
||||
// search-only WRITE is uncallable on Claude.ai, and the
|
||||
// TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED remediation instructs agents to call
|
||||
// this tool. Budget accounted for in payload-size.bench.test.ts (#1661).
|
||||
inputSchema: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
transaction_id: { type: 'string', description: 'UUID of the unbooked bank transaction' },
|
||||
restore: { type: 'boolean', description: 'true = clear the ignore flag instead (default false)' },
|
||||
dry_run: { type: 'boolean', description: 'Validate and preview without staging.' },
|
||||
idempotency_key: { type: 'string', description: 'Per-operation UUID for safe retries (24h TTL).' },
|
||||
},
|
||||
required: ['transaction_id'],
|
||||
},
|
||||
outputSchema: STAGED_OPERATION_SCHEMA,
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
||||
async execute(args, companyId, userId, supabase, actor) {
|
||||
const transactionId = String(args.transaction_id ?? '').trim()
|
||||
if (!transactionId) throw new Error('transaction_id is required')
|
||||
const restore = args.restore === true
|
||||
|
||||
const { data: tx, error: txError } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, description, merchant_name, amount, currency, date, is_ignored')
|
||||
.eq('id', transactionId)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (txError) throw dbError(txError)
|
||||
if (!tx) throw new Error('Transaction not found')
|
||||
|
||||
// Preflight through the shared core in dry run (issue #1661): the booked
|
||||
// check covers all three anchors (journal_entry_id, payment allocations,
|
||||
// voucher links) and `changed` tells the preview whether approval would
|
||||
// be a no-op. Nothing is written here; the commit path re-runs the core.
|
||||
const preflight = await setTransactionIgnored(supabase, companyId, transactionId, !restore, {
|
||||
dryRun: true,
|
||||
})
|
||||
if (!preflight.ok) {
|
||||
const entry = getErrorEntry(preflight.code)
|
||||
throw new Error(
|
||||
`Cannot ${restore ? 'restore' : 'ignore'} transaction: ${preflight.code}. ${entry?.message_en ?? ''}`.trim()
|
||||
)
|
||||
}
|
||||
|
||||
const label = tx.merchant_name || tx.description || transactionId
|
||||
return stagePendingOperation(supabase, companyId, userId, 'ignore_transaction',
|
||||
restore ? `Återställ ignorerad transaktion: ${label}` : `Ignorera transaktion: ${label}`,
|
||||
{ transaction_id: transactionId, ignored: !restore },
|
||||
{
|
||||
transaction_id: transactionId,
|
||||
transaction_description: label,
|
||||
amount: tx.amount,
|
||||
currency: tx.currency,
|
||||
date: tx.date,
|
||||
currently_ignored: Boolean(tx.is_ignored),
|
||||
will_be_ignored: !restore,
|
||||
already_in_state: !preflight.changed,
|
||||
// No verifikat is written, so period_status is informational only:
|
||||
// a locked or closed period does not block this operation.
|
||||
writes_verifikat: false,
|
||||
period_lock_applies: false,
|
||||
},
|
||||
actor,
|
||||
restore
|
||||
? {
|
||||
description: 'After approval the row is back in the "to book" list: book it via gnubok_categorize_transaction.',
|
||||
tool: 'gnubok_categorize_transaction',
|
||||
args: { transaction_id: transactionId },
|
||||
}
|
||||
: {
|
||||
description: 'After approval the row leaves the "to book" list. Continue with gnubok_list_uncategorized_transactions.',
|
||||
tool: 'gnubok_list_uncategorized_transactions',
|
||||
},
|
||||
{
|
||||
dryRun: Boolean(args.dry_run),
|
||||
idempotencyKey: typeof args.idempotency_key === 'string' ? args.idempotency_key : undefined,
|
||||
dateForPeriodCheck: tx.date,
|
||||
}
|
||||
)
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
name: 'gnubok_export_sie',
|
||||
keywords: ['sie', 'sie-fil', 'exportera bokföring'],
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `140`;
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `142`;
|
||||
|
||||
exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-keys 1`] = `
|
||||
[
|
||||
@@ -14,6 +14,7 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"DELETE /api/v1/companies/:companyId/salary-runs/:id/employees/:employeeId",
|
||||
"DELETE /api/v1/companies/:companyId/salary-runs/:id/lines/:lineId",
|
||||
"DELETE /api/v1/companies/:companyId/suppliers/:id",
|
||||
"DELETE /api/v1/companies/:companyId/transactions/:id/ignore",
|
||||
"DELETE /api/v1/companies/:companyId/webhooks/:id",
|
||||
"GET /api/v1/companies",
|
||||
"GET /api/v1/companies/:companyId/accounts",
|
||||
@@ -131,6 +132,7 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
|
||||
"POST /api/v1/companies/:companyId/suppliers",
|
||||
"POST /api/v1/companies/:companyId/suppliers/bulk-create",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/categorize",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/ignore",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/match-invoice",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/match-supplier-invoice",
|
||||
"POST /api/v1/companies/:companyId/transactions/:id/uncategorize",
|
||||
|
||||
@@ -64,6 +64,7 @@ import '@/app/api/v1/companies/[companyId]/accounts/route'
|
||||
import '@/app/api/v1/companies/[companyId]/fiscal-periods/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/categorize/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/uncategorize/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/ignore/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/match-invoice/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/[id]/match-supplier-invoice/route'
|
||||
import '@/app/api/v1/companies/[companyId]/transactions/ingest/route'
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
export const API_KEY_SCOPES = {
|
||||
'transactions:read': { label: 'Transaktioner: läs', description: 'Lista transaktioner, mallförslag, kategoriförslag' },
|
||||
'transactions:write': { label: 'Transaktioner: skriv', description: 'Kategorisera, av-kategorisera, kvittomatchning, koppling mot faktura' },
|
||||
'transactions:write': { label: 'Transaktioner: skriv', description: 'Kategorisera, av-kategorisera, ignorera, kvittomatchning, koppling mot faktura' },
|
||||
'customers:read': { label: 'Kunder: läs', description: 'Lista kunder' },
|
||||
'customers:write': { label: 'Kunder: skriv', description: 'Skapa och uppdatera kunder' },
|
||||
'articles:read': { label: 'Artiklar: läs', description: 'Lista artiklar i artikelregistret' },
|
||||
@@ -219,6 +219,7 @@ export const TOOL_SCOPE_MAP: Record<string, ApiKeyScope> = {
|
||||
gnubok_list_transactions_without_documents: 'transactions:read',
|
||||
gnubok_create_transactions: 'transactions:write',
|
||||
gnubok_categorize_transaction: 'transactions:write',
|
||||
gnubok_ignore_transaction: 'transactions:write',
|
||||
gnubok_receipt_matcher: 'transactions:write',
|
||||
gnubok_get_counterparty_templates: 'transactions:read',
|
||||
gnubok_suggest_categories: 'transactions:read',
|
||||
|
||||
@@ -138,6 +138,10 @@ export const V1_ENDPOINT_SCOPES: Record<string, ApiKeyScope> = {
|
||||
'POST /api/v1/companies/:companyId/transactions/:id/uncategorize': 'transactions:write',
|
||||
'POST /api/v1/companies/:companyId/transactions/:id/match-invoice': 'transactions:write',
|
||||
'POST /api/v1/companies/:companyId/transactions/:id/match-supplier-invoice': 'transactions:write',
|
||||
// Ignore / restore: no verifikat, so it is the locked-period escape hatch
|
||||
// for rows that are not business events (issue #1661).
|
||||
'POST /api/v1/companies/:companyId/transactions/:id/ignore': 'transactions:write',
|
||||
'DELETE /api/v1/companies/:companyId/transactions/:id/ignore': 'transactions:write',
|
||||
// Writes: bulk
|
||||
'POST /api/v1/companies/:companyId/transactions/ingest': 'transactions:write',
|
||||
'POST /api/v1/companies/:companyId/transactions/batch-categorize': 'transactions:write',
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -327,7 +327,7 @@ const BOOKKEEPING: Record<string, StructuredErrorEntry> = {
|
||||
message_en: 'Period is locked or closed; entries cannot be added.',
|
||||
remediation: {
|
||||
description:
|
||||
'Either unlock the period via gnubok_unlock_period (if status is "locked", not "closed") or change the entry date to fall inside an open period.',
|
||||
'Either unlock the period via gnubok_unlock_period (if status is "locked", not "closed") or change the entry date to fall inside an open period. A bank transaction that is not a business event (duplicate, never executed) needs no verifikat: ignore it instead (POST /transactions/{id}/ignore, gnubok_ignore_transaction).',
|
||||
tool: 'gnubok_unlock_period',
|
||||
},
|
||||
},
|
||||
@@ -497,6 +497,38 @@ const TRANSACTIONS: Record<string, StructuredErrorEntry> = {
|
||||
description: 'Reload and retry categorization. Report the conflict if it persists.',
|
||||
},
|
||||
},
|
||||
// Issue #1661: a private (is_business=false) marking is a real booking
|
||||
// (eget uttag/insättning on 2013/2018, or 2893 for an AB), so a locked or
|
||||
// closed period blocks it exactly like any other verifikat. The row the
|
||||
// caller usually wants to clear (a PSD2 ghost row, a duplicate, a never
|
||||
// executed transfer) is not an affärshändelse at all: ignoring it writes no
|
||||
// verifikat and is therefore allowed in a locked period. Returned instead
|
||||
// of PERIOD_LOCKED so the remediation names that path. The wording must not
|
||||
// contain "Bokföringen är låst" (inferCode maps that phrase to PERIOD_LOCKED).
|
||||
TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED: {
|
||||
httpStatus: 400,
|
||||
message_sv:
|
||||
'Perioden är låst. En privat markering bokförs som eget uttag eller insättning i perioden. Är raden ingen affärshändelse (dubblett, aldrig genomförd)? Ignorera den i stället. Annars: lås upp perioden.',
|
||||
message_en:
|
||||
'The period is locked. A private marking is booked as an owner withdrawal or deposit inside the period. If the row is not a business event (a duplicate, never executed), ignore it instead; otherwise unlock the period.',
|
||||
remediation: {
|
||||
description:
|
||||
'If the row is not a business event, ignore it: POST /api/v1/companies/{companyId}/transactions/{id}/ignore, the Ignorera action on the Transaktioner page, or gnubok_ignore_transaction. Ignoring writes no verifikat, so it is allowed in a locked or closed period. Otherwise unlock the period via gnubok_unlock_period (status "locked", not "closed") and categorize again.',
|
||||
tool: 'gnubok_ignore_transaction',
|
||||
},
|
||||
},
|
||||
TX_IGNORE_ALREADY_BOOKED: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
'Transaktionen är redan bokförd: använd Avmatcha eller backa verifikationen för att ändra status.',
|
||||
message_en:
|
||||
'The transaction is already booked (directly, via a payment allocation, or via a voucher link). Unlink it or reverse the verifikat (storno) before ignoring it.',
|
||||
remediation: {
|
||||
description:
|
||||
'A booked bank row cannot be ignored: the booking IS its status. Reverse it with gnubok_uncategorize_transaction (storno) or unlink the payment/voucher first, then ignore.',
|
||||
tool: 'gnubok_uncategorize_transaction',
|
||||
},
|
||||
},
|
||||
TX_CATEGORIZE_SUGGEST_SI_MATCH: {
|
||||
httpStatus: 409,
|
||||
message_sv:
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* Executor tests for the staged ignore_transaction operation (issue #1661):
|
||||
* commitIgnoreTransaction is private to commit.ts and reached through
|
||||
* commitPendingOperation (same pattern as account-and-note-executors.test.ts).
|
||||
* Staging-side coverage lives in
|
||||
* extensions/general/mcp-server/__tests__/ignore-transaction.test.ts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { PendingOperation } from '@/types'
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(),
|
||||
}))
|
||||
|
||||
import { commitPendingOperation } from '../commit'
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000aa'
|
||||
|
||||
function makePendingOp(overrides: Partial<PendingOperation>): PendingOperation {
|
||||
return {
|
||||
id: 'op-1',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
operation_type: 'ignore_transaction',
|
||||
status: 'pending',
|
||||
title: 'test',
|
||||
params: { transaction_id: TX_ID, ignored: true },
|
||||
preview_data: {},
|
||||
result_data: null,
|
||||
actor_type: 'user',
|
||||
actor_id: null,
|
||||
actor_label: null,
|
||||
risk_level: 'low',
|
||||
created_at: '2026-08-29T00:00:00Z',
|
||||
resolved_at: null,
|
||||
updated_at: '2026-08-29T00:00:00Z',
|
||||
...overrides,
|
||||
} as PendingOperation
|
||||
}
|
||||
|
||||
function enqueueNoAnchors(enqueue: (r: { data?: unknown; error?: unknown }) => void) {
|
||||
enqueue({ data: [] }) // transaction_voucher_links
|
||||
enqueue({ data: [] }) // invoice_payments
|
||||
enqueue({ data: [] }) // supplier_invoice_payments
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
})
|
||||
|
||||
describe('commitPendingOperation: ignore_transaction', () => {
|
||||
it('happy path: flips is_ignored on an unbooked row and returns committed', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { id: TX_ID, journal_entry_id: null, is_ignored: false } }) // core fetch
|
||||
enqueueNoAnchors(enqueue)
|
||||
enqueue({ data: null }) // update
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', makePendingOp({}))
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ transaction_id: TX_ID, is_ignored: true, changed: true })
|
||||
expect(findCalls('transactions', 'update')).toEqual([[{ is_ignored: true }]])
|
||||
})
|
||||
|
||||
it('is idempotent: an already-ignored row commits with changed=false and no write', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { id: TX_ID, journal_entry_id: null, is_ignored: true } }) // core fetch
|
||||
enqueueNoAnchors(enqueue)
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', makePendingOp({}))
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ is_ignored: true, changed: false })
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses a row that got booked between staging and approval (TX_IGNORE_ALREADY_BOOKED)', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { id: TX_ID, journal_entry_id: 'je-1', is_ignored: false } }) // core fetch: booked now
|
||||
enqueue({ data: null }) // dispatcher reject/finalize update
|
||||
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', makePendingOp({}))
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.code).toBe('TX_IGNORE_ALREADY_BOOKED')
|
||||
expect(result.error).toContain('redan bokförd')
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses a junction-anchored row (journal_entry_id NULL, voucher link present)', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { id: TX_ID, journal_entry_id: null, is_ignored: false } })
|
||||
enqueue({ data: [{ transaction_id: TX_ID }] }) // transaction_voucher_links
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(supabase as never, 'user-1', 'company-1', makePendingOp({}))
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.code).toBe('TX_IGNORE_ALREADY_BOOKED')
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('restore (ignored: false) clears the flag', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: { id: TX_ID, journal_entry_id: null, is_ignored: true } }) // core fetch
|
||||
enqueue({ data: null }) // update
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ params: { transaction_id: TX_ID, ignored: false } }),
|
||||
)
|
||||
|
||||
expect(result.status).toBe('committed')
|
||||
expect(result.data).toMatchObject({ is_ignored: false, changed: true })
|
||||
expect(findCalls('transactions', 'update')).toEqual([[{ is_ignored: false }]])
|
||||
})
|
||||
|
||||
it('rejects tampered params (non-UUID transaction_id) at the commit boundary', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { id: 'op-1' } }) // CAS claim
|
||||
enqueue({ data: null }) // finalize
|
||||
|
||||
const result = await commitPendingOperation(
|
||||
supabase as never, 'user-1', 'company-1',
|
||||
makePendingOp({ params: { transaction_id: 'not-a-uuid', ignored: true } }),
|
||||
)
|
||||
|
||||
expect(result.status).not.toBe('committed')
|
||||
expect(result.error).toMatch(/transaction_id/)
|
||||
expect(findCalls('transactions', 'select')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -148,6 +148,8 @@ import { RetagLineDimensionsParamsSchema } from '@/lib/pending-operations/schema
|
||||
import { CreateAccountParamsSchema, UpdateAccountParamsSchema } from '@/lib/pending-operations/schemas/account'
|
||||
import { defaultRateForVatTreatment } from '@/lib/vat/account-vat-treatment'
|
||||
import { SetVoucherNoteParamsSchema } from '@/lib/pending-operations/schemas/voucher-note'
|
||||
import { IgnoreTransactionParamsSchema } from '@/lib/pending-operations/schemas/ignore-transaction'
|
||||
import { setTransactionIgnored } from '@/lib/transactions/ignore'
|
||||
import { UpdateCompanySettingsParamsSchema } from '@/lib/pending-operations/schemas/company-settings'
|
||||
import { UpdateCustomerParamsSchema } from '@/lib/pending-operations/schemas/customer'
|
||||
import {
|
||||
@@ -1194,6 +1196,51 @@ async function commitSetVoucherNote(
|
||||
}
|
||||
}
|
||||
|
||||
async function commitIgnoreTransaction(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<ExecutorResult> {
|
||||
let validated
|
||||
try {
|
||||
validated = IgnoreTransactionParamsSchema.parse(params)
|
||||
} catch (err) {
|
||||
if (err instanceof z.ZodError) {
|
||||
const issue = err.issues[0]
|
||||
return { error: `Invalid ${issue?.path?.join('.') ?? 'params'}: ${issue?.message ?? 'validation failed'}`, status: 400 }
|
||||
}
|
||||
throw err
|
||||
}
|
||||
|
||||
// Issue #1661: the same core the dashboard and v1 routes use, so the three
|
||||
// doors cannot drift. It refuses a booked row through all three anchors
|
||||
// (journal_entry_id, payment allocations, voucher links), is idempotent,
|
||||
// and writes no verifikat: a locked or closed period does not block it.
|
||||
const outcome = await setTransactionIgnored(
|
||||
supabase,
|
||||
companyId,
|
||||
validated.transaction_id,
|
||||
validated.ignored,
|
||||
)
|
||||
if (!outcome.ok) {
|
||||
const entry = getErrorEntry(outcome.code)
|
||||
return {
|
||||
error: entry?.message_sv ?? 'Transaktionen kunde inte ignoreras.',
|
||||
errorCode: outcome.code,
|
||||
status: outcome.status,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
transaction_id: outcome.transaction_id,
|
||||
is_ignored: outcome.is_ignored,
|
||||
// false when the row was already in the requested state.
|
||||
changed: outcome.changed,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async function commitCreateSupplier(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
@@ -6647,6 +6694,9 @@ async function commitPendingOperationInner(
|
||||
case 'set_voucher_note':
|
||||
result = await commitSetVoucherNote(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'ignore_transaction':
|
||||
result = await commitIgnoreTransaction(supabase, companyId, pendingOp.params)
|
||||
break
|
||||
case 'create_dimension_value':
|
||||
result = await commitCreateDimensionValue(supabase, userId, companyId, pendingOp.params)
|
||||
break
|
||||
|
||||
@@ -45,6 +45,12 @@ export const OPERATION_RISK_TIERS: Record<string, RiskLevel> = {
|
||||
// notes-only diff on committed entries and rejects anything more, so the
|
||||
// op cannot touch booking data even if tampered with.
|
||||
set_voucher_note: 'low',
|
||||
// Ignoring a bank transaction flips transactions.is_ignored and nothing
|
||||
// else: no verifikat, no ledger impact, reversible with the same op
|
||||
// (ignored: false). The DB CHECK transactions_is_ignored_no_journal_entry
|
||||
// and the executor's isTransactionBooked() refusal keep it off booked rows,
|
||||
// so the op cannot hide a booking even if tampered with (issue #1661).
|
||||
ignore_transaction: 'low',
|
||||
|
||||
// ── Medium: reversible booking ─────────────────────────────────────
|
||||
categorize_transaction: 'medium',
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
// Commit-boundary re-validation for the staged ignore_transaction operation
|
||||
// (gnubok_ignore_transaction, issue #1661). Ignoring writes no verifikat: it
|
||||
// flips transactions.is_ignored so a row that is not an affärshändelse (a
|
||||
// PSD2 ghost row, a duplicate from a reconnect, a transfer that never
|
||||
// executed) leaves the "to book" funnels. The DB CHECK
|
||||
// transactions_is_ignored_no_journal_entry guarantees an ignored row is
|
||||
// unbooked, and lib/transactions/ignore.ts refuses a booked row through the
|
||||
// three anchors (journal_entry_id, payment allocations, voucher links), so
|
||||
// this schema only has to bound the shape.
|
||||
|
||||
export const IgnoreTransactionParamsSchema = z.object({
|
||||
transaction_id: z.string().uuid(),
|
||||
// true = ignore (default), false = restore a previously ignored row.
|
||||
ignored: z.boolean().default(true),
|
||||
})
|
||||
|
||||
export type IgnoreTransactionParams = z.infer<typeof IgnoreTransactionParamsSchema>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user