docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,126 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { daysUntilConsentExpiry, getChipState } from '../bank-sync-chip-state'
|
||||
|
||||
const NOW = Date.parse('2026-09-02T08:00:00Z')
|
||||
const HOUR_MS = 60 * 60 * 1000
|
||||
const DAY_MS = 24 * HOUR_MS
|
||||
const at = (msFromNow: number) => new Date(NOW + msFromNow).toISOString()
|
||||
|
||||
function row(overrides: Partial<Parameters<typeof getChipState>[0][number]> = {}) {
|
||||
return {
|
||||
id: 'conn-1',
|
||||
status: 'active',
|
||||
last_synced_at: at(-2 * HOUR_MS),
|
||||
consent_expires: at(60 * DAY_MS),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('daysUntilConsentExpiry', () => {
|
||||
it('rounds a partial day up so "1 day left" never reads as 0', () => {
|
||||
expect(daysUntilConsentExpiry(at(0.4 * DAY_MS), NOW)).toBe(1)
|
||||
expect(daysUntilConsentExpiry(at(6.5 * DAY_MS), NOW)).toBe(7)
|
||||
})
|
||||
|
||||
it('floors at zero once the consent has passed', () => {
|
||||
expect(daysUntilConsentExpiry(at(-3 * DAY_MS), NOW)).toBe(0)
|
||||
})
|
||||
|
||||
it('is null without a usable timestamp', () => {
|
||||
expect(daysUntilConsentExpiry(null, NOW)).toBeNull()
|
||||
expect(daysUntilConsentExpiry(undefined, NOW)).toBeNull()
|
||||
expect(daysUntilConsentExpiry('nope', NOW)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getChipState', () => {
|
||||
it('is hidden without connections', () => {
|
||||
expect(getChipState([], { now: NOW })).toEqual({ kind: 'none' })
|
||||
})
|
||||
|
||||
it('reads healthy for a recent sync with a distant consent', () => {
|
||||
expect(getChipState([row()], { now: NOW })).toEqual({ kind: 'healthy', mostRecent: at(-2 * HOUR_MS) })
|
||||
})
|
||||
|
||||
it('warns when a live consent ends within seven days', () => {
|
||||
expect(getChipState([row({ consent_expires: at(7 * DAY_MS) })], { now: NOW })).toEqual({
|
||||
kind: 'expiring',
|
||||
daysLeft: 7,
|
||||
count: 1,
|
||||
})
|
||||
})
|
||||
|
||||
it('stays quiet at eight days', () => {
|
||||
expect(getChipState([row({ consent_expires: at(8 * DAY_MS) })], { now: NOW }).kind).toBe('healthy')
|
||||
})
|
||||
|
||||
it('reports the soonest expiry and how many are affected', () => {
|
||||
const state = getChipState(
|
||||
[
|
||||
row({ id: 'a', consent_expires: at(5 * DAY_MS) }),
|
||||
row({ id: 'b', consent_expires: at(2 * DAY_MS) }),
|
||||
row({ id: 'c', consent_expires: at(30 * DAY_MS) }),
|
||||
],
|
||||
{ now: NOW },
|
||||
)
|
||||
expect(state).toEqual({ kind: 'expiring', daysLeft: 2, count: 2 })
|
||||
})
|
||||
|
||||
it('ranks a dead connection above an expiring one', () => {
|
||||
const state = getChipState(
|
||||
[
|
||||
row({ id: 'a', status: 'expired' }),
|
||||
row({ id: 'b', consent_expires: at(1 * DAY_MS) }),
|
||||
],
|
||||
{ now: NOW },
|
||||
)
|
||||
expect(state).toEqual({ kind: 'attention', count: 1 })
|
||||
})
|
||||
|
||||
it('ranks expiring above stale: the deadline matters more than the age', () => {
|
||||
const state = getChipState(
|
||||
[row({ last_synced_at: at(-3 * DAY_MS), consent_expires: at(3 * DAY_MS) })],
|
||||
{ now: NOW },
|
||||
)
|
||||
expect(state.kind).toBe('expiring')
|
||||
})
|
||||
|
||||
it('ignores the consent on rows that are not live yet', () => {
|
||||
const state = getChipState(
|
||||
[row({ status: 'pending_selection', consent_expires: at(1 * DAY_MS), last_synced_at: null })],
|
||||
{ now: NOW },
|
||||
)
|
||||
expect(state).toEqual({ kind: 'healthy', mostRecent: null })
|
||||
})
|
||||
|
||||
it('reads stale after 36 hours without a sync', () => {
|
||||
expect(getChipState([row({ last_synced_at: at(-37 * HOUR_MS) })], { now: NOW })).toEqual({
|
||||
kind: 'stale',
|
||||
mostRecent: at(-37 * HOUR_MS),
|
||||
})
|
||||
})
|
||||
|
||||
it('reads paused when the company lacks the bank_sync entitlement', () => {
|
||||
// 56 of 191 active connections on prod sat in this state on 2026-09-01:
|
||||
// the cron skips them, so they are neither dead nor merely stale.
|
||||
const state = getChipState([row({ last_synced_at: at(-20 * DAY_MS) })], {
|
||||
now: NOW,
|
||||
hasBankSync: false,
|
||||
})
|
||||
expect(state).toEqual({ kind: 'paused' })
|
||||
})
|
||||
|
||||
it('ranks paused above a dead connection: renewing without a subscription changes nothing', () => {
|
||||
const state = getChipState([row({ status: 'expired' })], { now: NOW, hasBankSync: false })
|
||||
expect(state).toEqual({ kind: 'paused' })
|
||||
})
|
||||
|
||||
it('stays hidden without connections even when unentitled', () => {
|
||||
expect(getChipState([], { now: NOW, hasBankSync: false })).toEqual({ kind: 'none' })
|
||||
})
|
||||
|
||||
it('tolerates rows without the consent column', () => {
|
||||
const state = getChipState([{ id: 'x', status: 'active', last_synced_at: at(-HOUR_MS) }], { now: NOW })
|
||||
expect(state.kind).toBe('healthy')
|
||||
})
|
||||
})
|
||||
@@ -1,139 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import {
|
||||
claimConnectionsLoad,
|
||||
clearBusyConnection,
|
||||
getBankSyncSnapshot,
|
||||
markConnectionStatus,
|
||||
publishConnections,
|
||||
releaseConnectionsLoad,
|
||||
resetBankSyncStore,
|
||||
setBusyConnection,
|
||||
setSyncingAll,
|
||||
subscribeBankSync,
|
||||
type BankConn,
|
||||
} from '@/lib/transactions/bank-sync-store'
|
||||
|
||||
const conn = (id: string, status = 'active'): BankConn => ({
|
||||
id,
|
||||
bank_name: 'Testbanken',
|
||||
status,
|
||||
provider: 'enablebanking-se',
|
||||
last_synced_at: null,
|
||||
})
|
||||
|
||||
describe('bank-sync-store', () => {
|
||||
beforeEach(() => {
|
||||
resetBankSyncStore()
|
||||
})
|
||||
|
||||
describe('connections load claiming', () => {
|
||||
it('lets only the first instance claim the fetch for a company', () => {
|
||||
expect(claimConnectionsLoad('co-1')).toBe(true)
|
||||
// Second surface mounting while the fetch is in flight must not refetch.
|
||||
expect(claimConnectionsLoad('co-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('does not re-claim once connections are published', () => {
|
||||
expect(claimConnectionsLoad('co-1')).toBe(true)
|
||||
publishConnections('co-1', [conn('c1')])
|
||||
expect(claimConnectionsLoad('co-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('allows a retry after a failed load is released', () => {
|
||||
expect(claimConnectionsLoad('co-1')).toBe(true)
|
||||
releaseConnectionsLoad('co-1')
|
||||
expect(claimConnectionsLoad('co-1')).toBe(true)
|
||||
})
|
||||
|
||||
it('claims independently per company (company switch refetches)', () => {
|
||||
expect(claimConnectionsLoad('co-1')).toBe(true)
|
||||
publishConnections('co-1', [conn('c1')])
|
||||
expect(claimConnectionsLoad('co-2')).toBe(true)
|
||||
publishConnections('co-2', [conn('c2')])
|
||||
expect(getBankSyncSnapshot().companyId).toBe('co-2')
|
||||
expect(getBankSyncSnapshot().connections).toEqual([conn('c2')])
|
||||
})
|
||||
|
||||
it('discards a stale resolve after the company switched mid-flight', () => {
|
||||
expect(claimConnectionsLoad('co-1')).toBe(true) // fetch for co-1 in flight
|
||||
expect(claimConnectionsLoad('co-2')).toBe(true) // switch re-claims the slot
|
||||
publishConnections('co-2', [conn('c2')])
|
||||
// co-1's fetch resolves late: it no longer owns the claim and must not
|
||||
// clobber co-2's published list.
|
||||
publishConnections('co-1', [conn('c1')])
|
||||
expect(getBankSyncSnapshot().companyId).toBe('co-2')
|
||||
expect(getBankSyncSnapshot().connections).toEqual([conn('c2')])
|
||||
})
|
||||
|
||||
it('ignores a publish that never claimed the load', () => {
|
||||
publishConnections('co-1', [conn('c1')])
|
||||
expect(getBankSyncSnapshot().connections).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('busy state', () => {
|
||||
it('shares busyId through the snapshot and notifies subscribers', () => {
|
||||
const listener = vi.fn()
|
||||
subscribeBankSync(listener)
|
||||
setBusyConnection('c1')
|
||||
expect(getBankSyncSnapshot().busyId).toBe('c1')
|
||||
expect(listener).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('clearBusyConnection only clears when that connection owns busy', () => {
|
||||
setBusyConnection('c1')
|
||||
clearBusyConnection('c2')
|
||||
expect(getBankSyncSnapshot().busyId).toBe('c1')
|
||||
clearBusyConnection('c1')
|
||||
expect(getBankSyncSnapshot().busyId).toBeNull()
|
||||
})
|
||||
|
||||
it('does not notify on a no-op write (stable snapshot identity)', () => {
|
||||
setBusyConnection('c1')
|
||||
const listener = vi.fn()
|
||||
subscribeBankSync(listener)
|
||||
const before = getBankSyncSnapshot()
|
||||
setBusyConnection('c1')
|
||||
setSyncingAll(false)
|
||||
expect(listener).not.toHaveBeenCalled()
|
||||
expect(getBankSyncSnapshot()).toBe(before)
|
||||
})
|
||||
|
||||
it('tracks syncingAll independently of busyId', () => {
|
||||
setSyncingAll(true)
|
||||
expect(getBankSyncSnapshot().syncingAll).toBe(true)
|
||||
expect(getBankSyncSnapshot().busyId).toBeNull()
|
||||
setSyncingAll(false)
|
||||
expect(getBankSyncSnapshot().syncingAll).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('markConnectionStatus', () => {
|
||||
it('updates one connection immutably', () => {
|
||||
claimConnectionsLoad('co-1')
|
||||
publishConnections('co-1', [conn('c1'), conn('c2')])
|
||||
const before = getBankSyncSnapshot().connections
|
||||
markConnectionStatus('c1', 'expired')
|
||||
const after = getBankSyncSnapshot().connections
|
||||
expect(after).not.toBe(before)
|
||||
expect(after?.find((c) => c.id === 'c1')?.status).toBe('expired')
|
||||
expect(after?.find((c) => c.id === 'c2')?.status).toBe('active')
|
||||
})
|
||||
|
||||
it('is a no-op before any connections are loaded', () => {
|
||||
const listener = vi.fn()
|
||||
subscribeBankSync(listener)
|
||||
markConnectionStatus('c1', 'expired')
|
||||
expect(listener).not.toHaveBeenCalled()
|
||||
expect(getBankSyncSnapshot().connections).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
it('unsubscribe stops notifications', () => {
|
||||
const listener = vi.fn()
|
||||
const unsubscribe = subscribeBankSync(listener)
|
||||
unsubscribe()
|
||||
setBusyConnection('c1')
|
||||
expect(listener).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,223 +0,0 @@
|
||||
/**
|
||||
* The duplicate-guard refusal message in `categorizeMatchedTransaction`.
|
||||
*
|
||||
* This message is what the agent (MCP categorize flow) and the pending-operation
|
||||
* executors surface when the booking-time duplicate guard fires, and it appends
|
||||
* "kr" verbatim to a number. The contract under test: that number is ALWAYS the
|
||||
* candidate's SEK figure from the detector (`dup.amount`), never the raw foreign
|
||||
* `transactions.amount`, and when the detector could not establish a SEK figure
|
||||
* at all (`dup.amount === null`) the message states the amount in the sibling's
|
||||
* own currency and says the kronor value cannot be determined, rather than
|
||||
* fabricating one.
|
||||
*
|
||||
* Companion to lib/transactions/__tests__/booking-duplicate-detection.test.ts,
|
||||
* which pins the producer side of the same contract.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
const mockDetectDup = vi.fn()
|
||||
const mockCreateJE = vi.fn()
|
||||
const mockMapping = vi.fn()
|
||||
const mockHasLiveLink = vi.fn()
|
||||
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookingDuplicate: (...args: unknown[]) => mockDetectDup(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
createTransactionJournalEntry: (...args: unknown[]) => mockCreateJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/category-mapping', () => ({
|
||||
buildMappingResultFromCategory: (...args: unknown[]) => mockMapping(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
|
||||
upsertCounterpartyTemplate: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/core/documents/document-service', () => ({
|
||||
linkToJournalEntry: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/link-journal-entry', () => ({
|
||||
hasLiveJournalEntryLink: (...args: unknown[]) => mockHasLiveLink(...args),
|
||||
}))
|
||||
|
||||
import { buildDuplicateBookingClaim, categorizeMatchedTransaction } from '../categorize-core'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
|
||||
/**
|
||||
* The exact sv-SE prose formatting the claim builder uses: two decimals,
|
||||
* Swedish grouping, magnitude only. Computed with the same toLocaleString
|
||||
* call so the tests stay correct across ICU variants (the group separator is
|
||||
* a non-breaking space in most builds).
|
||||
*/
|
||||
const sv = (n: number) =>
|
||||
Math.abs(n).toLocaleString('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||
|
||||
/** Queue-based supabase mock: each `from()` consumes the next queued result. */
|
||||
function queuedSupabase(results: Array<{ data?: unknown; error?: unknown }>) {
|
||||
const queue = [...results]
|
||||
const from = vi.fn(() => {
|
||||
const raw = queue.shift() ?? { data: null, error: null }
|
||||
const result = { data: raw.data ?? null, error: raw.error ?? null }
|
||||
const chain: object = new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop) {
|
||||
if (prop === 'then') return (resolve: (v: unknown) => void) => resolve(result)
|
||||
return () => chain
|
||||
},
|
||||
},
|
||||
)
|
||||
return chain
|
||||
})
|
||||
return { from } as never
|
||||
}
|
||||
|
||||
/** A `transactions` row as select('*') returns it. Synthetic fixture. */
|
||||
const txRow = (over: Record<string, unknown> = {}) => ({
|
||||
id: 'tx-1',
|
||||
date: '2026-06-01',
|
||||
amount: -1616,
|
||||
currency: 'SEK',
|
||||
amount_sek: null,
|
||||
exchange_rate: null,
|
||||
description: 'PROGRAMVARA AB',
|
||||
cash_account_id: null,
|
||||
journal_entry_id: null,
|
||||
...over,
|
||||
})
|
||||
|
||||
/** A detector candidate with the invariant defaults (SEK, verified). */
|
||||
const candidate = (over: Record<string, unknown> = {}) => ({
|
||||
transaction_id: 'sib-1',
|
||||
journal_entry_id: 'je-1',
|
||||
voucher_label: 'A142',
|
||||
entry_date: '2026-06-01',
|
||||
description: 'PROGRAMVARA AB',
|
||||
amount: -1616,
|
||||
account_number: null,
|
||||
currency: null,
|
||||
amount_in_currency: null,
|
||||
amount_verified: true,
|
||||
unverified_reason: null,
|
||||
...over,
|
||||
})
|
||||
|
||||
const OPTS = { category: 'expense_software' as const }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockHasLiveLink.mockResolvedValue(false)
|
||||
})
|
||||
|
||||
describe('categorizeMatchedTransaction duplicate refusal message', () => {
|
||||
it('states a verified SEK twin as an absolute, sv-SE-formatted kr amount', async () => {
|
||||
mockDetectDup.mockResolvedValue(candidate())
|
||||
const supabase = queuedSupabase([{ data: txRow() }])
|
||||
|
||||
const result = await categorizeMatchedTransaction(supabase, 'u1', 'c1', 'tx-1', OPTS)
|
||||
|
||||
expect(result.status).toBe(409)
|
||||
expect(result.error).toContain('verifikat A142')
|
||||
expect(result.error).toContain(`bokför redan ${sv(1616)} kr`)
|
||||
expect(result.error).not.toContain('-1616')
|
||||
// Raw JS number inside Swedish prose is the finding: '1616 kr' must be
|
||||
// '1 616,00 kr'.
|
||||
expect(result.error).not.toContain('1616 kr')
|
||||
})
|
||||
|
||||
it('prints the SIBLING SEK figure for a verified FX twin, never the raw EUR number as kr', async () => {
|
||||
// A 1 000 EUR sibling whose own booking states 11 500 kr. The message must
|
||||
// carry 11 500,00 kr; "1 000,00 kr" would be the original bug (foreign
|
||||
// figure with "kr" appended) in text form.
|
||||
mockDetectDup.mockResolvedValue(
|
||||
candidate({ amount: -11500, currency: 'EUR', amount_in_currency: -1000 }),
|
||||
)
|
||||
const supabase = queuedSupabase([
|
||||
{ data: txRow({ amount: -1000, currency: 'EUR', amount_sek: -11450, exchange_rate: 11.45 }) },
|
||||
])
|
||||
|
||||
const result = await categorizeMatchedTransaction(supabase, 'u1', 'c1', 'tx-1', OPTS)
|
||||
|
||||
expect(result.status).toBe(409)
|
||||
expect(result.error).toContain(`bokför redan ${sv(11500)} kr`)
|
||||
expect(result.error).not.toContain(`${sv(1000)} kr`)
|
||||
expect(result.error).not.toContain('1000 kr')
|
||||
})
|
||||
|
||||
it('refuses to fabricate kronor for a rateless foreign sibling: states the foreign amount instead', async () => {
|
||||
mockDetectDup.mockResolvedValue(
|
||||
candidate({
|
||||
amount: null,
|
||||
currency: 'EUR',
|
||||
amount_in_currency: -1000,
|
||||
amount_verified: false,
|
||||
unverified_reason: 'transaction_missing_sek_value',
|
||||
}),
|
||||
)
|
||||
const supabase = queuedSupabase([
|
||||
{ data: txRow({ amount: -1000, currency: 'EUR' }) },
|
||||
])
|
||||
|
||||
const result = await categorizeMatchedTransaction(supabase, 'u1', 'c1', 'tx-1', OPTS)
|
||||
|
||||
expect(result.status).toBe(409)
|
||||
expect(result.error).toContain(`samma belopp (${sv(1000)} EUR)`)
|
||||
expect(result.error).toContain('kan inte fastställas')
|
||||
// No number in the message wears a kr label (the group separator in
|
||||
// sv-SE output is a non-breaking space, so an ASCII-space match suffices).
|
||||
expect(result.error).not.toMatch(/\d ?kr\b/)
|
||||
})
|
||||
|
||||
it('says the amounts could not be compared for an unverified ledger candidate', async () => {
|
||||
// Ledger-voucher candidate found for a rateless foreign bank line: the kr
|
||||
// figure is the leg's own SEK amount (real), but no comparison was possible.
|
||||
mockDetectDup.mockResolvedValue(
|
||||
candidate({
|
||||
transaction_id: null,
|
||||
amount: 98565,
|
||||
account_number: '1930',
|
||||
amount_verified: false,
|
||||
unverified_reason: 'transaction_missing_sek_value',
|
||||
}),
|
||||
)
|
||||
const supabase = queuedSupabase([
|
||||
{ data: txRow({ amount: -8570.87, currency: 'EUR' }) },
|
||||
])
|
||||
|
||||
const result = await categorizeMatchedTransaction(supabase, 'u1', 'c1', 'tx-1', OPTS)
|
||||
|
||||
expect(result.status).toBe(409)
|
||||
expect(result.error).toContain(`bokför ${sv(98565)} kr`)
|
||||
expect(result.error).toContain('beloppen kunde inte jämföras')
|
||||
expect(result.error).toContain('EUR')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildDuplicateBookingClaim (shared web + MCP claim builder)', () => {
|
||||
it('never renders "null kr" for the rateless foreign sibling shape', () => {
|
||||
const claim = buildDuplicateBookingClaim(
|
||||
{ amount: null, currency: 'EUR', amount_in_currency: -1000, amount_verified: false },
|
||||
'EUR',
|
||||
)
|
||||
expect(claim).toContain(`samma belopp (${sv(1000)} EUR)`)
|
||||
expect(claim).toContain('växelkurs saknas')
|
||||
expect(claim).not.toContain('null')
|
||||
})
|
||||
|
||||
it('uses magnitude and sv-SE formatting for the verified kr figure', () => {
|
||||
const claim = buildDuplicateBookingClaim(
|
||||
{ amount: -11500, currency: 'EUR', amount_in_currency: -1000, amount_verified: true },
|
||||
'EUR',
|
||||
)
|
||||
expect(claim).toBe(`bokför redan ${sv(11500)} kr på bankkontot`)
|
||||
})
|
||||
|
||||
it('attributes the missing rate to the TARGET transaction in the unverified branch', () => {
|
||||
const claim = buildDuplicateBookingClaim(
|
||||
{ amount: 98565, currency: null, amount_in_currency: null, amount_verified: false },
|
||||
'EUR',
|
||||
)
|
||||
expect(claim).toContain(`bokför ${sv(98565)} kr`)
|
||||
expect(claim).toContain('transaktionen är i EUR utan växelkurs')
|
||||
})
|
||||
})
|
||||
@@ -1,199 +0,0 @@
|
||||
/**
|
||||
* categorizeMatchedTransaction fails closed on the engine's null return
|
||||
* (issue #1947).
|
||||
*
|
||||
* createTransactionJournalEntry returns null WITHOUT throwing when
|
||||
* findFiscalPeriod sees no OPEN period covering the date and the pre-FY clamp
|
||||
* does not apply: the covering rakenskapsar is closed (is_closed = true), or
|
||||
* no period exists there at all. The pre-fix core fell through to the
|
||||
* transactions update anyway, writing is_business/category with
|
||||
* journal_entry_id NULL: the row left "Att bokfora" and the nav badge while
|
||||
* still unbooked, and the pending operation / bulk driver reported success.
|
||||
*
|
||||
* These tests pin the guard: on a null entry NOTHING is written (no
|
||||
* transactions update, no counterparty template, no event) and the caller
|
||||
* gets a structured 400 whose errorCode distinguishes a closed period
|
||||
* (PERIOD_LOCKED) from a missing one (NO_OPEN_PERIOD_FOR_DATE), so
|
||||
* result_data.error_code carries it through the pending-operations layer.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const mockCreateJE = vi.fn()
|
||||
const mockReverseOrphanedJE = vi.fn()
|
||||
const mockUpsertTemplate = vi.fn()
|
||||
const mockCheckPeriodLock = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
createTransactionJournalEntry: (...args: unknown[]) => mockCreateJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/cancel-orphaned-entry', () => ({
|
||||
reverseOrphanedJournalEntry: (...args: unknown[]) => mockReverseOrphanedJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookingDuplicate: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/inbox-underlag', () => ({
|
||||
propagateUnderlagForBookedTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
|
||||
upsertCounterpartyTemplate: (...args: unknown[]) => mockUpsertTemplate(...args),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/link-journal-entry', () => ({
|
||||
hasLiveJournalEntryLink: vi.fn().mockResolvedValue(false),
|
||||
}))
|
||||
vi.mock('@/lib/processing-history/append', () => ({
|
||||
appendProcessingHistory: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/api/v1/check-period-lock', () => ({
|
||||
checkPeriodLock: (...args: unknown[]) => mockCheckPeriodLock(...args),
|
||||
}))
|
||||
|
||||
import { categorizeMatchedTransaction } from '../categorize-core'
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000aa'
|
||||
|
||||
/** A transaction dated inside a fiscal year that is klarmarkerad (closed). */
|
||||
const txRow = (over: Record<string, unknown> = {}) => ({
|
||||
id: TX_ID,
|
||||
company_id: 'company-1',
|
||||
date: '2024-11-15',
|
||||
amount: -1200,
|
||||
currency: 'SEK',
|
||||
amount_sek: -1200,
|
||||
exchange_rate: 1,
|
||||
description: 'PROGRAMVARA AB',
|
||||
merchant_name: null,
|
||||
cash_account_id: null,
|
||||
document_id: null,
|
||||
journal_entry_id: null,
|
||||
...over,
|
||||
})
|
||||
|
||||
const settingsRow = { entity_type: 'aktiebolag', fiscal_year_start_month: 1 }
|
||||
|
||||
/**
|
||||
* Queue the reads up to the engine call: transactions select,
|
||||
* company_settings, resolveSettlementAccount, ensureFiscalPeriod (no open
|
||||
* period, earliest period start not after the date, upsert bounces off the
|
||||
* closed year's range: return value is ignored by the caller).
|
||||
*/
|
||||
function enqueueUpToEngine(enqueue: (r: { data?: unknown; error?: unknown }) => void) {
|
||||
enqueue({ data: txRow() }) // transactions select
|
||||
enqueue({ data: settingsRow }) // company_settings
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [] }) // ensureFiscalPeriod: no OPEN period covers the date
|
||||
enqueue({ data: [{ period_start: '2024-01-01' }] }) // earliest period start (pre-FY guard passes)
|
||||
enqueue({ data: null }) // ensureFiscalPeriod upsert; its outcome is ignored by the caller
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockCreateJE.mockResolvedValue(null) // the engine's no-open-period null return
|
||||
})
|
||||
|
||||
describe('categorizeMatchedTransaction: null engine return fails closed (issue #1947)', () => {
|
||||
it('refuses with PERIOD_LOCKED and writes nothing when the covering year is closed', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
const categorizedHandler = vi.fn()
|
||||
eventBus.on('transaction.categorized', categorizedHandler)
|
||||
enqueueUpToEngine(enqueue)
|
||||
mockCheckPeriodLock.mockResolvedValue({
|
||||
locked: true,
|
||||
reason: 'period_is_closed',
|
||||
fiscal_period_id: 'fp-2024',
|
||||
})
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'expense_software' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(400)
|
||||
expect(result.errorCode).toBe('PERIOD_LOCKED')
|
||||
expect(result.error).toBe('Bokföringen är låst för denna period.')
|
||||
expect(result.data).toBeUndefined()
|
||||
// The #1947 defect: the update ran anyway and stranded the row as
|
||||
// categorized-but-unbooked. Nothing may be written now.
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
expect(mockUpsertTemplate).not.toHaveBeenCalled()
|
||||
expect(mockReverseOrphanedJE).not.toHaveBeenCalled()
|
||||
expect(categorizedHandler).not.toHaveBeenCalled()
|
||||
expect(mockCheckPeriodLock).toHaveBeenCalledWith(expect.anything(), 'company-1', '2024-11-15')
|
||||
})
|
||||
|
||||
it('refuses with NO_OPEN_PERIOD_FOR_DATE and writes nothing when no period exists', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueueUpToEngine(enqueue)
|
||||
mockCheckPeriodLock.mockResolvedValue({ locked: false, reason: 'no_fiscal_period' })
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'expense_software' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(400)
|
||||
expect(result.errorCode).toBe('NO_OPEN_PERIOD_FOR_DATE')
|
||||
expect(result.error).toContain('räkenskapsperiod')
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
expect(mockUpsertTemplate).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('categorizeMatchedTransaction: private marking in a locked period (issue #1661)', () => {
|
||||
it('refuses with TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED before the engine runs and writes nothing', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueueUpToEngine(enqueue)
|
||||
mockCheckPeriodLock.mockResolvedValue({
|
||||
locked: true,
|
||||
reason: 'period_locked_at_set',
|
||||
fiscal_period_id: 'fp-2024',
|
||||
})
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'private' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(400)
|
||||
expect(result.errorCode).toBe('TX_CATEGORIZE_PRIVATE_PERIOD_LOCKED')
|
||||
expect(result.error).toContain('Ignorera')
|
||||
expect(result.data).toBeUndefined()
|
||||
// A private marking is a real booking, so the lock applies; the pre-check
|
||||
// answers with the ignore-steering code instead of letting the engine run.
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
expect(mockUpsertTemplate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps PERIOD_LOCKED for a business categorization in the same period', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueueUpToEngine(enqueue)
|
||||
mockCheckPeriodLock.mockResolvedValue({
|
||||
locked: true,
|
||||
reason: 'period_locked_at_set',
|
||||
fiscal_period_id: 'fp-2024',
|
||||
})
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'expense_software' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(400)
|
||||
expect(result.errorCode).toBe('PERIOD_LOCKED')
|
||||
})
|
||||
})
|
||||
@@ -1,111 +0,0 @@
|
||||
/**
|
||||
* categorizeMatchedTransaction refuses a transaction that is anchored through
|
||||
* transaction_voucher_links (issue #1553).
|
||||
*
|
||||
* A row bulk-booked into a samlingsverifikat, or split over several verifikat
|
||||
* (linkTransactionToVouchers), carries journal_entry_id = NULL: the pointer
|
||||
* alone reads as "unbooked" and the categorize path would book it a second
|
||||
* time. The guard is role-aware: only 'bank_line' rows are slices of the
|
||||
* bank amount; a residual booking's 'other' row (lib/reconciliation/
|
||||
* residual.ts) left behind by a storno of the main verifikat must not strand
|
||||
* the row (its pointer is NULL and koppla-bort refuses it too).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const mockCreateJE = vi.fn()
|
||||
const mockCheckPeriodLock = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
createTransactionJournalEntry: (...args: unknown[]) => mockCreateJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/cancel-orphaned-entry', () => ({
|
||||
reverseOrphanedJournalEntry: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookingDuplicate: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/inbox-underlag', () => ({
|
||||
propagateUnderlagForBookedTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
|
||||
upsertCounterpartyTemplate: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/link-journal-entry', () => ({
|
||||
hasLiveJournalEntryLink: vi.fn().mockResolvedValue(false),
|
||||
}))
|
||||
vi.mock('@/lib/processing-history/append', () => ({
|
||||
appendProcessingHistory: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/api/v1/check-period-lock', () => ({
|
||||
checkPeriodLock: (...args: unknown[]) => mockCheckPeriodLock(...args),
|
||||
}))
|
||||
|
||||
import { categorizeMatchedTransaction } from '../categorize-core'
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000aa'
|
||||
|
||||
const txRow = (links: Array<{ journal_entry_id: string; role: string }>) => ({
|
||||
id: TX_ID,
|
||||
company_id: 'company-1',
|
||||
date: '2026-06-11',
|
||||
amount: -800,
|
||||
currency: 'SEK',
|
||||
amount_sek: -800,
|
||||
exchange_rate: 1,
|
||||
description: 'UTBETALNING',
|
||||
merchant_name: null,
|
||||
cash_account_id: null,
|
||||
document_id: null,
|
||||
journal_entry_id: null,
|
||||
transaction_voucher_links: links,
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockCreateJE.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
describe('categorizeMatchedTransaction: transaction_voucher_links guard (#1553)', () => {
|
||||
it('returns 409 and writes nothing for a row split over several verifikat (bank_line rows, NULL pointer)', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: txRow([
|
||||
{ journal_entry_id: 'je-utlagg-1', role: 'bank_line' },
|
||||
{ journal_entry_id: 'je-utlagg-2', role: 'bank_line' },
|
||||
]),
|
||||
})
|
||||
|
||||
const result = await categorizeMatchedTransaction(supabase as never, 'user-1', 'company-1', TX_ID, {
|
||||
category: 'expense_other',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(409)
|
||||
expect(result.error).toMatch(/already has a journal entry/)
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
// The read carried the junction rows along: no second query was needed.
|
||||
expect(supabase.from).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('lets a row carrying only a residual "other" row past the guard', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow([{ journal_entry_id: 'je-residual', role: 'other' }]) })
|
||||
enqueue({ data: { entity_type: 'aktiebolag', fiscal_year_start_month: 1 } }) // company_settings
|
||||
enqueue({ data: [] }) // resolveSettlementAccount
|
||||
enqueue({ data: [] }) // ensureFiscalPeriod: no open period
|
||||
enqueue({ data: [{ period_start: '2026-01-01' }] })
|
||||
enqueue({ data: null })
|
||||
mockCheckPeriodLock.mockResolvedValue({ locked: true, reason: 'period_is_closed', fiscal_period_id: 'fp-2026' })
|
||||
|
||||
const result = await categorizeMatchedTransaction(supabase as never, 'user-1', 'company-1', TX_ID, {
|
||||
category: 'expense_other',
|
||||
})
|
||||
|
||||
// Reached the engine (which fails closed on the locked period here):
|
||||
// the junction guard did not fire.
|
||||
expect(result.status).not.toBe(409)
|
||||
expect(mockCreateJE).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,122 +0,0 @@
|
||||
/**
|
||||
* Issue #1643 problem 4: the categorize commit path must never book the
|
||||
* COUNTER leg onto an orphaned cash-account ledger (a 19xx account held by a
|
||||
* revoked bank connection, or a stale IBAN twin of a live account). Confirming
|
||||
* such a proposal silently drops revenue/expense from the P&L onto a junk
|
||||
* balance-sheet account.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const mockCreateJE = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
createTransactionJournalEntry: (...args: unknown[]) => mockCreateJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/cancel-orphaned-entry', () => ({
|
||||
reverseOrphanedJournalEntry: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookingDuplicate: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/inbox-underlag', () => ({
|
||||
propagateUnderlagForBookedTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
|
||||
upsertCounterpartyTemplate: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/link-journal-entry', () => ({
|
||||
hasLiveJournalEntryLink: vi.fn().mockResolvedValue(false),
|
||||
}))
|
||||
vi.mock('@/lib/processing-history/append', () => ({
|
||||
appendProcessingHistory: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
import { categorizeMatchedTransaction } from '../categorize-core'
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000dd'
|
||||
|
||||
const txRow = (over: Record<string, unknown> = {}) => ({
|
||||
id: TX_ID,
|
||||
company_id: 'company-1',
|
||||
date: '2026-07-10',
|
||||
amount: 217.04,
|
||||
currency: 'SEK',
|
||||
amount_sek: 217.04,
|
||||
exchange_rate: 1,
|
||||
description: 'Insättningsränta',
|
||||
merchant_name: null,
|
||||
cash_account_id: null,
|
||||
document_id: null,
|
||||
journal_entry_id: null,
|
||||
...over,
|
||||
})
|
||||
|
||||
const settingsRow = { entity_type: 'aktiebolag', fiscal_year_start_month: 1 }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockCreateJE.mockResolvedValue({ id: 'je-1' })
|
||||
})
|
||||
|
||||
describe('categorizeMatchedTransaction: orphaned counter-account guard', () => {
|
||||
it('refuses to book when the override counter is a revoked-held twin of a live row', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() }) // transactions select
|
||||
enqueue({ data: settingsRow }) // company_settings
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
// Override chart hit: 1931 exists and is active in the chart (the orphaned
|
||||
// ledger was auto-created there by the broken reconnect).
|
||||
enqueue({ data: { account_number: '1931', account_class: 1, is_active: true } })
|
||||
// Guard: cash_accounts scan finds 1931 held by a revoked connection AND
|
||||
// sharing its (IBAN, currency) with the live 1940 row: a stale twin.
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'ca-live', ledger_account: '1940', bank_connection_id: 'conn-live', iban: 'SE455', enabled: true, currency: 'SEK' },
|
||||
{ id: 'ca-orphan', ledger_account: '1931', bank_connection_id: 'conn-old', iban: 'SE455', enabled: true, currency: 'SEK' },
|
||||
],
|
||||
})
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'conn-live', status: 'active' },
|
||||
{ id: 'conn-old', status: 'revoked' },
|
||||
],
|
||||
})
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never, 'user-1', 'company-1', TX_ID,
|
||||
{ category: 'income_services', vatTreatment: 'exempt', accountOverride: '1931' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(400)
|
||||
expect(result.error).toMatch(/1931/)
|
||||
expect(result.error).toMatch(/frånkopplad/)
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still books when the 19xx counter is a live cash account (genuine transfer target)', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow({ amount: -500, amount_sek: -500 }) })
|
||||
enqueue({ data: settingsRow })
|
||||
enqueue({ data: [] }) // resolveSettlementAccount fallback -> 1930
|
||||
enqueue({ data: { account_number: '1940', account_class: 1, is_active: true } }) // override chart hit
|
||||
// Guard: 1940 is held by an ACTIVE connection -> not orphaned.
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'ca-live', ledger_account: '1940', bank_connection_id: 'conn-live', iban: 'SE455', enabled: true },
|
||||
],
|
||||
})
|
||||
enqueue({ data: [{ id: 'conn-live', status: 'active' }] })
|
||||
enqueue({ data: [{ id: 'fp-1' }] }) // ensureFiscalPeriod
|
||||
enqueue({ data: [txRow({ journal_entry_id: 'je-1' })] }) // transactions update
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never, 'user-1', 'company-1', TX_ID,
|
||||
{ category: 'expense_other', vatTreatment: 'exempt', accountOverride: '1940' },
|
||||
)
|
||||
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(mockCreateJE).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,285 +0,0 @@
|
||||
/**
|
||||
* categorizeMatchedTransaction: the accountOverride commit path.
|
||||
*
|
||||
* The MCP staging tool validates the override once, but the account can be
|
||||
* deactivated between staging and the user's approval, so the core re-applies
|
||||
* and re-validates independently. These tests pin that the posted mapping
|
||||
* carries the override account, and that a stale override degrades to a
|
||||
* structured 400 (never a posted entry on a dead account).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const mockCreateJE = vi.fn()
|
||||
const mockReverseOrphanedJE = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
createTransactionJournalEntry: (...args: unknown[]) => mockCreateJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/cancel-orphaned-entry', () => ({
|
||||
reverseOrphanedJournalEntry: (...args: unknown[]) => mockReverseOrphanedJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookingDuplicate: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/inbox-underlag', () => ({
|
||||
propagateUnderlagForBookedTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
|
||||
upsertCounterpartyTemplate: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/link-journal-entry', () => ({
|
||||
hasLiveJournalEntryLink: vi.fn().mockResolvedValue(false),
|
||||
}))
|
||||
vi.mock('@/lib/processing-history/append', () => ({
|
||||
appendProcessingHistory: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
import { categorizeMatchedTransaction } from '../categorize-core'
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000cc'
|
||||
|
||||
const txRow = (over: Record<string, unknown> = {}) => ({
|
||||
id: TX_ID,
|
||||
company_id: 'company-1',
|
||||
date: '2026-07-10',
|
||||
amount: -479,
|
||||
currency: 'SEK',
|
||||
amount_sek: -479,
|
||||
exchange_rate: 1,
|
||||
description: 'SECOND HAND BUTIK',
|
||||
merchant_name: null,
|
||||
cash_account_id: null,
|
||||
document_id: null,
|
||||
journal_entry_id: null,
|
||||
...over,
|
||||
})
|
||||
|
||||
const settingsRow = { entity_type: 'aktiebolag', fiscal_year_start_month: 1 }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockCreateJE.mockResolvedValue({ id: 'je-override-1' })
|
||||
mockReverseOrphanedJE.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('categorizeMatchedTransaction: accountOverride', () => {
|
||||
it('atomically unignores the transaction when categorizing it', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
const categorizedHandler = vi.fn()
|
||||
eventBus.on('transaction.categorized', categorizedHandler)
|
||||
enqueue({ data: txRow({ is_ignored: true }) })
|
||||
enqueue({ data: settingsRow })
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [{ id: 'fp-1' }] })
|
||||
// Issue #1661: a private marking runs checkPeriodLock before the engine
|
||||
// (company lock date, then the covering fiscal period). Open here.
|
||||
enqueue({ data: { bookkeeping_locked_through: null } })
|
||||
enqueue({ data: { id: 'fp-1', is_closed: false, locked_at: null } })
|
||||
enqueue({
|
||||
data: [txRow({
|
||||
is_business: false,
|
||||
category: 'private',
|
||||
is_ignored: false,
|
||||
journal_entry_id: 'je-override-1',
|
||||
})],
|
||||
})
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'private' },
|
||||
)
|
||||
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(findCalls('transactions', 'update')).toContainEqual([
|
||||
expect.objectContaining({
|
||||
is_business: false,
|
||||
category: 'private',
|
||||
is_ignored: false,
|
||||
journal_entry_id: 'je-override-1',
|
||||
}),
|
||||
])
|
||||
expect(categorizedHandler).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
transaction: expect.objectContaining({ is_ignored: false }),
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns a race conflict and stornos the orphan when the guarded update matches no row', async () => {
|
||||
// Pre-#1947 this scenario reached the guarded update via a null engine
|
||||
// return; a null entry now fails closed BEFORE the update (see
|
||||
// categorize-core.fail-closed.test.ts), so the race is exercised with a
|
||||
// posted entry, whose orphan must be reversed.
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() })
|
||||
enqueue({ data: settingsRow })
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [{ id: 'fp-1' }] })
|
||||
enqueue({ data: [] }) // guarded update: no row matched (concurrent categorization)
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'private' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(409)
|
||||
expect(mockReverseOrphanedJE).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
'company-1',
|
||||
'user-1',
|
||||
'je-override-1',
|
||||
expect.any(String),
|
||||
)
|
||||
})
|
||||
|
||||
it('posts the entry with the override on the business side', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() }) // transactions select
|
||||
enqueue({ data: settingsRow }) // company_settings
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: { account_number: '4020', account_class: 4, is_active: true } }) // override chart hit
|
||||
enqueue({ data: [{ id: 'fp-1' }] }) // ensureFiscalPeriod: open period exists
|
||||
enqueue({ data: [{ id: TX_ID }] }) // transactions update
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never, 'user-1', 'company-1', TX_ID,
|
||||
{ category: 'expense_other', vatTreatment: 'exempt', accountOverride: '4020' },
|
||||
)
|
||||
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.data?.journal_entry_id).toBe('je-override-1')
|
||||
// 5th arg of createTransactionJournalEntry is the mapping result.
|
||||
const mappingArg = mockCreateJE.mock.calls[0][4] as {
|
||||
debit_account: string
|
||||
credit_account: string
|
||||
}
|
||||
expect(mappingArg.debit_account).toBe('4020')
|
||||
expect(mappingArg.credit_account).toBe('1930')
|
||||
})
|
||||
|
||||
it('books GROSS with no auto-VAT line when the override has no explicit VAT intent', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() })
|
||||
enqueue({ data: settingsRow })
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: { account_number: '4020', account_class: 4, is_active: true } })
|
||||
enqueue({ data: [{ id: 'fp-1' }] }) // ensureFiscalPeriod
|
||||
enqueue({ data: [{ id: TX_ID }] }) // transactions update
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never, 'user-1', 'company-1', TX_ID,
|
||||
// No vatTreatment and no vatAmount: the category default standard_25
|
||||
// must NOT ride along onto the custom account.
|
||||
{ category: 'expense_other', accountOverride: '4020' },
|
||||
)
|
||||
|
||||
expect(result.error).toBeUndefined()
|
||||
const mappingArg = mockCreateJE.mock.calls[0][4] as {
|
||||
debit_account: string
|
||||
vat_lines: unknown[]
|
||||
}
|
||||
expect(mappingArg.debit_account).toBe('4020')
|
||||
expect(mappingArg.vat_lines).toEqual([])
|
||||
})
|
||||
|
||||
it('returns 400 (never posts) when the override was deactivated after staging', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() })
|
||||
enqueue({ data: settingsRow })
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: { account_number: '4020', account_class: 4, is_active: false } })
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never, 'user-1', 'company-1', TX_ID,
|
||||
{ category: 'expense_other', vatTreatment: 'exempt', accountOverride: '4020' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(400)
|
||||
expect(result.error).toMatch(/inaktivt/)
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when accountOverride is combined with category "private"', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() })
|
||||
enqueue({ data: settingsRow })
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never, 'user-1', 'company-1', TX_ID,
|
||||
{ category: 'private', accountOverride: '4020' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(400)
|
||||
expect(result.error).toMatch(/private/)
|
||||
expect(mockCreateJE).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('stornos a posted entry when the ignored-row constraint rejects the link', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow({ is_ignored: true }) })
|
||||
enqueue({ data: settingsRow })
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [{ id: 'fp-1' }] })
|
||||
enqueue({
|
||||
data: null,
|
||||
error: {
|
||||
code: '23514',
|
||||
message:
|
||||
'new row for relation "transactions" violates check constraint "transactions_is_ignored_no_journal_entry"',
|
||||
},
|
||||
})
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'private' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(409)
|
||||
expect(mockReverseOrphanedJE).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'company-1',
|
||||
'user-1',
|
||||
'je-override-1',
|
||||
expect.any(String),
|
||||
)
|
||||
})
|
||||
|
||||
it('uses a company-scoped CAS and stornos a concurrent loser', async () => {
|
||||
const { supabase, enqueue, calls } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() })
|
||||
enqueue({ data: settingsRow })
|
||||
enqueue({ data: [] }) // resolveSettlementAccount: no enabled cash accounts -> 1930
|
||||
enqueue({ data: [{ id: 'fp-1' }] })
|
||||
enqueue({ data: [] })
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'private' },
|
||||
)
|
||||
|
||||
expect(result.status).toBe(409)
|
||||
expect(mockReverseOrphanedJE).toHaveBeenCalledTimes(1)
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ table: 'transactions', method: 'eq', args: ['id', TX_ID] },
|
||||
{ table: 'transactions', method: 'eq', args: ['company_id', 'company-1'] },
|
||||
{ table: 'transactions', method: 'is', args: ['journal_entry_id', null] },
|
||||
]),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,180 +0,0 @@
|
||||
/**
|
||||
* Pre-FY booking (issue #1825): a bank transaction dated before the company's
|
||||
* first rakenskapsar (the aktiekapital deposit paid in before the Bolagsverket
|
||||
* registration date is the canonical case).
|
||||
*
|
||||
* Pins two behaviours:
|
||||
* 1. ensureFiscalPeriod never mints a calendar-year period for a pre-FY
|
||||
* date: neither in the overlap case (constraint bounce) nor in the
|
||||
* non-overlap case (silent pre-registration year).
|
||||
* 2. categorizeMatchedTransaction books the transaction (journal_entry_id
|
||||
* set, no more "categorized without verifikat") via the clamp in
|
||||
* createTransactionJournalEntry: entry lands in the first open period on
|
||||
* its first day, with the real bank date in the verifikationstext.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
import type { CreateJournalEntryInput } from '@/types'
|
||||
|
||||
// Real categorize-core + real transaction-entries; only the engine (DB commit
|
||||
// path) and the side-channel helpers are stubbed.
|
||||
const mockFindFiscalPeriod = vi.fn()
|
||||
const mockCreateJournalEntry = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/engine', () => ({
|
||||
findFiscalPeriod: (...args: unknown[]) => mockFindFiscalPeriod(...args),
|
||||
createJournalEntry: (
|
||||
_supabase: unknown,
|
||||
_companyId: string,
|
||||
_userId: string,
|
||||
input: CreateJournalEntryInput,
|
||||
) => mockCreateJournalEntry(input),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookingDuplicate: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/link-journal-entry', () => ({
|
||||
hasLiveJournalEntryLink: vi.fn().mockResolvedValue(false),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/inbox-underlag', () => ({
|
||||
propagateUnderlagForBookedTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
|
||||
upsertCounterpartyTemplate: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/processing-history/append', () => ({
|
||||
appendProcessingHistory: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
import { categorizeMatchedTransaction, ensureFiscalPeriod } from '../categorize-core'
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000fe'
|
||||
|
||||
const txRow = (over: Record<string, unknown> = {}) => ({
|
||||
id: TX_ID,
|
||||
company_id: 'company-1',
|
||||
date: '2026-03-10',
|
||||
amount: 25000,
|
||||
currency: 'SEK',
|
||||
amount_sek: 25000,
|
||||
exchange_rate: 1,
|
||||
description: 'Insättning aktiekapital',
|
||||
merchant_name: null,
|
||||
cash_account_id: null,
|
||||
document_id: null,
|
||||
journal_entry_id: null,
|
||||
...over,
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockFindFiscalPeriod.mockResolvedValue(null)
|
||||
mockCreateJournalEntry.mockImplementation(async (input: CreateJournalEntryInput) => ({
|
||||
id: 'je-prefy-1',
|
||||
...input,
|
||||
}))
|
||||
})
|
||||
|
||||
describe('ensureFiscalPeriod: pre-FY guard', () => {
|
||||
it('performs no insert when the date predates the first period (overlap case)', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [] }) // no open period covers the date
|
||||
enqueue({ data: [{ period_start: '2026-05-12' }] }) // earliest period
|
||||
|
||||
// 2026-03-10 with fiscalYearStartMonth=1: the calendar period 2026-01-01 to
|
||||
// 2026-12-31 would OVERLAP the real first period and bounce off the
|
||||
// exclusion constraint. The guard must return before any upsert.
|
||||
const ok = await ensureFiscalPeriod(supabase as never, 'user-1', 'company-1', '2026-03-10', 1)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(findCalls('fiscal_periods', 'upsert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('performs no insert when the date predates the first period (non-overlap case)', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [{ period_start: '2026-05-12' }] })
|
||||
|
||||
// Deposit dated the calendar year BEFORE registration: the computed
|
||||
// 2025-01-01 to 2025-12-31 period would NOT overlap anything, and the old
|
||||
// code silently created a bogus pre-registration rakenskapsar.
|
||||
const ok = await ensureFiscalPeriod(supabase as never, 'user-1', 'company-1', '2025-12-15', 1)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(findCalls('fiscal_periods', 'upsert')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('still creates the next-year period for a date after the latest period', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [{ period_start: '2026-05-12' }] }) // earliest, before the date
|
||||
enqueue({ data: null }) // upsert
|
||||
|
||||
const ok = await ensureFiscalPeriod(supabase as never, 'user-1', 'company-1', '2027-03-10', 1)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(findCalls('fiscal_periods', 'upsert')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('still creates a period when the company has none at all', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] }) // no earliest period: brand-new company
|
||||
enqueue({ data: null }) // upsert
|
||||
|
||||
const ok = await ensureFiscalPeriod(supabase as never, 'user-1', 'company-1', '2026-03-10', 1)
|
||||
|
||||
expect(ok).toBe(true)
|
||||
expect(findCalls('fiscal_periods', 'upsert')).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('categorizeMatchedTransaction: pre-FY transaction gets a journal entry', () => {
|
||||
it('books via the clamp: journal_entry_id set, entry on the first day of the first period', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() }) // transactions select
|
||||
enqueue({ data: { entity_type: 'aktiebolag', fiscal_year_start_month: 1 } }) // settings
|
||||
enqueue({ data: [] }) // ensureFiscalPeriod: no covering open period
|
||||
enqueue({ data: [{ period_start: '2026-05-12' }] }) // ensureFiscalPeriod: earliest
|
||||
// Issue #1661: a private marking runs checkPeriodLock before the engine.
|
||||
// A pre-FY date has no covering period, which is not a lock.
|
||||
enqueue({ data: { bookkeeping_locked_through: null } })
|
||||
enqueue({ data: null })
|
||||
// createTransactionJournalEntry clamp: earliest full row (open, unlocked)
|
||||
enqueue({
|
||||
data: [{ id: 'period-first', period_start: '2026-05-12', is_closed: false, locked_at: null }],
|
||||
})
|
||||
// guarded transactions update
|
||||
enqueue({
|
||||
data: [txRow({ is_business: false, category: 'private', journal_entry_id: 'je-prefy-1' })],
|
||||
})
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'private' },
|
||||
)
|
||||
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.data?.journal_entry_id).toBe('je-prefy-1')
|
||||
|
||||
// The clamp booked into the first period on its first day, keeping the
|
||||
// real bank date in the verifikationstext.
|
||||
expect(mockCreateJournalEntry).toHaveBeenCalledOnce()
|
||||
const input = mockCreateJournalEntry.mock.calls[0][0] as CreateJournalEntryInput
|
||||
expect(input.fiscal_period_id).toBe('period-first')
|
||||
expect(input.entry_date).toBe('2026-05-12')
|
||||
expect(input.description).toContain('Affärshändelse 2026-03-10')
|
||||
|
||||
// No bogus pre-registration rakenskapsar was minted along the way.
|
||||
expect(findCalls('fiscal_periods', 'upsert')).toHaveLength(0)
|
||||
|
||||
// The transaction row carries the new verifikat (no more "Delvis bokförd").
|
||||
expect(findCalls('transactions', 'update')).toContainEqual([
|
||||
expect.objectContaining({ journal_entry_id: 'je-prefy-1' }),
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -1,118 +0,0 @@
|
||||
/**
|
||||
* categorizeMatchedTransaction: settlement-account currency fallback (#1722).
|
||||
*
|
||||
* A transaction with NO cash_account_id (legacy/unresolved rows) used to book
|
||||
* its bank leg on the hardcoded 1930 from the category/template mapping even
|
||||
* when the company's only bank account is e.g. 1920 (PlusGiro), while the
|
||||
* booking dialogs previewed 1920 via the client-side resolveAccount. The
|
||||
* server resolver now mirrors that fallback: exactly one enabled cash account
|
||||
* in the transaction's currency wins; anything ambiguous keeps 1930.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { eventBus } from '@/lib/events'
|
||||
|
||||
const mockCreateJE = vi.fn()
|
||||
vi.mock('@/lib/bookkeeping/transaction-entries', () => ({
|
||||
createTransactionJournalEntry: (...args: unknown[]) => mockCreateJE(...args),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/cancel-orphaned-entry', () => ({
|
||||
reverseOrphanedJournalEntry: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/booking-duplicate-detection', () => ({
|
||||
detectBookingDuplicate: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/inbox-underlag', () => ({
|
||||
propagateUnderlagForBookedTransaction: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/bookkeeping/counterparty-templates', () => ({
|
||||
upsertCounterpartyTemplate: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
vi.mock('@/lib/transactions/link-journal-entry', () => ({
|
||||
hasLiveJournalEntryLink: vi.fn().mockResolvedValue(false),
|
||||
}))
|
||||
vi.mock('@/lib/processing-history/append', () => ({
|
||||
appendProcessingHistory: vi.fn().mockResolvedValue(undefined),
|
||||
}))
|
||||
|
||||
import { categorizeMatchedTransaction } from '../categorize-core'
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000dd'
|
||||
|
||||
const txRow = (over: Record<string, unknown> = {}) => ({
|
||||
id: TX_ID,
|
||||
company_id: 'company-1',
|
||||
date: '2026-07-10',
|
||||
amount: -479,
|
||||
currency: 'SEK',
|
||||
amount_sek: -479,
|
||||
exchange_rate: 1,
|
||||
description: 'KONTORSMATERIAL',
|
||||
merchant_name: null,
|
||||
cash_account_id: null,
|
||||
document_id: null,
|
||||
journal_entry_id: null,
|
||||
...over,
|
||||
})
|
||||
|
||||
const settingsRow = { entity_type: 'aktiebolag', fiscal_year_start_month: 1 }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockCreateJE.mockResolvedValue({ id: 'je-settle-1' })
|
||||
})
|
||||
|
||||
describe('categorizeMatchedTransaction: single-account currency fallback (#1722)', () => {
|
||||
it('books the bank leg on the single enabled cash account, not the hardcoded 1930', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() }) // transactions select
|
||||
enqueue({ data: settingsRow }) // company_settings
|
||||
// The company's ONLY enabled SEK cash account books on 1920.
|
||||
enqueue({ data: [{ ledger_account: '1920' }] }) // resolveSettlementAccount currency fallback
|
||||
enqueue({ data: [{ id: 'fp-1' }] }) // ensureFiscalPeriod
|
||||
enqueue({ data: [{ id: TX_ID }] }) // transactions update (CAS)
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'expense_office' },
|
||||
)
|
||||
|
||||
expect(result.error).toBeUndefined()
|
||||
expect(result.data?.journal_entry_id).toBe('je-settle-1')
|
||||
// 5th arg of createTransactionJournalEntry is the mapping result: its
|
||||
// 1930 leg was rewritten to the company's real settlement account.
|
||||
const mappingArg = mockCreateJE.mock.calls[0][4] as { credit_account: string }
|
||||
expect(mappingArg.credit_account).toBe('1920')
|
||||
// The fallback listing was narrowed to enabled accounts in the
|
||||
// transaction's currency.
|
||||
const eqArgs = findCalls('cash_accounts', 'eq')
|
||||
expect(eqArgs).toContainEqual(['enabled', true])
|
||||
expect(eqArgs).toContainEqual(['currency', 'SEK'])
|
||||
})
|
||||
|
||||
it('keeps 1930 when the company has several enabled accounts in the currency', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: txRow() })
|
||||
enqueue({ data: settingsRow })
|
||||
// Two enabled SEK accounts: ambiguous, so no guessing.
|
||||
enqueue({ data: [{ ledger_account: '1920' }, { ledger_account: '1930' }] })
|
||||
enqueue({ data: [{ id: 'fp-1' }] })
|
||||
enqueue({ data: [{ id: TX_ID }] })
|
||||
|
||||
const result = await categorizeMatchedTransaction(
|
||||
supabase as never,
|
||||
'user-1',
|
||||
'company-1',
|
||||
TX_ID,
|
||||
{ category: 'expense_office' },
|
||||
)
|
||||
|
||||
expect(result.error).toBeUndefined()
|
||||
const mappingArg = mockCreateJE.mock.calls[0][4] as { credit_account: string }
|
||||
expect(mappingArg.credit_account).toBe('1930')
|
||||
})
|
||||
})
|
||||
@@ -1,207 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildMerchantHistory,
|
||||
getSuggestedCategories,
|
||||
merchantHistoryFor,
|
||||
} from '../category-suggestions'
|
||||
import type { Transaction } from '@/types'
|
||||
|
||||
/**
|
||||
* P2-1 (mcp_optimization_plan): suggestions must carry signal tied to THIS
|
||||
* transaction. The old company-wide frequency fallback emitted an identical
|
||||
* ~0.5 four-way spread on every transaction: noise agents correctly
|
||||
* distrusted. History is now counterparty-keyed with provenance; when no
|
||||
* source matches, the honest answer is an empty list.
|
||||
*/
|
||||
|
||||
const tx = (overrides: Partial<Transaction> = {}): Transaction =>
|
||||
({
|
||||
id: 'tx-1',
|
||||
company_id: 'company-1',
|
||||
date: '2026-06-01',
|
||||
description: 'KORTKÖP POLARN O PYRET',
|
||||
amount: -500,
|
||||
currency: 'SEK',
|
||||
merchant_name: 'Polarn O. Pyret',
|
||||
...overrides,
|
||||
}) as Transaction
|
||||
|
||||
describe('buildMerchantHistory / merchantHistoryFor', () => {
|
||||
const rows = [
|
||||
{ merchant_name: 'Polarn O. Pyret', category: 'expense_office' },
|
||||
{ merchant_name: 'polarn o. pyret', category: 'expense_office' },
|
||||
{ merchant_name: 'Polarn O. Pyret', category: 'expense_consumables' },
|
||||
{ merchant_name: 'DNB Bank', category: 'expense_bank_fees' },
|
||||
{ merchant_name: null, category: 'expense_other' },
|
||||
{ merchant_name: 'Ghost AB', category: null },
|
||||
]
|
||||
|
||||
it('groups case-insensitively by merchant and ignores null merchants/categories', () => {
|
||||
const map = buildMerchantHistory(rows)
|
||||
expect(merchantHistoryFor(map, 'POLARN O. PYRET')).toEqual({
|
||||
expense_office: 2,
|
||||
expense_consumables: 1,
|
||||
})
|
||||
expect(merchantHistoryFor(map, 'DNB Bank')).toEqual({ expense_bank_fees: 1 })
|
||||
expect(merchantHistoryFor(map, 'Unknown Vendor')).toEqual({})
|
||||
expect(merchantHistoryFor(map, null)).toEqual({})
|
||||
})
|
||||
|
||||
it('falls back to the description when merchant_name is null (card purchases)', () => {
|
||||
// Bank feeds only carry counterparty names for transfers; card purchases
|
||||
// arrive with merchant_name null and the merchant buried in a descriptor
|
||||
// whose tail (product, city) changes between charges. All of these are
|
||||
// one counterparty: the reported Anthropic no-signal bug.
|
||||
const map = buildMerchantHistory([
|
||||
{ merchant_name: null, description: 'ANTHROPIC* CLAUDE SUB SAN FRANCISCO', category: 'expense_software' },
|
||||
{ merchant_name: null, description: 'ANTHROPIC*CLAUDE SUB +14155551234', category: 'expense_software' },
|
||||
{ merchant_name: 'Anthropic', description: 'irrelevant when merchant_name set', category: 'expense_software' },
|
||||
])
|
||||
expect(merchantHistoryFor(map, null, 'ANTHROPIC* CLAUDE SUB LONDON')).toEqual({
|
||||
expense_software: 3,
|
||||
})
|
||||
expect(merchantHistoryFor(map, 'Anthropic')).toEqual({ expense_software: 3 })
|
||||
})
|
||||
|
||||
it('anchors on original_description so user renames do not sever history', () => {
|
||||
// description is a mutable working title; a user renaming the row to
|
||||
// "Software" must not detach it from the raw bank descriptor identity.
|
||||
const map = buildMerchantHistory([
|
||||
{
|
||||
merchant_name: null,
|
||||
description: 'Software',
|
||||
original_description: 'ANTHROPIC* CLAUDE SUB SAN FRANCISCO',
|
||||
category: 'expense_software',
|
||||
},
|
||||
])
|
||||
expect(merchantHistoryFor(map, null, 'ANTHROPIC*CLAUDE SUB +14155551234')).toEqual({
|
||||
expense_software: 1,
|
||||
})
|
||||
// Renamed title itself is NOT a key when the raw descriptor exists.
|
||||
expect(merchantHistoryFor(map, null, 'Software')).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSuggestedCategories: mapping rules on custom accounts', () => {
|
||||
const rule = (over: Record<string, unknown> = {}) =>
|
||||
({
|
||||
id: 'rule-1',
|
||||
company_id: 'company-1',
|
||||
is_active: true,
|
||||
merchant_pattern: 'Myrorna',
|
||||
description_pattern: null,
|
||||
mcc_codes: null,
|
||||
debit_account: '4020',
|
||||
credit_account: '1930',
|
||||
default_private: false,
|
||||
confidence_score: 0.9,
|
||||
priority: 10,
|
||||
source: 'user',
|
||||
user_description: null,
|
||||
...over,
|
||||
// MappingRule carries many more columns; only the fields the suggestion
|
||||
// engine reads are modelled here.
|
||||
}) as never
|
||||
|
||||
it('surfaces a rule booking on a custom account instead of silently dropping it', async () => {
|
||||
const result = getSuggestedCategories(
|
||||
tx({ merchant_name: 'Myrorna', description: 'MYRORNA BUTIK 1' }),
|
||||
[rule()],
|
||||
{},
|
||||
)
|
||||
// 4020 is outside the fixed category maps: the old reverse-lookup
|
||||
// returned null and the rule vanished with no diagnostic.
|
||||
expect(result.length).toBe(1)
|
||||
expect(result[0]).toMatchObject({
|
||||
category: 'expense_other',
|
||||
account: '4020',
|
||||
source: 'mapping_rule',
|
||||
confidence: 0.9,
|
||||
})
|
||||
expect(result[0].match_reason).toMatch(/konto 4020/)
|
||||
})
|
||||
|
||||
it('surfaces an unmapped INCOME account with the custom-account diagnostic', async () => {
|
||||
const result = getSuggestedCategories(
|
||||
tx({ amount: 100, merchant_name: 'Myrorna', description: 'SWISH MYRORNA' }),
|
||||
[rule({ debit_account: '3020' })],
|
||||
{},
|
||||
)
|
||||
expect(result.length).toBe(1)
|
||||
expect(result[0]).toMatchObject({
|
||||
category: 'income_other',
|
||||
account: '3020',
|
||||
source: 'mapping_rule',
|
||||
})
|
||||
expect(result[0].match_reason).toMatch(/konto 3020/)
|
||||
})
|
||||
|
||||
it('accumulates the user_description reason with the custom-account reason', async () => {
|
||||
const result = getSuggestedCategories(
|
||||
tx({ merchant_name: 'Myrorna', description: 'MYRORNA BUTIK 1' }),
|
||||
[rule({ source: 'user_description', user_description: 'Second hand-inköp till butiken' })],
|
||||
{},
|
||||
)
|
||||
expect(result.length).toBe(1)
|
||||
expect(result[0].match_reason).toMatch(/Matchad på din beskrivning: Second hand-inköp till butiken/)
|
||||
expect(result[0].match_reason).toMatch(/konto 4020/)
|
||||
})
|
||||
|
||||
it('keeps the exact category for rules on accounts inside the fixed maps', async () => {
|
||||
const result = getSuggestedCategories(
|
||||
tx({ merchant_name: 'Anthropic', description: 'ANTHROPIC* CLAUDE' }),
|
||||
[rule({ merchant_pattern: 'Anthropic', debit_account: '5420' })],
|
||||
{},
|
||||
)
|
||||
expect(result.length).toBe(1)
|
||||
expect(result[0]).toMatchObject({
|
||||
category: 'expense_software',
|
||||
account: '5420',
|
||||
source: 'mapping_rule',
|
||||
})
|
||||
expect(result[0].match_reason).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('getSuggestedCategories: counterparty history', () => {
|
||||
it('returns an empty list (not a fabricated spread) when nothing matches', () => {
|
||||
const result = getSuggestedCategories(
|
||||
tx({ merchant_name: 'Helt Okänd Motpart', description: 'XYZ 123' }),
|
||||
[],
|
||||
{},
|
||||
)
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('surfaces merchant history with provenance and occurrence-scaled confidence', () => {
|
||||
const result = getSuggestedCategories(tx({ description: 'XYZ 123' }), [], {
|
||||
expense_office: 3,
|
||||
expense_consumables: 1,
|
||||
})
|
||||
expect(result.length).toBe(2)
|
||||
expect(result[0]).toMatchObject({
|
||||
category: 'expense_office',
|
||||
source: 'history',
|
||||
confidence: Math.min(0.85, 0.5 + 3 * 0.06),
|
||||
})
|
||||
expect(result[0].match_reason).toMatch(/3 gånger tidigare för denna motpart/)
|
||||
expect(result[1].category).toBe('expense_consumables')
|
||||
expect(result[1].match_reason).toMatch(/1 gång tidigare/)
|
||||
})
|
||||
|
||||
it('caps history confidence at 0.85', () => {
|
||||
const result = getSuggestedCategories(tx({ description: 'XYZ 123' }), [], {
|
||||
expense_office: 50,
|
||||
})
|
||||
expect(result[0].confidence).toBe(0.85)
|
||||
})
|
||||
|
||||
it('filters history to the transaction direction', () => {
|
||||
const result = getSuggestedCategories(
|
||||
tx({ amount: 1000, description: 'XYZ 123' }), // income direction
|
||||
[],
|
||||
{ expense_office: 5 },
|
||||
)
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { buildCounterpartySuggestion } from '../category-suggestions'
|
||||
import { resolveQuickReviewDefaults } from '../quick-review-defaults'
|
||||
import { isCounterpartyTemplateId } from '@/lib/bookkeeping/counterparty-templates'
|
||||
import type { CategorizationTemplate } from '@/types'
|
||||
|
||||
/**
|
||||
* The "Tidigare motparter" suggestion is the only input the review dialog has
|
||||
* about a learned counterparty: there is no catalog template to look up by id.
|
||||
* Anything missing here surfaces as an undefined field in the dialog, which is
|
||||
* how picking a Bankavgift counterparty used to replace the page with the
|
||||
* "Något gick fel" error boundary.
|
||||
*/
|
||||
|
||||
function makeTemplate(overrides: Partial<CategorizationTemplate> = {}): CategorizationTemplate {
|
||||
return {
|
||||
id: '11111111-1111-1111-1111-111111111111',
|
||||
user_id: null,
|
||||
company_id: '22222222-2222-2222-2222-222222222222',
|
||||
counterparty_name: 'fee',
|
||||
counterparty_aliases: [],
|
||||
debit_account: '6570',
|
||||
credit_account: '1930',
|
||||
vat_treatment: null,
|
||||
vat_account: null,
|
||||
category: null,
|
||||
line_pattern: null,
|
||||
occurrence_count: 4,
|
||||
confidence: 0.8,
|
||||
last_seen_date: '2026-07-01',
|
||||
source: 'sie_import',
|
||||
is_active: true,
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
updated_at: '2026-07-01T00:00:00Z',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('buildCounterpartySuggestion', () => {
|
||||
it('carries the accounts the review dialog needs to seed its form', () => {
|
||||
const s = buildCounterpartySuggestion(makeTemplate(), 0.9)
|
||||
expect(s.debit_account).toBe('6570')
|
||||
expect(s.credit_account).toBe('1930')
|
||||
expect(isCounterpartyTemplateId(s.template_id)).toBe(true)
|
||||
expect(s.name_sv).toBe('Fee')
|
||||
expect(s.description_sv).toBe('4 tidigare bokföringar')
|
||||
})
|
||||
|
||||
it('carries the learned VAT treatment so the preview matches the booking', () => {
|
||||
const s = buildCounterpartySuggestion(
|
||||
makeTemplate({ debit_account: '5420', vat_treatment: 'standard_25', vat_account: '2641' }),
|
||||
0.9,
|
||||
)
|
||||
expect(s.vat_treatment).toBe('standard_25')
|
||||
})
|
||||
|
||||
it('passes a multi-line pattern through untouched', () => {
|
||||
const pattern = [
|
||||
{ account: '5010', side: 'debit' as const, type: 'business' as const, ratio: 1 },
|
||||
{ account: '2641', side: 'debit' as const, type: 'vat' as const, vat_rate: 0.25 },
|
||||
]
|
||||
const s = buildCounterpartySuggestion(makeTemplate({ line_pattern: pattern }), 0.9)
|
||||
expect(s.line_pattern).toEqual(pattern)
|
||||
})
|
||||
|
||||
it('normalises an empty dimension bag to null', () => {
|
||||
expect(buildCounterpartySuggestion(makeTemplate({ default_dimensions: {} }), 0.9).default_dimensions).toBeNull()
|
||||
expect(
|
||||
buildCounterpartySuggestion(makeTemplate({ default_dimensions: { '1': 'KS01' } }), 0.9).default_dimensions,
|
||||
).toEqual({ '1': 'KS01' })
|
||||
})
|
||||
|
||||
it('feeds the review dialog a defined account, which is what the crash needed', () => {
|
||||
// Exactly the reported case: a Bankavgift line, a "Fee" counterparty with
|
||||
// four prior bookings. The dialog reads defaultAccount off this shape and
|
||||
// immediately calls .startsWith() on it.
|
||||
const s = buildCounterpartySuggestion(makeTemplate(), 0.9)
|
||||
const { account, vat } = resolveQuickReviewDefaults(
|
||||
{
|
||||
id: s.template_id,
|
||||
name_sv: s.name_sv,
|
||||
debit_account: s.debit_account,
|
||||
credit_account: s.credit_account,
|
||||
vat_treatment: s.vat_treatment ?? null,
|
||||
},
|
||||
undefined,
|
||||
'expense_other',
|
||||
'enskild_firma',
|
||||
)
|
||||
expect(account).toBe('6570')
|
||||
expect(() => account.startsWith('2')).not.toThrow()
|
||||
expect(vat).toBe('none')
|
||||
})
|
||||
})
|
||||
@@ -1,181 +0,0 @@
|
||||
/**
|
||||
* Tests for the read-only bank-import duplicate preview.
|
||||
*
|
||||
* previewDuplicates must behave like the corresponding subset of
|
||||
* ingestTransactions' dedup (Layer-1 external_id + the Layer-2 text bridge
|
||||
* with counting semantics and the currency guard), because the wizard shows
|
||||
* its answer as "these rows will be skipped". The queue order per call is:
|
||||
* booked map page(s), unbooked map page(s), then one external_id chunk query
|
||||
* per 500 rows.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { previewDuplicates, type PreviewTransaction } from '../dedup-preview'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const COMPANY_ID = 'company-1'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
function makePreviewRow(overrides: Partial<PreviewTransaction> = {}): PreviewTransaction {
|
||||
return {
|
||||
date: '2024-06-15',
|
||||
amount: -250.0,
|
||||
description: 'ICA Maxi Solna',
|
||||
external_id: `csv_lunar_${Math.random().toString(36).slice(2, 8)}`,
|
||||
currency: 'SEK',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('previewDuplicates', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
})
|
||||
|
||||
// (a) Layer 1: exact external_id collision.
|
||||
it('flags an exact external_id hit under by_reason.external_id', async () => {
|
||||
const raw = makePreviewRow({ external_id: 'csv_lunar_stored' })
|
||||
|
||||
enqueue({ data: [] }) // booked map
|
||||
enqueue({ data: [] }) // unbooked map
|
||||
enqueue({ data: [{ external_id: 'csv_lunar_stored' }] }) // external_id chunk
|
||||
|
||||
const result = await previewDuplicates(supabase as never, COMPANY_ID, [raw])
|
||||
|
||||
expect(result.duplicate_row_indexes).toEqual([0])
|
||||
expect(result.duplicate_count).toBe(1)
|
||||
expect(result.by_reason).toEqual({ external_id: 1, content_bridge: 0 })
|
||||
})
|
||||
|
||||
// (b) Layer 2: content bridge against a stored unbooked import-feed row
|
||||
// whose description bridges by prefix containment.
|
||||
it('flags a content-bridge hit (same date+öre, prefix description) under by_reason.content_bridge', async () => {
|
||||
const raw = makePreviewRow({ description: 'ICA Maxi Solna Kortköp' })
|
||||
|
||||
enqueue({ data: [] }) // booked map
|
||||
enqueue({
|
||||
data: [{
|
||||
date: '2024-06-15', amount: -250.0,
|
||||
original_description: 'ICA Maxi Solna', description: 'ICA Maxi Solna',
|
||||
import_source: 'csv_lunar', currency: 'SEK',
|
||||
}],
|
||||
}) // unbooked map: stored CSV twin, stored title is a prefix of incoming
|
||||
enqueue({ data: [] }) // external_id chunk: different id, no Layer-1 hit
|
||||
|
||||
const result = await previewDuplicates(supabase as never, COMPANY_ID, [raw])
|
||||
|
||||
expect(result.duplicate_row_indexes).toEqual([0])
|
||||
expect(result.by_reason).toEqual({ external_id: 0, content_bridge: 1 })
|
||||
})
|
||||
|
||||
// (c) Counting semantics: N stored twins flag exactly N incoming rows.
|
||||
it('flags exactly one of two identical incoming rows against one stored twin', async () => {
|
||||
const rows = [
|
||||
makePreviewRow({ external_id: 'csv_lunar_a' }),
|
||||
makePreviewRow({ external_id: 'csv_lunar_b' }),
|
||||
]
|
||||
|
||||
enqueue({ data: [] }) // booked map
|
||||
enqueue({
|
||||
data: [{
|
||||
date: '2024-06-15', amount: -250.0,
|
||||
original_description: 'ICA Maxi Solna', description: 'ICA Maxi Solna',
|
||||
import_source: 'csv_lunar', currency: 'SEK',
|
||||
}],
|
||||
}) // unbooked map: ONE stored twin
|
||||
enqueue({ data: [] }) // external_id chunk
|
||||
|
||||
const result = await previewDuplicates(supabase as never, COMPANY_ID, rows)
|
||||
|
||||
expect(result.duplicate_row_indexes).toEqual([0])
|
||||
expect(result.duplicate_count).toBe(1)
|
||||
expect(result.by_reason.content_bridge).toBe(1)
|
||||
})
|
||||
|
||||
// (d) A same-(date, öre) row with a non-bridging description is NOT flagged
|
||||
// (mirrors ingest's same-channel different-description semantics).
|
||||
it('does not flag a same-(date, öre) row whose description does not bridge', async () => {
|
||||
const raw = makePreviewRow({ description: 'Coop Stockholm' })
|
||||
|
||||
enqueue({ data: [] }) // booked map
|
||||
enqueue({
|
||||
data: [{
|
||||
date: '2024-06-15', amount: -250.0,
|
||||
original_description: 'ICA Maxi Solna', description: 'ICA Maxi Solna',
|
||||
import_source: 'csv_lunar', currency: 'SEK',
|
||||
}],
|
||||
}) // unbooked map
|
||||
enqueue({ data: [] }) // external_id chunk
|
||||
|
||||
const result = await previewDuplicates(supabase as never, COMPANY_ID, [raw])
|
||||
|
||||
expect(result.duplicate_row_indexes).toEqual([])
|
||||
expect(result.duplicate_count).toBe(0)
|
||||
})
|
||||
|
||||
// (e) Currency guard: identical titles and öre in DIFFERENT currencies never
|
||||
// bridge (a stored 250,00 EUR row is not the incoming 250,00 SEK row).
|
||||
it('does not flag across currencies (stored EUR vs incoming SEK, same öre and title)', async () => {
|
||||
const raw = makePreviewRow({ currency: 'SEK' })
|
||||
|
||||
enqueue({ data: [] }) // booked map
|
||||
enqueue({
|
||||
data: [{
|
||||
date: '2024-06-15', amount: -250.0,
|
||||
original_description: 'ICA Maxi Solna', description: 'ICA Maxi Solna',
|
||||
import_source: 'csv_lunar', currency: 'EUR',
|
||||
}],
|
||||
}) // unbooked map: EUR twin in the same (date, öre) bucket
|
||||
enqueue({ data: [] }) // external_id chunk
|
||||
|
||||
const result = await previewDuplicates(supabase as never, COMPANY_ID, [raw])
|
||||
|
||||
expect(result.duplicate_row_indexes).toEqual([])
|
||||
expect(result.duplicate_count).toBe(0)
|
||||
})
|
||||
|
||||
// (f) Pagination: a stored twin beyond the 1000-row PostgREST page must
|
||||
// still land in the map (the fetchAllRows fix; the old un-paginated query
|
||||
// silently truncated at 1000 rows and missed it).
|
||||
it('flags a twin served on the second stored page (>1000 rows)', async () => {
|
||||
const raw = makePreviewRow()
|
||||
|
||||
// Page 1: exactly 1000 filler rows in other (date, öre) buckets, which
|
||||
// forces fetchAllRows to request a second page.
|
||||
const filler = Array.from({ length: 1000 }, (_, i) => ({
|
||||
date: '2024-06-01',
|
||||
amount: -(i + 1),
|
||||
original_description: `Filler ${i}`,
|
||||
description: `Filler ${i}`,
|
||||
import_source: 'csv_lunar',
|
||||
currency: 'SEK',
|
||||
}))
|
||||
enqueue({ data: filler }) // booked map page 1 (full page)
|
||||
enqueue({
|
||||
data: [{
|
||||
date: '2024-06-15', amount: -250.0,
|
||||
original_description: 'ICA Maxi Solna', description: 'ICA Maxi Solna',
|
||||
import_source: 'csv_lunar', currency: 'SEK',
|
||||
}],
|
||||
}) // booked map page 2: the twin
|
||||
enqueue({ data: [] }) // unbooked map
|
||||
enqueue({ data: [] }) // external_id chunk
|
||||
|
||||
const result = await previewDuplicates(supabase as never, COMPANY_ID, [raw])
|
||||
|
||||
expect(result.duplicate_row_indexes).toEqual([0])
|
||||
expect(result.by_reason.content_bridge).toBe(1)
|
||||
})
|
||||
|
||||
it('returns an empty result for an empty batch without querying', async () => {
|
||||
const result = await previewDuplicates(supabase as never, COMPANY_ID, [])
|
||||
|
||||
expect(result).toEqual({
|
||||
duplicate_row_indexes: [],
|
||||
duplicate_count: 0,
|
||||
by_reason: { external_id: 0, content_bridge: 0 },
|
||||
})
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,232 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
amountToOre,
|
||||
buildStableExternalIds,
|
||||
contentBucketKey,
|
||||
descriptionsBridge,
|
||||
normalizeImportedDescription,
|
||||
shiftIsoDate,
|
||||
FALLBACK_DESCRIPTION,
|
||||
} from '../external-id'
|
||||
|
||||
describe('amountToOre', () => {
|
||||
it('normalizes a JS number to integer öre', () => {
|
||||
expect(amountToOre(1234.5)).toBe(123450)
|
||||
expect(amountToOre(-250)).toBe(-25000)
|
||||
expect(amountToOre(0)).toBe(0)
|
||||
})
|
||||
|
||||
it('normalizes a numeric string (PostgREST representation) to the same öre', () => {
|
||||
// The core fix: a DB-fetched numeric string and a raw JS number for the
|
||||
// same amount must collapse to the same integer.
|
||||
expect(amountToOre('1234.50')).toBe(123450)
|
||||
expect(amountToOre('1234.5')).toBe(amountToOre(1234.5))
|
||||
expect(amountToOre('-250.00')).toBe(amountToOre(-250))
|
||||
expect(amountToOre('100')).toBe(10000)
|
||||
})
|
||||
|
||||
it('rounds sub-öre noise deterministically (never toFixed)', () => {
|
||||
expect(amountToOre(0.1 + 0.2)).toBe(30) // 0.30000000000000004 → 30
|
||||
expect(amountToOre(19.995)).toBe(2000)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildStableExternalIds', () => {
|
||||
it('derives the id from account + date + öre, not from any bank id', () => {
|
||||
const ids = buildStableExternalIds('eb', 'SE123', [{ date: '2024-06-15', amount: -500 }])
|
||||
expect(ids).toEqual(['eb_SE123_2024-06-15_-50000_0'])
|
||||
})
|
||||
|
||||
it('disambiguates genuinely identical transactions with an occurrence index', () => {
|
||||
const ids = buildStableExternalIds('eb', 'acc', [
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
])
|
||||
expect(ids).toEqual([
|
||||
'eb_acc_2024-06-15_-25000_0',
|
||||
'eb_acc_2024-06-15_-25000_1',
|
||||
'eb_acc_2024-06-15_-25000_2',
|
||||
])
|
||||
})
|
||||
|
||||
it('produces the SAME set of ids regardless of provider ordering (re-sync dedupe)', () => {
|
||||
const a = buildStableExternalIds('eb', 'acc', [
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
{ date: '2024-06-16', amount: -100 },
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
])
|
||||
// Same transactions, different order on a later sync.
|
||||
const b = buildStableExternalIds('eb', 'acc', [
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
{ date: '2024-06-16', amount: -100 },
|
||||
])
|
||||
expect(new Set(a)).toEqual(new Set(b))
|
||||
})
|
||||
|
||||
it('treats string and number amounts as the same id (provider type drift)', () => {
|
||||
const num = buildStableExternalIds('eb', 'acc', [{ date: '2024-06-15', amount: 1234.5 }])
|
||||
const str = buildStableExternalIds('eb', 'acc', [{ date: '2024-06-15', amount: '1234.50' }])
|
||||
expect(num).toEqual(str)
|
||||
})
|
||||
|
||||
it('keeps distinct amounts and dates on separate occurrence counters', () => {
|
||||
const ids = buildStableExternalIds('eb', 'acc', [
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
{ date: '2024-06-15', amount: -100 },
|
||||
{ date: '2024-06-16', amount: -250 },
|
||||
{ date: '2024-06-15', amount: -250 },
|
||||
])
|
||||
expect(ids).toEqual([
|
||||
'eb_acc_2024-06-15_-25000_0',
|
||||
'eb_acc_2024-06-15_-10000_0',
|
||||
'eb_acc_2024-06-16_-25000_0',
|
||||
'eb_acc_2024-06-15_-25000_1',
|
||||
])
|
||||
})
|
||||
|
||||
it('returns an empty array for an empty batch', () => {
|
||||
expect(buildStableExternalIds('eb', 'acc', [])).toEqual([])
|
||||
})
|
||||
|
||||
// FORMAT-FREEZE guard. `external_id` is a STORED key: changing the template
|
||||
// string orphans every prior row (its stored id stops matching the new scheme)
|
||||
// and re-imports the lot on the next sync: the June 2026 fleet-wide incident.
|
||||
// If you must change the format, you MUST ship a coordinated backfill of
|
||||
// existing rows; updating this assertion without one is the bug.
|
||||
it('FORMAT IS FROZEN: changing this template silently orphans every prior external_id', () => {
|
||||
expect(
|
||||
buildStableExternalIds('eb', 'SE0000000000000000000000', [
|
||||
{ date: '2026-04-07', amount: -11231 },
|
||||
]),
|
||||
).toEqual(['eb_SE0000000000000000000000_2026-04-07_-1123100_0'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('contentBucketKey', () => {
|
||||
it('keys off (date, öre) only: no description', () => {
|
||||
expect(contentBucketKey('2024-06-15', -250)).toBe('2024-06-15|-25000')
|
||||
})
|
||||
|
||||
it('matches a JS number against a PostgREST numeric string for the same amount', () => {
|
||||
// A DB-fetched numeric string and a raw JS number for the same amount must
|
||||
// land in the SAME bucket, otherwise the bridge silently misses.
|
||||
expect(contentBucketKey('2024-06-15', -250)).toBe(contentBucketKey('2024-06-15', '-250.00'))
|
||||
})
|
||||
|
||||
it('separates distinct amounts and dates into distinct buckets', () => {
|
||||
expect(contentBucketKey('2024-06-15', -250)).not.toBe(contentBucketKey('2024-06-15', -100))
|
||||
expect(contentBucketKey('2024-06-15', -250)).not.toBe(contentBucketKey('2024-06-16', -250))
|
||||
})
|
||||
})
|
||||
|
||||
describe('descriptionsBridge', () => {
|
||||
it('bridges prefix-preserving PSD2 enrichment (the June 2026 drift)', () => {
|
||||
// The same transaction whose title grew between syncs must still bridge.
|
||||
// (Synthetic stand-ins for the real prefix-preserving enrichment pattern.)
|
||||
expect(descriptionsBridge('KAFFE', 'KAFFE BG 0000000000 Bg-bet. via internet')).toBe(true)
|
||||
expect(descriptionsBridge('UTBETALNING Insättning', 'UTBETALNING')).toBe(true)
|
||||
expect(descriptionsBridge('REF 000000 Europabetalning', 'REF 000000')).toBe(true)
|
||||
})
|
||||
|
||||
it('is case- and whitespace-insensitive', () => {
|
||||
expect(descriptionsBridge(' Mataffär Solna ', 'mataffär solna')).toBe(true)
|
||||
})
|
||||
|
||||
it('bridges whitespace-only rendering drift, including a DROPPED space (2026-08-18 reconnect incident)', () => {
|
||||
// The same bank re-rendered the same transactions with different spacing
|
||||
// after a PSD2 reconnect; every pair below is a real observed twin shape.
|
||||
// CRLF vs space:
|
||||
expect(
|
||||
descriptionsBridge(
|
||||
'2025DEC58 BRANDHEROES\r\nURSPRUNGLIGT BELOPP M M: EUR',
|
||||
'2025DEC58 BRANDHEROES URSPRUNGLIGT BELOPP M M: EUR'
|
||||
)
|
||||
).toBe(true)
|
||||
// Dropped space (collapse-only normalization would still miss this):
|
||||
expect(
|
||||
descriptionsBridge(
|
||||
'005 BaBylissURSPRUNGLIGT BELOPP M M: SEK',
|
||||
'005 BaByliss URSPRUNGLIGT BELOPP M M: SEK'
|
||||
)
|
||||
).toBe(true)
|
||||
// Trailing padding + reference tail growth still bridges via prefix rule:
|
||||
expect(
|
||||
descriptionsBridge(
|
||||
'BRANDHEROES APSFAK 008URSPRUNGLIGT BELOPP M M: EUR',
|
||||
'BRANDHEROES APSFAK 008 URSPRUNGLIGT BELOPP M M: EUR 2162943703022614'
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('whitespace stripping does not bridge genuinely distinct references', () => {
|
||||
expect(descriptionsBridge('REF-AAAA 1111', 'REF-BBBB 2222')).toBe(false)
|
||||
// A whitespace-only description is still treated as blank (no wildcard).
|
||||
expect(descriptionsBridge(' \r\n ', 'anything')).toBe(false)
|
||||
expect(descriptionsBridge(' \r\n ', ' ')).toBe(true)
|
||||
})
|
||||
|
||||
it('does NOT bridge genuinely distinct descriptions sharing a date+amount', () => {
|
||||
// Distinct reference codes on same-day same-amount rows (e.g. verification
|
||||
// micro-deposits) must NOT collapse: each is a real transaction.
|
||||
expect(descriptionsBridge('REF-AAAA1111', 'REF-BBBB2222')).toBe(false)
|
||||
// Same common stem, diverging tails: still distinct.
|
||||
expect(descriptionsBridge('PMT.Ref AAA', 'PMT.Ref BBB')).toBe(false)
|
||||
expect(descriptionsBridge('Coffee', 'Lunch')).toBe(false)
|
||||
})
|
||||
|
||||
it('does not let a blank description wildcard-match a described row', () => {
|
||||
// A blank carries no signal: it must not consume a described same-(date,öre)
|
||||
// row. Live callers normalize blanks to FALLBACK_DESCRIPTION, so this is
|
||||
// defense-in-depth. Only two blanks bridge each other (date+öre identity).
|
||||
expect(descriptionsBridge('', 'anything')).toBe(false)
|
||||
expect(descriptionsBridge('anything', null)).toBe(false)
|
||||
expect(descriptionsBridge(undefined, '')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeImportedDescription', () => {
|
||||
it('maps empty / whitespace-only titles to the Swedish neutral', () => {
|
||||
expect(normalizeImportedDescription('')).toBe(FALLBACK_DESCRIPTION)
|
||||
expect(normalizeImportedDescription(' ')).toBe(FALLBACK_DESCRIPTION)
|
||||
expect(normalizeImportedDescription(null)).toBe(FALLBACK_DESCRIPTION)
|
||||
expect(normalizeImportedDescription(undefined)).toBe(FALLBACK_DESCRIPTION)
|
||||
})
|
||||
|
||||
it('maps the legacy English "Unknown" sentinel to the Swedish neutral (case-insensitive)', () => {
|
||||
expect(normalizeImportedDescription('Unknown')).toBe(FALLBACK_DESCRIPTION)
|
||||
expect(normalizeImportedDescription('unknown')).toBe(FALLBACK_DESCRIPTION)
|
||||
expect(normalizeImportedDescription(' UNKNOWN ')).toBe(FALLBACK_DESCRIPTION)
|
||||
})
|
||||
|
||||
it('preserves a real title and trims surrounding whitespace', () => {
|
||||
expect(normalizeImportedDescription('ICA Maxi Solna')).toBe('ICA Maxi Solna')
|
||||
expect(normalizeImportedDescription(' Lön juni ')).toBe('Lön juni')
|
||||
})
|
||||
|
||||
it('does NOT clobber a real title that merely contains the word "unknown"', () => {
|
||||
expect(normalizeImportedDescription('Unknown Pizza AB')).toBe('Unknown Pizza AB')
|
||||
})
|
||||
})
|
||||
|
||||
describe('shiftIsoDate', () => {
|
||||
it('shifts a date forward and backward by whole days', () => {
|
||||
expect(shiftIsoDate('2024-06-15', 1)).toBe('2024-06-16')
|
||||
expect(shiftIsoDate('2024-06-15', -1)).toBe('2024-06-14')
|
||||
expect(shiftIsoDate('2024-06-15', 0)).toBe('2024-06-15')
|
||||
})
|
||||
|
||||
it('crosses month and year boundaries', () => {
|
||||
expect(shiftIsoDate('2024-06-30', 1)).toBe('2024-07-01')
|
||||
expect(shiftIsoDate('2024-07-01', -1)).toBe('2024-06-30')
|
||||
expect(shiftIsoDate('2025-12-31', 1)).toBe('2026-01-01')
|
||||
expect(shiftIsoDate('2026-01-01', -1)).toBe('2025-12-31')
|
||||
})
|
||||
|
||||
it('handles the leap day deterministically (no wall-clock dependency)', () => {
|
||||
expect(shiftIsoDate('2024-02-28', 1)).toBe('2024-02-29') // 2024 is a leap year
|
||||
expect(shiftIsoDate('2024-03-01', -1)).toBe('2024-02-29')
|
||||
expect(shiftIsoDate('2025-02-28', 1)).toBe('2025-03-01') // 2025 is not
|
||||
})
|
||||
})
|
||||
@@ -1,178 +0,0 @@
|
||||
/**
|
||||
* setTransactionIgnored (issue #1661): the shared core behind the dashboard
|
||||
* ignore route, the v1 ignore verb and the staged MCP ignore_transaction
|
||||
* executor.
|
||||
*
|
||||
* Pins the contract the three doors rely on: "already booked" is decided by
|
||||
* isTransactionBooked() across all three anchors (journal_entry_id, payment
|
||||
* allocations, voucher links), the flag flip is idempotent, restore skips the
|
||||
* booked check (the DB CHECK already guarantees an ignored row is unbooked),
|
||||
* dry run writes nothing, and DB failures throw with their SQLSTATE intact.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { setTransactionIgnored } from '../ignore'
|
||||
|
||||
const TX_ID = '00000000-0000-4000-8000-0000000000aa'
|
||||
|
||||
const unbookedRow = { id: TX_ID, journal_entry_id: null, is_ignored: false }
|
||||
|
||||
/** Queue the three junction lookups (voucher links, invoice payments, supplier payments). */
|
||||
function enqueueNoAnchors(enqueue: (r: { data?: unknown; error?: unknown }) => void) {
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('setTransactionIgnored: refusals', () => {
|
||||
it('returns 404 TX_CATEGORIZE_TX_NOT_FOUND when the row is not in this company', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: null })
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, true)
|
||||
|
||||
expect(outcome).toEqual({ ok: false, code: 'TX_CATEGORIZE_TX_NOT_FOUND', status: 404 })
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses a directly booked row without consulting the junction tables', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { ...unbookedRow, journal_entry_id: 'je-1' } })
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, true)
|
||||
|
||||
expect(outcome).toEqual({ ok: false, code: 'TX_IGNORE_ALREADY_BOOKED', status: 409 })
|
||||
expect(findCalls('transaction_voucher_links', 'select')).toEqual([])
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses a bulk-booked row anchored only through transaction_voucher_links', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: unbookedRow })
|
||||
enqueue({ data: [{ transaction_id: TX_ID }] }) // voucher links
|
||||
enqueue({ data: [] }) // invoice payments
|
||||
enqueue({ data: [] }) // supplier payments
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, true)
|
||||
|
||||
expect(outcome).toEqual({ ok: false, code: 'TX_IGNORE_ALREADY_BOOKED', status: 409 })
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('refuses a multi-allocated row anchored only through invoice_payments', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: unbookedRow })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [{ transaction_id: TX_ID }] }) // invoice payments
|
||||
enqueue({ data: [] })
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, true)
|
||||
|
||||
expect(outcome).toEqual({ ok: false, code: 'TX_IGNORE_ALREADY_BOOKED', status: 409 })
|
||||
})
|
||||
|
||||
it('refuses a row anchored only through supplier_invoice_payments', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: unbookedRow })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [] })
|
||||
enqueue({ data: [{ transaction_id: TX_ID }] }) // supplier payments
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, true)
|
||||
|
||||
expect(outcome).toEqual({ ok: false, code: 'TX_IGNORE_ALREADY_BOOKED', status: 409 })
|
||||
})
|
||||
|
||||
it('throws (with the SQLSTATE) when the fetch itself fails', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: { message: 'db down', code: '57P01' } })
|
||||
|
||||
await expect(
|
||||
setTransactionIgnored(supabase as never, 'company-1', TX_ID, true),
|
||||
).rejects.toMatchObject({ message: 'db down', code: '57P01' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('setTransactionIgnored: writes', () => {
|
||||
it('flips is_ignored on an unbooked row scoped to the company (happy path)', async () => {
|
||||
const { supabase, enqueue, findCalls, calls } = createQueuedMockSupabase()
|
||||
enqueue({ data: unbookedRow })
|
||||
enqueueNoAnchors(enqueue)
|
||||
enqueue({ data: null })
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, true)
|
||||
|
||||
expect(outcome).toEqual({
|
||||
ok: true,
|
||||
transaction_id: TX_ID,
|
||||
is_ignored: true,
|
||||
changed: true,
|
||||
dry_run: false,
|
||||
})
|
||||
expect(findCalls('transactions', 'update')).toEqual([[{ is_ignored: true }]])
|
||||
// Defense in depth: the update is filtered by company_id, not just id.
|
||||
const eqArgs = calls.filter((c) => c.table === 'transactions' && c.method === 'eq').map((c) => c.args)
|
||||
expect(eqArgs).toContainEqual(['company_id', 'company-1'])
|
||||
})
|
||||
|
||||
it('is idempotent: an already-ignored row returns changed=false and writes nothing', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { ...unbookedRow, is_ignored: true } })
|
||||
enqueueNoAnchors(enqueue)
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, true)
|
||||
|
||||
expect(outcome).toMatchObject({ ok: true, is_ignored: true, changed: false })
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('dry run reports what would change and writes nothing', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: unbookedRow })
|
||||
enqueueNoAnchors(enqueue)
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, true, {
|
||||
dryRun: true,
|
||||
})
|
||||
|
||||
expect(outcome).toMatchObject({ ok: true, changed: true, dry_run: true })
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('restore clears the flag without the booked check (the DB CHECK already guarantees unbooked)', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { ...unbookedRow, is_ignored: true } })
|
||||
enqueue({ data: null }) // update
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, false)
|
||||
|
||||
expect(outcome).toMatchObject({ ok: true, is_ignored: false, changed: true })
|
||||
expect(findCalls('transaction_voucher_links', 'select')).toEqual([])
|
||||
expect(findCalls('transactions', 'update')).toEqual([[{ is_ignored: false }]])
|
||||
})
|
||||
|
||||
it('restore on a row that is not ignored is a no-op', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: unbookedRow })
|
||||
|
||||
const outcome = await setTransactionIgnored(supabase as never, 'company-1', TX_ID, false)
|
||||
|
||||
expect(outcome).toMatchObject({ ok: true, is_ignored: false, changed: false })
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('throws when the update fails', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: unbookedRow })
|
||||
enqueueNoAnchors(enqueue)
|
||||
enqueue({ data: null, error: { message: 'db down', code: '57P01' } })
|
||||
|
||||
await expect(
|
||||
setTransactionIgnored(supabase as never, 'company-1', TX_ID, true),
|
||||
).rejects.toMatchObject({ code: '57P01' })
|
||||
})
|
||||
})
|
||||
@@ -1,441 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
// The reconciler orchestrates the shared underlag helpers; those are covered
|
||||
// in inbox-underlag.test.ts, so here they are mocked and the run's own
|
||||
// logic is what is under test: grouping, dry-run vs execute, classification,
|
||||
// the history trail, the scan cap, and never throwing.
|
||||
const resolveBooked = vi.fn()
|
||||
const resolveAnchoring = vi.fn()
|
||||
const propagate = vi.fn()
|
||||
vi.mock('@/lib/transactions/inbox-underlag', () => ({
|
||||
resolveBookedJournalEntryIds: (...a: unknown[]) => resolveBooked(...a),
|
||||
resolveUnderlagAnchoring: (...a: unknown[]) => resolveAnchoring(...a),
|
||||
propagateUnderlagForBookedTransaction: (...a: unknown[]) => propagate(...a),
|
||||
}))
|
||||
|
||||
const appendHistory = vi.fn()
|
||||
vi.mock('@/lib/processing-history/append', () => ({
|
||||
appendProcessingHistoryWithClient: (...a: unknown[]) => appendHistory(...a),
|
||||
}))
|
||||
|
||||
import {
|
||||
reconcileStrandedInboxUnderlag,
|
||||
INBOX_UNDERLAG_RECONCILED_EVENT,
|
||||
} from '../inbox-underlag-reconcile'
|
||||
|
||||
const C1 = 'company-1'
|
||||
const C2 = 'company-2'
|
||||
const TX1 = 'tx-1'
|
||||
const TX2 = 'tx-2'
|
||||
const TX3 = 'tx-3'
|
||||
const JE1 = 'je-1'
|
||||
const JE2 = 'je-2'
|
||||
|
||||
function item(id: string, company: string, tx: string, doc: string | null = `doc-${id}`) {
|
||||
return { id, company_id: company, matched_transaction_id: tx, document_id: doc }
|
||||
}
|
||||
|
||||
function anchoring(
|
||||
entries: Record<string, 'anchored' | 'unlinked' | 'unlinked_locked' | 'anchored_elsewhere'>,
|
||||
) {
|
||||
return new Map(
|
||||
Object.entries(entries).map(([id, status]) => [
|
||||
id,
|
||||
{ status, document_journal_entry_id: status === 'anchored_elsewhere' ? 'je-other' : null },
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), child: vi.fn() }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
propagate.mockResolvedValue(undefined)
|
||||
appendHistory.mockResolvedValue('event-1')
|
||||
})
|
||||
|
||||
describe('reconcileStrandedInboxUnderlag', () => {
|
||||
it('dry-run classifies without writing and counts stranded items', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1), item('i2', C1, TX2), item('i3', C1, TX3)] })
|
||||
// TX3 is not booked: its item is scanned but not stranded.
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1], [TX2, JE2]]))
|
||||
resolveAnchoring.mockResolvedValue(anchoring({ i1: 'unlinked', i2: 'anchored_elsewhere' }))
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: false,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary).toMatchObject({
|
||||
execute: false,
|
||||
scanned: 3,
|
||||
truncated: false,
|
||||
strandedOnBooked: 2,
|
||||
repaired: 0,
|
||||
stillUnlinked: 1,
|
||||
anchoredElsewhere: 1,
|
||||
companiesTouched: 1,
|
||||
historyAppended: 0,
|
||||
failures: 0,
|
||||
})
|
||||
expect(propagate).not.toHaveBeenCalled()
|
||||
expect(appendHistory).not.toHaveBeenCalled()
|
||||
expect(resolveAnchoring).toHaveBeenCalledTimes(1)
|
||||
expect(resolveAnchoring).toHaveBeenCalledWith(expect.anything(), C1, [
|
||||
{ id: 'i1', document_id: 'doc-i1', journalEntryId: JE1 },
|
||||
{ id: 'i2', document_id: 'doc-i2', journalEntryId: JE2 },
|
||||
])
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('execute propagates unlinked and anchored transactions but logs history only for repaired ones', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
// Two items on TX1 (a samlingsverifikat) and one on TX2.
|
||||
enqueue({ data: [item('i1', C1, TX1), item('i2', C1, TX1), item('i3', C1, TX2)] })
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1], [TX2, JE2]]))
|
||||
resolveAnchoring
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'unlinked', i2: 'anchored', i3: 'anchored' })) // before
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'anchored' })) // after, only the linked item is re-read
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
actorId: 'test-actor',
|
||||
})
|
||||
|
||||
// TX2's item was already anchored, so its link is settled, but the
|
||||
// propagation still runs for the legs only it covers (the transaction's
|
||||
// pinned document, the created_journal_entry_id stamp); only TX1's
|
||||
// unlinked item is re-read afterwards.
|
||||
expect(propagate).toHaveBeenCalledTimes(2)
|
||||
expect(propagate).toHaveBeenCalledWith(expect.anything(), C1, TX1, JE1)
|
||||
expect(propagate).toHaveBeenCalledWith(expect.anything(), C1, TX2, JE2)
|
||||
expect(resolveAnchoring).toHaveBeenCalledTimes(2)
|
||||
expect(resolveAnchoring).toHaveBeenNthCalledWith(2, expect.anything(), C1, [
|
||||
{ id: 'i1', document_id: 'doc-i1', journalEntryId: JE1 },
|
||||
])
|
||||
expect(summary).toMatchObject({
|
||||
strandedOnBooked: 3,
|
||||
repaired: 1,
|
||||
alreadyAnchored: 2,
|
||||
stillUnlinked: 0,
|
||||
anchoredElsewhere: 0,
|
||||
historyAppended: 1,
|
||||
failures: 0,
|
||||
})
|
||||
// Only TX1 changed linkage (i1); TX2's item was already anchored, so no
|
||||
// changelog row pretends a repair happened there.
|
||||
expect(appendHistory).toHaveBeenCalledTimes(1)
|
||||
expect(appendHistory).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
companyId: C1,
|
||||
aggregateType: 'BankTransaction',
|
||||
aggregateId: TX1,
|
||||
correlationId: TX1,
|
||||
eventType: INBOX_UNDERLAG_RECONCILED_EVENT,
|
||||
payload: {
|
||||
transaction_id: TX1,
|
||||
journal_entry_id: JE1,
|
||||
inbox_item_ids: ['i1'],
|
||||
source: 'test-actor',
|
||||
},
|
||||
actor: { type: 'system', id: 'test-actor' },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('counts a link that failed again as still unlinked and appends nothing', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1)] })
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1]]))
|
||||
resolveAnchoring
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'unlinked' }))
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'unlinked' }))
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary).toMatchObject({ repaired: 0, stillUnlinked: 1, historyAppended: 0 })
|
||||
expect(appendHistory).not.toHaveBeenCalled()
|
||||
expect(log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('still unlinked'),
|
||||
expect.objectContaining({ inbox_item_id: 'i1', transaction_id: TX1 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('counts a document anchored to another verifikat as a conflict, greppable by its verifikat', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1)] })
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1]]))
|
||||
// Settled from the pre-state alone: no propagation, no after-read.
|
||||
resolveAnchoring.mockResolvedValue(anchoring({ i1: 'anchored_elsewhere' }))
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary).toMatchObject({ repaired: 0, anchoredElsewhere: 1, historyAppended: 0 })
|
||||
expect(propagate).not.toHaveBeenCalled()
|
||||
expect(resolveAnchoring).toHaveBeenCalledTimes(1)
|
||||
expect(appendHistory).not.toHaveBeenCalled()
|
||||
expect(log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('another verifikat'),
|
||||
expect.objectContaining({ inbox_item_id: 'i1', document_journal_entry_id: 'je-other' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('treats an item the anchoring read could not classify as unlinked, never repaired', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1)] })
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1]]))
|
||||
resolveAnchoring.mockResolvedValue(new Map())
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary).toMatchObject({ repaired: 0, stillUnlinked: 1, historyAppended: 0 })
|
||||
})
|
||||
|
||||
it('groups per company and skips companies with no booked matches', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1), item('i2', C2, TX2)] })
|
||||
resolveBooked.mockImplementation(async (_s: unknown, companyId: string) =>
|
||||
companyId === C1 ? new Map([[TX1, JE1]]) : new Map(),
|
||||
)
|
||||
resolveAnchoring
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'unlinked' }))
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'anchored' }))
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(resolveBooked).toHaveBeenCalledWith(expect.anything(), C1, [TX1])
|
||||
expect(resolveBooked).toHaveBeenCalledWith(expect.anything(), C2, [TX2])
|
||||
expect(summary).toMatchObject({ scanned: 2, strandedOnBooked: 1, companiesTouched: 1, repaired: 1 })
|
||||
expect(propagate).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reads every candidate and spends maxItems on unlinked items only, deferring the rest', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
// Six candidates: two already anchored, one anchored elsewhere, three
|
||||
// unlinked. A read cap would have stopped at the first rows; the link
|
||||
// budget (2) must reach past the settled ones and defer only the third
|
||||
// unlinked item.
|
||||
enqueue({
|
||||
data: [
|
||||
item('a1', C1, TX1),
|
||||
item('a2', C1, TX1),
|
||||
item('e1', C1, TX2),
|
||||
item('u1', C1, TX3),
|
||||
item('u2', C2, 'tx-4'),
|
||||
item('u3', C2, 'tx-5'),
|
||||
],
|
||||
})
|
||||
resolveBooked.mockImplementation(async (_s: unknown, companyId: string) =>
|
||||
companyId === C1
|
||||
? new Map([[TX1, JE1], [TX2, JE2], [TX3, 'je-3']])
|
||||
: new Map([['tx-4', 'je-4'], ['tx-5', 'je-5']]),
|
||||
)
|
||||
resolveAnchoring.mockImplementation(async (_s: unknown, companyId: string) =>
|
||||
companyId === C1
|
||||
? anchoring({ a1: 'anchored', a2: 'anchored', e1: 'anchored_elsewhere', u1: 'unlinked' })
|
||||
: anchoring({ u2: 'unlinked', u3: 'unlinked' }),
|
||||
)
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
maxItems: 2,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(findCalls('invoice_inbox_items', 'range')).toEqual([[0, 999]])
|
||||
expect(summary).toMatchObject({
|
||||
scanned: 6,
|
||||
strandedOnBooked: 6,
|
||||
alreadyAnchored: 2,
|
||||
anchoredElsewhere: 1,
|
||||
deferred: 1,
|
||||
truncated: true,
|
||||
})
|
||||
// u1 and u2 got the budget; u3 waits for the next run, without a
|
||||
// misleading "still unlinked after re-run" line. TX1 (anchored items)
|
||||
// is propagated outside the budget for its pin and stamp legs; the
|
||||
// anchored-elsewhere conflict on TX2 is not.
|
||||
expect(propagate).toHaveBeenCalledTimes(3)
|
||||
expect(propagate).toHaveBeenCalledWith(expect.anything(), C1, TX1, JE1)
|
||||
expect(propagate).toHaveBeenCalledWith(expect.anything(), C1, TX3, 'je-3')
|
||||
expect(propagate).toHaveBeenCalledWith(expect.anything(), C2, 'tx-4', 'je-4')
|
||||
expect(propagate).not.toHaveBeenCalledWith(expect.anything(), C1, TX2, JE2)
|
||||
expect(propagate).not.toHaveBeenCalledWith(expect.anything(), C2, 'tx-5', 'je-5')
|
||||
expect(log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('link budget spent'),
|
||||
expect.objectContaining({ max_items: 2, deferred: 1 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('pages through more than one page of candidates', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
const firstPage = Array.from({ length: 1000 }, (_, i) => item(`p${i}`, C1, TX1))
|
||||
enqueue({ data: firstPage })
|
||||
enqueue({ data: [item('tail', C1, TX1)] })
|
||||
resolveBooked.mockResolvedValue(new Map())
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: false,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary.scanned).toBe(1001)
|
||||
expect(summary.truncated).toBe(false)
|
||||
expect(findCalls('invoice_inbox_items', 'range')).toEqual([[0, 999], [1000, 1999]])
|
||||
})
|
||||
|
||||
it('still propagates a transaction whose only item is anchored so an unlinked pin is repaired', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
// i1's own document is anchored; i2 carries no document at all. Both
|
||||
// read 'anchored', but the transaction may still have a pinned document
|
||||
// (transactions.document_id) whose link failed earlier, and the items
|
||||
// still lack their stamp: only the propagation repairs those.
|
||||
enqueue({ data: [item('i1', C1, TX1), item('i2', C1, TX2, null)] })
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1], [TX2, JE2]]))
|
||||
resolveAnchoring.mockResolvedValue(anchoring({ i1: 'anchored', i2: 'anchored' }))
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
maxItems: 0,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
// Outside the link budget (maxItems 0 still lets this run), no after-read
|
||||
// (the pre-state is the verdict) and no history: nothing this run can
|
||||
// vouch for changed the item's linkage.
|
||||
expect(propagate).toHaveBeenCalledTimes(2)
|
||||
expect(propagate).toHaveBeenCalledWith(expect.anything(), C1, TX1, JE1)
|
||||
expect(propagate).toHaveBeenCalledWith(expect.anything(), C1, TX2, JE2)
|
||||
expect(resolveAnchoring).toHaveBeenCalledTimes(1)
|
||||
expect(summary).toMatchObject({
|
||||
strandedOnBooked: 2,
|
||||
repaired: 0,
|
||||
alreadyAnchored: 2,
|
||||
deferred: 0,
|
||||
truncated: false,
|
||||
historyAppended: 0,
|
||||
})
|
||||
expect(appendHistory).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('counts a locked-period item separately, never propagates it, and appends nothing', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1)] })
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1]]))
|
||||
resolveAnchoring.mockResolvedValue(anchoring({ i1: 'unlinked_locked' }))
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary).toMatchObject({
|
||||
strandedOnBooked: 1,
|
||||
repaired: 0,
|
||||
stillUnlinked: 0,
|
||||
unlinkedLocked: 1,
|
||||
deferred: 0,
|
||||
truncated: false,
|
||||
historyAppended: 0,
|
||||
})
|
||||
// The link is known to fail (enforce_period_lock_documents): no
|
||||
// propagation, no budget spent, no daily "still unlinked" warning.
|
||||
expect(propagate).not.toHaveBeenCalled()
|
||||
expect(appendHistory).not.toHaveBeenCalled()
|
||||
expect(log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('locked period'),
|
||||
expect.objectContaining({ inbox_item_id: 'i1' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('does not count an unreadable pre-state that reads anchored afterwards as repaired', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1)] })
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1]]))
|
||||
resolveAnchoring
|
||||
.mockResolvedValueOnce(new Map()) // before: document row unreadable
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'anchored' })) // after
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
// Unknown before is a reason to look (propagate), not evidence that this
|
||||
// run changed the linkage: no InboxUnderlagReconciled event.
|
||||
expect(propagate).toHaveBeenCalledTimes(1)
|
||||
expect(summary).toMatchObject({ repaired: 0, alreadyAnchored: 1, historyAppended: 0 })
|
||||
expect(appendHistory).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns a zero summary with one failure when the scan errors, without throwing', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: { message: 'connection reset' } })
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary).toMatchObject({ scanned: 0, strandedOnBooked: 0, repaired: 0, failures: 1 })
|
||||
expect(propagate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('counts a failing company and continues with the next one', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1), item('i2', C2, TX2)] })
|
||||
resolveBooked.mockImplementation(async (_s: unknown, companyId: string) => {
|
||||
if (companyId === C1) throw new Error('resolver blew up')
|
||||
return new Map([[TX2, JE2]])
|
||||
})
|
||||
resolveAnchoring
|
||||
.mockResolvedValueOnce(anchoring({ i2: 'unlinked' }))
|
||||
.mockResolvedValueOnce(anchoring({ i2: 'anchored' }))
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary).toMatchObject({ failures: 1, companiesTouched: 1, repaired: 1 })
|
||||
expect(propagate).toHaveBeenCalledWith(expect.anything(), C2, TX2, JE2)
|
||||
})
|
||||
|
||||
it('keeps the repair when the history append fails', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [item('i1', C1, TX1)] })
|
||||
resolveBooked.mockResolvedValue(new Map([[TX1, JE1]]))
|
||||
resolveAnchoring
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'unlinked' }))
|
||||
.mockResolvedValueOnce(anchoring({ i1: 'anchored' }))
|
||||
appendHistory.mockRejectedValue(new Error('fk violation'))
|
||||
|
||||
const summary = await reconcileStrandedInboxUnderlag(supabase as unknown as SupabaseClient, {
|
||||
execute: true,
|
||||
log: log as never,
|
||||
})
|
||||
|
||||
expect(summary).toMatchObject({ repaired: 1, historyAppended: 0, failures: 0 })
|
||||
expect(log.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining('processing_history append failed'),
|
||||
expect.objectContaining({ transaction_id: TX1 }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,468 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
vi.mock('@/lib/core/documents/document-service', () => ({
|
||||
linkToJournalEntry: vi.fn().mockResolvedValue({}),
|
||||
}))
|
||||
|
||||
import {
|
||||
completeInboxItemsForBookedTransaction,
|
||||
propagateUnderlagForBookedTransaction,
|
||||
resolveBookedJournalEntryIds,
|
||||
resolveUnderlagAnchoring,
|
||||
} from '../inbox-underlag'
|
||||
import { linkToJournalEntry } from '@/lib/core/documents/document-service'
|
||||
|
||||
const COMPANY = 'company-1'
|
||||
const TX1 = 'tx-1'
|
||||
const TX2 = 'tx-2'
|
||||
const JE1 = 'je-1'
|
||||
const JE2 = 'je-2'
|
||||
|
||||
describe('resolveBookedJournalEntryIds', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('returns an empty map without querying for an empty id list', async () => {
|
||||
const { supabase, calls } = createQueuedMockSupabase()
|
||||
const map = await resolveBookedJournalEntryIds(supabase as unknown as SupabaseClient, COMPANY, [])
|
||||
expect(map.size).toBe(0)
|
||||
expect(calls.length).toBe(0)
|
||||
})
|
||||
|
||||
it('resolves direct journal_entry_id and falls back to voucher links', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: TX1, journal_entry_id: JE1 },
|
||||
{ id: TX2, journal_entry_id: null },
|
||||
],
|
||||
})
|
||||
// Voucher-link fallback runs only for the unbooked remainder (TX2).
|
||||
enqueue({ data: [{ transaction_id: TX2, journal_entry_id: JE2 }] })
|
||||
|
||||
const map = await resolveBookedJournalEntryIds(supabase as unknown as SupabaseClient, COMPANY, [
|
||||
TX1,
|
||||
TX2,
|
||||
])
|
||||
expect(map.get(TX1)).toBe(JE1)
|
||||
expect(map.get(TX2)).toBe(JE2)
|
||||
})
|
||||
|
||||
it('omits transactions booked by neither route', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ id: TX1, journal_entry_id: null }] })
|
||||
enqueue({ data: [] }) // no voucher links either
|
||||
|
||||
const map = await resolveBookedJournalEntryIds(supabase as unknown as SupabaseClient, COMPANY, [
|
||||
TX1,
|
||||
])
|
||||
expect(map.size).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('propagateUnderlagForBookedTransaction', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('links the document and stamps the matched item', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: null } }) // tx pin lookup: nothing pinned
|
||||
enqueue({ data: [{ id: 'i1', document_id: 'doc-1' }] }) // matched items
|
||||
enqueue({ data: { journal_entry_id: null } }) // doc not yet anchored
|
||||
enqueue({ data: null }) // stamp update
|
||||
|
||||
await propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
)
|
||||
|
||||
expect(linkToJournalEntry).toHaveBeenCalledWith(expect.anything(), COMPANY, 'doc-1', JE1)
|
||||
const stamps = findCalls('invoice_inbox_items', 'update')
|
||||
expect(stamps).toContainEqual([{ created_journal_entry_id: JE1 }])
|
||||
})
|
||||
|
||||
it('skips the document write when it already points at the verifikat', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: null } }) // tx pin lookup: nothing pinned
|
||||
enqueue({ data: [{ id: 'i1', document_id: 'doc-1' }] })
|
||||
enqueue({ data: { journal_entry_id: JE1 } }) // already anchored to JE1
|
||||
enqueue({ data: null }) // stamp update
|
||||
|
||||
await propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
)
|
||||
|
||||
expect(linkToJournalEntry).not.toHaveBeenCalled()
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toContainEqual([
|
||||
{ created_journal_entry_id: JE1 },
|
||||
])
|
||||
})
|
||||
|
||||
it('never steals a document anchored to another verifikat, and does not stamp', async () => {
|
||||
// The doc stays on its verifikat, but THIS transaction's verifikat then
|
||||
// has no underlag from the item: stamping it consumed would hide the
|
||||
// mismatch from every future run and from manual reconciliation
|
||||
// (BFL 5 kap 6-7 §).
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: null } }) // tx pin lookup: nothing pinned
|
||||
enqueue({ data: [{ id: 'i1', document_id: 'doc-1' }] })
|
||||
enqueue({ data: { journal_entry_id: 'je-other' } })
|
||||
|
||||
await propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
)
|
||||
|
||||
expect(linkToJournalEntry).not.toHaveBeenCalled()
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('stamps an item without a document (no document read)', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: null } }) // tx pin lookup: nothing pinned
|
||||
enqueue({ data: [{ id: 'i1', document_id: null }] })
|
||||
enqueue({ data: null }) // stamp update
|
||||
|
||||
await propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
)
|
||||
|
||||
expect(linkToJournalEntry).not.toHaveBeenCalled()
|
||||
expect(findCalls('document_attachments', 'select').length).toBe(0)
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toContainEqual([
|
||||
{ created_journal_entry_id: JE1 },
|
||||
])
|
||||
})
|
||||
|
||||
it('tolerates the UNIQUE violation when a sibling item already claimed the verifikat', async () => {
|
||||
// Samlingsverifikat: created_journal_entry_id is UNIQUE, so on N matched
|
||||
// items only the first stamp lands. The rest must resolve quietly: the
|
||||
// inbox list derives "booked" from the transaction's state for them.
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: null } }) // tx pin lookup: nothing pinned
|
||||
enqueue({ data: [{ id: 'i1', document_id: null }] })
|
||||
enqueue({ data: null, error: { code: '23505', message: 'duplicate key value' } })
|
||||
|
||||
await expect(
|
||||
propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
),
|
||||
).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('does NOT stamp when the document link fails, so a re-run can still repair it', async () => {
|
||||
// Stamping over a failed link would hide 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 §)
|
||||
// and nothing left to surface or repair it.
|
||||
vi.mocked(linkToJournalEntry).mockRejectedValueOnce(new Error('period locked'))
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: null } }) // tx pin lookup: nothing pinned
|
||||
enqueue({ data: [{ id: 'i1', document_id: 'doc-1' }] })
|
||||
enqueue({ data: { journal_entry_id: null } })
|
||||
|
||||
await expect(
|
||||
propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
),
|
||||
).resolves.toBeUndefined()
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
// ── The transaction's own pinned document (transactions.document_id) ──
|
||||
// A doc attached directly to the transaction has no inbox item to carry
|
||||
// it, so the propagation must anchor it itself: this was the 2026-08-13
|
||||
// "Underlag saknas" gap (attach-before-book via the manual booking dialog).
|
||||
|
||||
it('anchors the pinned document even when no inbox item exists', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: 'doc-pin' } }) // tx pin lookup
|
||||
enqueue({ data: { journal_entry_id: null } }) // pinned doc not yet anchored
|
||||
enqueue({ data: [] }) // no matched inbox items
|
||||
|
||||
await propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
)
|
||||
|
||||
expect(linkToJournalEntry).toHaveBeenCalledWith(expect.anything(), COMPANY, 'doc-pin', JE1)
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('leaves a pinned document that already points at this verifikat alone', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: 'doc-pin' } })
|
||||
enqueue({ data: { journal_entry_id: JE1 } }) // already anchored here
|
||||
enqueue({ data: [] })
|
||||
|
||||
await propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
)
|
||||
|
||||
expect(linkToJournalEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('never steals a pinned document anchored to another verifikat', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: 'doc-pin' } })
|
||||
enqueue({ data: { journal_entry_id: 'je-other' } })
|
||||
enqueue({ data: [] })
|
||||
|
||||
await propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
)
|
||||
|
||||
expect(linkToJournalEntry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still processes inbox items when the pinned-document link fails', async () => {
|
||||
vi.mocked(linkToJournalEntry).mockRejectedValueOnce(new Error('period locked'))
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: 'doc-pin' } })
|
||||
enqueue({ data: { journal_entry_id: null } }) // pinned doc; link will throw
|
||||
enqueue({ data: [{ id: 'i1', document_id: null }] }) // docless matched item
|
||||
enqueue({ data: null }) // stamp update
|
||||
|
||||
await expect(
|
||||
propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
),
|
||||
).resolves.toBeUndefined()
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toContainEqual([
|
||||
{ created_journal_entry_id: JE1 },
|
||||
])
|
||||
})
|
||||
|
||||
it('links a document shared by the pin and a matched item only once', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: 'doc-1' } }) // pin points at the same doc
|
||||
enqueue({ data: { journal_entry_id: null } }) // pin leg links it
|
||||
enqueue({ data: [{ id: 'i1', document_id: 'doc-1' }] }) // matched item, same doc
|
||||
enqueue({ data: { journal_entry_id: JE1 } }) // item leg finds it anchored
|
||||
enqueue({ data: null }) // stamp update
|
||||
|
||||
await propagateUnderlagForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
JE1,
|
||||
)
|
||||
|
||||
expect(linkToJournalEntry).toHaveBeenCalledTimes(1)
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toContainEqual([
|
||||
{ created_journal_entry_id: JE1 },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('completeInboxItemsForBookedTransaction', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('is a no-op for an unbooked transaction', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ id: TX1, journal_entry_id: null }] })
|
||||
enqueue({ data: [] }) // no voucher links
|
||||
|
||||
const result = await completeInboxItemsForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
)
|
||||
expect(result).toBeNull()
|
||||
expect(findCalls('invoice_inbox_items', 'select').length).toBe(0)
|
||||
})
|
||||
|
||||
it('skips the resolution fetch when the caller passes the direct id', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: { document_id: null } }) // tx pin lookup inside propagate
|
||||
enqueue({ data: [] }) // matched items (none)
|
||||
|
||||
const result = await completeInboxItemsForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
{ directJournalEntryId: JE1 },
|
||||
)
|
||||
expect(result).toBe(JE1)
|
||||
// The only transactions read is the pin lookup inside the propagation:
|
||||
// the id/journal_entry_id resolution query never runs.
|
||||
expect(findCalls('transactions', 'select')).toEqual([['document_id']])
|
||||
})
|
||||
|
||||
it('resolves the samlingsverifikat through voucher links when the direct id is null', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ transaction_id: TX1, journal_entry_id: JE2 }] }) // voucher links
|
||||
enqueue({ data: { document_id: null } }) // tx pin lookup inside propagate
|
||||
enqueue({ data: [{ id: 'i1', document_id: null }] }) // matched items
|
||||
enqueue({ data: null }) // stamp update
|
||||
|
||||
const result = await completeInboxItemsForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
{ directJournalEntryId: null },
|
||||
)
|
||||
expect(result).toBe(JE2)
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toContainEqual([
|
||||
{ created_journal_entry_id: JE2 },
|
||||
])
|
||||
})
|
||||
|
||||
it('anchors a pinned document against the samlingsverifikat on attach-after-bulk-book', async () => {
|
||||
// A bulk-booked tx keeps transactions.journal_entry_id null: its verifikat
|
||||
// hangs off transaction_voucher_links. A document attached AFTER that
|
||||
// booking (with no inbox item) must still land on the samlingsverifikat:
|
||||
// voucher-link resolution feeds the pin leg of the propagation.
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ transaction_id: TX1, journal_entry_id: JE2 }] }) // voucher links
|
||||
enqueue({ data: { document_id: 'doc-pin' } }) // tx pin lookup
|
||||
enqueue({ data: { journal_entry_id: null } }) // pinned doc unanchored
|
||||
enqueue({ data: [] }) // no matched inbox items
|
||||
|
||||
const result = await completeInboxItemsForBookedTransaction(
|
||||
supabase as unknown as SupabaseClient,
|
||||
COMPANY,
|
||||
TX1,
|
||||
{ directJournalEntryId: null },
|
||||
)
|
||||
expect(result).toBe(JE2)
|
||||
expect(linkToJournalEntry).toHaveBeenCalledWith(expect.anything(), COMPANY, 'doc-pin', JE2)
|
||||
expect(findCalls('invoice_inbox_items', 'update')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveUnderlagAnchoring', () => {
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
it('reads an item without a document as anchored, without querying', async () => {
|
||||
// No underlag to carry onto the verifikat: only the stamp is missing.
|
||||
const { supabase, calls } = createQueuedMockSupabase()
|
||||
const map = await resolveUnderlagAnchoring(supabase as unknown as SupabaseClient, COMPANY, [
|
||||
{ id: 'i1', document_id: null, journalEntryId: JE1 },
|
||||
])
|
||||
expect(map.get('i1')).toEqual({ status: 'anchored', document_journal_entry_id: null })
|
||||
expect(calls.length).toBe(0)
|
||||
})
|
||||
|
||||
it('classifies anchored, unlinked and anchored_elsewhere from one batched select', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'doc-a', journal_entry_id: JE1 },
|
||||
{ id: 'doc-b', journal_entry_id: null },
|
||||
{ id: 'doc-c', journal_entry_id: JE2 },
|
||||
],
|
||||
})
|
||||
|
||||
const map = await resolveUnderlagAnchoring(supabase as unknown as SupabaseClient, COMPANY, [
|
||||
{ id: 'i-a', document_id: 'doc-a', journalEntryId: JE1 },
|
||||
{ id: 'i-b', document_id: 'doc-b', journalEntryId: JE1 },
|
||||
{ id: 'i-c', document_id: 'doc-c', journalEntryId: JE1 },
|
||||
{ id: 'i-none', document_id: null, journalEntryId: JE1 },
|
||||
])
|
||||
|
||||
expect(map.get('i-a')?.status).toBe('anchored')
|
||||
expect(map.get('i-b')?.status).toBe('unlinked')
|
||||
expect(map.get('i-c')).toEqual({ status: 'anchored_elsewhere', document_journal_entry_id: JE2 })
|
||||
expect(map.get('i-none')?.status).toBe('anchored')
|
||||
const selects = findCalls('document_attachments', 'select')
|
||||
expect(selects.length).toBe(1)
|
||||
expect(findCalls('document_attachments', 'in')).toEqual([['id', ['doc-a', 'doc-b', 'doc-c']]])
|
||||
})
|
||||
|
||||
it('reads an unlinked item whose verifikat sits in a locked or closed period as unlinked_locked', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: 'doc-a', journal_entry_id: null },
|
||||
{ id: 'doc-b', journal_entry_id: null },
|
||||
{ id: 'doc-c', journal_entry_id: null },
|
||||
{ id: 'doc-d', journal_entry_id: JE1 },
|
||||
],
|
||||
})
|
||||
enqueue({
|
||||
data: [
|
||||
{ id: JE1, fiscal_period: { is_closed: false, locked_at: '2026-08-01T00:00:00Z' } },
|
||||
{ id: JE2, fiscal_period: { is_closed: true, locked_at: null } },
|
||||
{ id: 'je-open', fiscal_period: { is_closed: false, locked_at: null } },
|
||||
],
|
||||
})
|
||||
|
||||
const map = await resolveUnderlagAnchoring(supabase as unknown as SupabaseClient, COMPANY, [
|
||||
{ id: 'i-a', document_id: 'doc-a', journalEntryId: JE1 },
|
||||
{ id: 'i-b', document_id: 'doc-b', journalEntryId: JE2 },
|
||||
{ id: 'i-c', document_id: 'doc-c', journalEntryId: 'je-open' },
|
||||
{ id: 'i-d', document_id: 'doc-d', journalEntryId: JE1 },
|
||||
])
|
||||
|
||||
expect(map.get('i-a')).toEqual({ status: 'unlinked_locked', document_journal_entry_id: null })
|
||||
expect(map.get('i-b')).toEqual({ status: 'unlinked_locked', document_journal_entry_id: null })
|
||||
expect(map.get('i-c')?.status).toBe('unlinked')
|
||||
// Already anchored: the lock does not matter and it is not looked up.
|
||||
expect(map.get('i-d')?.status).toBe('anchored')
|
||||
expect(findCalls('journal_entries', 'in')).toEqual([['id', [JE1, JE2, 'je-open']]])
|
||||
// The bare `fiscal_periods(...)` embed is ambiguous on prod (fiscal_periods
|
||||
// has closing_entry_id and opening_balance_entry_id back to journal_entries)
|
||||
// and made every lock-state read fail on the first cron run (2026-08-29).
|
||||
expect(findCalls('journal_entries', 'select')).toEqual([
|
||||
['id, fiscal_period:fiscal_periods!journal_entries_fiscal_period_id_fkey(is_closed, locked_at)'],
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps an unlinked item unlinked (retryable) when the lock-state read fails', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [{ id: 'doc-a', journal_entry_id: null }] })
|
||||
enqueue({ data: null, error: { message: 'boom' } })
|
||||
const map = await resolveUnderlagAnchoring(supabase as unknown as SupabaseClient, COMPANY, [
|
||||
{ id: 'i-a', document_id: 'doc-a', journalEntryId: JE1 },
|
||||
])
|
||||
expect(map.get('i-a')?.status).toBe('unlinked')
|
||||
})
|
||||
|
||||
it('leaves items absent (unknown, not anchored) when the document read fails', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: { message: 'boom' } })
|
||||
const map = await resolveUnderlagAnchoring(supabase as unknown as SupabaseClient, COMPANY, [
|
||||
{ id: 'i-a', document_id: 'doc-a', journalEntryId: JE1 },
|
||||
{ id: 'i-none', document_id: null, journalEntryId: JE1 },
|
||||
])
|
||||
expect(map.has('i-a')).toBe(false)
|
||||
expect(map.get('i-none')?.status).toBe('anchored')
|
||||
})
|
||||
|
||||
it('leaves an item absent when its document row is not returned', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: [] })
|
||||
const map = await resolveUnderlagAnchoring(supabase as unknown as SupabaseClient, COMPANY, [
|
||||
{ id: 'i-a', document_id: 'doc-a', journalEntryId: JE1 },
|
||||
])
|
||||
expect(map.has('i-a')).toBe(false)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,74 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { isTransactionBooked, getPrimaryJournalEntryId } from '../is-booked'
|
||||
|
||||
describe('isTransactionBooked', () => {
|
||||
it('returns false for a tx with no journal entry, payments, or voucher links', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
expect(isTransactionBooked(tx)).toBe(false)
|
||||
expect(isTransactionBooked(tx, [], [])).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when transactions.journal_entry_id is set (1:1 case)', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: 'je-1' }
|
||||
expect(isTransactionBooked(tx)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true when a matching invoice_payments row exists (multi-allocation)', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
const payments = [{ transaction_id: 'tx-1' }]
|
||||
expect(isTransactionBooked(tx, payments)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true when a matching supplier_invoice_payments row exists', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
const payments = [{ transaction_id: 'tx-1' }]
|
||||
expect(isTransactionBooked(tx, payments)).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true when a transaction_voucher_links row references the tx (bulk-book)', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
const links = [{ transaction_id: 'tx-1' }]
|
||||
expect(isTransactionBooked(tx, [], links)).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores payment / voucher-link rows that reference a different tx', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
const payments = [{ transaction_id: 'tx-other' }]
|
||||
const links = [{ transaction_id: 'tx-other' }]
|
||||
expect(isTransactionBooked(tx, payments, links)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getPrimaryJournalEntryId', () => {
|
||||
it('returns null when nothing is anchored', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
expect(getPrimaryJournalEntryId(tx)).toBeNull()
|
||||
})
|
||||
|
||||
it('prefers transactions.journal_entry_id when set', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: 'je-1' }
|
||||
const payments = [{ transaction_id: 'tx-1', journal_entry_id: 'je-payment' }]
|
||||
const links = [{ transaction_id: 'tx-1', journal_entry_id: 'je-link' }]
|
||||
expect(getPrimaryJournalEntryId(tx, payments, links)).toBe('je-1')
|
||||
})
|
||||
|
||||
it('falls back to voucher-link when tx.journal_entry_id is null', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
const links = [{ transaction_id: 'tx-1', journal_entry_id: 'je-link' }]
|
||||
expect(getPrimaryJournalEntryId(tx, [], links)).toBe('je-link')
|
||||
})
|
||||
|
||||
it('falls back to invoice_payments JE when no link exists', () => {
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
const payments = [{ transaction_id: 'tx-1', journal_entry_id: 'je-payment' }]
|
||||
expect(getPrimaryJournalEntryId(tx, payments, [])).toBe('je-payment')
|
||||
})
|
||||
|
||||
it('returns null when matching payment has journal_entry_id=null', () => {
|
||||
// Edge: an invoice_payments row that pre-dates the JE creation (the
|
||||
// engine's non-blocking JE write can leave this null briefly).
|
||||
const tx = { id: 'tx-1', journal_entry_id: null }
|
||||
const payments = [{ transaction_id: 'tx-1', journal_entry_id: null }]
|
||||
expect(getPrimaryJournalEntryId(tx, payments, [])).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,107 +0,0 @@
|
||||
/**
|
||||
* Unit tests for hasLiveJournalEntryLink.
|
||||
*
|
||||
* This is the predicate the re-booking guards (linkTransactionToJournalEntry,
|
||||
* manualLink, categorize-core, the MCP stage-check) share to decide whether a
|
||||
* transaction's journal_entry_id is a LIVE link that should block re-linking,
|
||||
* or a stale pointer at a reversed/cancelled entry that the UI already shows as
|
||||
* "utan koppling" and must stay re-linkable (issue #988).
|
||||
*
|
||||
* The end-to-end re-link behaviour is covered by the route test
|
||||
* (app/api/transactions/[id]/link-journal-entry/__tests__/route.test.ts) and
|
||||
* the pending-op commit test.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { createQueuedMockSupabase } from '@/tests/helpers'
|
||||
import { hasLiveJournalEntryLink, linkTransactionToJournalEntry } from '../link-journal-entry'
|
||||
|
||||
describe('hasLiveJournalEntryLink', () => {
|
||||
it('returns false for a null/undefined pointer without querying', async () => {
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
expect(await hasLiveJournalEntryLink(supabase as never, 'company-1', null)).toBe(false)
|
||||
expect(await hasLiveJournalEntryLink(supabase as never, 'company-1', undefined)).toBe(false)
|
||||
})
|
||||
|
||||
it('returns true when the entry is posted (a live link)', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { status: 'posted' }, error: null })
|
||||
expect(await hasLiveJournalEntryLink(supabase as never, 'company-1', 'je-1')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false when the entry is reversed (stale link, #988)', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { status: 'reversed' }, error: null })
|
||||
expect(await hasLiveJournalEntryLink(supabase as never, 'company-1', 'je-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when the entry is cancelled', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: { status: 'cancelled' }, error: null })
|
||||
expect(await hasLiveJournalEntryLink(supabase as never, 'company-1', 'je-1')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when the referenced entry row is missing', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: null })
|
||||
expect(await hasLiveJournalEntryLink(supabase as never, 'company-1', 'je-gone')).toBe(false)
|
||||
})
|
||||
|
||||
it('fails closed (returns true) on a read error so a live link is never clobbered', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({ data: null, error: { message: 'statement timeout' } })
|
||||
expect(await hasLiveJournalEntryLink(supabase as never, 'company-1', 'je-1')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('linkTransactionToJournalEntry: junction-row guard (#1553)', () => {
|
||||
const base = {
|
||||
id: 'tx-1',
|
||||
date: '2026-06-11',
|
||||
amount: -800,
|
||||
currency: 'SEK',
|
||||
exchange_rate: null,
|
||||
journal_entry_id: null,
|
||||
invoice_id: null,
|
||||
is_business: null,
|
||||
potential_invoice_id: null,
|
||||
potential_supplier_invoice_id: null,
|
||||
}
|
||||
|
||||
it('refuses a transaction anchored through a bank_line junction row (1:N split, bulk-book) even though the pointer is NULL', async () => {
|
||||
const { supabase, enqueue, findCalls } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: { ...base, transaction_voucher_links: [{ journal_entry_id: 'je-split-a', role: 'bank_line' }] },
|
||||
error: null,
|
||||
})
|
||||
|
||||
const outcome = await linkTransactionToJournalEntry(supabase as never, 'user-1', 'company-1', {
|
||||
transactionId: 'tx-1',
|
||||
journalEntryId: 'je-other',
|
||||
})
|
||||
|
||||
expect(outcome).toEqual({
|
||||
ok: false,
|
||||
code: 'LINK_TX_TX_ALREADY_LINKED',
|
||||
details: { existingJournalEntryId: 'je-split-a' },
|
||||
})
|
||||
expect(findCalls('transactions', 'update')).toEqual([])
|
||||
})
|
||||
|
||||
it('lets a residual booking\'s "other" row through: the row must stay re-linkable after a storno of its main verifikat', async () => {
|
||||
const { supabase, enqueue } = createQueuedMockSupabase()
|
||||
enqueue({
|
||||
data: { ...base, transaction_voucher_links: [{ journal_entry_id: 'je-residual', role: 'other' }] },
|
||||
error: null,
|
||||
})
|
||||
enqueue({ data: null, error: { message: 'not found' } }) // the verifikat lookup that follows the guard
|
||||
|
||||
const outcome = await linkTransactionToJournalEntry(supabase as never, 'user-1', 'company-1', {
|
||||
transactionId: 'tx-1',
|
||||
journalEntryId: 'je-other',
|
||||
})
|
||||
|
||||
expect(outcome.ok).toBe(false)
|
||||
expect((outcome as { code: string }).code).not.toBe('LINK_TX_TX_ALREADY_LINKED')
|
||||
expect(supabase.from).toHaveBeenCalledWith('journal_entries')
|
||||
})
|
||||
})
|
||||
@@ -1,108 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { fetchMigrationCoverageEnd } from '@/lib/transactions/migration-coverage'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
/**
|
||||
* Recording chain mock: remembers every chained call so the test can assert
|
||||
* the exact filters. The generic createMockSupabase proxy swallows arguments.
|
||||
* Results are dequeued per from() call: first for sie_imports (arm gate),
|
||||
* second for journal_entries.
|
||||
*/
|
||||
function createRecordingSupabase(results: Array<{ data: unknown; error: unknown }>) {
|
||||
const calls: Array<{ method: string; args: unknown[] }> = []
|
||||
const queue = [...results]
|
||||
const buildChain = () => {
|
||||
const result = queue.shift() ?? { data: null, error: null }
|
||||
const chain: Record<string, unknown> = {}
|
||||
const record =
|
||||
(method: string) =>
|
||||
(...args: unknown[]) => {
|
||||
calls.push({ method, args })
|
||||
return chain
|
||||
}
|
||||
for (const method of ['select', 'eq', 'neq', 'not', 'order', 'limit']) {
|
||||
chain[method] = record(method)
|
||||
}
|
||||
chain.maybeSingle = vi.fn().mockImplementation(() => {
|
||||
calls.push({ method: 'maybeSingle', args: [] })
|
||||
return Promise.resolve(result)
|
||||
})
|
||||
return chain
|
||||
}
|
||||
const from = vi.fn().mockImplementation((...args: unknown[]) => {
|
||||
calls.push({ method: 'from', args })
|
||||
return buildChain()
|
||||
})
|
||||
return { supabase: { from } as unknown as SupabaseClient, calls }
|
||||
}
|
||||
|
||||
const armed = { data: { id: 'import-1' }, error: null }
|
||||
|
||||
describe('fetchMigrationCoverageEnd', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns the latest imported entry date for a migrated company', async () => {
|
||||
const { supabase } = createRecordingSupabase([
|
||||
armed,
|
||||
{ data: { entry_date: '2026-06-30' }, error: null },
|
||||
])
|
||||
await expect(fetchMigrationCoverageEnd(supabase, 'company-1')).resolves.toBe('2026-06-30')
|
||||
})
|
||||
|
||||
it('returns null without a completed SIE import, even if import-typed entries exist', async () => {
|
||||
// Arm gate: source_type='import' is accepted from API clients, so a
|
||||
// company that never migrated must never get a cutoff from such entries.
|
||||
const { supabase, calls } = createRecordingSupabase([
|
||||
{ data: null, error: null },
|
||||
{ data: { entry_date: '2026-12-31' }, error: null },
|
||||
])
|
||||
await expect(fetchMigrationCoverageEnd(supabase, 'company-1')).resolves.toBeNull()
|
||||
expect(calls.filter((c) => c.method === 'from').map((c) => c.args[0])).toEqual(['sie_imports'])
|
||||
})
|
||||
|
||||
it('returns null when a migrated company has no imported entries', async () => {
|
||||
const { supabase } = createRecordingSupabase([armed, { data: null, error: null }])
|
||||
await expect(fetchMigrationCoverageEnd(supabase, 'company-1')).resolves.toBeNull()
|
||||
})
|
||||
|
||||
it('arms on completed imports and takes the max over posted import entries excluding the omföringsverifikation', async () => {
|
||||
const { supabase, calls } = createRecordingSupabase([armed, { data: null, error: null }])
|
||||
await fetchMigrationCoverageEnd(supabase, 'company-1')
|
||||
|
||||
expect(calls.filter((c) => c.method === 'from').map((c) => c.args[0])).toEqual([
|
||||
'sie_imports',
|
||||
'journal_entries',
|
||||
])
|
||||
expect(calls).toContainEqual({ method: 'eq', args: ['status', 'completed'] })
|
||||
expect(calls).toContainEqual({ method: 'eq', args: ['company_id', 'company-1'] })
|
||||
expect(calls).toContainEqual({ method: 'eq', args: ['status', 'posted'] })
|
||||
expect(calls).toContainEqual({ method: 'eq', args: ['source_type', 'import'] })
|
||||
// The importer's omföringsverifikation is dated at fiscal year end; without
|
||||
// this exclusion a mid-year migration with skipped vouchers would get a
|
||||
// future cutoff again (the bug this module exists to fix). Excluded by its
|
||||
// hardcoded description prefix, NOT by voucher series: imported vouchers
|
||||
// keep the source file's series, and real files use series M.
|
||||
expect(calls).toContainEqual({
|
||||
method: 'not',
|
||||
args: ['description', 'like', 'Omföringsverifikation:%'],
|
||||
})
|
||||
expect(calls.filter((c) => c.method === 'neq')).toEqual([])
|
||||
expect(calls).toContainEqual({
|
||||
method: 'order',
|
||||
args: ['entry_date', { ascending: false }],
|
||||
})
|
||||
expect(calls).toContainEqual({ method: 'limit', args: [1] })
|
||||
})
|
||||
|
||||
it('never reads sie_imports.fiscal_year_end as the cutoff', async () => {
|
||||
// Regression guard for the original bug: the cutoff value must come from
|
||||
// actual imported data, never the #RAR-declared fiscal year. sie_imports
|
||||
// is consulted only as the arm gate (select id).
|
||||
const { supabase, calls } = createRecordingSupabase([armed, { data: null, error: null }])
|
||||
await fetchMigrationCoverageEnd(supabase, 'company-1')
|
||||
const selects = calls.filter((c) => c.method === 'select').map((c) => c.args[0])
|
||||
expect(selects).toEqual(['id', 'entry_date'])
|
||||
})
|
||||
})
|
||||
@@ -1,52 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { isImportedTransaction } from '@/lib/transactions/origin'
|
||||
|
||||
describe('isImportedTransaction', () => {
|
||||
describe('imported (ignore-only, never deletable)', () => {
|
||||
it('treats a row with a live bank connection as imported', () => {
|
||||
expect(isImportedTransaction({ bank_connection_id: 'bc-1', import_source: null })).toBe(true)
|
||||
})
|
||||
|
||||
it('treats a row with a bank connection as imported even if import_source looks in-app', () => {
|
||||
// The bank link wins: a PSD2 row is imported regardless of the source tag.
|
||||
expect(isImportedTransaction({ bank_connection_id: 'bc-1', import_source: 'manual' })).toBe(true)
|
||||
})
|
||||
|
||||
it('treats Enable Banking sync rows as imported', () => {
|
||||
expect(isImportedTransaction({ bank_connection_id: null, import_source: 'enable_banking' })).toBe(true)
|
||||
})
|
||||
|
||||
it('treats CAMT053 bank-file imports as imported', () => {
|
||||
expect(isImportedTransaction({ bank_connection_id: null, import_source: 'camt053' })).toBe(true)
|
||||
})
|
||||
|
||||
it.each(['csv_nordea', 'csv_lunar', 'csv_seb'])(
|
||||
'treats CSV bank-file import %s as imported',
|
||||
(source) => {
|
||||
expect(isImportedTransaction({ bank_connection_id: null, import_source: source })).toBe(true)
|
||||
},
|
||||
)
|
||||
|
||||
it('treats an unknown future import source as imported (safe default)', () => {
|
||||
expect(isImportedTransaction({ bank_connection_id: null, import_source: 'some_new_feed' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('user-created (deletable when unbooked)', () => {
|
||||
it('treats a null source with no bank link as user-created (manual add)', () => {
|
||||
expect(isImportedTransaction({ bank_connection_id: null, import_source: null })).toBe(false)
|
||||
})
|
||||
|
||||
it('treats create-from-document (manual) as user-created', () => {
|
||||
expect(isImportedTransaction({ bank_connection_id: null, import_source: 'manual' })).toBe(false)
|
||||
})
|
||||
|
||||
it('treats MCP/agent-created rows as user-created', () => {
|
||||
expect(isImportedTransaction({ bank_connection_id: null, import_source: 'mcp' })).toBe(false)
|
||||
})
|
||||
|
||||
it('tolerates omitted (undefined) origin fields', () => {
|
||||
expect(isImportedTransaction({})).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,114 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
quarterBounds,
|
||||
resolvePeriodBounds,
|
||||
isWithinBounds,
|
||||
QUARTERS,
|
||||
} from '@/lib/transactions/period-filter'
|
||||
|
||||
const calendarYear = { period_start: '2026-01-01', period_end: '2026-12-31' }
|
||||
// Brutet rakenskapsar: the reporter's July-June case.
|
||||
const brokenYear = { period_start: '2025-07-01', period_end: '2026-06-30' }
|
||||
// Shortened first year (6 months).
|
||||
const shortYear = { period_start: '2026-01-01', period_end: '2026-06-30' }
|
||||
// Extended first year (18 months).
|
||||
const extendedYear = { period_start: '2025-01-01', period_end: '2026-06-30' }
|
||||
|
||||
describe('quarterBounds', () => {
|
||||
it('splits a calendar fiscal year into calendar quarters', () => {
|
||||
expect(quarterBounds(calendarYear, 1)).toEqual({ start: '2026-01-01', end: '2026-03-31' })
|
||||
expect(quarterBounds(calendarYear, 2)).toEqual({ start: '2026-04-01', end: '2026-06-30' })
|
||||
expect(quarterBounds(calendarYear, 3)).toEqual({ start: '2026-07-01', end: '2026-09-30' })
|
||||
expect(quarterBounds(calendarYear, 4)).toEqual({ start: '2026-10-01', end: '2026-12-31' })
|
||||
})
|
||||
|
||||
it('follows the fiscal year for a brutet rakenskapsar (July-June)', () => {
|
||||
expect(quarterBounds(brokenYear, 1)).toEqual({ start: '2025-07-01', end: '2025-09-30' })
|
||||
expect(quarterBounds(brokenYear, 2)).toEqual({ start: '2025-10-01', end: '2025-12-31' })
|
||||
expect(quarterBounds(brokenYear, 3)).toEqual({ start: '2026-01-01', end: '2026-03-31' })
|
||||
expect(quarterBounds(brokenYear, 4)).toEqual({ start: '2026-04-01', end: '2026-06-30' })
|
||||
})
|
||||
|
||||
it('returns null for quarters beyond a shortened period', () => {
|
||||
expect(quarterBounds(shortYear, 1)).toEqual({ start: '2026-01-01', end: '2026-03-31' })
|
||||
expect(quarterBounds(shortYear, 2)).toEqual({ start: '2026-04-01', end: '2026-06-30' })
|
||||
expect(quarterBounds(shortYear, 3)).toBeNull()
|
||||
expect(quarterBounds(shortYear, 4)).toBeNull()
|
||||
})
|
||||
|
||||
it('clamps a quarter end that would pass period_end', () => {
|
||||
const fiveMonths = { period_start: '2026-01-01', period_end: '2026-05-31' }
|
||||
expect(quarterBounds(fiveMonths, 2)).toEqual({ start: '2026-04-01', end: '2026-05-31' })
|
||||
})
|
||||
|
||||
it('lets Q4 absorb the tail of an extended fiscal year', () => {
|
||||
expect(quarterBounds(extendedYear, 4)).toEqual({ start: '2025-10-01', end: '2026-06-30' })
|
||||
})
|
||||
|
||||
it('covers every day of a regular period across the four quarters', () => {
|
||||
for (const period of [calendarYear, brokenYear]) {
|
||||
const bounds = QUARTERS.map((q) => quarterBounds(period, q))
|
||||
expect(bounds[0]?.start).toBe(period.period_start)
|
||||
expect(bounds[3]?.end).toBe(period.period_end)
|
||||
for (let i = 1; i < 4; i++) {
|
||||
const prevEnd = bounds[i - 1]?.end
|
||||
const nextStart = bounds[i]?.start
|
||||
expect(prevEnd).toBeDefined()
|
||||
expect(nextStart).toBeDefined()
|
||||
// Next quarter starts the day after the previous one ends.
|
||||
const followingDay = new Date(`${prevEnd}T00:00:00Z`)
|
||||
followingDay.setUTCDate(followingDay.getUTCDate() + 1)
|
||||
expect(nextStart).toBe(followingDay.toISOString().slice(0, 10))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('handles a period start that is not the first of a month', () => {
|
||||
const midMonth = { period_start: '2026-01-15', period_end: '2027-01-14' }
|
||||
expect(quarterBounds(midMonth, 1)).toEqual({ start: '2026-01-15', end: '2026-04-14' })
|
||||
expect(quarterBounds(midMonth, 2)).toEqual({ start: '2026-04-15', end: '2026-07-14' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolvePeriodBounds', () => {
|
||||
it('returns null without a period', () => {
|
||||
expect(resolvePeriodBounds(null, null)).toBeNull()
|
||||
expect(resolvePeriodBounds(null, 2)).toBeNull()
|
||||
})
|
||||
|
||||
it('returns the whole period without a quarter', () => {
|
||||
expect(resolvePeriodBounds(brokenYear, null)).toEqual({
|
||||
start: '2025-07-01',
|
||||
end: '2026-06-30',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns quarter bounds with a quarter', () => {
|
||||
expect(resolvePeriodBounds(calendarYear, 3)).toEqual({
|
||||
start: '2026-07-01',
|
||||
end: '2026-09-30',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null for a quarter outside the period', () => {
|
||||
expect(resolvePeriodBounds(shortYear, 4)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isWithinBounds', () => {
|
||||
const bounds = { start: '2026-01-01', end: '2026-03-31' }
|
||||
|
||||
it('accepts everything when no bounds are set', () => {
|
||||
expect(isWithinBounds('1999-01-01', null)).toBe(true)
|
||||
})
|
||||
|
||||
it('includes both endpoints', () => {
|
||||
expect(isWithinBounds('2026-01-01', bounds)).toBe(true)
|
||||
expect(isWithinBounds('2026-03-31', bounds)).toBe(true)
|
||||
})
|
||||
|
||||
it('excludes dates outside the bounds', () => {
|
||||
expect(isWithinBounds('2025-12-31', bounds)).toBe(false)
|
||||
expect(isWithinBounds('2026-04-01', bounds)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,110 +0,0 @@
|
||||
/**
|
||||
* What counts as a purchase still missing its underlag.
|
||||
*
|
||||
* The interesting cases are the ones the column filter cannot see. A bank
|
||||
* transaction can be booked three ways, and only one of them sets
|
||||
* `journal_entry_id`: bulk-booking many transactions onto one verifikat records
|
||||
* it in transaction_voucher_links, and a payment split across invoices records
|
||||
* it in the payment tables. Both leave the column null.
|
||||
*
|
||||
* The receipt hunt tolerates those false candidates because the worst case is a
|
||||
* proposal nobody accepts. This list is shown to a person, where the same rows
|
||||
* would sit under "saknar underlag" forever, already booked, with nothing the
|
||||
* user could do to clear them.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { fetchPurchasesWithoutUnderlag } from '../purchases-without-underlag'
|
||||
|
||||
const rows = vi.fn()
|
||||
vi.mock('@/lib/supabase/fetch-all', () => ({
|
||||
fetchAllRows: async () => rows(),
|
||||
}))
|
||||
|
||||
function tx(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'tx-1',
|
||||
company_id: 'company-1',
|
||||
date: '2026-08-04',
|
||||
description: 'Elgiganten',
|
||||
merchant_name: 'Elgiganten',
|
||||
amount: -21639,
|
||||
currency: 'SEK',
|
||||
amount_sek: null,
|
||||
exchange_rate: null,
|
||||
journal_entry_id: null,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
/** Supabase double whose link tables answer per table name. */
|
||||
function db(links: { voucher?: string[]; invoice?: string[]; supplier?: string[] } = {}) {
|
||||
const calls: string[] = []
|
||||
return {
|
||||
calls,
|
||||
from(table: string) {
|
||||
calls.push(table)
|
||||
const ids =
|
||||
table === 'transaction_voucher_links'
|
||||
? links.voucher
|
||||
: table === 'invoice_payments'
|
||||
? links.invoice
|
||||
: links.supplier
|
||||
const data = (ids ?? []).map((id) => ({ transaction_id: id }))
|
||||
const chain = { select: () => chain, in: async () => ({ data }) }
|
||||
return chain
|
||||
},
|
||||
} as never
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
describe('fetchPurchasesWithoutUnderlag', () => {
|
||||
it('returns purchases nothing has booked', async () => {
|
||||
rows.mockReturnValue([tx()])
|
||||
const out = await fetchPurchasesWithoutUnderlag(db(), 'company-1')
|
||||
expect(out).toHaveLength(1)
|
||||
expect(out[0].id).toBe('tx-1')
|
||||
})
|
||||
|
||||
it('skips the link-table lookups when there is nothing to check', async () => {
|
||||
rows.mockReturnValue([])
|
||||
const supabase = db()
|
||||
const out = await fetchPurchasesWithoutUnderlag(supabase, 'company-1')
|
||||
expect(out).toEqual([])
|
||||
expect((supabase as unknown as { calls: string[] }).calls).toEqual([])
|
||||
})
|
||||
|
||||
it('excludes a transaction bulk-booked through a voucher link', async () => {
|
||||
// Many transactions, one verifikat: journal_entry_id stays null on every
|
||||
// one of them, so the column filter lets them all through.
|
||||
rows.mockReturnValue([tx({ id: 'tx-bulk' })])
|
||||
const out = await fetchPurchasesWithoutUnderlag(db({ voucher: ['tx-bulk'] }), 'company-1')
|
||||
expect(out).toEqual([])
|
||||
})
|
||||
|
||||
it('excludes a transaction that paid a customer invoice', async () => {
|
||||
rows.mockReturnValue([tx({ id: 'tx-pay' })])
|
||||
const out = await fetchPurchasesWithoutUnderlag(db({ invoice: ['tx-pay'] }), 'company-1')
|
||||
expect(out).toEqual([])
|
||||
})
|
||||
|
||||
it('excludes a transaction that paid a supplier invoice', async () => {
|
||||
rows.mockReturnValue([tx({ id: 'tx-sup' })])
|
||||
const out = await fetchPurchasesWithoutUnderlag(db({ supplier: ['tx-sup'] }), 'company-1')
|
||||
expect(out).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps the unbooked ones when only some of a batch are booked', async () => {
|
||||
rows.mockReturnValue([tx({ id: 'a' }), tx({ id: 'b' }), tx({ id: 'c' })])
|
||||
const out = await fetchPurchasesWithoutUnderlag(db({ voucher: ['b'] }), 'company-1')
|
||||
expect(out.map((p) => p.id)).toEqual(['a', 'c'])
|
||||
})
|
||||
|
||||
it('excludes a row that already carries a journal entry', async () => {
|
||||
// Belt and braces: the query filters this out, but the predicate is what
|
||||
// the page trusts and it must agree.
|
||||
rows.mockReturnValue([tx({ journal_entry_id: 'je-1' })])
|
||||
const out = await fetchPurchasesWithoutUnderlag(db(), 'company-1')
|
||||
expect(out).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,94 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { resolveQuickReviewDefaults, resolveExplicitVat, type ReviewTemplate } from '../quick-review-defaults'
|
||||
import { getDefaultAccountForCategory } from '@/lib/bookkeeping/category-mapping'
|
||||
|
||||
/**
|
||||
* Regression cover for the "Tidigare motparter" crash: picking a learned
|
||||
* counterparty template in the Bokför-transaktion modal replaced the whole
|
||||
* page with the "Något gick fel" error boundary.
|
||||
*
|
||||
* The synthetic counterparty template carried only { id, name_sv }, so
|
||||
* `template.debit_account` was undefined, the dialog's `defaultAccount` prop
|
||||
* (declared `string`) received undefined, and the first render threw on
|
||||
* `accountOverride.startsWith('2')`.
|
||||
*/
|
||||
describe('resolveQuickReviewDefaults', () => {
|
||||
const counterparty: ReviewTemplate = {
|
||||
id: 'counterparty:11111111-1111-1111-1111-111111111111',
|
||||
name_sv: 'Fee',
|
||||
debit_account: '6570',
|
||||
credit_account: '1930',
|
||||
vat_treatment: null,
|
||||
}
|
||||
|
||||
it('never returns undefined for the account, whatever the template omits', () => {
|
||||
const bare: ReviewTemplate = { id: 'counterparty:abc', name_sv: 'Fee' }
|
||||
const { account, vat } = resolveQuickReviewDefaults(bare, undefined, 'expense_other', 'enskild_firma')
|
||||
expect(account).toBe(getDefaultAccountForCategory('expense_other', 'enskild_firma'))
|
||||
expect(typeof account).toBe('string')
|
||||
expect(vat).toBe('none')
|
||||
})
|
||||
|
||||
it('returns an empty account rather than undefined when there is nothing at all', () => {
|
||||
expect(resolveQuickReviewDefaults(null, undefined, null, 'enskild_firma')).toEqual({ account: '', vat: 'none' })
|
||||
expect(resolveQuickReviewDefaults({ id: 'counterparty:abc', name_sv: 'Fee' }, undefined, null, 'enskild_firma'))
|
||||
.toEqual({ account: '', vat: 'none' })
|
||||
})
|
||||
|
||||
it('seeds from the counterparty template accounts, not the category fallback', () => {
|
||||
const { account, vat } = resolveQuickReviewDefaults(counterparty, undefined, 'expense_other', 'enskild_firma')
|
||||
expect(account).toBe('6570')
|
||||
expect(vat).toBe('none')
|
||||
})
|
||||
|
||||
it('carries the learned VAT treatment of a counterparty template', () => {
|
||||
const { vat } = resolveQuickReviewDefaults(
|
||||
{ ...counterparty, debit_account: '5420', vat_treatment: 'standard_25' },
|
||||
undefined,
|
||||
'expense_other',
|
||||
'enskild_firma',
|
||||
)
|
||||
expect(vat).toBe('standard_25')
|
||||
})
|
||||
|
||||
it('ignores the template and uses the category when a catalog templateId is present', () => {
|
||||
const catalog: ReviewTemplate = {
|
||||
id: 'bank_fees',
|
||||
name_sv: 'Bankavgifter',
|
||||
debit_account: '6570',
|
||||
credit_account: '1930',
|
||||
vat_treatment: null,
|
||||
}
|
||||
const { account } = resolveQuickReviewDefaults(catalog, 'bank_fees', 'expense_other', 'enskild_firma')
|
||||
// Catalog templates are validated server-side by id; the form's account
|
||||
// field is not the source of truth for them.
|
||||
expect(account).toBe(getDefaultAccountForCategory('expense_other', 'enskild_firma'))
|
||||
})
|
||||
|
||||
it('falls back to the category defaults when no template is involved', () => {
|
||||
const { account, vat } = resolveQuickReviewDefaults(null, undefined, 'expense_other', 'enskild_firma')
|
||||
expect(account).toBe(getDefaultAccountForCategory('expense_other', 'enskild_firma'))
|
||||
expect(vat === 'none' || typeof vat === 'string').toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveExplicitVat', () => {
|
||||
it('passes explicit rate-bearing treatments through unchanged', () => {
|
||||
expect(resolveExplicitVat('standard_25', 'standard_25')).toBe('standard_25')
|
||||
expect(resolveExplicitVat('reduced_12', 'standard_25')).toBe('reduced_12')
|
||||
expect(resolveExplicitVat('reverse_charge', 'none')).toBe('reverse_charge')
|
||||
})
|
||||
|
||||
it("keeps a seeded 'none' default off the wire (server derives, no VAT line)", () => {
|
||||
// Bank fees etc.: category default is null -> displayed as 'none'.
|
||||
// Untouched submit must stay byte-identical to the pre-fix behavior.
|
||||
expect(resolveExplicitVat('none', 'none')).toBeUndefined()
|
||||
})
|
||||
|
||||
it("sends explicit 'exempt' when the user deviates to Ingen moms", () => {
|
||||
// The old collapse to undefined made the server re-derive the category
|
||||
// default and book 25% moms against an explicit no-VAT choice.
|
||||
expect(resolveExplicitVat('none', 'standard_25')).toBe('exempt')
|
||||
expect(resolveExplicitVat('none', 'reduced_12')).toBe('exempt')
|
||||
})
|
||||
})
|
||||
@@ -1,228 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { classifyTransactionMethod } from '../transaction-method'
|
||||
import { TRANSACTION_METHODS } from '@/types'
|
||||
|
||||
describe('classifyTransactionMethod', () => {
|
||||
// ── Trailing channel phrases (real Swedbank-style PSD2 strings) ──────────
|
||||
|
||||
it('classifies and strips "Överföring via internet"', () => {
|
||||
const r = classifyTransactionMethod({ description: 'Vercel Jul Överföring via internet' })
|
||||
expect(r.method).toBe('transfer')
|
||||
expect(r.displayTitle).toBe('Vercel Jul')
|
||||
})
|
||||
|
||||
it('classifies and strips "Kortköp/uttag"', () => {
|
||||
const r = classifyTransactionMethod({
|
||||
description: 'ANTHROPIC* CLAUDE SUB SAN FRANCISCO Kortköp/uttag',
|
||||
})
|
||||
expect(r.method).toBe('card')
|
||||
expect(r.displayTitle).toBe('ANTHROPIC* CLAUDE SUB SAN FRANCISCO')
|
||||
})
|
||||
|
||||
it('classifies and strips "Bg-bet. via internet"', () => {
|
||||
const r = classifyTransactionMethod({
|
||||
description: 'Inbetalning skat BG 0000050501055 Bg-bet. via internet',
|
||||
})
|
||||
expect(r.method).toBe('bankgiro')
|
||||
expect(r.displayTitle).toBe('Inbetalning skat BG 0000050501055')
|
||||
})
|
||||
|
||||
it('classifies and strips "Europabetalning" and its fee sibling "Pris betalning"', () => {
|
||||
const eu = classifyTransactionMethod({ description: '1260624917587 Europabetalning' })
|
||||
expect(eu.method).toBe('international')
|
||||
expect(eu.displayTitle).toBe('1260624917587')
|
||||
|
||||
const fee = classifyTransactionMethod({ description: '1260624917587 Pris betalning' })
|
||||
expect(fee.method).toBe('fee')
|
||||
expect(fee.displayTitle).toBe('1260624917587')
|
||||
})
|
||||
|
||||
it('classifies and strips "Insättning"', () => {
|
||||
const r = classifyTransactionMethod({ description: 'SWED2607270AUEOU Insättning' })
|
||||
expect(r.method).toBe('deposit')
|
||||
expect(r.displayTitle).toBe('SWED2607270AUEOU')
|
||||
})
|
||||
|
||||
it('keeps a title that IS the phrase instead of emptying it', () => {
|
||||
const r = classifyTransactionMethod({ description: 'Insättning' })
|
||||
expect(r.method).toBe('deposit')
|
||||
expect(r.displayTitle).toBe('Insättning')
|
||||
})
|
||||
|
||||
it('prefers the longer phrase over its substring', () => {
|
||||
// "överföring via internet" must win over the bare "överföring";
|
||||
// "kortköp/uttag" must win over "uttag" (which never matches: no
|
||||
// preceding whitespace).
|
||||
const r = classifyTransactionMethod({ description: 'Lön Juli Emil Överföring via internet' })
|
||||
expect(r.method).toBe('transfer')
|
||||
expect(r.displayTitle).toBe('Lön Juli Emil')
|
||||
})
|
||||
|
||||
it('does not match a phrase inside a word', () => {
|
||||
// "Löneinsättning" ends in "insättning" but is salary, not deposit.
|
||||
const salary = classifyTransactionMethod({ description: 'ACME AB Löneinsättning' })
|
||||
expect(salary.method).toBe('salary')
|
||||
expect(salary.displayTitle).toBe('ACME AB')
|
||||
|
||||
// "Bankavgift" (single word) is untouched by the bare "avgift" rule.
|
||||
const bankfee = classifyTransactionMethod({ description: 'Bankavgift' })
|
||||
expect(bankfee.method).toBeNull()
|
||||
expect(bankfee.displayTitle).toBe('Bankavgift')
|
||||
})
|
||||
|
||||
it('classifies leading "Swish till/från" without stripping the counterparty', () => {
|
||||
const r = classifyTransactionMethod({ description: 'Swish till Erik Andersson' })
|
||||
expect(r.method).toBe('swish')
|
||||
expect(r.displayTitle).toBe('Swish till Erik Andersson')
|
||||
})
|
||||
|
||||
it('adjective guard: classifies but never strips "Egen insättning" / "Eget uttag"', () => {
|
||||
// The phrase IS the meaning when preceded by a possessive/scope adjective:
|
||||
// stripping would leave a nonsense title ("Egen").
|
||||
const deposit = classifyTransactionMethod({ description: 'Egen insättning' })
|
||||
expect(deposit.method).toBe('deposit')
|
||||
expect(deposit.displayTitle).toBe('Egen insättning')
|
||||
|
||||
const withdrawal = classifyTransactionMethod({ description: 'Eget uttag' })
|
||||
expect(withdrawal.method).toBe('withdrawal')
|
||||
expect(withdrawal.displayTitle).toBe('Eget uttag')
|
||||
|
||||
const transfer = classifyTransactionMethod({ description: 'Intern överföring' })
|
||||
expect(transfer.method).toBe('transfer')
|
||||
expect(transfer.displayTitle).toBe('Intern överföring')
|
||||
})
|
||||
|
||||
// ── ISO 20022 / proprietary codes ────────────────────────────────────────
|
||||
|
||||
it('classifies from the ISO 20022 family when no phrase matches', () => {
|
||||
const r = classifyTransactionMethod({
|
||||
description: 'COOP KONSUM STOCKHOLM',
|
||||
bankTransactionCode: 'PMNT-CCRD-POSD',
|
||||
})
|
||||
expect(r.method).toBe('card')
|
||||
expect(r.displayTitle).toBe('COOP KONSUM STOCKHOLM')
|
||||
})
|
||||
|
||||
it('lets the ISO subfamily refine the family default', () => {
|
||||
expect(
|
||||
classifyTransactionMethod({
|
||||
description: 'Payroll run',
|
||||
bankTransactionCode: 'PMNT/ICDT/SALA',
|
||||
}).method
|
||||
).toBe('salary')
|
||||
expect(
|
||||
classifyTransactionMethod({
|
||||
description: 'Payment abroad',
|
||||
bankTransactionCode: 'PMNT/ICDT/XBCT',
|
||||
}).method
|
||||
).toBe('international')
|
||||
})
|
||||
|
||||
it('lets a subfamily on the second code beat a family match on the first', () => {
|
||||
// The ISO code carries only DOMAIN/FAMILY while the proprietary code
|
||||
// carries the full triple: the SALA refinement must still win.
|
||||
const r = classifyTransactionMethod({
|
||||
description: 'Payroll run',
|
||||
bankTransactionCode: 'PMNT/ICDT',
|
||||
proprietaryBankTransactionCode: 'PMNT-ICDT-SALA',
|
||||
})
|
||||
expect(r.method).toBe('salary')
|
||||
})
|
||||
|
||||
it('prefers the bank-authored phrase over the generic ISO family', () => {
|
||||
// A Bankgiro payment travels as an issued credit transfer (ICDT): the
|
||||
// phrase is the more specific truth.
|
||||
const r = classifyTransactionMethod({
|
||||
description: 'TELIA AB Bg-betalning',
|
||||
bankTransactionCode: 'PMNT/ICDT',
|
||||
})
|
||||
expect(r.method).toBe('bankgiro')
|
||||
expect(r.displayTitle).toBe('TELIA AB')
|
||||
})
|
||||
|
||||
it('falls back to a keyword scan over proprietary codes', () => {
|
||||
const r = classifyTransactionMethod({
|
||||
description: 'Some row',
|
||||
proprietaryBankTransactionCode: 'SWISH_PAYMENT',
|
||||
})
|
||||
expect(r.method).toBe('swish')
|
||||
})
|
||||
|
||||
it('reads the flattened Enable Banking description "Kortköp/uttag" as card, not withdrawal', () => {
|
||||
// SEB/Swedbank send this combined channel wording as the code description
|
||||
// for ordinary card purchases; the row title carries only the merchant.
|
||||
expect(
|
||||
classifyTransactionMethod({ description: 'AIMO PARK', bankTransactionCode: 'Kortköp/uttag' }).method
|
||||
).toBe('card')
|
||||
expect(
|
||||
classifyTransactionMethod({ description: 'SPOTIFY', bankTransactionCode: 'Card purchase' }).method
|
||||
).toBe('card')
|
||||
// A bare withdrawal wording still classifies as withdrawal.
|
||||
expect(
|
||||
classifyTransactionMethod({ description: 'BANKOMAT 123', bankTransactionCode: 'ATM WITHDRAWAL' }).method
|
||||
).toBe('withdrawal')
|
||||
})
|
||||
|
||||
// ── MCC and explicit methods ─────────────────────────────────────────────
|
||||
|
||||
it('uses MCC presence as the card-rail fallback (6011 = ATM withdrawal)', () => {
|
||||
expect(
|
||||
classifyTransactionMethod({ description: 'SPOTIFY AB', mccCode: 5815 }).method
|
||||
).toBe('card')
|
||||
expect(
|
||||
classifyTransactionMethod({ description: 'BANKOMAT 123', mccCode: 6011 }).method
|
||||
).toBe('withdrawal')
|
||||
})
|
||||
|
||||
it('lets an explicit source method beat every heuristic', () => {
|
||||
const r = classifyTransactionMethod({
|
||||
description: 'Stripe-utbetalning po_123 Kortköp',
|
||||
explicitMethod: 'transfer',
|
||||
})
|
||||
expect(r.method).toBe('transfer')
|
||||
// The phrase strip still applies to the title.
|
||||
expect(r.displayTitle).toBe('Stripe-utbetalning po_123')
|
||||
})
|
||||
|
||||
it('returns null method and the untouched title when nothing matches', () => {
|
||||
const r = classifyTransactionMethod({ description: 'Okänd transaktion' })
|
||||
expect(r.method).toBeNull()
|
||||
expect(r.displayTitle).toBe('Okänd transaktion')
|
||||
})
|
||||
|
||||
it('every classified method is part of the closed vocabulary', () => {
|
||||
const samples = [
|
||||
'X Överföring via internet',
|
||||
'X Kortköp',
|
||||
'X Bg-betalning',
|
||||
'X Plusgiro',
|
||||
'X Swish',
|
||||
'X Autogiro',
|
||||
'X E-faktura',
|
||||
'X Europabetalning',
|
||||
'X Insättning',
|
||||
'X Uttag',
|
||||
'X Lönebetalning',
|
||||
'X Avgift',
|
||||
'X Ränta',
|
||||
]
|
||||
for (const description of samples) {
|
||||
const { method } = classifyTransactionMethod({ description })
|
||||
expect(method).not.toBeNull()
|
||||
expect(TRANSACTION_METHODS).toContain(method)
|
||||
}
|
||||
})
|
||||
|
||||
it('stripping yields a prefix of the original (dedup-bridge invariant)', () => {
|
||||
const cases = [
|
||||
'Vercel Jul Överföring via internet',
|
||||
'TIC BG 0000005786439 Bg-bet. via internet',
|
||||
'UTBETALNING Insättning',
|
||||
'ANTHROPIC* CLAUDE SUB SAN FRANCISCO Kortköp/uttag',
|
||||
]
|
||||
for (const description of cases) {
|
||||
const { displayTitle } = classifyTransactionMethod({ description })
|
||||
expect(description.toLowerCase().startsWith(displayTitle.toLowerCase())).toBe(true)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,66 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { computeJeUnderlagStatus } from '../underlag-status'
|
||||
|
||||
describe('computeJeUnderlagStatus', () => {
|
||||
it('marks entries with a current-version document as has', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[{ id: 'je-1', source_type: 'bank_transaction' }],
|
||||
new Set(['je-1']),
|
||||
new Set(),
|
||||
)
|
||||
expect(result['je-1']).toBe('has')
|
||||
})
|
||||
|
||||
it('marks doc-requiring entries without documents as missing', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[
|
||||
{ id: 'je-1', source_type: 'bank_transaction' },
|
||||
{ id: 'je-2', source_type: 'manual' },
|
||||
{ id: 'je-3', source_type: 'import' },
|
||||
],
|
||||
new Set(),
|
||||
new Set(),
|
||||
)
|
||||
expect(result).toEqual({ 'je-1': 'missing', 'je-2': 'missing', 'je-3': 'missing' })
|
||||
})
|
||||
|
||||
it('respects journal_entry_no_doc_required exemptions', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[{ id: 'je-1', source_type: 'manual' }],
|
||||
new Set(),
|
||||
new Set(['je-1']),
|
||||
)
|
||||
expect(result['je-1']).toBe('none')
|
||||
})
|
||||
|
||||
it('never flags system-generated source types (exempt by omission)', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[
|
||||
{ id: 'je-1', source_type: 'vat_settlement' },
|
||||
{ id: 'je-2', source_type: 'invoice_payment' },
|
||||
{ id: 'je-3', source_type: 'year_end' },
|
||||
],
|
||||
new Set(),
|
||||
new Set(),
|
||||
)
|
||||
expect(result).toEqual({ 'je-1': 'none', 'je-2': 'none', 'je-3': 'none' })
|
||||
})
|
||||
|
||||
it('treats null source_type as no statement', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[{ id: 'je-1', source_type: null }],
|
||||
new Set(),
|
||||
new Set(),
|
||||
)
|
||||
expect(result['je-1']).toBe('none')
|
||||
})
|
||||
|
||||
it('has wins over missing when both a doc and a needs-doc source type are present', () => {
|
||||
const result = computeJeUnderlagStatus(
|
||||
[{ id: 'je-1', source_type: 'manual' }],
|
||||
new Set(['je-1']),
|
||||
new Set(['je-1']),
|
||||
)
|
||||
expect(result['je-1']).toBe('has')
|
||||
})
|
||||
})
|
||||
@@ -1,95 +0,0 @@
|
||||
/**
|
||||
* State machine for the bank sync status chip on the transactions page.
|
||||
*
|
||||
* Pure module (no React, no fetch) so the precedence between the states is
|
||||
* unit-testable. Precedence, highest first:
|
||||
*
|
||||
* paused the company has no bank_sync entitlement: the cron skips it,
|
||||
* so nothing below applies until the subscription is back
|
||||
* attention a connection is expired or errored: only BankID fixes it
|
||||
* expiring a live consent ends within CONSENT_WARNING_DAYS: renew in time
|
||||
* stale nothing synced for STALE_THRESHOLD_MS: check the connection
|
||||
* healthy synced recently
|
||||
*
|
||||
* The expiring threshold matches the 7-day consent-expiry email in the sync
|
||||
* cron, so the chip and the mail warn on the same day.
|
||||
*/
|
||||
|
||||
export interface ConnectionRow {
|
||||
id: string
|
||||
status: string | null
|
||||
last_synced_at: string | null
|
||||
consent_expires?: string | null
|
||||
}
|
||||
|
||||
export const STALE_THRESHOLD_MS = 36 * 60 * 60 * 1000
|
||||
export const CONSENT_WARNING_DAYS = 7
|
||||
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
export type ChipState =
|
||||
| { kind: 'none' }
|
||||
| { kind: 'paused' }
|
||||
| { kind: 'attention'; count: number }
|
||||
| { kind: 'expiring'; daysLeft: number; count: number }
|
||||
| { kind: 'stale'; mostRecent: string }
|
||||
| { kind: 'healthy'; mostRecent: string | null }
|
||||
|
||||
/** Whole days until the consent ends, floored at 0; null when unknown. */
|
||||
export function daysUntilConsentExpiry(
|
||||
consentExpires: string | null | undefined,
|
||||
now: number,
|
||||
): number | null {
|
||||
if (!consentExpires) return null
|
||||
const expiresAt = new Date(consentExpires).getTime()
|
||||
if (!Number.isFinite(expiresAt)) return null
|
||||
return Math.max(0, Math.ceil((expiresAt - now) / DAY_MS))
|
||||
}
|
||||
|
||||
export interface ChipStateOptions {
|
||||
/** Clock override for tests; defaults to Date.now() at call time. */
|
||||
now?: number
|
||||
/**
|
||||
* Whether the company holds the bank_sync capability. Without it the daily
|
||||
* cron skips every connection, so rows keep status=active with a frozen
|
||||
* last_synced_at and would otherwise read as a mysterious "stale".
|
||||
*/
|
||||
hasBankSync?: boolean
|
||||
}
|
||||
|
||||
export function getChipState(
|
||||
rows: ConnectionRow[],
|
||||
{ now = Date.now(), hasBankSync = true }: ChipStateOptions = {},
|
||||
): ChipState {
|
||||
if (rows.length === 0) return { kind: 'none' }
|
||||
if (!hasBankSync) return { kind: 'paused' }
|
||||
|
||||
const needsAttention = rows.filter(
|
||||
(r) => r.status === 'expired' || r.status === 'error',
|
||||
)
|
||||
if (needsAttention.length > 0) {
|
||||
return { kind: 'attention', count: needsAttention.length }
|
||||
}
|
||||
|
||||
// Only live connections can be "about to expire": a pending row has no
|
||||
// consent yet, and expired ones were caught above.
|
||||
const expiring = rows
|
||||
.filter((r) => r.status === 'active')
|
||||
.map((r) => daysUntilConsentExpiry(r.consent_expires, now))
|
||||
.filter((d): d is number => d !== null && d <= CONSENT_WARNING_DAYS)
|
||||
if (expiring.length > 0) {
|
||||
return { kind: 'expiring', daysLeft: Math.min(...expiring), count: expiring.length }
|
||||
}
|
||||
|
||||
const mostRecent = rows
|
||||
.map((r) => r.last_synced_at)
|
||||
.filter((s): s is string => Boolean(s))
|
||||
.sort()
|
||||
.pop()
|
||||
|
||||
if (mostRecent && now - new Date(mostRecent).getTime() > STALE_THRESHOLD_MS) {
|
||||
return { kind: 'stale', mostRecent }
|
||||
}
|
||||
|
||||
return { kind: 'healthy', mostRecent: mostRecent ?? null }
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
/**
|
||||
* Cross-component signal that a bank sync (or reconnect) just changed
|
||||
* `bank_connections` rows or imported new transactions.
|
||||
*
|
||||
* Several surfaces render bank-sync status from a client-side fetch on mount
|
||||
* (the transactions-page status chip, the "since last visit" pill, the banking
|
||||
* settings panel). Without a shared signal they show stale data until a hard
|
||||
* reload: e.g. a manual "Sync now" pulls fresh rows but the neighbouring chip
|
||||
* keeps showing the old "synced 2d ago" until the page is reloaded.
|
||||
*
|
||||
* Sync entry points call `notifyBankSyncUpdated()` on success; status surfaces
|
||||
* subscribe with `onBankSyncUpdated()` and refetch. This is a browser-only
|
||||
* CustomEvent, so it is a no-op during SSR.
|
||||
*/
|
||||
export const BANK_SYNC_UPDATED_EVENT = 'gnubok:bank-sync-updated'
|
||||
|
||||
export function notifyBankSyncUpdated(): void {
|
||||
if (typeof window === 'undefined') return
|
||||
window.dispatchEvent(new Event(BANK_SYNC_UPDATED_EVENT))
|
||||
}
|
||||
|
||||
export function onBankSyncUpdated(handler: () => void): () => void {
|
||||
if (typeof window === 'undefined') return () => {}
|
||||
window.addEventListener(BANK_SYNC_UPDATED_EVENT, handler)
|
||||
return () => window.removeEventListener(BANK_SYNC_UPDATED_EVENT, handler)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user