* fix(booking-templates): scope template list to the active company GET /api/settings/booking-templates relied solely on the btl_select RLS policy, which is membership-wide (user_company_ids) and returns templates from every company the user belongs to. A user who owns multiple companies saw all their templates merged regardless of which company was active. Narrow the list in the API layer (mirroring counterparty-templates) to system + the active company + the active company's team. RLS stays the security backstop; this fixes the cross-company merge within a single user's own view (it was never a cross-tenant data leak). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * fix(import): show proper message for duplicate bank file upload The bank file import page mis-parsed the structured error envelope ({ error: { code, message, details } }), so a BANK_FILE_DUPLICATE (409) fell through to the generic "Kunde inte läsa filen" fallback. The upload step also hardcoded that same string as the error heading, so duplicates were doubly misreported as parse failures. - Parse the structured envelope by error.code; surface error.message for all codes instead of rendering the error object. - Add a dedicated BANK_FILE_DUPLICATE message using the importedAt / importedCount details the route already returns. - Add an optional errorTitle prop to BankFileUploadStep (defaults to the previous text) and pass "Filen är redan importerad" for dupes. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> * feat(tests): add comprehensive tests for recordateEntry, inbox-linking, and external-id handling - Implemented unit tests for recordateEntry in the bookkeeping module to validate various scenarios including date changes, non-posted entries, and fiscal period restrictions. - Created tests for inbox-linking status in pending operations to ensure correct handling of invoice inbox items and supplier invoices, addressing historical bugs related to status updates. - Added tests for external-id utilities to ensure consistent handling of monetary amounts and deduplication keys across different transaction sources. - Introduced new functions in external-id.ts for stable external ID generation and normalization of imported descriptions, enhancing transaction deduplication reliability. feat(migrations): add new database migrations for transaction handling - Created migration to exclude storno and correction vouchers from unmatched GL lines, ensuring accurate reconciliation. - Added a migration to preserve original bank transaction descriptions in a new immutable column, allowing for user edits while maintaining audit trails and deduplication integrity. * feat(migrations): add function to exclude storno/correction vouchers from unmatched GL lines * feat(transactions): enhance transaction handling with improved description normalization and preloaded original entries --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
297 lines
10 KiB
TypeScript
297 lines
10 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
|
|
|
// Mock jwt module before importing api-client
|
|
const mockGenerateJWT = vi.fn().mockReturnValue('test-jwt-token')
|
|
vi.mock('../jwt', () => ({
|
|
generateJWT: (...args: unknown[]) => mockGenerateJWT(...args),
|
|
getAuthorizationHeader: () => `Bearer ${mockGenerateJWT()}`,
|
|
_resetTokenCache: vi.fn(),
|
|
}))
|
|
|
|
// Mock environment
|
|
vi.stubEnv('ENABLE_BANKING_API_URL', 'https://api.test.com')
|
|
|
|
import {
|
|
getASPSPs,
|
|
getAccountBalances,
|
|
getAccountTransactions,
|
|
getAllTransactions,
|
|
getAllTransactionsWithRaw,
|
|
convertTransaction,
|
|
type Transaction,
|
|
} from '../api-client'
|
|
|
|
describe('api-client', () => {
|
|
let fetchSpy: ReturnType<typeof vi.spyOn>
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
fetchSpy = vi.spyOn(globalThis, 'fetch')
|
|
})
|
|
|
|
afterEach(() => {
|
|
fetchSpy.mockRestore()
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Timeout
|
|
// -------------------------------------------------------------------------
|
|
describe('timeout', () => {
|
|
it('aborts fetch after timeout', async () => {
|
|
fetchSpy.mockImplementation(
|
|
() => new Promise((_, reject) => {
|
|
// Simulate a hanging request — the AbortController will fire
|
|
setTimeout(() => reject(new DOMException('Aborted', 'AbortError')), 100)
|
|
})
|
|
)
|
|
|
|
await expect(getAccountBalances('acc-1')).rejects.toThrow('Aborted')
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Retry
|
|
// -------------------------------------------------------------------------
|
|
describe('retry', () => {
|
|
it('retries on 503 and succeeds', async () => {
|
|
const failResponse = new Response('Service Unavailable', { status: 503 })
|
|
const successResponse = new Response(JSON.stringify({ balances: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(failResponse)
|
|
.mockResolvedValueOnce(failResponse)
|
|
.mockResolvedValueOnce(successResponse)
|
|
|
|
const result = await getAccountBalances('acc-1')
|
|
expect(result).toEqual([])
|
|
expect(fetchSpy).toHaveBeenCalledTimes(3)
|
|
})
|
|
|
|
it('retries on AbortError (timeout) and succeeds', async () => {
|
|
const abortError = new DOMException('Aborted', 'AbortError')
|
|
const successResponse = new Response(JSON.stringify({ aspsps: [{ name: 'TestBank', country: 'SE' }] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
|
|
fetchSpy
|
|
.mockRejectedValueOnce(abortError)
|
|
.mockResolvedValueOnce(successResponse)
|
|
|
|
const result = await getASPSPs('SE')
|
|
expect(result).toEqual([{ name: 'TestBank', country: 'SE' }])
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
})
|
|
|
|
it('does not retry on 400 errors', async () => {
|
|
const badRequest = new Response('Bad Request', { status: 400 })
|
|
fetchSpy.mockResolvedValueOnce(badRequest)
|
|
|
|
// getAccountTransactions throws on non-ok response
|
|
await expect(getAccountTransactions('acc-1')).rejects.toThrow('Failed to get transactions')
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// Pagination cap
|
|
// -------------------------------------------------------------------------
|
|
describe('pagination cap', () => {
|
|
it('stops at MAX_PAGINATION_PAGES', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
// Every response returns a continuation_key
|
|
fetchSpy.mockImplementation(() => {
|
|
return Promise.resolve(
|
|
new Response(
|
|
JSON.stringify({
|
|
transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }],
|
|
continuation_key: 'keep-going',
|
|
}),
|
|
{ status: 200, headers: { 'Content-Type': 'application/json' } }
|
|
)
|
|
)
|
|
})
|
|
|
|
const result = await getAllTransactions('acc-1', '2024-01-01', '2024-12-31')
|
|
|
|
// Should have exactly 100 transactions (1 per page, 100 pages)
|
|
expect(result).toHaveLength(100)
|
|
expect(fetchSpy).toHaveBeenCalledTimes(100)
|
|
expect(warnSpy).toHaveBeenCalledWith(
|
|
expect.stringContaining('Pagination cap reached')
|
|
)
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// getAllTransactionsWithRaw
|
|
// -------------------------------------------------------------------------
|
|
describe('getAllTransactionsWithRaw', () => {
|
|
it('returns both transactions and raw pages', async () => {
|
|
const page1 = {
|
|
transactions: [{ transaction_amount: { amount: '100', currency: 'SEK' } }],
|
|
continuation_key: 'page2',
|
|
}
|
|
const page2 = {
|
|
transactions: [{ transaction_amount: { amount: '200', currency: 'SEK' } }],
|
|
}
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify(page1), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
|
)
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify(page2), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
|
)
|
|
|
|
const result = await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31')
|
|
|
|
expect(result.transactions).toHaveLength(2)
|
|
expect(result.rawPages).toHaveLength(2)
|
|
expect(JSON.parse(result.rawPages[0])).toEqual(page1)
|
|
expect(JSON.parse(result.rawPages[1])).toEqual(page2)
|
|
})
|
|
|
|
it('appends strategy=longest to the request URL when supplied', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
|
|
await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31', 'longest')
|
|
|
|
expect(fetchSpy).toHaveBeenCalledTimes(1)
|
|
const requestedUrl = fetchSpy.mock.calls[0][0] as string
|
|
expect(requestedUrl).toContain('strategy=longest')
|
|
expect(requestedUrl).toContain('date_from=2024-01-01')
|
|
expect(requestedUrl).toContain('date_to=2024-12-31')
|
|
})
|
|
|
|
it('omits the strategy param when not supplied', async () => {
|
|
fetchSpy.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
|
|
await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31')
|
|
|
|
const requestedUrl = fetchSpy.mock.calls[0][0] as string
|
|
expect(requestedUrl).not.toContain('strategy=')
|
|
})
|
|
|
|
it('falls back to no-strategy on 400 and retries the same page', async () => {
|
|
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
|
|
fetchSpy
|
|
.mockResolvedValueOnce(
|
|
new Response('Invalid strategy', { status: 400 })
|
|
)
|
|
.mockResolvedValueOnce(
|
|
new Response(JSON.stringify({ transactions: [{ transaction_amount: { amount: '50', currency: 'SEK' } }] }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
})
|
|
)
|
|
|
|
const result = await getAllTransactionsWithRaw('acc-1', '2024-01-01', '2024-12-31', 'longest')
|
|
|
|
expect(result.transactions).toHaveLength(1)
|
|
expect(fetchSpy).toHaveBeenCalledTimes(2)
|
|
|
|
const firstUrl = fetchSpy.mock.calls[0][0] as string
|
|
const secondUrl = fetchSpy.mock.calls[1][0] as string
|
|
expect(firstUrl).toContain('strategy=longest')
|
|
expect(secondUrl).not.toContain('strategy=')
|
|
|
|
expect(warnSpy).toHaveBeenCalledWith(
|
|
'[enable-banking] strategy rejected by API, retrying without strategy',
|
|
expect.objectContaining({ strategy: 'longest' })
|
|
)
|
|
|
|
warnSpy.mockRestore()
|
|
})
|
|
})
|
|
})
|
|
|
|
// -------------------------------------------------------------------------
|
|
// JWT cache tests
|
|
// -------------------------------------------------------------------------
|
|
describe('JWT cache', () => {
|
|
it('reuses cached token within validity window', async () => {
|
|
// Reset mocks and re-import to test cache behavior
|
|
vi.resetModules()
|
|
const jwtCallCount = { count: 0 }
|
|
|
|
vi.doMock('../jwt', () => ({
|
|
generateJWT: () => {
|
|
jwtCallCount.count++
|
|
return 'cached-token'
|
|
},
|
|
getAuthorizationHeader: () => {
|
|
// Simulate cached behavior: first call generates, subsequent calls reuse
|
|
jwtCallCount.count++
|
|
return `Bearer cached-token`
|
|
},
|
|
_resetTokenCache: vi.fn(),
|
|
}))
|
|
|
|
// The actual cache test is in jwt.ts — we verify the cache function exists
|
|
const jwt = await import('../jwt')
|
|
expect(typeof jwt._resetTokenCache).toBe('function')
|
|
})
|
|
})
|
|
|
|
describe('convertTransaction', () => {
|
|
function makeTx(overrides: Partial<Transaction> = {}): Transaction {
|
|
return {
|
|
transaction_amount: { amount: '250.00', currency: 'SEK' },
|
|
credit_debit_indicator: 'DBIT',
|
|
booking_date: '2024-06-15',
|
|
...overrides,
|
|
}
|
|
}
|
|
|
|
it('uses remittance_information when present', () => {
|
|
const tx = makeTx({ remittance_information: ['Faktura 123', ' '] })
|
|
expect(convertTransaction(tx, 'SEK').description).toBe('Faktura 123')
|
|
})
|
|
|
|
it('falls back to the counterparty name when remittance is empty', () => {
|
|
const out = makeTx({ remittance_information: [' '], creditor_name: 'Telia AB' })
|
|
expect(convertTransaction(out, 'SEK').description).toBe('Telia AB')
|
|
})
|
|
|
|
it('derives a Swedish label from bank_transaction_code when remittance and counterparty are both absent', () => {
|
|
const tx = makeTx({ bank_transaction_code: 'PMNT-CCRD-POSD', merchant_category_code: '5411' })
|
|
// MCC 5411 wins (most specific).
|
|
expect(convertTransaction(tx, 'SEK').description).toBe('Inköp dagligvaror')
|
|
})
|
|
|
|
it('uses the ISO family label when only bank_transaction_code is present', () => {
|
|
const tx = makeTx({ bank_transaction_code: 'PMNT/CCRD' })
|
|
expect(convertTransaction(tx, 'SEK').description).toBe('Kortköp')
|
|
})
|
|
|
|
it('falls back to the Swedish neutral (never English "Unknown") when nothing is recognized', () => {
|
|
const tx = makeTx({})
|
|
expect(convertTransaction(tx, 'SEK').description).toBe('Okänd transaktion')
|
|
})
|
|
|
|
it('carries the ISO codes through onto the converted transaction', () => {
|
|
const tx = makeTx({ bank_transaction_code: 'PMNT/RCDT', proprietary_bank_transaction_code: 'XB' })
|
|
const out = convertTransaction(tx, 'SEK')
|
|
expect(out.bank_transaction_code).toBe('PMNT/RCDT')
|
|
expect(out.proprietary_bank_transaction_code).toBe('XB')
|
|
})
|
|
})
|