fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* matchBankByName: the deep-link resolver behind /import?mode=psd2&bank=<name>.
|
||||
* Conservative on purpose: starting a consent at the wrong institution is
|
||||
* worse than falling back to the prefilled picker.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { matchBankByName } from '../lib/bank-match'
|
||||
|
||||
const BANKS = [
|
||||
{ name: 'Swedbank' },
|
||||
{ name: 'SEB' },
|
||||
{ name: 'Nordea' },
|
||||
{ name: 'Handelsbanken' },
|
||||
{ name: 'Danske Bank' },
|
||||
{ name: 'Länsförsäkringar Bank' },
|
||||
{ name: 'Länsförsäkringar Skåne' },
|
||||
{ name: 'ICA Banken' },
|
||||
]
|
||||
|
||||
describe('matchBankByName', () => {
|
||||
it('matches exact names case-insensitively', () => {
|
||||
expect(matchBankByName(BANKS, 'swedbank')?.name).toBe('Swedbank')
|
||||
expect(matchBankByName(BANKS, 'SEB')?.name).toBe('SEB')
|
||||
expect(matchBankByName(BANKS, ' handelsbanken ')?.name).toBe('Handelsbanken')
|
||||
})
|
||||
|
||||
it('matches a unique prefix', () => {
|
||||
expect(matchBankByName(BANKS, 'nord')?.name).toBe('Nordea')
|
||||
expect(matchBankByName(BANKS, 'danske')?.name).toBe('Danske Bank')
|
||||
})
|
||||
|
||||
it('matches a unique substring', () => {
|
||||
expect(matchBankByName(BANKS, 'ica')?.name).toBe('ICA Banken')
|
||||
})
|
||||
|
||||
it('returns null for an ambiguous name instead of guessing an institution', () => {
|
||||
expect(matchBankByName(BANKS, 'länsförsäkringar')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for unknown or empty input', () => {
|
||||
expect(matchBankByName(BANKS, 'Monopolbanken')).toBeNull()
|
||||
expect(matchBankByName(BANKS, '')).toBeNull()
|
||||
expect(matchBankByName(BANKS, ' ')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// Force the gate to run (no dev bypass) but stub requireCapability so we control
|
||||
// entitlement per test. Mirrors the skatteverket capability-gate suite.
|
||||
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
|
||||
return { ...actual, requireCapability: vi.fn() }
|
||||
})
|
||||
|
||||
import { enableBankingExtension } from '../index'
|
||||
import { requireCapability, capabilityBlockedResponse } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
|
||||
// The interactive bank-sync entry points gated on CAPABILITY.bank_sync.
|
||||
const GATED: Array<{ method: string; path: string }> = [
|
||||
{ method: 'POST', path: '/connect' },
|
||||
{ method: 'POST', path: '/sync' },
|
||||
]
|
||||
|
||||
function makeContext(): ExtensionContext {
|
||||
return {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'enable-banking',
|
||||
requestId: 'req_test',
|
||||
supabase: {
|
||||
auth: {
|
||||
getUser: vi
|
||||
.fn()
|
||||
.mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null }),
|
||||
},
|
||||
from: vi.fn(),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
emit: vi.fn().mockResolvedValue(undefined),
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), child: vi.fn() },
|
||||
settings: {
|
||||
get: vi.fn().mockResolvedValue(null),
|
||||
set: vi.fn().mockResolvedValue(undefined),
|
||||
clear: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
}
|
||||
|
||||
describe('enable-banking paywall gate', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it.each(GATED)(
|
||||
'$method $path returns 403 capability_blocked when not entitled',
|
||||
async ({ method, path }) => {
|
||||
vi.mocked(requireCapability).mockResolvedValue(
|
||||
capabilityBlockedResponse(CAPABILITY.bank_sync),
|
||||
)
|
||||
const route = enableBankingExtension.apiRoutes?.find(
|
||||
(r) => r.method === method && r.path === path,
|
||||
)
|
||||
expect(route, `${method} ${path} must be registered`).toBeDefined()
|
||||
|
||||
const request = new Request(
|
||||
`https://test.local/api/extensions/ext/enable-banking${path}`,
|
||||
{
|
||||
method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
},
|
||||
)
|
||||
const response = await route!.handler(request, makeContext())
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
const body = (await response.json()) as {
|
||||
capability_blocked?: boolean
|
||||
capability?: string
|
||||
}
|
||||
expect(body.capability_blocked).toBe(true)
|
||||
expect(body.capability).toBe(CAPABILITY.bank_sync)
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,499 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// Entitlement gate passes in these tests; the gate itself is covered by
|
||||
// capability-gate.test.ts.
|
||||
vi.mock('@/lib/entitlements/has-capability', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/entitlements/has-capability')>()
|
||||
return { ...actual, requireCapability: vi.fn() }
|
||||
})
|
||||
|
||||
const { mockStartAuthorization, mockGetPreferredAuthMethod } = vi.hoisted(() => ({
|
||||
mockStartAuthorization: vi.fn(),
|
||||
mockGetPreferredAuthMethod: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../lib/api-client', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../lib/api-client')>()
|
||||
return {
|
||||
...actual,
|
||||
startAuthorization: (...args: unknown[]) => mockStartAuthorization(...args),
|
||||
// index.ts resolves the pinned auth method (with metadata for logging)
|
||||
// through the details variant; both point at one mock for simplicity.
|
||||
getPreferredAuthMethod: (...args: unknown[]) => mockGetPreferredAuthMethod(...args),
|
||||
getPreferredAuthMethodDetails: (...args: unknown[]) => mockGetPreferredAuthMethod(...args),
|
||||
}
|
||||
})
|
||||
|
||||
// The connect handler records the initiating origin through the brands-table
|
||||
// resolver; no brand host is registered in these tests.
|
||||
vi.mock('@/lib/branding/resolve', () => ({
|
||||
resolveBrandResultByHost: vi.fn(async () => ({ brand: null, lookupFailed: false })),
|
||||
}))
|
||||
|
||||
import { enableBankingExtension } from '../index'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
|
||||
interface RecordedCall {
|
||||
method: string
|
||||
args: unknown[]
|
||||
}
|
||||
|
||||
interface RecordedChain {
|
||||
_calls: RecordedCall[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
function makeChain(result: { data?: unknown; error?: unknown }): RecordedChain {
|
||||
const calls: RecordedCall[] = []
|
||||
const chain: Record<string, unknown> = { _calls: calls }
|
||||
for (const m of ['select', 'eq', 'neq', 'in', 'is', 'order', 'limit', 'update', 'delete', 'insert']) {
|
||||
chain[m] = vi.fn((...args: unknown[]) => {
|
||||
calls.push({ method: m, args })
|
||||
return chain
|
||||
})
|
||||
}
|
||||
chain.maybeSingle = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
|
||||
chain.single = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
|
||||
chain.then = (resolve: (v: unknown) => void) => resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||
return chain as RecordedChain
|
||||
}
|
||||
|
||||
function makeContext(fromImpl: (table: string) => unknown): ExtensionContext {
|
||||
return {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'enable-banking',
|
||||
requestId: 'req_test',
|
||||
supabase: {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null }),
|
||||
},
|
||||
from: vi.fn(fromImpl),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any,
|
||||
emit: vi.fn().mockResolvedValue(undefined),
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn(), child: vi.fn() },
|
||||
settings: {
|
||||
get: vi.fn().mockResolvedValue(null),
|
||||
set: vi.fn().mockResolvedValue(undefined),
|
||||
clear: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any
|
||||
}
|
||||
|
||||
function connectRoute() {
|
||||
const route = enableBankingExtension.apiRoutes?.find(
|
||||
(r) => r.method === 'POST' && r.path === '/connect',
|
||||
)
|
||||
expect(route, 'POST /connect must be registered').toBeDefined()
|
||||
return route!
|
||||
}
|
||||
|
||||
function makeConnectRequest() {
|
||||
return new Request('https://test.local/api/extensions/ext/enable-banking/connect', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ aspsp_name: 'Nordea', aspsp_country: 'SE', psu_type: 'business' }),
|
||||
})
|
||||
}
|
||||
|
||||
describe('POST /connect never-activated row cleanup', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(requireCapability).mockResolvedValue(null)
|
||||
mockGetPreferredAuthMethod.mockResolvedValue(undefined)
|
||||
mockStartAuthorization.mockResolvedValue({
|
||||
url: 'https://bank.example/auth',
|
||||
authorization_id: 'auth-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('deletes stale pending and error zombies instead of parking them in error', async () => {
|
||||
const chains: RecordedChain[] = []
|
||||
let call = 0
|
||||
const ctx = makeContext(() => {
|
||||
call++
|
||||
let chain: RecordedChain
|
||||
if (call === 1) {
|
||||
// Latest pending row is stale (45s > 30s threshold): not a live attempt.
|
||||
chain = makeChain({
|
||||
data: { id: 'stale-1', created_at: new Date(Date.now() - 45_000).toISOString() },
|
||||
})
|
||||
} else if (call === 2) {
|
||||
// The sweep: returns the deleted never-activated rows.
|
||||
chain = makeChain({ data: [{ id: 'stale-1' }, { id: 'old-error' }] })
|
||||
} else if (call === 3) {
|
||||
// Existing-connection guard: nothing established remains post-sweep.
|
||||
chain = makeChain({ data: null })
|
||||
} else {
|
||||
// Insert of the fresh connection row.
|
||||
chain = makeChain({ data: { id: 'new-conn' } })
|
||||
}
|
||||
chains.push(chain)
|
||||
return chain
|
||||
})
|
||||
|
||||
const response = await connectRoute().handler(makeConnectRequest(), ctx)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const body = (await response.json()) as { connection_id: string; authorization_url: string }
|
||||
expect(body.connection_id).toBe('new-conn')
|
||||
expect(body.authorization_url).toBe('https://bank.example/auth')
|
||||
|
||||
// The sweep DELETEs never-activated rows: stale pendings and error rows
|
||||
// from failed attempts, guarded so established connections (session_id or
|
||||
// accounts_data present) are untouched.
|
||||
const sweep = chains[1]
|
||||
const methods = sweep._calls.map((c) => c.method)
|
||||
expect(methods).toContain('delete')
|
||||
const inCall = sweep._calls.find((c) => c.method === 'in')
|
||||
expect(inCall?.args).toEqual(['status', ['pending', 'error']])
|
||||
const isCalls = sweep._calls.filter((c) => c.method === 'is')
|
||||
expect(isCalls.map((c) => c.args)).toEqual(
|
||||
expect.arrayContaining([
|
||||
['session_id', null],
|
||||
['accounts_data', null],
|
||||
]),
|
||||
)
|
||||
|
||||
// Nothing gets parked as status='error' anymore: no update on any chain.
|
||||
for (const chain of chains) {
|
||||
expect(chain._calls.some((c) => c.method === 'update')).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('still rejects a duplicate connect while a recent pending attempt is live', async () => {
|
||||
const chains: RecordedChain[] = []
|
||||
const ctx = makeContext(() => {
|
||||
// Latest pending row is 5s old: the user is mid-redirect at the bank.
|
||||
const chain = makeChain({
|
||||
data: { id: 'live-1', created_at: new Date(Date.now() - 5_000).toISOString() },
|
||||
})
|
||||
chains.push(chain)
|
||||
return chain
|
||||
})
|
||||
|
||||
const response = await connectRoute().handler(makeConnectRequest(), ctx)
|
||||
|
||||
expect(response.status).toBe(409)
|
||||
// No sweep while an attempt is live: the live pending row must survive.
|
||||
for (const chain of chains) {
|
||||
expect(chain._calls.some((c) => c.method === 'delete')).toBe(false)
|
||||
}
|
||||
expect(mockStartAuthorization).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('sweeps error zombies even when no pending row exists', async () => {
|
||||
const chains: RecordedChain[] = []
|
||||
let call = 0
|
||||
const ctx = makeContext(() => {
|
||||
call++
|
||||
let chain: RecordedChain
|
||||
if (call === 1) {
|
||||
chain = makeChain({ data: null })
|
||||
} else if (call === 2) {
|
||||
chain = makeChain({ data: [{ id: 'old-error' }] })
|
||||
} else if (call === 3) {
|
||||
// Existing-connection guard: the swept zombie is gone, nothing remains.
|
||||
chain = makeChain({ data: null })
|
||||
} else {
|
||||
chain = makeChain({ data: { id: 'new-conn' } })
|
||||
}
|
||||
chains.push(chain)
|
||||
return chain
|
||||
})
|
||||
|
||||
const response = await connectRoute().handler(makeConnectRequest(), ctx)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const sweep = chains[1]
|
||||
expect(sweep._calls.some((c) => c.method === 'delete')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /connect auth-method pinning wired into startAuthorization', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(requireCapability).mockResolvedValue(null)
|
||||
mockStartAuthorization.mockResolvedValue({
|
||||
url: 'https://bank.example/auth',
|
||||
authorization_id: 'auth-1',
|
||||
})
|
||||
})
|
||||
|
||||
// Fresh-connect from() sequence: recent-pending check, zombie sweep,
|
||||
// existing-connection guard, insert. Explicit psu_type in the body skips
|
||||
// the companies entity_type lookup.
|
||||
function makeFreshConnectContext() {
|
||||
let call = 0
|
||||
return makeContext(() => {
|
||||
call++
|
||||
if (call === 1) return makeChain({ data: null })
|
||||
if (call === 2) return makeChain({ data: [] })
|
||||
if (call === 3) return makeChain({ data: null })
|
||||
return makeChain({ data: { id: 'new-conn' } })
|
||||
})
|
||||
}
|
||||
|
||||
function makeHandelsbankenRequest() {
|
||||
return new Request('https://test.local/api/extensions/ext/enable-banking/connect', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ aspsp_name: 'Handelsbanken', aspsp_country: 'SE', psu_type: 'business' }),
|
||||
})
|
||||
}
|
||||
|
||||
it('forwards the pinned method name into the auth_method argument (Handelsbanken corporate regression)', async () => {
|
||||
// The documented real Handelsbanken shape: Mobile BankID is a hidden
|
||||
// DECOUPLED method carrying NO psu_types restriction.
|
||||
mockGetPreferredAuthMethod.mockResolvedValue({
|
||||
name: 'BANKID',
|
||||
approach: 'DECOUPLED',
|
||||
hidden_method: true,
|
||||
title: 'Bank ID',
|
||||
})
|
||||
|
||||
const ctx = makeFreshConnectContext()
|
||||
const response = await connectRoute().handler(makeHandelsbankenRequest(), ctx)
|
||||
expect(response.status).toBe(200)
|
||||
|
||||
expect(mockGetPreferredAuthMethod).toHaveBeenCalledWith('Handelsbanken', 'SE', 'business')
|
||||
|
||||
// startAuthorization(aspspName, aspspCountry, redirectUrl, state, psuType,
|
||||
// authMethod): the pinned method's NAME must land in the auth_method
|
||||
// position (index 5). This binds selection to the outgoing request: the
|
||||
// selection tests alone cannot catch a route that resolves 'BANKID' and
|
||||
// then starts a default REDIRECT authorization anyway.
|
||||
expect(mockStartAuthorization).toHaveBeenCalledTimes(1)
|
||||
const args = mockStartAuthorization.mock.calls[0]
|
||||
expect(args[0]).toBe('Handelsbanken')
|
||||
expect(args[1]).toBe('SE')
|
||||
expect(args[4]).toBe('business')
|
||||
expect(args[5]).toBe('BANKID')
|
||||
|
||||
// A pinned method without psu_types applies to all PSU types: the log must
|
||||
// say '(all)', never '(aspsp default)', which would contradict
|
||||
// auth_method='BANKID' on the same line.
|
||||
expect(ctx.log.info).toHaveBeenCalledWith(
|
||||
'[enable-banking] Starting bank connection',
|
||||
expect.objectContaining({
|
||||
auth_method: 'BANKID',
|
||||
auth_method_psu_types: '(all)',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('passes undefined auth_method when no method is pinned (ASPSP default flow)', async () => {
|
||||
mockGetPreferredAuthMethod.mockResolvedValue(undefined)
|
||||
|
||||
const ctx = makeFreshConnectContext()
|
||||
const response = await connectRoute().handler(makeHandelsbankenRequest(), ctx)
|
||||
expect(response.status).toBe(200)
|
||||
|
||||
expect(mockStartAuthorization).toHaveBeenCalledTimes(1)
|
||||
const args = mockStartAuthorization.mock.calls[0]
|
||||
expect(args[5]).toBeUndefined()
|
||||
|
||||
// Only the unpinned case logs the '(aspsp default)' sentinel.
|
||||
expect(ctx.log.info).toHaveBeenCalledWith(
|
||||
'[enable-banking] Starting bank connection',
|
||||
expect.objectContaining({
|
||||
auth_method: '(aspsp default)',
|
||||
auth_method_psu_types: '(aspsp default)',
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('forwards the pinned method name on the reconnect path too', async () => {
|
||||
mockGetPreferredAuthMethod.mockResolvedValue({
|
||||
name: 'BANKID',
|
||||
approach: 'DECOUPLED',
|
||||
hidden_method: true,
|
||||
title: 'Bank ID',
|
||||
})
|
||||
|
||||
let call = 0
|
||||
const ctx = makeContext(() => {
|
||||
call++
|
||||
if (call === 1) {
|
||||
// The existing connection loaded up front: reconnect derives the bank
|
||||
// identity and psu_type from this row. session_id null skips the
|
||||
// sibling check + revoke.
|
||||
return makeChain({
|
||||
data: {
|
||||
id: 'conn-1',
|
||||
bank_name: 'Handelsbanken',
|
||||
provider: 'handelsbanken-se',
|
||||
session_id: null,
|
||||
psu_type: 'business',
|
||||
},
|
||||
})
|
||||
}
|
||||
// CSRF-state staging update and the authorization_id follow-up write.
|
||||
return makeChain({ data: null })
|
||||
})
|
||||
|
||||
const req = new Request('https://test.local/api/extensions/ext/enable-banking/connect', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ connection_id: 'conn-1' }),
|
||||
})
|
||||
|
||||
const response = await connectRoute().handler(req, ctx)
|
||||
expect(response.status).toBe(200)
|
||||
|
||||
// The reconnect branch calls startAuthorization from its own call site:
|
||||
// the pinned name must reach the auth_method position there as well.
|
||||
expect(mockStartAuthorization).toHaveBeenCalledTimes(1)
|
||||
const args = mockStartAuthorization.mock.calls[0]
|
||||
expect(args[0]).toBe('Handelsbanken')
|
||||
expect(args[1]).toBe('SE')
|
||||
expect(args[4]).toBe('business')
|
||||
expect(args[5]).toBe('BANKID')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /connect existing-connection guard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.mocked(requireCapability).mockResolvedValue(null)
|
||||
mockGetPreferredAuthMethod.mockResolvedValue(undefined)
|
||||
mockStartAuthorization.mockResolvedValue({
|
||||
url: 'https://bank.example/auth',
|
||||
authorization_id: 'auth-1',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns 409 EXISTING_CONNECTION when a dead (expired) row for the same bank exists', async () => {
|
||||
const chains: RecordedChain[] = []
|
||||
let call = 0
|
||||
const ctx = makeContext(() => {
|
||||
call++
|
||||
let chain: RecordedChain
|
||||
if (call === 1) {
|
||||
// No live pending attempt.
|
||||
chain = makeChain({ data: null })
|
||||
} else if (call === 2) {
|
||||
// Sweep finds nothing to delete.
|
||||
chain = makeChain({ data: [] })
|
||||
} else {
|
||||
// Guard: an established expired row for this bank survives the sweep.
|
||||
chain = makeChain({ data: { id: 'existing-1', status: 'expired' } })
|
||||
}
|
||||
chains.push(chain)
|
||||
return chain
|
||||
})
|
||||
|
||||
const response = await connectRoute().handler(makeConnectRequest(), ctx)
|
||||
|
||||
expect(response.status).toBe(409)
|
||||
const body = (await response.json()) as {
|
||||
code: string
|
||||
existing_connection_id: string
|
||||
error: string
|
||||
}
|
||||
expect(body.code).toBe('EXISTING_CONNECTION')
|
||||
expect(body.existing_connection_id).toBe('existing-1')
|
||||
// The message names the bank and points at Förnya samtycke.
|
||||
expect(body.error).toContain('Nordea')
|
||||
expect(body.error).toContain('behöver förnyas')
|
||||
expect(body.error).toContain('Förnya samtycke')
|
||||
// The bank flow is never started and no duplicate row is inserted.
|
||||
expect(mockStartAuthorization).not.toHaveBeenCalled()
|
||||
for (const chain of chains) {
|
||||
expect(chain._calls.some((c) => c.method === 'insert')).toBe(false)
|
||||
}
|
||||
// The guard only matches DEAD-BUT-ESTABLISHED rows: an active row (a
|
||||
// legitimate second login at the same bank) and revoked rows never 409.
|
||||
const guard = chains[2]
|
||||
const inCall = guard._calls.find((c) => c.method === 'in')
|
||||
expect(inCall?.args).toEqual(['status', ['expired', 'error', 'pending_selection']])
|
||||
})
|
||||
|
||||
it('never 409s over an ACTIVE same-bank connection: the guard status filter excludes it', async () => {
|
||||
const chains: RecordedChain[] = []
|
||||
let call = 0
|
||||
const ctx = makeContext(() => {
|
||||
call++
|
||||
let chain: RecordedChain
|
||||
if (call === 1) {
|
||||
chain = makeChain({ data: null })
|
||||
} else if (call === 2) {
|
||||
chain = makeChain({ data: [] })
|
||||
} else if (call === 3) {
|
||||
// Guard: only an ACTIVE row exists for this bank; the dead-status
|
||||
// filter matches nothing, so the query returns null.
|
||||
chain = makeChain({ data: null })
|
||||
} else {
|
||||
chain = makeChain({ data: { id: 'second-login' } })
|
||||
}
|
||||
chains.push(chain)
|
||||
return chain
|
||||
})
|
||||
|
||||
const response = await connectRoute().handler(makeConnectRequest(), ctx)
|
||||
|
||||
// The second legitimate login at the same bank goes through.
|
||||
expect(response.status).toBe(200)
|
||||
const body = (await response.json()) as { connection_id: string }
|
||||
expect(body.connection_id).toBe('second-login')
|
||||
expect(mockStartAuthorization).toHaveBeenCalledTimes(1)
|
||||
|
||||
// The guard queried with the dead-status filter (so an active row can
|
||||
// never be returned) rather than neq('status', 'revoked').
|
||||
const guard = chains[2]
|
||||
const inCall = guard._calls.find((c) => c.method === 'in')
|
||||
expect(inCall?.args).toEqual(['status', ['expired', 'error', 'pending_selection']])
|
||||
expect(guard._calls.some((c) => c.method === 'neq')).toBe(false)
|
||||
})
|
||||
|
||||
it('force_new: true bypasses the guard and inserts a fresh row', async () => {
|
||||
const chains: RecordedChain[] = []
|
||||
let call = 0
|
||||
const ctx = makeContext(() => {
|
||||
call++
|
||||
let chain: RecordedChain
|
||||
if (call === 1) {
|
||||
chain = makeChain({ data: null })
|
||||
} else if (call === 2) {
|
||||
chain = makeChain({ data: [] })
|
||||
} else {
|
||||
// With force_new the guard query is skipped entirely: call 3 is the
|
||||
// insert of the fresh connection row.
|
||||
chain = makeChain({ data: { id: 'new-conn' } })
|
||||
}
|
||||
chains.push(chain)
|
||||
return chain
|
||||
})
|
||||
|
||||
const req = new Request('https://test.local/api/extensions/ext/enable-banking/connect', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
aspsp_name: 'Nordea',
|
||||
aspsp_country: 'SE',
|
||||
psu_type: 'business',
|
||||
force_new: true,
|
||||
}),
|
||||
})
|
||||
|
||||
const response = await connectRoute().handler(req, ctx)
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
const body = (await response.json()) as { connection_id: string }
|
||||
expect(body.connection_id).toBe('new-conn')
|
||||
expect(mockStartAuthorization).toHaveBeenCalledTimes(1)
|
||||
// No guard query ran: nothing filtered on the guard's dead-status set
|
||||
// (the sweep's in() uses ['pending', 'error'] and is expected).
|
||||
for (const chain of chains) {
|
||||
const guardIn = chain._calls.find(
|
||||
(c) =>
|
||||
c.method === 'in' &&
|
||||
JSON.stringify(c.args) === JSON.stringify(['status', ['expired', 'error', 'pending_selection']]),
|
||||
)
|
||||
expect(guardIn).toBeUndefined()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,273 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// Mock the Enable Banking API client so revoking the PSD2 session never makes
|
||||
// a network call. SessionExpiredError must stay a real class: index.ts uses it
|
||||
// in an instanceof check.
|
||||
vi.mock('../lib/api-client', () => ({
|
||||
startAuthorization: vi.fn(),
|
||||
getASPSPs: vi.fn(),
|
||||
getPreferredAuthMethod: vi.fn(),
|
||||
getPreferredAuthMethodDetails: vi.fn(),
|
||||
deleteSession: vi.fn().mockResolvedValue(undefined),
|
||||
isSandboxMode: vi.fn(() => true),
|
||||
SessionExpiredError: class SessionExpiredError extends Error {},
|
||||
}))
|
||||
|
||||
// A PSD2 session can be shared by several of a user's companies, so the route
|
||||
// refcounts before revoking. That count runs on a service-role client (RLS
|
||||
// would hide a sibling in a company the user has since left), which without
|
||||
// this mock tries to build a real client and fails on missing env vars.
|
||||
const { siblingState } = vi.hoisted(() => ({
|
||||
siblingState: { count: 0, error: null as { message: string } | null },
|
||||
}))
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(async () => ({
|
||||
from: vi.fn(() => {
|
||||
const chain: Record<string, unknown> = {}
|
||||
for (const method of ['select', 'eq', 'neq']) {
|
||||
chain[method] = vi.fn(() => chain)
|
||||
}
|
||||
chain.then = (onFulfilled: (value: unknown) => unknown) =>
|
||||
Promise.resolve({ count: siblingState.count, error: siblingState.error }).then(onFulfilled)
|
||||
return chain
|
||||
}),
|
||||
})),
|
||||
}))
|
||||
|
||||
import { enableBankingExtension } from '../index'
|
||||
import { deleteSession } from '../lib/api-client'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
|
||||
const mockedDeleteSession = vi.mocked(deleteSession)
|
||||
|
||||
const disconnectRoute = enableBankingExtension.apiRoutes?.find(
|
||||
r => r.method === 'DELETE' && r.path === '/disconnect'
|
||||
)
|
||||
|
||||
if (!disconnectRoute) {
|
||||
throw new Error('DELETE /disconnect route not registered on enable-banking extension')
|
||||
}
|
||||
|
||||
interface DisconnectStub {
|
||||
authUser: { id: string } | null
|
||||
connectionRow: {
|
||||
id: string
|
||||
session_id: string | null
|
||||
status: string
|
||||
bank_name?: string | null
|
||||
} | null
|
||||
connectionError?: { message: string } | null
|
||||
connUpdateError?: { message: string } | null
|
||||
cashUpdateError?: { message: string } | null
|
||||
/** Captured bank_connections update payloads. */
|
||||
connUpdates: Array<Record<string, unknown>>
|
||||
/** Captured cash_accounts update payloads + their eq() filters, in order. */
|
||||
cashUpdates: Array<{ payload: Record<string, unknown>; filters: Array<[string, unknown]> }>
|
||||
}
|
||||
|
||||
function makeStub(partial: Partial<DisconnectStub> = {}): DisconnectStub {
|
||||
return {
|
||||
authUser: { id: 'user-1' },
|
||||
connectionRow: {
|
||||
id: 'conn-1',
|
||||
session_id: 'sess-1',
|
||||
status: 'active',
|
||||
bank_name: 'Lunar',
|
||||
},
|
||||
connUpdates: [],
|
||||
cashUpdates: [],
|
||||
...partial,
|
||||
}
|
||||
}
|
||||
|
||||
function buildSupabase(stub: DisconnectStub) {
|
||||
return {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: stub.authUser }, error: null }),
|
||||
},
|
||||
from: vi.fn((table: string) => {
|
||||
if (table === 'cash_accounts') {
|
||||
return {
|
||||
update: vi.fn((payload: Record<string, unknown>) => {
|
||||
const filters: Array<[string, unknown]> = []
|
||||
stub.cashUpdates.push({ payload, filters })
|
||||
const result = Promise.resolve({ error: stub.cashUpdateError ?? null })
|
||||
const builder = {
|
||||
eq: vi.fn((col: string, val: unknown) => {
|
||||
filters.push([col, val])
|
||||
return builder
|
||||
}),
|
||||
then: result.then.bind(result),
|
||||
catch: result.catch.bind(result),
|
||||
}
|
||||
return builder
|
||||
}),
|
||||
}
|
||||
}
|
||||
// bank_connections
|
||||
return {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
single: vi.fn().mockResolvedValue({
|
||||
data: stub.connectionRow,
|
||||
error: stub.connectionError ?? null,
|
||||
}),
|
||||
update: vi.fn((payload: Record<string, unknown>) => {
|
||||
stub.connUpdates.push(payload)
|
||||
return { eq: vi.fn().mockResolvedValue({ error: stub.connUpdateError ?? null }) }
|
||||
}),
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
function makeContext(supabase: ReturnType<typeof buildSupabase>): ExtensionContext {
|
||||
return {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'enable-banking',
|
||||
requestId: 'req_test',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
supabase: supabase as any,
|
||||
emit: vi.fn().mockResolvedValue(undefined),
|
||||
settings: { get: vi.fn(), set: vi.fn(), getAll: vi.fn() } as never,
|
||||
storage: {} as never,
|
||||
log: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
} as never,
|
||||
services: {} as never,
|
||||
}
|
||||
}
|
||||
|
||||
function makeRequest(body: unknown): Request {
|
||||
return new Request('http://localhost/api/extensions/ext/enable-banking/disconnect', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
describe('DELETE /disconnect (enable-banking)', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockedDeleteSession.mockResolvedValue(undefined)
|
||||
siblingState.count = 0
|
||||
siblingState.error = null
|
||||
})
|
||||
|
||||
it('leaves the shared consent alone while another company still uses it', async () => {
|
||||
// Sessions are shared across a user's companies (lib/session-sharing.ts).
|
||||
// Revoking here would take down a sibling company's bank feed, which is the
|
||||
// exact failure cross-company session reuse exists to remove.
|
||||
siblingState.count = 1
|
||||
const stub = makeStub()
|
||||
const ctx = makeContext(buildSupabase(stub))
|
||||
|
||||
const res = await disconnectRoute.handler(makeRequest({ connection_id: 'conn-1' }), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockedDeleteSession).not.toHaveBeenCalled()
|
||||
// This company is still fully disconnected: only the upstream consent
|
||||
// survives, and it lapses on its own within 90 days.
|
||||
expect(stub.connUpdates).toEqual([{ status: 'revoked', session_id: null }])
|
||||
expect(stub.cashUpdates).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('treats a failed sibling count as shared rather than risk a live feed', async () => {
|
||||
siblingState.error = { message: 'timeout' }
|
||||
const stub = makeStub()
|
||||
const ctx = makeContext(buildSupabase(stub))
|
||||
|
||||
const res = await disconnectRoute.handler(makeRequest({ connection_id: 'conn-1' }), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockedDeleteSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 401 when unauthenticated', async () => {
|
||||
const stub = makeStub({ authUser: null })
|
||||
const ctx = makeContext(buildSupabase(stub))
|
||||
|
||||
const res = await disconnectRoute.handler(makeRequest({ connection_id: 'conn-1' }), ctx)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 when the connection is not found', async () => {
|
||||
const stub = makeStub({ connectionRow: null, connectionError: { message: 'not found' } })
|
||||
const ctx = makeContext(buildSupabase(stub))
|
||||
|
||||
const res = await disconnectRoute.handler(makeRequest({ connection_id: 'conn-1' }), ctx)
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
it('revokes the connection AND releases its cash_accounts ledger claims (issue #916)', async () => {
|
||||
const stub = makeStub()
|
||||
const ctx = makeContext(buildSupabase(stub))
|
||||
|
||||
const res = await disconnectRoute.handler(makeRequest({ connection_id: 'conn-1' }), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.success).toBe(true)
|
||||
|
||||
// PSD2 consent revoked upstream.
|
||||
expect(mockedDeleteSession).toHaveBeenCalledWith('sess-1')
|
||||
|
||||
// Connection marked revoked.
|
||||
expect(stub.connUpdates).toEqual([{ status: 'revoked', session_id: null }])
|
||||
|
||||
// The connection's cash_accounts rows are demoted to manual (NOT deleted):
|
||||
// transactions and ledger history reference them, and upsertFromPsd2
|
||||
// promotes manual holders in place on reconnect so the same bank lands
|
||||
// back on its original BAS account.
|
||||
expect(stub.cashUpdates).toHaveLength(1)
|
||||
expect(stub.cashUpdates[0].payload).toEqual({ bank_connection_id: null })
|
||||
expect(stub.cashUpdates[0].filters).toEqual([
|
||||
['company_id', 'company-1'],
|
||||
['bank_connection_id', 'conn-1'],
|
||||
])
|
||||
|
||||
expect(ctx.emit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
type: 'bank_connection.revoked',
|
||||
payload: expect.objectContaining({ connectionId: 'conn-1', companyId: 'company-1' }),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('still succeeds when the ledger claim release fails (self-heal covers it)', async () => {
|
||||
// The connection is already revoked at that point; the allocator and the
|
||||
// picker-save collision guard both skip revoked connections, so orphaned
|
||||
// rows recover on the next picker save.
|
||||
const stub = makeStub({ cashUpdateError: { message: 'transient' } })
|
||||
const ctx = makeContext(buildSupabase(stub))
|
||||
|
||||
const res = await disconnectRoute.handler(makeRequest({ connection_id: 'conn-1' }), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const body = await res.json()
|
||||
expect(body.success).toBe(true)
|
||||
expect(ctx.log.error).toHaveBeenCalledWith(
|
||||
expect.stringContaining('release cash_accounts'),
|
||||
expect.objectContaining({ connectionId: 'conn-1' })
|
||||
)
|
||||
})
|
||||
|
||||
it('skips PSD2 session revocation when the connection has no session', async () => {
|
||||
const stub = makeStub({
|
||||
connectionRow: { id: 'conn-1', session_id: null, status: 'expired', bank_name: 'Lunar' },
|
||||
})
|
||||
const ctx = makeContext(buildSupabase(stub))
|
||||
|
||||
const res = await disconnectRoute.handler(makeRequest({ connection_id: 'conn-1' }), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(mockedDeleteSession).not.toHaveBeenCalled()
|
||||
// Ledger claims are still released.
|
||||
expect(stub.cashUpdates).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,208 @@
|
||||
import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
import type { StoredAccount } from '../types'
|
||||
|
||||
// Mock the JWT signer so api-client can be imported without real
|
||||
// ENABLE_BANKING credentials.
|
||||
vi.mock('../lib/jwt', () => ({
|
||||
getAuthorizationHeader: () => 'Bearer test-token',
|
||||
}))
|
||||
|
||||
// Mock the sync orchestrator so the /sync handler tests can force success or
|
||||
// failure without hitting the network.
|
||||
vi.mock('../lib/sync', () => ({
|
||||
syncAccountTransactions: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
import { SYNC_FAILED_MESSAGE, CONNECTOR_UNAVAILABLE_MESSAGE, ConnectorSyncError } from '../lib/api-client'
|
||||
import { enableBankingExtension } from '../index'
|
||||
import { syncAccountTransactions } from '../lib/sync'
|
||||
|
||||
const syncRoute = enableBankingExtension.apiRoutes?.find(
|
||||
r => r.method === 'POST' && r.path === '/sync'
|
||||
)
|
||||
|
||||
if (!syncRoute) {
|
||||
throw new Error('POST /sync route not registered on enable-banking extension')
|
||||
}
|
||||
|
||||
const RAW_EB_ERROR =
|
||||
'Failed to get transactions (400): {"code":400,"message":"Error interacting with ASPSP","detail":null,"error":"ASPSP_ERROR"}'
|
||||
|
||||
function makeContext(connection: Record<string, unknown>, updateSpy: Mock): ExtensionContext {
|
||||
// One universal chainable per from() call (same shape as the other /sync
|
||||
// handler tests): bank_connections terminates on single(), sie_imports /
|
||||
// company_members on maybeSingle(), and update() records its payload while
|
||||
// returning the chain so trailing .eq() calls resolve.
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const chain: any = {}
|
||||
chain.select = vi.fn(() => chain)
|
||||
chain.eq = vi.fn(() => chain)
|
||||
chain.gte = vi.fn(() => chain)
|
||||
chain.limit = vi.fn(() => chain)
|
||||
chain.order = vi.fn(() => chain)
|
||||
chain.single = vi.fn().mockResolvedValue({ data: connection, error: null })
|
||||
chain.maybeSingle = vi.fn().mockResolvedValue({ data: null, error: null })
|
||||
chain.update = vi.fn((payload: unknown) => {
|
||||
updateSpy(payload)
|
||||
return chain
|
||||
})
|
||||
|
||||
const supabase = {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null }),
|
||||
},
|
||||
from: vi.fn(() => chain),
|
||||
}
|
||||
|
||||
return {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'enable-banking',
|
||||
requestId: 'req_test',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
supabase: supabase as any,
|
||||
emit: vi.fn().mockResolvedValue(undefined),
|
||||
settings: { get: vi.fn(), set: vi.fn(), getAll: vi.fn() } as never,
|
||||
storage: {} as never,
|
||||
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as never,
|
||||
services: {} as never,
|
||||
}
|
||||
}
|
||||
|
||||
function makeRequest(): Request {
|
||||
return new Request('http://localhost/api/extensions/ext/enable-banking/sync', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ connection_id: 'conn-1' }),
|
||||
})
|
||||
}
|
||||
|
||||
function makeConnection(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
return {
|
||||
id: 'conn-1',
|
||||
company_id: 'company-1',
|
||||
bank_name: 'SEB',
|
||||
accounts_data: [{ uid: 'acc-1', currency: 'SEK', enabled: true }] as StoredAccount[],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('POST /sync (enable-banking): retry from error status', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('allows sync from status=error and restores active + clears error_message on success', async () => {
|
||||
// Regression: a transient ASPSP failure parked the connection in 'error',
|
||||
// but the old status gate rejected everything but 'active', so the UI's
|
||||
// "Försök igen" button always got 400 and the connection was stranded
|
||||
// until a full re-auth.
|
||||
;(syncAccountTransactions as unknown as Mock).mockResolvedValue({
|
||||
imported: 0,
|
||||
duplicates: 0,
|
||||
errors: 0,
|
||||
})
|
||||
|
||||
const updateSpy = vi.fn()
|
||||
const ctx = makeContext(
|
||||
makeConnection({ status: 'error', error_message: RAW_EB_ERROR }),
|
||||
updateSpy
|
||||
)
|
||||
|
||||
const res = await syncRoute.handler(makeRequest(), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(syncAccountTransactions).toHaveBeenCalledTimes(1)
|
||||
expect(updateSpy).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
status: 'active',
|
||||
error_message: null,
|
||||
last_synced_at: expect.any(String),
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('still rejects expired connections with 400 (re-auth required, not retry)', async () => {
|
||||
const updateSpy = vi.fn()
|
||||
const ctx = makeContext(makeConnection({ status: 'expired' }), updateSpy)
|
||||
|
||||
const res = await syncRoute.handler(makeRequest(), ctx)
|
||||
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toMatch(/not active/i)
|
||||
expect(syncAccountTransactions).not.toHaveBeenCalled()
|
||||
expect(updateSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not touch status for an active connection but clears a leftover error_message', async () => {
|
||||
;(syncAccountTransactions as unknown as Mock).mockResolvedValue({
|
||||
imported: 0,
|
||||
duplicates: 0,
|
||||
errors: 0,
|
||||
})
|
||||
|
||||
const updateSpy = vi.fn()
|
||||
const ctx = makeContext(
|
||||
makeConnection({ status: 'active', error_message: RAW_EB_ERROR }),
|
||||
updateSpy
|
||||
)
|
||||
|
||||
const res = await syncRoute.handler(makeRequest(), ctx)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
const payload = updateSpy.mock.calls[0][0]
|
||||
expect(payload).not.toHaveProperty('status')
|
||||
expect(payload).toMatchObject({ error_message: null })
|
||||
})
|
||||
|
||||
it('maps a non-session failure to the Swedish user message and refreshes the stored error_message', async () => {
|
||||
// The raw Enable Banking body is an English JSON envelope: it belongs in
|
||||
// server logs, never in the toast or the settings panel.
|
||||
;(syncAccountTransactions as unknown as Mock).mockRejectedValue(new Error(RAW_EB_ERROR))
|
||||
|
||||
const updateSpy = vi.fn()
|
||||
const ctx = makeContext(
|
||||
makeConnection({ status: 'error', error_message: RAW_EB_ERROR }),
|
||||
updateSpy
|
||||
)
|
||||
|
||||
const res = await syncRoute.handler(makeRequest(), ctx)
|
||||
|
||||
expect(res.status).toBe(500)
|
||||
const body = await res.json()
|
||||
expect(body.error).toBe(SYNC_FAILED_MESSAGE)
|
||||
expect(body.error).not.toContain('ASPSP_ERROR')
|
||||
expect(updateSpy).toHaveBeenCalledWith({ error_message: SYNC_FAILED_MESSAGE })
|
||||
})
|
||||
|
||||
it('answers 503 retryable without renewal advice when the connector hop fails, and leaves the row alone', async () => {
|
||||
;(syncAccountTransactions as unknown as Mock).mockRejectedValue(
|
||||
new ConnectorSyncError(200, 'CONNECTOR_BAD_SHAPE', '{}', ['transactions.0.amount: Invalid input'])
|
||||
)
|
||||
|
||||
const updateSpy = vi.fn()
|
||||
const ctx = makeContext(makeConnection({ status: 'error', error_message: SYNC_FAILED_MESSAGE }), updateSpy)
|
||||
|
||||
const res = await syncRoute.handler(makeRequest(), ctx)
|
||||
|
||||
expect(res.status).toBe(503)
|
||||
const body = await res.json()
|
||||
expect(body).toMatchObject({ error: CONNECTOR_UNAVAILABLE_MESSAGE, code: 'CONNECTOR_UNAVAILABLE', retryable: true })
|
||||
expect(body.error).not.toContain('Förnya')
|
||||
expect(updateSpy).not.toHaveBeenCalled()
|
||||
expect(ctx.log.warn).toHaveBeenCalledWith(
|
||||
'[enable-banking] Sync: connector hop failed',
|
||||
expect.objectContaining({ code: 'CONNECTOR_BAD_SHAPE', issues: ['transactions.0.amount: Invalid input'] })
|
||||
)
|
||||
// The raw connector body can carry bank data: never in the log line.
|
||||
const logged = (ctx.log.warn as Mock).mock.calls.find((c) => c[0] === '[enable-banking] Sync: connector hop failed')?.[1]
|
||||
expect(logged).not.toHaveProperty('body')
|
||||
expect(logged).toHaveProperty('bodyLength', 2)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,428 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
import {
|
||||
unclaimedAccountsFor,
|
||||
findReusableSessions,
|
||||
countLiveSiblings,
|
||||
fanOutSessionRenewal,
|
||||
remapAccountUids,
|
||||
} from '../lib/session-sharing'
|
||||
import type { StoredAccount } from '../types'
|
||||
|
||||
/**
|
||||
* Thenable query stub: PostgREST chains terminate on await, not on a fixed
|
||||
* method, so the same object has to answer .eq()/.neq()/.gt()/.in() and still
|
||||
* resolve when awaited. Mirrors the stub in lib/cash-accounts/__tests__.
|
||||
*/
|
||||
/** A recorded builder call: the method name and the arguments it got. */
|
||||
type RecordedCall = [string, unknown[]]
|
||||
|
||||
interface ChainStub {
|
||||
calls: RecordedCall[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
function chainable(result: Record<string, unknown>): ChainStub {
|
||||
const calls: RecordedCall[] = []
|
||||
const chain = { calls } as ChainStub
|
||||
for (const method of [
|
||||
'select', 'eq', 'neq', 'not', 'is', 'in', 'gt', 'order', 'limit', 'update', 'insert',
|
||||
]) {
|
||||
chain[method] = vi.fn((...args: unknown[]) => {
|
||||
calls.push([method, args])
|
||||
return chain
|
||||
})
|
||||
}
|
||||
chain.then = (onFulfilled: (value: unknown) => unknown) =>
|
||||
Promise.resolve(result).then(onFulfilled)
|
||||
chain.maybeSingle = vi.fn(() => Promise.resolve(result))
|
||||
chain.single = vi.fn(() => Promise.resolve(result))
|
||||
return chain
|
||||
}
|
||||
|
||||
type MockClient = SupabaseClient & { used: Record<string, ChainStub[]> }
|
||||
|
||||
/** Per-table result queues; each from(table) shifts the next result. */
|
||||
function makeSupabase(queues: Record<string, Array<Record<string, unknown>>>): MockClient {
|
||||
const used: Record<string, ChainStub[]> = {}
|
||||
const client = {
|
||||
used,
|
||||
from: vi.fn((table: string) => {
|
||||
const queue = queues[table] ?? []
|
||||
const result = queue.shift() ?? { data: [], error: null }
|
||||
const chain = chainable(result)
|
||||
;(used[table] ??= []).push(chain)
|
||||
return chain
|
||||
}),
|
||||
}
|
||||
return client as unknown as MockClient
|
||||
}
|
||||
|
||||
const FUTURE = new Date(Date.now() + 30 * 24 * 3600 * 1000).toISOString()
|
||||
|
||||
function makeAccount(over: Partial<StoredAccount> = {}): StoredAccount {
|
||||
return { uid: 'uid-1', iban: 'SE1122334455667788990011', currency: 'SEK', ...over }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('unclaimedAccountsFor', () => {
|
||||
it('drops accounts whose IBAN a cash account already claims', () => {
|
||||
const accounts = [
|
||||
makeAccount({ uid: 'a', iban: 'SE1111111111111111111111' }),
|
||||
makeAccount({ uid: 'b', iban: 'SE2222222222222222222222' }),
|
||||
]
|
||||
const result = unclaimedAccountsFor(accounts, new Set(['SE1111111111111111111111']))
|
||||
expect(result.map(a => a.uid)).toEqual(['b'])
|
||||
})
|
||||
|
||||
it('matches claimed IBANs regardless of spacing', () => {
|
||||
const accounts = [makeAccount({ uid: 'a', iban: 'SE11 1111 1111 1111 1111 1111' })]
|
||||
const result = unclaimedAccountsFor(accounts, new Set(['SE1111111111111111111111']))
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
it('never offers an account without an IBAN', () => {
|
||||
// Identity is the IBAN. Without one we cannot prove the account is
|
||||
// unclaimed, and two companies booking one physical account is worse than
|
||||
// making the user authorize separately.
|
||||
const accounts = [makeAccount({ uid: 'a', iban: undefined })]
|
||||
expect(unclaimedAccountsFor(accounts, new Set())).toEqual([])
|
||||
})
|
||||
|
||||
it('offers a repeated IBAN only once', () => {
|
||||
// Some ASPSPs return one resource per balance type on the same account;
|
||||
// offering it twice lets the picker map two rows onto one ledger and trip
|
||||
// the (company_id, ledger_account) UNIQUE constraint on save.
|
||||
const accounts = [
|
||||
makeAccount({ uid: 'a', iban: 'SE3333333333333333333333' }),
|
||||
makeAccount({ uid: 'b', iban: 'SE33 3333 3333 3333 3333 3333' }),
|
||||
]
|
||||
expect(unclaimedAccountsFor(accounts, new Set()).map(a => a.uid)).toEqual(['a'])
|
||||
})
|
||||
|
||||
it('strips the source company ledger mapping and enables the account', () => {
|
||||
const accounts = [makeAccount({ ledger_account: '1942', enabled: false })]
|
||||
const [result] = unclaimedAccountsFor(accounts, new Set())
|
||||
expect(result.ledger_account).toBeUndefined()
|
||||
expect(result.enabled).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('findReusableSessions', () => {
|
||||
it('returns a session with the accounts no company has claimed', async () => {
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [{
|
||||
data: [{
|
||||
id: 'conn-a', company_id: 'company-a', bank_name: 'Testbanken',
|
||||
provider: 'testbanken-se', session_id: 'sess-1', psu_type: 'business',
|
||||
consent_expires: FUTURE,
|
||||
accounts_data: [
|
||||
makeAccount({ uid: 'claimed', iban: 'SE1111111111111111111111' }),
|
||||
makeAccount({ uid: 'free', iban: 'SE2222222222222222222222' }),
|
||||
],
|
||||
}],
|
||||
error: null,
|
||||
}],
|
||||
cash_accounts: [{ data: [{ iban: 'SE1111111111111111111111' }], error: null }],
|
||||
companies: [{ data: [{ id: 'company-a', name: 'Bolag A' }], error: null }],
|
||||
})
|
||||
|
||||
const sessions = await findReusableSessions(supabase, 'user-1', 'company-b')
|
||||
|
||||
expect(sessions).toHaveLength(1)
|
||||
expect(sessions[0].companyName).toBe('Bolag A')
|
||||
expect(sessions[0].sessionId).toBe('sess-1')
|
||||
expect(sessions[0].availableAccounts.map(a => a.uid)).toEqual(['free'])
|
||||
})
|
||||
|
||||
it('offers nothing when every account is already claimed', async () => {
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [{
|
||||
data: [{
|
||||
id: 'conn-a', company_id: 'company-a', bank_name: 'Testbanken',
|
||||
provider: 'testbanken-se', session_id: 'sess-1', psu_type: 'business',
|
||||
consent_expires: FUTURE,
|
||||
accounts_data: [makeAccount({ uid: 'claimed', iban: 'SE1111111111111111111111' })],
|
||||
}],
|
||||
error: null,
|
||||
}],
|
||||
cash_accounts: [{ data: [{ iban: 'SE1111111111111111111111' }], error: null }],
|
||||
companies: [{ data: [{ id: 'company-a', name: 'Bolag A' }], error: null }],
|
||||
})
|
||||
|
||||
expect(await findReusableSessions(supabase, 'user-1', 'company-b')).toEqual([])
|
||||
})
|
||||
|
||||
it('stops offering an account another company already holds but has not mapped', async () => {
|
||||
// The gap between attaching a company and that company finishing its
|
||||
// picker: no cash_accounts row exists yet, so a claimed-ledger check alone
|
||||
// would hand the same physical account to a third company.
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [
|
||||
{
|
||||
data: [{
|
||||
id: 'conn-a', company_id: 'company-a', bank_name: 'Testbanken',
|
||||
provider: 'testbanken-se', session_id: 'sess-1', psu_type: 'business',
|
||||
consent_expires: FUTURE,
|
||||
accounts_data: [makeAccount({ uid: 'free', iban: 'SE2222222222222222222222' })],
|
||||
}],
|
||||
error: null,
|
||||
},
|
||||
{
|
||||
// Carrier pass: company-b already took that account on attach.
|
||||
data: [
|
||||
{ company_id: 'company-a', accounts_data: [makeAccount({ iban: 'SE2222222222222222222222' })] },
|
||||
{ company_id: 'company-b', accounts_data: [makeAccount({ iban: 'SE2222222222222222222222' })] },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
],
|
||||
cash_accounts: [{ data: [], error: null }],
|
||||
companies: [{ data: [{ id: 'company-a', name: 'Bolag A' }], error: null }],
|
||||
})
|
||||
|
||||
expect(await findReusableSessions(supabase, 'user-1', 'company-c')).toEqual([])
|
||||
})
|
||||
|
||||
it('counts only enabled cash accounts as claimed', async () => {
|
||||
// The connect callback mirrors EVERY account in the consent into
|
||||
// cash_accounts, deselected ones included. Treating any row as a claim
|
||||
// would mean the first company to connect speaks for the whole bank and
|
||||
// nothing is ever free to offer, so the feature would never fire.
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [
|
||||
{
|
||||
data: [{
|
||||
id: 'conn-a', company_id: 'company-a', bank_name: 'Testbanken',
|
||||
provider: 'testbanken-se', session_id: 'sess-1', psu_type: 'business',
|
||||
consent_expires: FUTURE,
|
||||
accounts_data: [
|
||||
makeAccount({ uid: 'deselected', iban: 'SE2222222222222222222222', enabled: false }),
|
||||
],
|
||||
}],
|
||||
error: null,
|
||||
},
|
||||
{ data: [], error: null },
|
||||
],
|
||||
// The mirrored row exists but is disabled, so it holds nothing.
|
||||
cash_accounts: [{ data: [], error: null }],
|
||||
companies: [{ data: [{ id: 'company-a', name: 'Bolag A' }], error: null }],
|
||||
})
|
||||
|
||||
const sessions = await findReusableSessions(supabase, 'user-1', 'company-b')
|
||||
|
||||
expect(sessions).toHaveLength(1)
|
||||
expect(sessions[0].availableAccounts.map(a => a.uid)).toEqual(['deselected'])
|
||||
// The enabled filter is what the query must ask for.
|
||||
expect(supabase.used.cash_accounts[0].calls).toContainEqual(['eq', ['enabled', true]])
|
||||
})
|
||||
|
||||
it('scopes the query to the user, other companies, and a live consent', async () => {
|
||||
const supabase = makeSupabase({ bank_connections: [{ data: [], error: null }] })
|
||||
|
||||
await findReusableSessions(supabase, 'user-1', 'company-b')
|
||||
|
||||
const filters = supabase.used.bank_connections[0].calls
|
||||
expect(filters).toContainEqual(['eq', ['user_id', 'user-1']])
|
||||
expect(filters).toContainEqual(['eq', ['status', 'active']])
|
||||
expect(filters).toContainEqual(['neq', ['company_id', 'company-b']])
|
||||
expect(filters.some(([m, args]) => m === 'gt' && args[0] === 'consent_expires')).toBe(true)
|
||||
})
|
||||
|
||||
it('offers nothing when the claimed-IBAN lookup fails', async () => {
|
||||
// Fail closed: without the claimed set we cannot tell a free account from
|
||||
// one another company already books to.
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [{
|
||||
data: [{
|
||||
id: 'conn-a', company_id: 'company-a', bank_name: 'Testbanken',
|
||||
provider: 'testbanken-se', session_id: 'sess-1', psu_type: 'business',
|
||||
consent_expires: FUTURE,
|
||||
accounts_data: [makeAccount({ uid: 'free', iban: 'SE2222222222222222222222' })],
|
||||
}],
|
||||
error: null,
|
||||
}],
|
||||
cash_accounts: [{ data: null, error: { message: 'boom' } }],
|
||||
companies: [{ data: [], error: null }],
|
||||
})
|
||||
|
||||
// Nothing is offered: an unreadable claimed set cannot prove an account
|
||||
// free, and offering one another company books to is the outcome this
|
||||
// feature must never produce. The failure must also not throw and take the
|
||||
// settings panel down with it, hence awaiting a value rather than a reject.
|
||||
const sessions = await findReusableSessions(supabase, 'user-1', 'company-b')
|
||||
expect(sessions).toEqual([])
|
||||
})
|
||||
|
||||
it('returns an empty list when the session lookup fails', async () => {
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [{ data: null, error: { message: 'rls' } }],
|
||||
})
|
||||
expect(await findReusableSessions(supabase, 'user-1', 'company-b')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('countLiveSiblings', () => {
|
||||
it('counts the other non-revoked connections on the session', async () => {
|
||||
const supabase = makeSupabase({ bank_connections: [{ count: 2, error: null }] })
|
||||
|
||||
const count = await countLiveSiblings(supabase, 'sess-1', 'conn-a')
|
||||
|
||||
expect(count).toBe(2)
|
||||
const filters = supabase.used.bank_connections[0].calls
|
||||
expect(filters).toContainEqual(['eq', ['session_id', 'sess-1']])
|
||||
expect(filters).toContainEqual(['neq', ['id', 'conn-a']])
|
||||
expect(filters).toContainEqual(['neq', ['status', 'revoked']])
|
||||
})
|
||||
|
||||
it('reports a sibling when the count fails, so the session is never revoked', async () => {
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [{ count: null, error: { message: 'timeout' } }],
|
||||
})
|
||||
expect(await countLiveSiblings(supabase, 'sess-1', 'conn-a')).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fanOutSessionRenewal', () => {
|
||||
it('does nothing when the session did not actually change', async () => {
|
||||
const supabase = makeSupabase({})
|
||||
const result = await fanOutSessionRenewal(supabase, {
|
||||
oldSessionId: 'sess-1',
|
||||
newSessionId: 'sess-1',
|
||||
consentExpires: FUTURE,
|
||||
excludeConnectionId: 'conn-a',
|
||||
})
|
||||
expect(result.movedCount).toBe(0)
|
||||
expect(supabase.from).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('revives a dead sibling and leaves a pending_selection one pending', async () => {
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [
|
||||
{
|
||||
data: [
|
||||
{ id: 'conn-b', status: 'expired', accounts_data: [] },
|
||||
{ id: 'conn-c', status: 'pending_selection', accounts_data: [] },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ error: null },
|
||||
{ error: null },
|
||||
],
|
||||
})
|
||||
|
||||
const result = await fanOutSessionRenewal(supabase, {
|
||||
oldSessionId: 'sess-old',
|
||||
newSessionId: 'sess-new',
|
||||
consentExpires: FUTURE,
|
||||
excludeConnectionId: 'conn-a',
|
||||
})
|
||||
|
||||
expect(result.movedCount).toBe(2)
|
||||
|
||||
// The connection that just re-authorized is already correct; touching it
|
||||
// again would be a no-op at best and a status regression at worst.
|
||||
expect(supabase.used.bank_connections[0].calls).toContainEqual(['neq', ['id', 'conn-a']])
|
||||
|
||||
const revived = supabase.used.bank_connections[1].calls
|
||||
expect(revived).toContainEqual([
|
||||
'update',
|
||||
[{ session_id: 'sess-new', consent_expires: FUTURE, status: 'active', error_message: null }],
|
||||
])
|
||||
|
||||
// Still owes an account selection, so it must not be flipped to active:
|
||||
// that would skip the picker and sync nothing.
|
||||
const stillPending = supabase.used.bank_connections[2].calls
|
||||
expect(stillPending).toContainEqual([
|
||||
'update',
|
||||
[{ session_id: 'sess-new', consent_expires: FUTURE }],
|
||||
])
|
||||
})
|
||||
|
||||
it('re-points sibling accounts at the uids the new session issued', async () => {
|
||||
// The uid churn is the subtle half of the renewal: carrying only the
|
||||
// session id leaves siblings calling accounts the bank has retired.
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [
|
||||
{
|
||||
data: [{
|
||||
id: 'conn-b',
|
||||
status: 'active',
|
||||
accounts_data: [
|
||||
{ uid: 'old-uid', iban: 'SE4444444444444444444444', currency: 'SEK', ledger_account: '1930', enabled: true },
|
||||
],
|
||||
}],
|
||||
error: null,
|
||||
},
|
||||
{ error: null },
|
||||
{ error: null },
|
||||
],
|
||||
})
|
||||
|
||||
await fanOutSessionRenewal(supabase, {
|
||||
oldSessionId: 'sess-old',
|
||||
newSessionId: 'sess-new',
|
||||
consentExpires: FUTURE,
|
||||
excludeConnectionId: 'conn-a',
|
||||
sessionAccounts: [{ uid: 'new-uid', iban: 'SE44 4444 4444 4444 4444 4444' }],
|
||||
})
|
||||
|
||||
// The uid re-point is its own write, after the session move.
|
||||
const update = supabase.used.bank_connections[2].calls.find(([m]) => m === 'update')
|
||||
const payload = (update?.[1][0] ?? {}) as { accounts_data?: StoredAccount[] }
|
||||
expect(payload.accounts_data?.[0].uid).toBe('new-uid')
|
||||
// The company's own mapping choices survive the remap.
|
||||
expect(payload.accounts_data?.[0].ledger_account).toBe('1930')
|
||||
})
|
||||
|
||||
it('counts only the siblings that actually moved', async () => {
|
||||
const supabase = makeSupabase({
|
||||
bank_connections: [
|
||||
{
|
||||
data: [
|
||||
{ id: 'conn-b', status: 'active', accounts_data: [] },
|
||||
{ id: 'conn-c', status: 'active', accounts_data: [] },
|
||||
],
|
||||
error: null,
|
||||
},
|
||||
{ error: { message: 'boom' } },
|
||||
{ error: null },
|
||||
],
|
||||
})
|
||||
|
||||
const result = await fanOutSessionRenewal(supabase, {
|
||||
oldSessionId: 'sess-old',
|
||||
newSessionId: 'sess-new',
|
||||
consentExpires: FUTURE,
|
||||
excludeConnectionId: 'conn-a',
|
||||
})
|
||||
|
||||
expect(result.movedCount).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('remapAccountUids', () => {
|
||||
it('matches on IBAN regardless of spacing and keeps everything else', () => {
|
||||
const { accounts, remapped } = remapAccountUids(
|
||||
[{ uid: 'old', iban: 'SE55 5555 5555 5555 5555 5555', currency: 'SEK', enabled: false, ledger_account: '1940' }],
|
||||
[{ uid: 'new', iban: 'SE5555555555555555555555' }],
|
||||
)
|
||||
expect(remapped).toBe(1)
|
||||
expect(accounts[0]).toMatchObject({ uid: 'new', enabled: false, ledger_account: '1940' })
|
||||
})
|
||||
|
||||
it('leaves an account the new consent does not cover untouched', () => {
|
||||
// Silently dropping a mapped account is worse than a visible sync error.
|
||||
const { accounts, remapped, unmatched } = remapAccountUids(
|
||||
[{ uid: 'old', iban: 'SE6666666666666666666666', currency: 'SEK' }],
|
||||
[{ uid: 'new', iban: 'SE7777777777777777777777' }],
|
||||
)
|
||||
expect(remapped).toBe(0)
|
||||
expect(unmatched).toBe(1)
|
||||
expect(accounts[0].uid).toBe('old')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,338 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
const { mockDeleteSession, mockCountLiveSiblings } = vi.hoisted(() => ({
|
||||
mockDeleteSession: vi.fn(),
|
||||
mockCountLiveSiblings: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../lib/api-client', () => ({
|
||||
deleteSession: (...args: unknown[]) => mockDeleteSession(...args),
|
||||
}))
|
||||
vi.mock('../lib/session-sharing', () => ({
|
||||
countLiveSiblings: (...args: unknown[]) => mockCountLiveSiblings(...args),
|
||||
}))
|
||||
|
||||
import { supersedeSiblingConnections } from '../lib/supersede'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
import type { StoredAccount } from '../types'
|
||||
|
||||
interface RecordedCall {
|
||||
method: string
|
||||
args: unknown[]
|
||||
}
|
||||
|
||||
interface RecordedChain {
|
||||
_calls: RecordedCall[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
function makeChain(result: { data?: unknown; error?: unknown } = {}): RecordedChain {
|
||||
const calls: RecordedCall[] = []
|
||||
const chain: Record<string, unknown> = { _calls: calls }
|
||||
for (const m of ['select', 'eq', 'neq', 'in', 'order', 'limit', 'update', 'delete']) {
|
||||
chain[m] = vi.fn((...args: unknown[]) => {
|
||||
calls.push({ method: m, args })
|
||||
return chain
|
||||
})
|
||||
}
|
||||
chain.single = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
|
||||
chain.maybeSingle = vi.fn().mockResolvedValue({ data: result.data ?? null, error: result.error ?? null })
|
||||
chain.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||
return chain as RecordedChain
|
||||
}
|
||||
|
||||
interface ScriptStep {
|
||||
table: string
|
||||
chain: RecordedChain
|
||||
}
|
||||
|
||||
/** from() dispatcher that asserts the table order and hands out scripted chains. */
|
||||
function makeSupabase(script: ScriptStep[]): { client: SupabaseClient; from: ReturnType<typeof vi.fn> } {
|
||||
let i = 0
|
||||
const from = vi.fn((table: string) => {
|
||||
const step = script[i]
|
||||
i++
|
||||
expect(step, `unexpected from('${table}') call #${i}`).toBeDefined()
|
||||
expect(table).toBe(step.table)
|
||||
return step.chain
|
||||
})
|
||||
return { client: { from } as unknown as SupabaseClient, from }
|
||||
}
|
||||
|
||||
function updatePayload(chain: RecordedChain): Record<string, unknown> {
|
||||
const call = chain._calls.find((c) => c.method === 'update')
|
||||
expect(call, 'expected an update on this chain').toBeDefined()
|
||||
return call!.args[0] as Record<string, unknown>
|
||||
}
|
||||
|
||||
const BASE_INPUT = {
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
newConnectionId: 'new-1',
|
||||
bankName: 'TestBank',
|
||||
newSessionId: 'sess-new',
|
||||
}
|
||||
|
||||
function makeSibling(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 'old-1',
|
||||
status: 'expired',
|
||||
session_id: 'sess-old',
|
||||
accounts_data: [
|
||||
{
|
||||
uid: 'uid-old',
|
||||
iban: 'SE45 5000 0000 0583 9825 7466',
|
||||
currency: 'SEK',
|
||||
dedup_scope: 'legacy-scope',
|
||||
},
|
||||
] as StoredAccount[],
|
||||
last_synced_at: '2026-08-01T00:00:00Z',
|
||||
initial_sync_completed_at: '2026-06-01T00:00:00Z',
|
||||
initial_sync_requested_from: '2026-01-01',
|
||||
initial_sync_returned_min_date: '2026-01-02',
|
||||
initial_sync_returned_max_date: '2026-07-31',
|
||||
initial_sync_lookback_days: 365,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const NEW_ACCOUNTS: StoredAccount[] = [
|
||||
{ uid: 'uid-new', iban: 'SE4550000000058398257466', currency: 'SEK' },
|
||||
]
|
||||
|
||||
describe('supersedeSiblingConnections', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
eventBus.clear()
|
||||
mockCountLiveSiblings.mockResolvedValue(0)
|
||||
mockDeleteSession.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('supersedes an IBAN-overlapping sibling: revoked + superseded_by, transactions re-pointed, claims released', async () => {
|
||||
const emitSpy = vi.spyOn(eventBus, 'emit')
|
||||
|
||||
const siblingSelect = makeChain({ data: [makeSibling()] })
|
||||
const revokeUpdate = makeChain({})
|
||||
const txSelect = makeChain({ data: [{ id: 't1' }, { id: 't2' }] })
|
||||
const txUpdate = makeChain({})
|
||||
const cashDemote = makeChain({})
|
||||
const newRowSelect = makeChain({ data: { last_synced_at: null, initial_sync_completed_at: null } })
|
||||
const carryUpdate = makeChain({})
|
||||
|
||||
const { client } = makeSupabase([
|
||||
{ table: 'bank_connections', chain: siblingSelect },
|
||||
{ table: 'bank_connections', chain: revokeUpdate },
|
||||
{ table: 'transactions', chain: txSelect },
|
||||
{ table: 'transactions', chain: txUpdate },
|
||||
{ table: 'cash_accounts', chain: cashDemote },
|
||||
{ table: 'bank_connections', chain: newRowSelect },
|
||||
{ table: 'bank_connections', chain: carryUpdate },
|
||||
])
|
||||
|
||||
const result = await supersedeSiblingConnections(client, {
|
||||
...BASE_INPUT,
|
||||
newAccounts: NEW_ACCOUNTS,
|
||||
})
|
||||
|
||||
expect(result.supersededIds).toEqual(['old-1'])
|
||||
// The explicit dedup scope travels, keyed by normalized IBAN.
|
||||
expect(result.dedupScopeByIban.get('SE4550000000058398257466')).toBe('legacy-scope')
|
||||
|
||||
// The dead consent is revoked at EB (nobody else shares it).
|
||||
expect(mockDeleteSession).toHaveBeenCalledWith('sess-old')
|
||||
|
||||
// The row is parked, not deleted: revoked + superseded_by disambiguates
|
||||
// a supersede from a user disconnect.
|
||||
const parked = updatePayload(revokeUpdate)
|
||||
expect(parked.status).toBe('revoked')
|
||||
expect(parked.session_id).toBeNull()
|
||||
expect(parked.superseded_by).toBe('new-1')
|
||||
expect(typeof parked.superseded_at).toBe('string')
|
||||
|
||||
// Feed rows follow the survivor, batch-scoped by the selected ids.
|
||||
expect(updatePayload(txUpdate)).toEqual({ bank_connection_id: 'new-1' })
|
||||
const inCall = txUpdate._calls.find((c) => c.method === 'in')
|
||||
expect(inCall?.args).toEqual(['id', ['t1', 't2']])
|
||||
|
||||
// Leftover ledger claims are demoted to manual, mirroring /disconnect.
|
||||
expect(updatePayload(cashDemote)).toEqual({ bank_connection_id: null })
|
||||
|
||||
// Sync state is carried onto the survivor so neither the cron's
|
||||
// first-sync backfill nor the picker treats the renewal as a first connect.
|
||||
const carried = updatePayload(carryUpdate)
|
||||
expect(carried.last_synced_at).toBe('2026-08-01T00:00:00Z')
|
||||
expect(carried.initial_sync_completed_at).toBe('2026-06-01T00:00:00Z')
|
||||
expect(carried.initial_sync_requested_from).toBe('2026-01-01')
|
||||
expect(carried.initial_sync_lookback_days).toBe(365)
|
||||
|
||||
expect(emitSpy).toHaveBeenCalledWith({
|
||||
type: 'bank_connection.superseded',
|
||||
payload: {
|
||||
connectionId: 'old-1',
|
||||
supersededById: 'new-1',
|
||||
bankName: 'TestBank',
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('parks the sibling row BEFORE revoking its session at Enable Banking', async () => {
|
||||
// Revoking first and then failing to park would leave a live-looking row
|
||||
// whose session is already dead at the bank: the park update must come
|
||||
// first, in call order.
|
||||
const sequence: string[] = []
|
||||
mockDeleteSession.mockImplementation(async () => {
|
||||
sequence.push('deleteSession')
|
||||
})
|
||||
|
||||
const siblingSelect = makeChain({ data: [makeSibling()] })
|
||||
const revokeUpdate = makeChain({})
|
||||
const originalUpdate = revokeUpdate.update as ReturnType<typeof vi.fn>
|
||||
revokeUpdate.update = vi.fn((...args: unknown[]) => {
|
||||
sequence.push('parkUpdate')
|
||||
return originalUpdate(...args)
|
||||
})
|
||||
const txSelect = makeChain({ data: [] })
|
||||
const cashDemote = makeChain({})
|
||||
const newRowSelect = makeChain({ data: { last_synced_at: null, initial_sync_completed_at: null } })
|
||||
const carryUpdate = makeChain({})
|
||||
|
||||
const { client } = makeSupabase([
|
||||
{ table: 'bank_connections', chain: siblingSelect },
|
||||
{ table: 'bank_connections', chain: revokeUpdate },
|
||||
{ table: 'transactions', chain: txSelect },
|
||||
{ table: 'cash_accounts', chain: cashDemote },
|
||||
{ table: 'bank_connections', chain: newRowSelect },
|
||||
{ table: 'bank_connections', chain: carryUpdate },
|
||||
])
|
||||
|
||||
const result = await supersedeSiblingConnections(client, {
|
||||
...BASE_INPUT,
|
||||
newAccounts: NEW_ACCOUNTS,
|
||||
})
|
||||
|
||||
expect(result.supersededIds).toEqual(['old-1'])
|
||||
expect(sequence).toEqual(['parkUpdate', 'deleteSession'])
|
||||
})
|
||||
|
||||
it('skips the EB session revoke entirely when the park update fails', async () => {
|
||||
const siblingSelect = makeChain({ data: [makeSibling()] })
|
||||
const failedPark = makeChain({ error: { message: 'update refused' } })
|
||||
|
||||
// Only the lookup and the failed park run: no revoke, no re-point, no
|
||||
// demote, no sync-state carry.
|
||||
const { client, from } = makeSupabase([
|
||||
{ table: 'bank_connections', chain: siblingSelect },
|
||||
{ table: 'bank_connections', chain: failedPark },
|
||||
])
|
||||
|
||||
const result = await supersedeSiblingConnections(client, {
|
||||
...BASE_INPUT,
|
||||
newAccounts: NEW_ACCOUNTS,
|
||||
})
|
||||
|
||||
expect(result.supersededIds).toEqual([])
|
||||
expect(mockDeleteSession).not.toHaveBeenCalled()
|
||||
expect(from).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('never supersedes an ACTIVE sibling without IBAN overlap (separate login at the same bank)', async () => {
|
||||
const siblingSelect = makeChain({
|
||||
data: [
|
||||
makeSibling({
|
||||
id: 'other-login',
|
||||
status: 'active',
|
||||
accounts_data: [{ uid: 'uid-x', iban: 'SE9999999999999999999999', currency: 'SEK' }],
|
||||
}),
|
||||
],
|
||||
})
|
||||
const { client, from } = makeSupabase([{ table: 'bank_connections', chain: siblingSelect }])
|
||||
|
||||
const result = await supersedeSiblingConnections(client, {
|
||||
...BASE_INPUT,
|
||||
newAccounts: NEW_ACCOUNTS,
|
||||
})
|
||||
|
||||
expect(result.supersededIds).toEqual([])
|
||||
// Only the sibling lookup ran: nothing was updated, revoked, or re-pointed.
|
||||
expect(from).toHaveBeenCalledTimes(1)
|
||||
expect(mockDeleteSession).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('parks the row but keeps the EB session when other connections still share it', async () => {
|
||||
mockCountLiveSiblings.mockResolvedValue(2)
|
||||
|
||||
const siblingSelect = makeChain({ data: [makeSibling()] })
|
||||
const revokeUpdate = makeChain({})
|
||||
const txSelect = makeChain({ data: [] })
|
||||
const cashDemote = makeChain({})
|
||||
const newRowSelect = makeChain({ data: { last_synced_at: null, initial_sync_completed_at: null } })
|
||||
const carryUpdate = makeChain({})
|
||||
|
||||
const { client } = makeSupabase([
|
||||
{ table: 'bank_connections', chain: siblingSelect },
|
||||
{ table: 'bank_connections', chain: revokeUpdate },
|
||||
{ table: 'transactions', chain: txSelect },
|
||||
{ table: 'cash_accounts', chain: cashDemote },
|
||||
{ table: 'bank_connections', chain: newRowSelect },
|
||||
{ table: 'bank_connections', chain: carryUpdate },
|
||||
])
|
||||
|
||||
const result = await supersedeSiblingConnections(client, {
|
||||
...BASE_INPUT,
|
||||
newAccounts: NEW_ACCOUNTS,
|
||||
})
|
||||
|
||||
expect(result.supersededIds).toEqual(['old-1'])
|
||||
// A shared consent is never revoked upstream; the row is still parked.
|
||||
expect(mockDeleteSession).not.toHaveBeenCalled()
|
||||
expect(updatePayload(revokeUpdate).status).toBe('revoked')
|
||||
})
|
||||
|
||||
it('matches a DEAD sibling on bank identity alone only when neither side has IBANs', async () => {
|
||||
const siblingSelect = makeChain({
|
||||
data: [
|
||||
makeSibling({
|
||||
session_id: null,
|
||||
accounts_data: [{ uid: 'uid-old', currency: 'SEK' }],
|
||||
initial_sync_completed_at: null,
|
||||
last_synced_at: null,
|
||||
}),
|
||||
],
|
||||
})
|
||||
const revokeUpdate = makeChain({})
|
||||
const txSelect = makeChain({ data: [] })
|
||||
const cashDemote = makeChain({})
|
||||
const newRowSelect = makeChain({ data: { last_synced_at: null, initial_sync_completed_at: null } })
|
||||
|
||||
const { client } = makeSupabase([
|
||||
{ table: 'bank_connections', chain: siblingSelect },
|
||||
{ table: 'bank_connections', chain: revokeUpdate },
|
||||
{ table: 'transactions', chain: txSelect },
|
||||
{ table: 'cash_accounts', chain: cashDemote },
|
||||
{ table: 'bank_connections', chain: newRowSelect },
|
||||
])
|
||||
|
||||
const result = await supersedeSiblingConnections(client, {
|
||||
...BASE_INPUT,
|
||||
newAccounts: [{ uid: 'uid-new', currency: 'SEK' }],
|
||||
})
|
||||
|
||||
expect(result.supersededIds).toEqual(['old-1'])
|
||||
expect(updatePayload(revokeUpdate).superseded_by).toBe('new-1')
|
||||
})
|
||||
|
||||
it('does nothing without a bank name', async () => {
|
||||
const { client, from } = makeSupabase([])
|
||||
const result = await supersedeSiblingConnections(client, {
|
||||
...BASE_INPUT,
|
||||
bankName: null,
|
||||
newAccounts: NEW_ACCOUNTS,
|
||||
})
|
||||
expect(result.supersededIds).toEqual([])
|
||||
expect(from).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const h = vi.hoisted(() => ({ upload: vi.fn(), connector: { value: null as null | { baseUrl: string; key: string } } }))
|
||||
vi.mock('@/lib/core/documents/document-service', () => ({ uploadDocument: (...a: unknown[]) => h.upload(...a) }))
|
||||
vi.mock('@/lib/connect/instance/upstreams', () => ({
|
||||
bankConnectorMode: () => h.connector.value,
|
||||
CONNECTOR_COMPANY_HEADER: 'X-Connector-Company',
|
||||
}))
|
||||
vi.mock('../lib/api-client', async () => {
|
||||
const actual = await vi.importActual<typeof import('../lib/api-client')>('../lib/api-client')
|
||||
return { ...actual, getAllTransactionsWithRaw: vi.fn(), getAccountBalance: vi.fn().mockResolvedValue(null) }
|
||||
})
|
||||
|
||||
import { syncAccountTransactions } from '../lib/sync'
|
||||
import { SessionExpiredError, ConnectorSyncError } from '../lib/api-client'
|
||||
import { buildStableExternalIds } from '@/lib/transactions/external-id'
|
||||
import type { StoredAccount } from '../types'
|
||||
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const account: StoredAccount = {
|
||||
uid: 'acc-1',
|
||||
iban: 'SE45 5000 0000 0583 9825 7466',
|
||||
name: 'Företagskonto',
|
||||
currency: 'SEK',
|
||||
enabled: true,
|
||||
balance_updated_at: new Date().toISOString(),
|
||||
}
|
||||
|
||||
/** A supabase stand-in that answers the connection lookup with the session id. */
|
||||
const supabase = {
|
||||
from: (table: string) => {
|
||||
if (table !== 'bank_connections') throw new Error(`unexpected table ${table}`)
|
||||
const chain = { select: () => chain, eq: () => chain, maybeSingle: async () => ({ data: { session_id: 'sess-1' }, error: null }) }
|
||||
return chain
|
||||
},
|
||||
} as never
|
||||
|
||||
const remote = {
|
||||
transactions: [
|
||||
{ booking_date: '2026-09-01', amount: -125.5, currency: 'SEK', description: 'Kortköp ICA', counterparty_name: 'ICA Maxi', counterparty_account: 'SE45 5000 0000 0583 9825 7466', reference: null, merchant_category_code: '5411', bank_transaction_code: 'PMNT/CCRD', proprietary_bank_transaction_code: null },
|
||||
{ booking_date: '2026-09-01', amount: -125.5, currency: 'SEK', description: 'Kortköp ICA', counterparty_name: 'ICA Maxi', counterparty_account: '123456789', reference: null, merchant_category_code: null, bank_transaction_code: null, proprietary_bank_transaction_code: null },
|
||||
],
|
||||
raw_pages: ['{"page":1}', '{"page":2}'],
|
||||
skipped_pending: 1,
|
||||
returned_min_booking_date: '2026-09-01',
|
||||
returned_max_booking_date: '2026-09-01',
|
||||
effective_date_from: null,
|
||||
pages: 2,
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
h.connector.value = { baseUrl: 'https://connect.accounted.se/api/connect/bank', key: 'gnubok_ck_test' }
|
||||
h.upload.mockResolvedValue({ id: 'doc' })
|
||||
})
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
describe('syncAccountTransactions in connector mode', () => {
|
||||
it('calls the connector sync operation and ingests with the same stored keys the direct path mints', async () => {
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify(remote), { status: 200, headers: { 'content-type': 'application/json' } }))
|
||||
const ingest = vi.fn().mockResolvedValue({ imported: 2, duplicates: 0, errors: 0, reconciled: 0, auto_categorized: 0, auto_matched_invoices: 0, transaction_ids: [] })
|
||||
const result = await syncAccountTransactions(supabase, 'company-1', 'user-1', 'conn-1', account, '2026-08-01', '2026-09-03', ingest, { strategy: 'longest' })
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
|
||||
expect(url).toBe('https://connect.accounted.se/api/connect/bank/sync')
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer gnubok_ck_test')
|
||||
expect((init.headers as Record<string, string>)['X-Connector-Company']).toBe('company-1')
|
||||
expect(JSON.parse(init.body as string)).toEqual({ session_id: 'sess-1', account_uid: 'acc-1', account_currency: 'SEK', date_from: '2026-08-01', date_to: '2026-09-03', strategy: 'longest' })
|
||||
|
||||
const raw = ingest.mock.calls[0][3] as Array<{ external_id: string; date: string; amount: number; counterparty_iban: string | null; counterparty_account: string | null; import_source: string; bank_connection_id: string }>
|
||||
const expectedIds = buildStableExternalIds('eb', 'SE4550000000058398257466', [{ date: '2026-09-01', amount: -125.5 }, { date: '2026-09-01', amount: -125.5 }])
|
||||
expect(raw.map((r) => r.external_id)).toEqual(expectedIds)
|
||||
expect(raw[0]).toMatchObject({ date: '2026-09-01', amount: -125.5, counterparty_iban: 'SE4550000000058398257466', counterparty_account: null, import_source: 'enable_banking', bank_connection_id: 'conn-1' })
|
||||
expect(raw[1]).toMatchObject({ counterparty_iban: null, counterparty_account: '123456789' })
|
||||
expect(account.dedup_scope).toBe('SE4550000000058398257466')
|
||||
expect(h.upload).toHaveBeenCalledTimes(2)
|
||||
expect(result).toMatchObject({ imported: 2, returnedMinBookingDate: '2026-09-01', returnedMaxBookingDate: '2026-09-01' })
|
||||
})
|
||||
|
||||
it('maps the connector 410 onto SessionExpiredError so callers flip the connection to expired', async () => {
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ error: 'expired', code: 'CONNECTOR_BANK_SESSION_EXPIRED', retryable: false }), { status: 410 }))
|
||||
await expect(syncAccountTransactions(supabase, 'company-1', 'user-1', 'conn-1', account, '2026-08-01', '2026-09-03', vi.fn())).rejects.toBeInstanceOf(SessionExpiredError)
|
||||
})
|
||||
|
||||
it('surfaces other connector failures as ConnectorSyncError, never as a dead session', async () => {
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ error: 'busy', code: 'CONNECTOR_RATE_LIMITED' }), { status: 429 }))
|
||||
const failed = syncAccountTransactions(supabase, 'company-1', 'user-1', 'conn-1', account, '2026-08-01', '2026-09-03', vi.fn())
|
||||
await expect(failed).rejects.toThrow(/CONNECTOR_RATE_LIMITED/)
|
||||
await expect(failed).rejects.toBeInstanceOf(ConnectorSyncError)
|
||||
await expect(failed).rejects.toMatchObject({ status: 429, code: 'CONNECTOR_RATE_LIMITED' })
|
||||
await expect(failed).rejects.not.toBeInstanceOf(SessionExpiredError)
|
||||
})
|
||||
|
||||
it('refuses an unexpected response shape and names the failing fields', async () => {
|
||||
// 2026-09-04: the service answered 200 with a body the contract rejects
|
||||
// and four canary companies were parked in error with renewal advice.
|
||||
// The field paths are what lets the service side be fixed.
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({
|
||||
transactions: [{ booking_date: '2026-09-03', amount: '12.50', currency: 'SEK', description: 'x' }],
|
||||
raw_pages: [],
|
||||
skipped_pending: 0,
|
||||
returned_min_booking_date: null,
|
||||
returned_max_booking_date: null,
|
||||
effective_date_from: null,
|
||||
pages: 1,
|
||||
}), { status: 200 }))
|
||||
const failed = syncAccountTransactions(supabase, 'company-1', 'user-1', 'conn-1', account, '2026-08-01', '2026-09-03', vi.fn())
|
||||
await expect(failed).rejects.toThrow(/unexpected shape/)
|
||||
await expect(failed).rejects.toBeInstanceOf(ConnectorSyncError)
|
||||
const err = await failed.catch((e: unknown) => e) as ConnectorSyncError
|
||||
expect(err.code).toBe('CONNECTOR_BAD_SHAPE')
|
||||
expect(err.issues?.some((i) => i.startsWith('transactions.0.amount'))).toBe(true)
|
||||
expect(err.issues?.some((i) => i.startsWith('transactions.0.counterparty_name'))).toBe(true)
|
||||
expect(warn).toHaveBeenCalledWith(
|
||||
'[enable-banking] Connector sync response failed the wire contract',
|
||||
expect.objectContaining({ connectionId: 'conn-1', accountUid: 'acc-1', issues: err.issues }),
|
||||
)
|
||||
warn.mockRestore()
|
||||
})
|
||||
|
||||
it('wraps the timeout abort as ConnectorSyncError CONNECTOR_TIMEOUT', async () => {
|
||||
const abort = new Error('This operation was aborted')
|
||||
abort.name = 'AbortError'
|
||||
fetchMock.mockRejectedValueOnce(abort)
|
||||
const failed = syncAccountTransactions(supabase, 'company-1', 'user-1', 'conn-1', account, '2026-08-01', '2026-09-03', vi.fn())
|
||||
await expect(failed).rejects.toBeInstanceOf(ConnectorSyncError)
|
||||
await expect(failed).rejects.toMatchObject({ status: null, code: 'CONNECTOR_TIMEOUT' })
|
||||
})
|
||||
|
||||
it('wraps a transport failure as ConnectorSyncError', async () => {
|
||||
fetchMock.mockRejectedValueOnce(new TypeError('fetch failed'))
|
||||
const failed = syncAccountTransactions(supabase, 'company-1', 'user-1', 'conn-1', account, '2026-08-01', '2026-09-03', vi.fn())
|
||||
await expect(failed).rejects.toBeInstanceOf(ConnectorSyncError)
|
||||
await expect(failed).rejects.toMatchObject({ status: null, code: 'CONNECTOR_TRANSPORT' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('connector timeout covers the body read', () => {
|
||||
it('aborts a response whose body stalls instead of hanging past the budget', async () => {
|
||||
vi.useFakeTimers()
|
||||
try {
|
||||
const stalled = { ok: true, status: 200, text: () => new Promise<string>(() => {}) } as unknown as Response
|
||||
fetchMock.mockImplementationOnce(() => Promise.resolve(stalled))
|
||||
const pending = syncAccountTransactions(supabase, 'company-1', 'user-1', 'conn-1', account, '2026-08-01', '2026-09-03', vi.fn())
|
||||
// Only the abort signal can end this: the body promise never settles.
|
||||
const raced = Promise.race([pending.then(() => 'settled', () => 'settled'), new Promise((r) => setTimeout(r, 200_000, 'timed-out'))])
|
||||
await vi.advanceTimersByTimeAsync(130_000)
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const signal = (fetchMock.mock.calls[0] as [string, RequestInit])[1].signal as AbortSignal
|
||||
expect(signal.aborted).toBe(true)
|
||||
await vi.advanceTimersByTimeAsync(200_000)
|
||||
await raced
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
import { enableBankingExtension } from '../index'
|
||||
import type { ExtensionContext } from '@/lib/extensions/types'
|
||||
import type { StoredAccount } from '../types'
|
||||
|
||||
const syncRoute = enableBankingExtension.apiRoutes?.find(
|
||||
r => r.method === 'POST' && r.path === '/sync'
|
||||
)
|
||||
|
||||
if (!syncRoute) {
|
||||
throw new Error('POST /sync route not registered on enable-banking extension')
|
||||
}
|
||||
|
||||
function makeContext(connectionRow: {
|
||||
status: string
|
||||
accounts_data: StoredAccount[]
|
||||
}): ExtensionContext {
|
||||
const supabase = {
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } }, error: null }),
|
||||
},
|
||||
from: vi.fn(() => ({
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
single: vi.fn().mockResolvedValue({
|
||||
data: { id: 'conn-1', company_id: 'company-1', ...connectionRow },
|
||||
error: null,
|
||||
}),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: null, error: null }),
|
||||
})),
|
||||
}
|
||||
|
||||
return {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
extensionId: 'enable-banking',
|
||||
requestId: 'req_test',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
supabase: supabase as any,
|
||||
emit: vi.fn().mockResolvedValue(undefined),
|
||||
settings: { get: vi.fn(), set: vi.fn(), getAll: vi.fn() } as never,
|
||||
storage: {} as never,
|
||||
log: {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
} as never,
|
||||
services: {} as never,
|
||||
}
|
||||
}
|
||||
|
||||
function makeRequest(): Request {
|
||||
return new Request('http://localhost/api/extensions/ext/enable-banking/sync', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ connection_id: 'conn-1' }),
|
||||
})
|
||||
}
|
||||
|
||||
describe('POST /sync (enable-banking): account filtering', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('returns 400 when status is pending_selection', async () => {
|
||||
const ctx = makeContext({
|
||||
status: 'pending_selection',
|
||||
accounts_data: [{ uid: 'acc-1', currency: 'SEK', enabled: true }],
|
||||
})
|
||||
|
||||
const res = await syncRoute.handler(makeRequest(), ctx)
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toMatch(/not active/i)
|
||||
})
|
||||
|
||||
it('returns 400 when every account is disabled', async () => {
|
||||
const ctx = makeContext({
|
||||
status: 'active',
|
||||
accounts_data: [
|
||||
{ uid: 'acc-1', currency: 'SEK', enabled: false },
|
||||
{ uid: 'acc-2', currency: 'SEK', enabled: false },
|
||||
],
|
||||
})
|
||||
|
||||
const res = await syncRoute.handler(makeRequest(), ctx)
|
||||
expect(res.status).toBe(400)
|
||||
const body = await res.json()
|
||||
expect(body.error).toMatch(/Inga konton är valda/i)
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,401 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { cn, formatDate } from '@/lib/utils'
|
||||
import { ChevronRight, Loader2, MoreHorizontal } from 'lucide-react'
|
||||
import { getConnectionUiState } from '../lib/connection-state'
|
||||
import { describeClaimedElsewhere, partitionByClaim } from '../lib/claimed-accounts'
|
||||
import type { BankConnection } from '@/types'
|
||||
|
||||
interface BankConnectionStatusProps {
|
||||
connection: BankConnection
|
||||
onSync: (connectionId: string) => void
|
||||
onDisconnect: (connectionId: string) => void
|
||||
onReconnect?: (connection: BankConnection, psuType?: 'personal' | 'business') => void
|
||||
onManageAccounts?: (connectionId: string) => void
|
||||
isSyncing?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* One bank connection as a flat hairline row (Fönster settings language):
|
||||
* identity + state on one line, exactly ONE primary action decided by the
|
||||
* derived UI state, every secondary action behind a "..." menu, and the
|
||||
* details (accounts, IBAN, balances, initial backfill) behind a collapsed
|
||||
* disclosure. The page-level attention sentence lives in the panel, not
|
||||
* here (design convention 6: one .attn per page).
|
||||
*/
|
||||
export function BankConnectionStatus({
|
||||
connection,
|
||||
onSync,
|
||||
onDisconnect,
|
||||
onReconnect,
|
||||
onManageAccounts,
|
||||
isSyncing = false,
|
||||
}: BankConnectionStatusProps) {
|
||||
const [now] = useState(() => Date.now())
|
||||
const [detailsOpen, setDetailsOpen] = useState(false)
|
||||
|
||||
const uiState = getConnectionUiState(connection, now)
|
||||
|
||||
// Parse accounts from connection
|
||||
const accounts = (connection.accounts_data as Array<{
|
||||
uid: string
|
||||
iban?: string
|
||||
name?: string
|
||||
currency: string
|
||||
balance?: number
|
||||
balance_updated_at?: string
|
||||
enabled?: boolean
|
||||
claimed_by_company_id?: string
|
||||
claimed_by_company_name?: string
|
||||
}>) || []
|
||||
// Accounts another of the user's companies books (one SEB consent covers
|
||||
// every company the signer represents) are not this company's accounts:
|
||||
// they are left out of the list and the count, and summarised in one line.
|
||||
const { own: ownAccounts, claimedElsewhere } = partitionByClaim(accounts)
|
||||
const enabledCount = ownAccounts.filter((a) => a.enabled !== false).length
|
||||
|
||||
function formatBalanceAge(updatedAt: string): string {
|
||||
const hoursAgo = Math.floor((now - new Date(updatedAt).getTime()) / (1000 * 60 * 60))
|
||||
if (hoursAgo < 1) return 'Nyss uppdaterat'
|
||||
if (hoursAgo < 24) return `${hoursAgo}h sedan`
|
||||
const daysAgo = Math.floor(hoursAgo / 24)
|
||||
return `${daysAgo}d sedan`
|
||||
}
|
||||
|
||||
// In-flight authorization: the row exists but the user is still at the
|
||||
// bank. Render it as a quiet spinner row instead of hiding it (the connect
|
||||
// button lock alone made this state invisible).
|
||||
if (uiState === 'pending') {
|
||||
return (
|
||||
<div className="flex min-h-10 flex-wrap items-center gap-x-3 gap-y-1 border-b border-border px-1 py-3">
|
||||
<span className="text-sm font-medium">{connection.bank_name}</span>
|
||||
<span className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
Väntar på banken…
|
||||
</span>
|
||||
<span className="ml-auto shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
onClick={() => onDisconnect(connection.id)}
|
||||
>
|
||||
Avbryt
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Status display: muted text for the normal state, Badge only when the row
|
||||
// deviates (design convention 5).
|
||||
type StatusEntry =
|
||||
| { kind: 'text'; label: string }
|
||||
| { kind: 'badge'; label: string; variant: 'warning' | 'destructive' | 'secondary' }
|
||||
const statusDisplay: StatusEntry = (() => {
|
||||
switch (uiState) {
|
||||
case 'pending_selection':
|
||||
return { kind: 'badge', label: 'Välj konton', variant: 'warning' }
|
||||
case 'error':
|
||||
return { kind: 'badge', label: 'Fel', variant: 'destructive' }
|
||||
case 'expired':
|
||||
return { kind: 'badge', label: 'Utgånget samtycke', variant: 'warning' }
|
||||
case 'expiring':
|
||||
return { kind: 'badge', label: 'Går ut snart', variant: 'warning' }
|
||||
default:
|
||||
return { kind: 'text', label: 'Aktiv' }
|
||||
}
|
||||
})()
|
||||
|
||||
const isExpired = uiState === 'expired'
|
||||
const canReconnect = !!onReconnect
|
||||
const canSync = connection.status === 'active' || connection.status === 'error'
|
||||
|
||||
// Exactly ONE primary action per state; everything else goes in the menu.
|
||||
function renderPrimaryAction() {
|
||||
switch (uiState) {
|
||||
case 'pending_selection':
|
||||
return onManageAccounts ? (
|
||||
<Button size="sm" onClick={() => onManageAccounts(connection.id)}>
|
||||
Välj konton
|
||||
</Button>
|
||||
) : null
|
||||
case 'error':
|
||||
return (
|
||||
<Button size="sm" onClick={() => onSync(connection.id)} disabled={isSyncing}>
|
||||
{isSyncing ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
|
||||
Försök igen
|
||||
</Button>
|
||||
)
|
||||
case 'expired':
|
||||
case 'expiring':
|
||||
// No psu override: the server reuses the stored psu_type, so renewal
|
||||
// is one click. Switching account type lives in the menu.
|
||||
return canReconnect ? (
|
||||
<Button size="sm" onClick={() => onReconnect!(connection)}>
|
||||
Förnya samtycke
|
||||
</Button>
|
||||
) : null
|
||||
case 'stale':
|
||||
case 'never_synced':
|
||||
return (
|
||||
<Button size="sm" onClick={() => onSync(connection.id)} disabled={isSyncing}>
|
||||
{isSyncing ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
|
||||
Synka nu
|
||||
</Button>
|
||||
)
|
||||
default:
|
||||
// Healthy active row: no primary needed; sync stays reachable as a
|
||||
// quiet ghost button.
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
onClick={() => onSync(connection.id)}
|
||||
disabled={isSyncing}
|
||||
>
|
||||
{isSyncing ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
|
||||
Synka
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const primaryIsSync = uiState === 'stale' || uiState === 'never_synced' || uiState === 'active' || uiState === 'error'
|
||||
const primaryIsReconnect = uiState === 'expired' || uiState === 'expiring'
|
||||
|
||||
return (
|
||||
<div className="border-b border-border px-1 py-3">
|
||||
{/* Main line: identity + state left, one primary action + menu right */}
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<span className="text-sm font-medium">{connection.bank_name}</span>
|
||||
{statusDisplay.kind === 'badge' ? (
|
||||
<Badge variant={statusDisplay.variant}>{statusDisplay.label}</Badge>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">{statusDisplay.label}</span>
|
||||
)}
|
||||
{uiState === 'pending_selection' ? (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{ownAccounts.length > 0
|
||||
? `${ownAccounts.length} konton tillgängliga: inga transaktioner synkas ännu`
|
||||
: claimedElsewhere.length > 0
|
||||
? 'Alla konton i kopplingen synkas redan i andra bolag'
|
||||
: 'Inga konton i kopplingen: inga transaktioner synkas ännu'}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{connection.last_synced_at && (
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
Synkad {formatDate(connection.last_synced_at)}
|
||||
</span>
|
||||
)}
|
||||
{connection.consent_expires && !isExpired && (
|
||||
<span className="text-xs text-muted-foreground tabular-nums">
|
||||
Samtycke till {formatDate(connection.consent_expires)}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<span className="ml-auto flex shrink-0 items-center gap-1">
|
||||
{renderPrimaryAction()}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
aria-label={`Fler åtgärder för ${connection.bank_name}`}
|
||||
>
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{uiState === 'pending_selection' ? (
|
||||
<DropdownMenuItem onSelect={() => onDisconnect(connection.id)}>
|
||||
Avbryt
|
||||
</DropdownMenuItem>
|
||||
) : (
|
||||
<>
|
||||
{onManageAccounts && (
|
||||
<DropdownMenuItem onSelect={() => onManageAccounts(connection.id)}>
|
||||
Välj konton
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canSync && !primaryIsSync && (
|
||||
<DropdownMenuItem onSelect={() => onSync(connection.id)}>
|
||||
Synka
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canReconnect && !primaryIsReconnect && (
|
||||
<DropdownMenuItem onSelect={() => onReconnect!(connection)}>
|
||||
Förnya samtycke
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{canReconnect && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{/* Some banks (notably Handelsbanken) only sign with one
|
||||
account type: keep the explicit choice reachable even
|
||||
though the primary renew reuses the stored type. */}
|
||||
<DropdownMenuLabel className="text-xs font-normal normal-case tracking-normal">
|
||||
Förnya och logga in som
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuItem onSelect={() => onReconnect!(connection, 'business')}>
|
||||
Företagskonto
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => onReconnect!(connection, 'personal')}>
|
||||
Privatkonto
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/import?mode=bank">Importera bankfil</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive"
|
||||
onSelect={() => onDisconnect(connection.id)}
|
||||
>
|
||||
Koppla från
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Error detail: the page-level .attn owns the ochre sentence; the
|
||||
row's own message stays quiet. */}
|
||||
{uiState === 'error' && connection.error_message && (
|
||||
<p className="mt-1 text-[12.5px] leading-relaxed text-muted-foreground">
|
||||
{connection.error_message}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Details behind a collapsed disclosure: accounts, IBAN, balances,
|
||||
initial backfill. Expired rows never show balances (stale numbers
|
||||
would read as current). */}
|
||||
{accounts.length > 0 && uiState !== 'pending_selection' && (
|
||||
<div className="mt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDetailsOpen((v) => !v)}
|
||||
aria-expanded={detailsOpen}
|
||||
className="flex min-h-9 items-center gap-1 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground"
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn('h-3.5 w-3.5 transition-transform duration-150', detailsOpen && 'rotate-90')}
|
||||
/>
|
||||
<span className="tabular-nums">
|
||||
{enabledCount} av {ownAccounts.length} konton synkas
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{detailsOpen && (
|
||||
<div className="ml-3 border-l border-border pl-4">
|
||||
{/* Initial backfill summary: what the bank actually returned vs
|
||||
what we asked for. Diagnostics, so it lives in the details. */}
|
||||
{!isExpired &&
|
||||
connection.initial_sync_completed_at &&
|
||||
connection.initial_sync_requested_from &&
|
||||
(() => {
|
||||
const requested = connection.initial_sync_requested_from
|
||||
const min = connection.initial_sync_returned_min_date
|
||||
const max = connection.initial_sync_returned_max_date
|
||||
// Truncation = bank returned less history than requested.
|
||||
// 7-day grace for off-by-one + weekend posting differences.
|
||||
let truncated = false
|
||||
if (min && requested) {
|
||||
const requestedTime = new Date(requested).getTime()
|
||||
const minTime = new Date(min).getTime()
|
||||
truncated = minTime - requestedTime > 7 * 24 * 60 * 60 * 1000
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2 py-2 text-xs text-muted-foreground">
|
||||
<span>
|
||||
Initial historik:{' '}
|
||||
<span className="tabular-nums">
|
||||
{min ? formatDate(min) : '-'} → {max ? formatDate(max) : '-'}
|
||||
</span>{' '}
|
||||
(begärde <span className="tabular-nums">{formatDate(requested)}</span>)
|
||||
</span>
|
||||
{truncated && (
|
||||
<Badge variant="outline">
|
||||
Bankens API returnerade kortare period än begärt: använd SIE-import för äldre data
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})()}
|
||||
|
||||
{ownAccounts.map((account) => {
|
||||
const isDisabled = account.enabled === false
|
||||
return (
|
||||
<div
|
||||
key={account.uid}
|
||||
className={cn(
|
||||
'flex flex-wrap items-center gap-x-3 gap-y-1 py-2',
|
||||
isDisabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
<span className="text-sm">
|
||||
{account.name || account.iban || 'Okänt konto'}
|
||||
</span>
|
||||
{isDisabled && (
|
||||
<Badge variant="outline" className="text-[10px] uppercase tracking-wide text-muted-foreground">
|
||||
Synkas ej
|
||||
</Badge>
|
||||
)}
|
||||
{account.iban && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{account.iban.replace(/(.{4})/g, '$1 ').trim()}
|
||||
</span>
|
||||
)}
|
||||
{!isExpired && account.balance !== undefined && (
|
||||
<span className="ml-auto inline-flex shrink-0 items-baseline gap-2">
|
||||
{account.balance_updated_at && (
|
||||
<span className="text-[10px] text-muted-foreground">
|
||||
{formatBalanceAge(account.balance_updated_at)}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-sm tabular-nums">
|
||||
{new Intl.NumberFormat('sv-SE', {
|
||||
style: 'currency',
|
||||
currency: account.currency,
|
||||
}).format(account.balance)}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
{/* Sibling companies' accounts carried by this consent: one
|
||||
muted line, never rows. Moving one here is done in the
|
||||
account picker ("Hantera konton"), where it is a deliberate
|
||||
tick inside a disclosure. */}
|
||||
{claimedElsewhere.length > 0 && (
|
||||
<div className="py-2 text-xs text-muted-foreground tabular-nums" data-ph-mask="">
|
||||
{describeClaimedElsewhere(claimedElsewhere)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { ChevronRight, Landmark, Loader2, Search } from 'lucide-react'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { matchBankByName } from '../lib/bank-match'
|
||||
|
||||
export interface Bank {
|
||||
name: string
|
||||
country: string
|
||||
logo?: string
|
||||
bic?: string
|
||||
}
|
||||
|
||||
const POPULAR_SWEDISH_BANKS = [
|
||||
'Swedbank',
|
||||
'SEB',
|
||||
'Nordea',
|
||||
'Handelsbanken',
|
||||
'Danske Bank',
|
||||
]
|
||||
|
||||
interface BankSelectorProps {
|
||||
onConnect: (bank: Bank) => void
|
||||
onPsuTypeDetected?: (psuType: 'personal' | 'business') => void
|
||||
isConnecting?: boolean
|
||||
connectingBankName?: string | null
|
||||
className?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Eyebrow above a list section: same micro-label and same px-1 inset as the
|
||||
* SettingsGroup eyebrow, so the two sit on one left edge.
|
||||
*/
|
||||
function SectionLabel({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<h3 className="px-1 pb-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
|
||||
{children}
|
||||
</h3>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 32px leading mark for a row. Real bank logos are drawn for a white
|
||||
* background, so they sit on a white chip (same treatment as LogoMark in
|
||||
* components/onboarding/NewUserChecklist.tsx); the no-logo fallback uses the
|
||||
* neutral surface instead, which keeps the icon readable in dark mode.
|
||||
* While connecting, the mark is replaced by a bare spinner: quiet inline
|
||||
* state, no tint, no box.
|
||||
*/
|
||||
function BankMark({ bank, connecting }: { bank: Bank; connecting: boolean }) {
|
||||
if (connecting) {
|
||||
return (
|
||||
<span className="flex h-8 w-8 shrink-0 items-center justify-center">
|
||||
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" aria-hidden="true" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
if (bank.logo) {
|
||||
return (
|
||||
<span className="flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-md border border-border bg-white">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={bank.logo} alt="" className="h-6 w-6 object-contain" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-border bg-secondary">
|
||||
<Landmark className="h-4 w-4 text-muted-foreground" aria-hidden="true" />
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function BankRow({ bank, isConnecting, connectingBankName, onConnect }: {
|
||||
bank: Bank
|
||||
isConnecting: boolean
|
||||
connectingBankName: string | null
|
||||
onConnect: (bank: Bank) => void
|
||||
}) {
|
||||
const connecting = isConnecting && connectingBankName === bank.name
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
disabled={isConnecting}
|
||||
onClick={() => onConnect(bank)}
|
||||
className={cn(
|
||||
// 32px mark + py-2 keeps the row at 48px: comfortably past the 44px
|
||||
// touch target without turning back into a card.
|
||||
'flex w-full items-center gap-3 px-1 py-2 text-left transition-colors duration-150',
|
||||
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',
|
||||
!isConnecting && 'hover:bg-secondary/60',
|
||||
isConnecting && 'cursor-not-allowed',
|
||||
isConnecting && !connecting && 'opacity-50',
|
||||
)}
|
||||
>
|
||||
<BankMark bank={bank} connecting={connecting} />
|
||||
<span
|
||||
className={cn(
|
||||
'min-w-0 flex-1 truncate text-sm',
|
||||
connecting ? 'text-muted-foreground' : 'text-foreground',
|
||||
)}
|
||||
>
|
||||
{bank.name}
|
||||
</span>
|
||||
{/* No per-row "Ansluter..." text: the spinner mark carries the row's
|
||||
share of the state, the wording lives once in the line below the
|
||||
list. */}
|
||||
{!connecting && (
|
||||
<ChevronRight className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export function BankSelector({
|
||||
onConnect,
|
||||
onPsuTypeDetected,
|
||||
isConnecting = false,
|
||||
connectingBankName = null,
|
||||
className,
|
||||
}: BankSelectorProps) {
|
||||
const [banks, setBanks] = useState<Bank[]>([])
|
||||
const [isSandbox, setIsSandbox] = useState(true)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
const autoStartHandled = useRef(false)
|
||||
|
||||
// Deep-link preselect (?bank=<name>, set by the MCP connect card when the
|
||||
// user already named their bank in chat): auto-start that bank's consent
|
||||
// the way clicking its row would, so the flow feels like Skatteverket's
|
||||
// one-click authorize. The param is stripped immediately so an abort at
|
||||
// the bank followed by back-navigation does not silently re-launch; an
|
||||
// unknown or ambiguous name just prefills the search instead of guessing.
|
||||
// Guards further down (duplicate pending, renew-instead-409) stay fully
|
||||
// interactive because this runs through the same onConnect handler.
|
||||
useEffect(() => {
|
||||
if (autoStartHandled.current || isLoading || banks.length === 0 || isConnecting) return
|
||||
const params = new URLSearchParams(window.location.search)
|
||||
const requested = params.get('bank')
|
||||
if (!requested) {
|
||||
autoStartHandled.current = true
|
||||
return
|
||||
}
|
||||
autoStartHandled.current = true
|
||||
params.delete('bank')
|
||||
const query = params.toString()
|
||||
window.history.replaceState(
|
||||
null,
|
||||
'',
|
||||
`${window.location.pathname}${query ? `?${query}` : ''}${window.location.hash}`
|
||||
)
|
||||
const match = matchBankByName(banks, requested)
|
||||
if (match) {
|
||||
onConnect(match)
|
||||
} else {
|
||||
setSearchQuery(requested)
|
||||
searchRef.current?.focus()
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- one-shot after the bank list arrives
|
||||
}, [isLoading, banks, isConnecting])
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchBanks() {
|
||||
try {
|
||||
const res = await fetch('/api/extensions/ext/enable-banking/banks')
|
||||
if (!res.ok) {
|
||||
// A non-OK response (500, or the 403 capability gate) has no `banks`
|
||||
// array; without this guard it falls through to the "no banks
|
||||
// available" empty state, which misreads as a successful-but-empty
|
||||
// load rather than a failure.
|
||||
setError('Kunde inte ladda banker')
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
if (data.banks) {
|
||||
setBanks(data.banks as Bank[])
|
||||
}
|
||||
if (data.sandbox !== undefined) {
|
||||
setIsSandbox(data.sandbox)
|
||||
}
|
||||
if (data.psu_type && onPsuTypeDetected) {
|
||||
onPsuTypeDetected(data.psu_type)
|
||||
}
|
||||
} catch {
|
||||
setError('Kunde inte ladda banker')
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
fetchBanks()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps -- onPsuTypeDetected is a stable setter, only run on mount
|
||||
}, [onPsuTypeDetected])
|
||||
|
||||
const filteredBanks = banks.filter((bank) =>
|
||||
bank.name.toLowerCase().includes(searchQuery.toLowerCase())
|
||||
)
|
||||
|
||||
const showPopular = !isSandbox && !searchQuery
|
||||
const popularBanks = showPopular
|
||||
? filteredBanks.filter((bank) => POPULAR_SWEDISH_BANKS.includes(bank.name))
|
||||
: []
|
||||
const otherBanks = showPopular
|
||||
? filteredBanks.filter((bank) => !POPULAR_SWEDISH_BANKS.includes(bank.name))
|
||||
: filteredBanks
|
||||
|
||||
return (
|
||||
<div className={cn('space-y-4', className)}>
|
||||
{/* Search input */}
|
||||
<div className="relative">
|
||||
<Search
|
||||
className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<Input
|
||||
ref={searchRef}
|
||||
type="text"
|
||||
placeholder="Sök efter din bank..."
|
||||
aria-label="Sök efter din bank"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="pl-10"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Loading state. The spinner is decorative, so the state needs a text
|
||||
equivalent: without it a screen-reader user gets silence between
|
||||
submitting and the list appearing. */}
|
||||
{isLoading && (
|
||||
<div role="status" className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" aria-hidden="true" />
|
||||
<span className="sr-only">Laddar banker...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error state: one quiet line, not a tinted panel. role="alert" so the
|
||||
failure is announced rather than only redrawn. */}
|
||||
{error && (
|
||||
<p role="alert" className="px-1 text-[12.5px] leading-relaxed text-destructive">{error}</p>
|
||||
)}
|
||||
|
||||
{/* Bank list */}
|
||||
{!isLoading && !error && (
|
||||
<>
|
||||
{filteredBanks.length === 0 ? (
|
||||
<div className="px-1 py-8 text-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{searchQuery
|
||||
? `Inga banker matchar "${searchQuery}"`
|
||||
: 'Inga banker tillgängliga'}
|
||||
</p>
|
||||
{searchQuery && (
|
||||
<p className="mt-1 text-xs text-muted-foreground/70">
|
||||
Försök med ett annat sökord
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
// -mx-1 cancels the px-1 the settings panel wraps this in, so the
|
||||
// hairlines and the hover band run the full width of the settings
|
||||
// content, level with the SettingsRow hairlines above; the rows'
|
||||
// own px-1 then puts the bank mark on the same left edge as the
|
||||
// settings labels.
|
||||
// max-h-96 is exactly eight 48px rows: a scroll box with a reason.
|
||||
<div className="-mx-1 max-h-96 space-y-6 overflow-y-auto overscroll-contain">
|
||||
{popularBanks.length > 0 && (
|
||||
<section>
|
||||
<SectionLabel>Populära banker</SectionLabel>
|
||||
<div className="divide-y divide-border border-t border-border">
|
||||
{popularBanks.map((bank) => (
|
||||
<BankRow key={bank.name} bank={bank} isConnecting={isConnecting} connectingBankName={connectingBankName} onConnect={onConnect} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{otherBanks.length > 0 && (
|
||||
<section>
|
||||
{popularBanks.length > 0 && <SectionLabel>Alla banker</SectionLabel>}
|
||||
<div className="divide-y divide-border border-t border-border">
|
||||
{otherBanks.map((bank) => (
|
||||
<BankRow key={bank.name} bank={bank} isConnecting={isConnecting} connectingBankName={connectingBankName} onConnect={onConnect} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* The single worded home of the connecting state: one muted line rather
|
||||
than a tinted bordered panel, and it names the bank so the state is
|
||||
still readable when the chosen row has scrolled out of view. */}
|
||||
{isConnecting && connectingBankName && (
|
||||
<p role="status" className="flex items-center gap-2 px-1 text-[12.5px] leading-relaxed text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 shrink-0 animate-spin" aria-hidden="true" />
|
||||
Ansluter till {connectingBankName}...
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useState } from 'react'
|
||||
import Link from 'next/link'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Loader2, CheckCircle2, AlertTriangle } from 'lucide-react'
|
||||
import { daysBetween } from '@/lib/company/fiscal-year'
|
||||
import type { StoredAccount } from '../types'
|
||||
|
||||
export interface SyncProgressSummary {
|
||||
imported: number
|
||||
duplicates: number
|
||||
/**
|
||||
* Rows the post-backfill reconciliation sweep linked to existing verifikat
|
||||
* (renewal over an already-bookkept period). Optional: responses from before
|
||||
* the sweep existed omit it.
|
||||
*/
|
||||
auto_matched?: number
|
||||
requested_from: string
|
||||
returned_min_date: string | null
|
||||
returned_max_date: string | null
|
||||
}
|
||||
|
||||
export interface SyncProgressError {
|
||||
message: string
|
||||
}
|
||||
|
||||
export type SyncProgressState =
|
||||
| { kind: 'syncing' }
|
||||
| { kind: 'done'; summary: SyncProgressSummary }
|
||||
| { kind: 'failed'; error: SyncProgressError }
|
||||
|
||||
interface BankSyncProgressDialogProps {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
bankName: string
|
||||
accounts: StoredAccount[]
|
||||
state: SyncProgressState
|
||||
}
|
||||
|
||||
// Past this point the sync has run longer than the promised "up to a minute".
|
||||
// We stop hard-locking the modal so the user isn't trapped: the request keeps
|
||||
// running server-side (idempotent) and completion still resolves the state.
|
||||
const GRACE_SEC = 75
|
||||
|
||||
function formatElapsed(sec: number): string {
|
||||
if (sec < 60) return `${sec}s`
|
||||
return `${Math.floor(sec / 60)}m ${String(sec % 60).padStart(2, '0')}s`
|
||||
}
|
||||
|
||||
export function BankSyncProgressDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
bankName,
|
||||
accounts,
|
||||
state,
|
||||
}: BankSyncProgressDialogProps) {
|
||||
const enabledAccounts = accounts.filter((a) => a.enabled !== false)
|
||||
|
||||
// Tick a visible elapsed counter while syncing so a slow bank doesn't look
|
||||
// frozen, and so we know when to release the close-lock (GRACE_SEC). State is
|
||||
// only ever set from the timer callbacks (never synchronously in the effect
|
||||
// body), and elapsed is never computed from Date.now() during render, so this
|
||||
// stays clear of the react-hooks purity rules.
|
||||
const [elapsedSec, setElapsedSec] = useState(0)
|
||||
useEffect(() => {
|
||||
if (!open || state.kind !== 'syncing') return
|
||||
const started = Date.now()
|
||||
const tick = () => setElapsedSec(Math.max(0, Math.floor((Date.now() - started) / 1000)))
|
||||
// Reset to ~0 on the next tick (async, so not a synchronous effect setState).
|
||||
const reset = setTimeout(tick, 0)
|
||||
const id = setInterval(tick, 1000)
|
||||
return () => {
|
||||
clearTimeout(reset)
|
||||
clearInterval(id)
|
||||
}
|
||||
}, [open, state.kind])
|
||||
|
||||
const overGrace = state.kind === 'syncing' && elapsedSec >= GRACE_SEC
|
||||
// Only hard-block the close affordances during the expected window; after the
|
||||
// grace period the user may background the (still-running) sync.
|
||||
const blockClose = state.kind === 'syncing' && !overGrace
|
||||
|
||||
// The payoff: once the first sync lands, name the work now waiting so the
|
||||
// moment points onward instead of stranding the user on the settings panel.
|
||||
// Same authenticated endpoint the dashboard pane refetches; best-effort.
|
||||
const [workCounts, setWorkCounts] = useState<{ book: number; matches: number } | null>(null)
|
||||
useEffect(() => {
|
||||
if (!open || state.kind !== 'done' || state.summary.imported === 0) {
|
||||
// A later sync must not inherit the previous run's numbers.
|
||||
setWorkCounts(null)
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
fetch('/api/worklist/counts')
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((json: { data?: { counts?: Record<string, number> } } | null) => {
|
||||
if (cancelled || !json?.data?.counts) return
|
||||
setWorkCounts({
|
||||
book: json.data.counts.book_transaction ?? 0,
|
||||
matches: json.data.counts.suggested_match ?? 0,
|
||||
})
|
||||
})
|
||||
.catch(() => {
|
||||
// The CTA degrades to a plain link; the numbers are a nicety.
|
||||
})
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [open, state])
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(next) => {
|
||||
if (!next && blockClose) return
|
||||
onOpenChange(next)
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
className="max-w-md"
|
||||
onPointerDownOutside={(e) => {
|
||||
if (blockClose) e.preventDefault()
|
||||
}}
|
||||
onEscapeKeyDown={(e) => {
|
||||
if (blockClose) e.preventDefault()
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
{/* data-ph-mask: the bank name reveals which bank the user uses */}
|
||||
<DialogTitle data-ph-mask="">
|
||||
{state.kind === 'syncing' && `Hämtar transaktioner från ${bankName}`}
|
||||
{state.kind === 'done' && 'Klart'}
|
||||
{state.kind === 'failed' && 'Synkningen misslyckades'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{state.kind === 'syncing' && (
|
||||
overGrace ? (
|
||||
<>
|
||||
Det tar längre tid än vanligt. Vi fortsätter i bakgrunden: du kan
|
||||
stänga rutan och komma tillbaka senare.
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Vi hämtar transaktioner från {enabledAccounts.length}{' '}
|
||||
{enabledAccounts.length === 1 ? 'konto' : 'konton'}. Detta kan ta upp till en minut. Stäng inte fönstret.
|
||||
</>
|
||||
)
|
||||
)}
|
||||
{state.kind === 'done' && (
|
||||
<>
|
||||
Vi hämtade {state.summary.imported}{' '}
|
||||
{state.summary.imported === 1 ? 'transaktion' : 'transaktioner'}.
|
||||
</>
|
||||
)}
|
||||
{state.kind === 'failed' && (
|
||||
<>Vi försöker igen automatiskt i bakgrunden. Du kan stänga den här rutan.</>
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{state.kind === 'syncing' && (
|
||||
<div className="space-y-3 py-2">
|
||||
<div className="flex flex-col items-center justify-center gap-2 py-6">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
<span className="text-xs text-muted-foreground tabular-nums" aria-live="polite">
|
||||
{formatElapsed(elapsedSec)}
|
||||
</span>
|
||||
</div>
|
||||
<ul className="rounded-lg border border-border divide-y divide-border text-sm">
|
||||
{enabledAccounts.map((a) => (
|
||||
<li key={a.uid} className="flex items-center justify-between gap-3 px-3 py-2">
|
||||
<span className="truncate">{a.name || a.iban || a.uid}</span>
|
||||
<span className="text-xs text-muted-foreground">{a.currency}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{state.kind === 'done' && (
|
||||
<DoneBody summary={state.summary} workCounts={workCounts} />
|
||||
)}
|
||||
|
||||
{state.kind === 'failed' && (
|
||||
<div className="rounded-lg border border-border bg-muted/30 p-3 text-sm text-muted-foreground">
|
||||
{state.error.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DialogFooter>
|
||||
{state.kind === 'done' && state.summary.imported > 0 ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
Stäng
|
||||
</Button>
|
||||
<Button asChild>
|
||||
<Link href="/transactions">
|
||||
{workCounts && workCounts.book > 0
|
||||
? `Visa ${workCounts.book} att bokföra`
|
||||
: 'Öppna transaktionerna'}
|
||||
</Link>
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={blockClose}
|
||||
>
|
||||
{state.kind === 'syncing'
|
||||
? (overGrace ? 'Fortsätt i bakgrunden' : 'Hämtar…')
|
||||
: 'Klar'}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function DoneBody({
|
||||
summary,
|
||||
workCounts,
|
||||
}: {
|
||||
summary: SyncProgressSummary
|
||||
workCounts: { book: number; matches: number } | null
|
||||
}) {
|
||||
const requestedDays = daysBetween(summary.requested_from)
|
||||
const returnedDays =
|
||||
summary.returned_min_date && summary.returned_max_date
|
||||
? daysBetween(summary.returned_min_date, new Date(summary.returned_max_date))
|
||||
: 0
|
||||
const wasTruncated = requestedDays - returnedDays > 7
|
||||
|
||||
return (
|
||||
<div className="space-y-3 py-2">
|
||||
<div className="flex items-center gap-3 rounded-lg border border-border bg-muted/30 p-4">
|
||||
<CheckCircle2 className="h-6 w-6 shrink-0 text-foreground" />
|
||||
<div className="text-sm">
|
||||
<p>
|
||||
<span className="tabular-nums font-medium">{summary.imported}</span> nya transaktioner
|
||||
importerade.
|
||||
</p>
|
||||
{summary.returned_min_date && summary.returned_max_date && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Datum: {summary.returned_min_date} → {summary.returned_max_date}
|
||||
</p>
|
||||
)}
|
||||
{(summary.auto_matched ?? 0) > 0 && (
|
||||
<p className="text-xs text-muted-foreground tabular-nums">
|
||||
{summary.auto_matched} kopplades automatiskt till redan bokförda verifikat.
|
||||
</p>
|
||||
)}
|
||||
{workCounts && workCounts.book > 0 && (
|
||||
<p className="mt-1 text-xs text-muted-foreground tabular-nums">
|
||||
{workCounts.book} att bokföra
|
||||
{workCounts.matches > 0 && <> · {workCounts.matches} matchar fakturor</>}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{wasTruncated && (
|
||||
<div className="flex items-start gap-2 rounded-lg border border-border bg-muted/30 p-3 text-xs text-muted-foreground">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<span>
|
||||
Banken returnerade kortare historik än begärt. För äldre data, använd{' '}
|
||||
<Link href="/import?mode=sie" className="text-foreground underline underline-offset-2">
|
||||
SIE- eller bankfil-import
|
||||
</Link>
|
||||
.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
import { describeClaimedElsewhere, partitionByClaim } from '../claimed-accounts'
|
||||
import type { StoredAccount } from '../../types'
|
||||
|
||||
function account(over: Partial<StoredAccount> & { uid: string }): StoredAccount {
|
||||
return { currency: 'SEK', ...over }
|
||||
}
|
||||
|
||||
describe('partitionByClaim', () => {
|
||||
it('keeps unclaimed accounts in the main list and moves claimed ones aside', () => {
|
||||
const own1 = account({ uid: 'a', iban: 'SE1' })
|
||||
const own2 = account({ uid: 'b', iban: 'SE2', enabled: false })
|
||||
const foreign = account({
|
||||
uid: 'c',
|
||||
iban: 'SE3',
|
||||
enabled: false,
|
||||
claimed_by_company_id: 'company-b',
|
||||
claimed_by_company_name: 'Testbrand Holding AB',
|
||||
})
|
||||
|
||||
const { own, claimedElsewhere } = partitionByClaim([own1, foreign, own2])
|
||||
|
||||
expect(own).toEqual([own1, own2])
|
||||
expect(claimedElsewhere).toEqual([foreign])
|
||||
})
|
||||
|
||||
it('treats a legacy double-claim (no flag, enabled here) as own', () => {
|
||||
// The callback lets the active company's standing state outrank a sibling
|
||||
// claim, so such an account carries no flag: it must stay visible.
|
||||
const legacy = account({ uid: 'a', iban: 'SE1', enabled: true })
|
||||
expect(partitionByClaim([legacy]).own).toEqual([legacy])
|
||||
expect(partitionByClaim([legacy]).claimedElsewhere).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps a flagged account visible when it is enabled here (invariant breach must not hide a syncing feed)', () => {
|
||||
const flaggedButEnabled = account({ uid: 'a', iban: 'SE1', enabled: true, claimed_by_company_id: 'x' })
|
||||
const flaggedNoEnabledField = account({ uid: 'b', iban: 'SE2', claimed_by_company_id: 'x' })
|
||||
const { own, claimedElsewhere } = partitionByClaim([flaggedButEnabled, flaggedNoEnabledField])
|
||||
// enabled missing means enabled (back-compat default), so both stay own.
|
||||
expect(own).toEqual([flaggedButEnabled, flaggedNoEnabledField])
|
||||
expect(claimedElsewhere).toEqual([])
|
||||
})
|
||||
|
||||
it('treats a carried deselection without a claim as own', () => {
|
||||
const deselected = account({ uid: 'a', iban: 'SE1', enabled: false, deselected_elsewhere: true })
|
||||
expect(partitionByClaim([deselected]).own).toEqual([deselected])
|
||||
})
|
||||
|
||||
it('preserves order within each partition and handles an empty list', () => {
|
||||
expect(partitionByClaim([])).toEqual({ own: [], claimedElsewhere: [] })
|
||||
const rows = ['1', '2', '3', '4'].map((n, i) =>
|
||||
account({ uid: n, enabled: false, claimed_by_company_id: i % 2 ? 'x' : undefined }),
|
||||
)
|
||||
const { own, claimedElsewhere } = partitionByClaim(rows)
|
||||
expect(own.map((a) => a.uid)).toEqual(['1', '3'])
|
||||
expect(claimedElsewhere.map((a) => a.uid)).toEqual(['2', '4'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('describeClaimedElsewhere', () => {
|
||||
it('names the claimant when every account belongs to the same company', () => {
|
||||
const rows = [
|
||||
account({ uid: 'a', claimed_by_company_id: 'x', claimed_by_company_name: 'Testbrand AB' }),
|
||||
account({ uid: 'b', claimed_by_company_id: 'x', claimed_by_company_name: 'Testbrand AB' }),
|
||||
]
|
||||
expect(describeClaimedElsewhere(rows)).toBe('2 konton synkas i Testbrand AB')
|
||||
})
|
||||
|
||||
it('uses the singular noun for one account', () => {
|
||||
const rows = [account({ uid: 'a', claimed_by_company_id: 'x', claimed_by_company_name: 'Testbrand AB' })]
|
||||
expect(describeClaimedElsewhere(rows)).toBe('1 konto synkas i Testbrand AB')
|
||||
})
|
||||
|
||||
it('falls back to a generic phrase when claimants differ or a name is missing', () => {
|
||||
const mixed = [
|
||||
account({ uid: 'a', claimed_by_company_id: 'x', claimed_by_company_name: 'Testbrand AB' }),
|
||||
account({ uid: 'b', claimed_by_company_id: 'y', claimed_by_company_name: 'Testbrand Holding AB' }),
|
||||
]
|
||||
expect(describeClaimedElsewhere(mixed)).toBe('2 konton synkas i andra bolag')
|
||||
|
||||
const unnamed = [account({ uid: 'a', claimed_by_company_id: 'x' })]
|
||||
expect(describeClaimedElsewhere(unnamed)).toBe('1 konto synkas i ett annat bolag')
|
||||
})
|
||||
|
||||
it('does not merge two different companies that share a display name', () => {
|
||||
const sameNameDifferentIds = [
|
||||
account({ uid: 'a', claimed_by_company_id: 'x', claimed_by_company_name: 'Testbrand AB' }),
|
||||
account({ uid: 'b', claimed_by_company_id: 'y', claimed_by_company_name: 'Testbrand AB' }),
|
||||
]
|
||||
expect(describeClaimedElsewhere(sameNameDifferentIds)).toBe('2 konton synkas i andra bolag')
|
||||
})
|
||||
|
||||
it('returns an empty string for no accounts', () => {
|
||||
expect(describeClaimedElsewhere([])).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
buildPageAttentionSentence,
|
||||
getConnectionUiState,
|
||||
selectPageAttention,
|
||||
sortConnectionsByPrecedence,
|
||||
EXPIRY_WARNING_DAYS,
|
||||
STALE_SYNC_DAYS,
|
||||
} from '../connection-state'
|
||||
|
||||
const NOW = new Date('2026-08-19T12:00:00Z').getTime()
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
function iso(offsetDays: number): string {
|
||||
return new Date(NOW + offsetDays * DAY_MS).toISOString()
|
||||
}
|
||||
|
||||
function conn(overrides: {
|
||||
status?: string
|
||||
consent_expires?: string | null
|
||||
last_synced_at?: string | null
|
||||
created_at?: string
|
||||
bank_name?: string
|
||||
}) {
|
||||
return {
|
||||
status: 'active',
|
||||
consent_expires: iso(60),
|
||||
last_synced_at: iso(-1),
|
||||
created_at: iso(-30),
|
||||
bank_name: 'SEB',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('getConnectionUiState', () => {
|
||||
it('maps DB statuses straight through', () => {
|
||||
expect(getConnectionUiState(conn({ status: 'pending_selection' }), NOW)).toBe('pending_selection')
|
||||
expect(getConnectionUiState(conn({ status: 'pending' }), NOW)).toBe('pending')
|
||||
expect(getConnectionUiState(conn({ status: 'error' }), NOW)).toBe('error')
|
||||
expect(getConnectionUiState(conn({ status: 'expired' }), NOW)).toBe('expired')
|
||||
})
|
||||
|
||||
it('classifies a healthy active row as active', () => {
|
||||
expect(getConnectionUiState(conn({}), NOW)).toBe('active')
|
||||
})
|
||||
|
||||
it('flags consent expiring within the warning window', () => {
|
||||
expect(
|
||||
getConnectionUiState(conn({ consent_expires: iso(EXPIRY_WARNING_DAYS - 1) }), NOW),
|
||||
).toBe('expiring')
|
||||
expect(
|
||||
getConnectionUiState(conn({ consent_expires: iso(EXPIRY_WARNING_DAYS + 1) }), NOW),
|
||||
).toBe('active')
|
||||
})
|
||||
|
||||
it('expiring beats stale on the same row', () => {
|
||||
expect(
|
||||
getConnectionUiState(
|
||||
conn({ consent_expires: iso(2), last_synced_at: iso(-10) }),
|
||||
NOW,
|
||||
),
|
||||
).toBe('expiring')
|
||||
})
|
||||
|
||||
it('flags stale and never-synced active rows', () => {
|
||||
expect(
|
||||
getConnectionUiState(conn({ last_synced_at: iso(-STALE_SYNC_DAYS) }), NOW),
|
||||
).toBe('stale')
|
||||
expect(
|
||||
getConnectionUiState(conn({ last_synced_at: iso(-(STALE_SYNC_DAYS - 1)) }), NOW),
|
||||
).toBe('active')
|
||||
expect(getConnectionUiState(conn({ last_synced_at: null }), NOW)).toBe('never_synced')
|
||||
})
|
||||
|
||||
it('handles a row with no consent date', () => {
|
||||
expect(getConnectionUiState(conn({ consent_expires: null }), NOW)).toBe('active')
|
||||
})
|
||||
})
|
||||
|
||||
describe('sortConnectionsByPrecedence', () => {
|
||||
it('orders pending_selection, pending, error, expired, expiring, active', () => {
|
||||
const rows = [
|
||||
conn({ bank_name: 'Healthy' }),
|
||||
conn({ bank_name: 'Expiring', consent_expires: iso(2) }),
|
||||
conn({ bank_name: 'Expired', status: 'expired' }),
|
||||
conn({ bank_name: 'Errored', status: 'error' }),
|
||||
conn({ bank_name: 'InFlight', status: 'pending' }),
|
||||
conn({ bank_name: 'PickAccounts', status: 'pending_selection' }),
|
||||
]
|
||||
expect(sortConnectionsByPrecedence(rows, NOW).map((r) => r.bank_name)).toEqual([
|
||||
'PickAccounts',
|
||||
'InFlight',
|
||||
'Errored',
|
||||
'Expired',
|
||||
'Expiring',
|
||||
'Healthy',
|
||||
])
|
||||
})
|
||||
|
||||
it('breaks ties by newest created_at first and does not mutate the input', () => {
|
||||
const older = conn({ bank_name: 'Older', created_at: iso(-100) })
|
||||
const newer = conn({ bank_name: 'Newer', created_at: iso(-1) })
|
||||
const rows = [older, newer]
|
||||
const sorted = sortConnectionsByPrecedence(rows, NOW)
|
||||
expect(sorted.map((r) => r.bank_name)).toEqual(['Newer', 'Older'])
|
||||
expect(rows[0]).toBe(older)
|
||||
})
|
||||
})
|
||||
|
||||
describe('selectPageAttention', () => {
|
||||
it('returns null when every connection is healthy or has no attention state', () => {
|
||||
expect(selectPageAttention([conn({})], NOW)).toBeNull()
|
||||
expect(selectPageAttention([conn({ status: 'pending_selection' })], NOW)).toBeNull()
|
||||
expect(selectPageAttention([], NOW)).toBeNull()
|
||||
})
|
||||
|
||||
it('picks the worst state: error beats expired beats expiring beats stale', () => {
|
||||
const errored = conn({ bank_name: 'Errored', status: 'error' })
|
||||
const expired = conn({ bank_name: 'Expired', status: 'expired' })
|
||||
const expiring = conn({ bank_name: 'Expiring', consent_expires: iso(2) })
|
||||
const stale = conn({ bank_name: 'Stale', last_synced_at: iso(-10) })
|
||||
|
||||
expect(selectPageAttention([stale, expiring, expired, errored], NOW)?.connection.bank_name).toBe('Errored')
|
||||
expect(selectPageAttention([stale, expiring, expired], NOW)?.connection.bank_name).toBe('Expired')
|
||||
expect(selectPageAttention([stale, expiring], NOW)?.connection.bank_name).toBe('Expiring')
|
||||
expect(selectPageAttention([stale], NOW)?.state).toBe('stale')
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildPageAttentionSentence', () => {
|
||||
it('names the bank and the state', () => {
|
||||
const attention = selectPageAttention([conn({ status: 'expired' })], NOW)!
|
||||
expect(buildPageAttentionSentence(attention, NOW)).toBe(
|
||||
'SEB: PSD2-samtycket har löpt ut. Förnya samtycket för att återuppta synkroniseringen.',
|
||||
)
|
||||
})
|
||||
|
||||
it('counts days for the expiring state with singular/plural', () => {
|
||||
const one = selectPageAttention([conn({ consent_expires: iso(1) })], NOW)!
|
||||
expect(buildPageAttentionSentence(one, NOW)).toContain('går ut om 1 dag.')
|
||||
const five = selectPageAttention([conn({ consent_expires: iso(5) })], NOW)!
|
||||
expect(buildPageAttentionSentence(five, NOW)).toContain('går ut om 5 dagar.')
|
||||
})
|
||||
|
||||
it('counts days since sync for the stale state', () => {
|
||||
const attention = selectPageAttention([conn({ last_synced_at: iso(-10) })], NOW)!
|
||||
expect(buildPageAttentionSentence(attention, NOW)).toContain('ingen synkning på 10 dagar')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
|
||||
import {
|
||||
isOneSessionBank,
|
||||
isVerifiedMultiSessionBank,
|
||||
sameBankWarning,
|
||||
type SameBankClash,
|
||||
} from '../connection-warning'
|
||||
|
||||
function clash(over: Partial<SameBankClash> = {}): SameBankClash {
|
||||
return {
|
||||
companyId: 'company-1',
|
||||
companyName: 'Testbrand AB',
|
||||
sessionId: 'sess-other',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
describe('bank tier matching', () => {
|
||||
it('matches SEB regardless of casing and whitespace', () => {
|
||||
expect(isOneSessionBank('SEB')).toBe(true)
|
||||
expect(isOneSessionBank(' seb ')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches Handelsbanken as verified multi-session', () => {
|
||||
expect(isVerifiedMultiSessionBank('Handelsbanken')).toBe(true)
|
||||
expect(isVerifiedMultiSessionBank('handelsbanken')).toBe(true)
|
||||
})
|
||||
|
||||
it('does not match banks merely containing the letters, nor null', () => {
|
||||
expect(isOneSessionBank('SEB Kort Bank')).toBe(false)
|
||||
expect(isOneSessionBank(null)).toBe(false)
|
||||
expect(isOneSessionBank(undefined)).toBe(false)
|
||||
expect(isVerifiedMultiSessionBank('Nordea')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sameBankWarning', () => {
|
||||
const base = {
|
||||
bankName: 'Handelsbanken',
|
||||
clashes: [clash()],
|
||||
isReconnect: false,
|
||||
}
|
||||
|
||||
it('returns null when nothing clashes', () => {
|
||||
expect(sameBankWarning({ ...base, clashes: [] })).toBeNull()
|
||||
})
|
||||
|
||||
it('is silent when renewing at a verified multi-session bank', () => {
|
||||
// The regression this module fixes: a user abandoned a legitimate
|
||||
// Handelsbanken renewal because the old dialog warned about sibling
|
||||
// connections that HB demonstrably tolerates.
|
||||
expect(sameBankWarning({ ...base, isReconnect: true })).toBeNull()
|
||||
})
|
||||
|
||||
it('calmly confirms a fresh second connection at a verified multi-session bank', () => {
|
||||
const warning = sameBankWarning(base)
|
||||
expect(warning).not.toBeNull()
|
||||
expect(warning?.confirmLabel).toBe('Anslut')
|
||||
expect(warning?.description).not.toContain('sluta synka')
|
||||
expect(warning?.description).toContain('Testbrand AB')
|
||||
})
|
||||
|
||||
it('hard-warns for a one-session bank on fresh connect and reconnect alike', () => {
|
||||
// A renewal also mints a new authorization, which at a one-session bank
|
||||
// revokes the sibling companies' session just like a fresh connect does.
|
||||
for (const isReconnect of [false, true]) {
|
||||
const warning = sameBankWarning({ ...base, bankName: 'SEB', isReconnect })
|
||||
expect(warning?.title).toBe('Du har redan 1 anslutning till SEB')
|
||||
expect(warning?.description).toContain('slutar de andra att synka')
|
||||
expect(warning?.confirmLabel).toBe('Fortsätt ändå')
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the hedged warning for banks with unknown session policy, on both paths', () => {
|
||||
// Fail closed: absence of evidence about a bank is not evidence that it
|
||||
// tolerates parallel sessions, so unknown banks keep the old behavior.
|
||||
for (const isReconnect of [false, true]) {
|
||||
const warning = sameBankWarning({ ...base, bankName: 'Nordea', isReconnect })
|
||||
expect(warning).not.toBeNull()
|
||||
expect(warning?.description).toContain('Vissa banker tillåter bara en aktiv anslutning')
|
||||
expect(warning?.description).toContain('kan de andra sluta synka')
|
||||
expect(warning?.confirmLabel).toBe('Fortsätt')
|
||||
}
|
||||
})
|
||||
|
||||
it('exempts siblings sharing the session being renewed', () => {
|
||||
// fanOutSessionRenewal carries the renewed session to every sibling on
|
||||
// it, so they never break and must not trigger the warning: even at SEB,
|
||||
// even at an unknown bank.
|
||||
for (const bankName of ['SEB', 'Nordea']) {
|
||||
const warning = sameBankWarning({
|
||||
bankName,
|
||||
clashes: [clash({ sessionId: 'sess-current' })],
|
||||
isReconnect: true,
|
||||
currentSessionId: 'sess-current',
|
||||
})
|
||||
expect(warning).toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
it('still warns about siblings on OTHER sessions when renewing', () => {
|
||||
const warning = sameBankWarning({
|
||||
bankName: 'SEB',
|
||||
clashes: [
|
||||
clash({ sessionId: 'sess-current', companyName: 'Delad AB' }),
|
||||
clash({ sessionId: 'sess-other', companyName: 'Separat AB' }),
|
||||
],
|
||||
isReconnect: true,
|
||||
currentSessionId: 'sess-current',
|
||||
})
|
||||
expect(warning?.title).toBe('Du har redan 1 anslutning till SEB')
|
||||
expect(warning?.description).toContain('Separat AB')
|
||||
expect(warning?.description).not.toContain('Delad AB')
|
||||
})
|
||||
|
||||
it('never exempts on null session ids', () => {
|
||||
// A null on either side proves nothing about sharing.
|
||||
const warning = sameBankWarning({
|
||||
bankName: 'SEB',
|
||||
clashes: [clash({ sessionId: null })],
|
||||
isReconnect: true,
|
||||
currentSessionId: null,
|
||||
})
|
||||
expect(warning).not.toBeNull()
|
||||
})
|
||||
|
||||
it('dedupes company names and phrases by company count', () => {
|
||||
// One company can hold two connections (privat + företag) to one bank:
|
||||
// that is still "ett annat bolag", named once.
|
||||
const warning = sameBankWarning({
|
||||
bankName: 'SEB',
|
||||
clashes: [
|
||||
clash({ sessionId: 'a' }),
|
||||
clash({ sessionId: 'b' }),
|
||||
],
|
||||
isReconnect: false,
|
||||
})
|
||||
expect(warning?.title).toBe('Du har redan 2 anslutningar till SEB')
|
||||
expect(warning?.description).toContain('ett annat bolag (Testbrand AB)')
|
||||
expect(warning?.description).not.toContain('Testbrand AB, Testbrand AB')
|
||||
})
|
||||
|
||||
it('pluralizes across distinct companies', () => {
|
||||
const warning = sameBankWarning({
|
||||
bankName: 'SEB',
|
||||
clashes: [
|
||||
clash({ companyName: 'Testbrand AB' }),
|
||||
clash({ companyId: 'company-2', companyName: 'Provbolaget AB', sessionId: 'sess-2' }),
|
||||
],
|
||||
isReconnect: false,
|
||||
})
|
||||
expect(warning?.description).toContain('andra bolag (Testbrand AB, Provbolaget AB)')
|
||||
})
|
||||
|
||||
it('counts companies by id, not display name', () => {
|
||||
// Two DISTINCT companies sharing a name, or a company whose name failed
|
||||
// to resolve, must still pluralize: names are display-only.
|
||||
const sameName = sameBankWarning({
|
||||
bankName: 'SEB',
|
||||
clashes: [
|
||||
clash({ companyId: 'company-1', companyName: 'Testbrand AB' }),
|
||||
clash({ companyId: 'company-2', companyName: 'Testbrand AB', sessionId: 'sess-2' }),
|
||||
],
|
||||
isReconnect: false,
|
||||
})
|
||||
expect(sameName?.description).toContain('andra bolag (Testbrand AB)')
|
||||
|
||||
const mixedNamedUnnamed = sameBankWarning({
|
||||
bankName: 'SEB',
|
||||
clashes: [
|
||||
clash({ companyId: 'company-1', companyName: 'Testbrand AB' }),
|
||||
clash({ companyId: 'company-2', companyName: null, sessionId: 'sess-2' }),
|
||||
],
|
||||
isReconnect: false,
|
||||
})
|
||||
expect(mixedNamedUnnamed?.description).toContain('andra bolag (Testbrand AB)')
|
||||
})
|
||||
|
||||
it('omits the company list when no names are known', () => {
|
||||
const warning = sameBankWarning({
|
||||
...base,
|
||||
bankName: 'SEB',
|
||||
clashes: [clash({ companyName: null })],
|
||||
})
|
||||
expect(warning?.description).not.toContain('(')
|
||||
})
|
||||
|
||||
it('survives a null bank name', () => {
|
||||
const warning = sameBankWarning({ ...base, bankName: null })
|
||||
expect(warning).not.toBeNull()
|
||||
expect(warning?.title).toContain('Banken')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { incrementalLookbackDays } from '../cron-lookback'
|
||||
|
||||
const NOW = Date.parse('2026-09-02T05:00:00Z')
|
||||
const daysAgo = (d: number) => new Date(NOW - d * 24 * 60 * 60 * 1000).toISOString()
|
||||
|
||||
describe('incrementalLookbackDays', () => {
|
||||
it('keeps the 7-day window when the last sync is recent', () => {
|
||||
expect(incrementalLookbackDays(daysAgo(0), NOW)).toBe(7)
|
||||
expect(incrementalLookbackDays(daysAgo(1), NOW)).toBe(7)
|
||||
expect(incrementalLookbackDays(daysAgo(5), NOW)).toBe(7)
|
||||
})
|
||||
|
||||
it('widens the window to cover a gap, with one day of overlap', () => {
|
||||
expect(incrementalLookbackDays(daysAgo(7), NOW)).toBe(8)
|
||||
expect(incrementalLookbackDays(daysAgo(20), NOW)).toBe(21)
|
||||
})
|
||||
|
||||
it('rounds a partial day up so the gap is never under-covered', () => {
|
||||
expect(incrementalLookbackDays(daysAgo(10.4), NOW)).toBe(12)
|
||||
})
|
||||
|
||||
it('caps at the 90-day PSD2 limit', () => {
|
||||
expect(incrementalLookbackDays(daysAgo(200), NOW)).toBe(90)
|
||||
expect(incrementalLookbackDays(daysAgo(89), NOW)).toBe(90)
|
||||
})
|
||||
|
||||
it('falls back to 7 days when there is no usable timestamp', () => {
|
||||
expect(incrementalLookbackDays(null, NOW)).toBe(7)
|
||||
expect(incrementalLookbackDays(undefined, NOW)).toBe(7)
|
||||
expect(incrementalLookbackDays('not a date', NOW)).toBe(7)
|
||||
})
|
||||
|
||||
it('never goes below 7 days for a future timestamp (clock skew)', () => {
|
||||
expect(incrementalLookbackDays(daysAgo(-2), NOW)).toBe(7)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
resolveBookedCoverage,
|
||||
resolveFiscalYearStart,
|
||||
resolveGapFillStart,
|
||||
} from '../date-suggestions'
|
||||
|
||||
describe('resolveBookedCoverage', () => {
|
||||
it('suggests the day after the last posted verifikat date', () => {
|
||||
expect(resolveBookedCoverage('2026-05-14')).toEqual({
|
||||
lastBookedDate: '2026-05-14',
|
||||
suggestedStartDate: '2026-05-15',
|
||||
})
|
||||
})
|
||||
|
||||
it('rolls over month and year boundaries', () => {
|
||||
// Pin "today" past every case so the clamp does not kick in.
|
||||
const today = new Date('2030-01-01T12:00:00Z')
|
||||
expect(resolveBookedCoverage('2026-01-31', today)?.suggestedStartDate).toBe('2026-02-01')
|
||||
expect(resolveBookedCoverage('2026-12-31', today)?.suggestedStartDate).toBe('2027-01-01')
|
||||
// Leap year: 2028-02-28 is not the last day of February.
|
||||
expect(resolveBookedCoverage('2028-02-28', today)?.suggestedStartDate).toBe('2028-02-29')
|
||||
})
|
||||
|
||||
it('clamps to today when the last posted verifikat is dated today (backend rejects non-past dates)', () => {
|
||||
// Day after 2026-07-09 would be 2026-07-10 (tomorrow), which the PATCH
|
||||
// handler rejects with 400; the suggestion must stay clickable.
|
||||
const today = new Date('2026-07-09T12:00:00Z')
|
||||
expect(resolveBookedCoverage('2026-07-09', today)).toEqual({
|
||||
lastBookedDate: '2026-07-09',
|
||||
suggestedStartDate: '2026-07-09',
|
||||
})
|
||||
})
|
||||
|
||||
it('clamps to today when the last posted verifikat is dated in the future', () => {
|
||||
const today = new Date('2026-07-09T12:00:00Z')
|
||||
expect(resolveBookedCoverage('2026-08-15', today)).toEqual({
|
||||
lastBookedDate: '2026-08-15',
|
||||
suggestedStartDate: '2026-07-09',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when the company has no posted entries (issue #917: never fall back to fiscal_year_end)', () => {
|
||||
expect(resolveBookedCoverage(null)).toBeNull()
|
||||
expect(resolveBookedCoverage(undefined)).toBeNull()
|
||||
expect(resolveBookedCoverage('')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveGapFillStart', () => {
|
||||
it('suggests one week of overlap before the newest imported transaction', () => {
|
||||
const today = new Date('2026-08-13T12:00:00Z')
|
||||
expect(resolveGapFillStart('2026-08-06', today)).toEqual({
|
||||
latestImportedDate: '2026-08-06',
|
||||
suggestedStartDate: '2026-07-30',
|
||||
})
|
||||
})
|
||||
|
||||
it('rolls over month and year boundaries', () => {
|
||||
// Todays within the 365-day floor of each case so only the 7-day overlap acts.
|
||||
expect(resolveGapFillStart('2026-01-03', new Date('2026-01-15T12:00:00Z'))?.suggestedStartDate).toBe('2025-12-27')
|
||||
expect(resolveGapFillStart('2026-03-04', new Date('2026-03-10T12:00:00Z'))?.suggestedStartDate).toBe('2026-02-25')
|
||||
})
|
||||
|
||||
it('clamps to today when bank data claims a future date (backend rejects non-past dates)', () => {
|
||||
const today = new Date('2026-08-13T12:00:00Z')
|
||||
expect(resolveGapFillStart('2026-09-20', today)).toEqual({
|
||||
latestImportedDate: '2026-09-20',
|
||||
suggestedStartDate: '2026-08-13',
|
||||
})
|
||||
})
|
||||
|
||||
it('clamps a stale renewal to the backend 365-day lookback floor so the shown date matches the actual backfill', () => {
|
||||
const today = new Date('2026-08-13T12:00:00Z')
|
||||
// Newest import 2025-01-10; minus 7d = 2025-01-03, older than the 365-day
|
||||
// floor (2025-08-13), which the backend would silently clamp to anyway.
|
||||
expect(resolveGapFillStart('2025-01-10', today)).toEqual({
|
||||
latestImportedDate: '2025-01-10',
|
||||
suggestedStartDate: '2025-08-13',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns null when the connection has never imported anything (first connect has no gap)', () => {
|
||||
expect(resolveGapFillStart(null)).toBeNull()
|
||||
expect(resolveGapFillStart(undefined)).toBeNull()
|
||||
expect(resolveGapFillStart('')).toBeNull()
|
||||
})
|
||||
|
||||
it('returns null for an unparsable date', () => {
|
||||
expect(resolveGapFillStart('not-a-date')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveFiscalYearStart', () => {
|
||||
const calendarYearSettings = {
|
||||
fiscal_year_start_month: 1,
|
||||
entity_type: 'aktiebolag' as const,
|
||||
}
|
||||
|
||||
it('prefers the actual fiscal period row over the recurring start month (issue #917: extended first year)', () => {
|
||||
// Company with an extended first fiscal year 2025-10-01 to 2026-12-31 that
|
||||
// later runs calendar years: the recurring setting would wrongly resolve
|
||||
// to 2026-01-01.
|
||||
expect(
|
||||
resolveFiscalYearStart('2025-10-01', calendarYearSettings, new Date('2026-07-09')),
|
||||
).toBe('2025-10-01')
|
||||
})
|
||||
|
||||
it('falls back to the recurring fiscal_year_start_month when no period row exists', () => {
|
||||
expect(
|
||||
resolveFiscalYearStart(null, calendarYearSettings, new Date('2026-07-09')),
|
||||
).toBe('2026-01-01')
|
||||
expect(
|
||||
resolveFiscalYearStart(
|
||||
undefined,
|
||||
{ fiscal_year_start_month: 7, entity_type: 'aktiebolag' },
|
||||
new Date('2026-05-01'),
|
||||
),
|
||||
).toBe('2025-07-01')
|
||||
})
|
||||
|
||||
it('falls back to calendar year when settings are missing too', () => {
|
||||
expect(resolveFiscalYearStart(null, null, new Date('2026-07-09'))).toBe('2026-01-01')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,306 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
vi.mock('@/lib/cash-accounts/service', () => ({
|
||||
normalizeIban: (iban?: string | null) => {
|
||||
if (!iban) return null
|
||||
const normalized = iban.replace(/\s+/g, '').toUpperCase()
|
||||
return normalized || null
|
||||
},
|
||||
}))
|
||||
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
fetchCrossCompanyAccountContext,
|
||||
unclaimedAccountsFor,
|
||||
} from '../session-sharing'
|
||||
import type { StoredAccount } from '../../types'
|
||||
|
||||
interface TableResult {
|
||||
data?: unknown
|
||||
error?: { message: string } | null
|
||||
}
|
||||
|
||||
type MockChain = Record<string, ReturnType<typeof vi.fn>> & {
|
||||
then: (resolve: (v: unknown) => void) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Chainable mock resolving per table: every filter method returns the chain,
|
||||
* awaiting it yields the preset result for that table. Chains are recorded so
|
||||
* tests can assert which filters were applied (the mock does not filter).
|
||||
*/
|
||||
function makeSupabase(results: Record<string, TableResult>): {
|
||||
supabase: SupabaseClient
|
||||
chainsByTable: Map<string, MockChain[]>
|
||||
} {
|
||||
const chainsByTable = new Map<string, MockChain[]>()
|
||||
const supabase = {
|
||||
from: (table: string) => {
|
||||
const result = results[table] ?? { data: [], error: null }
|
||||
const chain = {} as MockChain
|
||||
for (const m of ['select', 'eq', 'neq', 'in', 'not', 'is', 'order', 'limit', 'range']) {
|
||||
chain[m] = vi.fn().mockReturnValue(chain)
|
||||
}
|
||||
chain.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null })
|
||||
const bucket = chainsByTable.get(table)
|
||||
if (bucket) bucket.push(chain)
|
||||
else chainsByTable.set(table, [chain])
|
||||
return chain
|
||||
},
|
||||
} as unknown as SupabaseClient
|
||||
return { supabase, chainsByTable }
|
||||
}
|
||||
|
||||
describe('fetchCrossCompanyAccountContext', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('claims enabled accounts of sibling companies, remembers deselections, resolves names', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
company_members: {
|
||||
data: [{ company_id: 'company-1' }, { company_id: 'company-2' }],
|
||||
},
|
||||
bank_connections: {
|
||||
data: [
|
||||
{
|
||||
id: 'conn-sibling',
|
||||
company_id: 'company-2',
|
||||
accounts_data: [
|
||||
{ uid: 'a1', iban: 'SE11', currency: 'SEK', enabled: true },
|
||||
{ uid: 'a2', iban: 'SE22', currency: 'SEK', enabled: false },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'conn-own-other-row',
|
||||
company_id: 'company-1',
|
||||
// The active company's own account never becomes a claim; its
|
||||
// enabled accounts are its standing set and its deselections are
|
||||
// remembered.
|
||||
accounts_data: [
|
||||
{ uid: 'a3', iban: 'SE33', currency: 'SEK', enabled: true },
|
||||
{ uid: 'a4', iban: 'SE44', currency: 'SEK', enabled: false },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
cash_accounts: { data: [] },
|
||||
companies: { data: [{ id: 'company-2', name: 'Sibling AB' }] },
|
||||
})
|
||||
|
||||
const context = await fetchCrossCompanyAccountContext(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
'conn-active',
|
||||
)
|
||||
|
||||
expect(context).not.toBeNull()
|
||||
expect(context!.claims.get('SE11')).toEqual({
|
||||
companyId: 'company-2',
|
||||
companyName: 'Sibling AB',
|
||||
})
|
||||
expect(context!.claims.has('SE33')).toBe(false)
|
||||
expect(context!.activeCompanyIbans).toEqual(new Set(['SE33']))
|
||||
expect(context!.deselectedIbans).toEqual(new Set(['SE22', 'SE44']))
|
||||
})
|
||||
|
||||
it("lets the active company's own standing state outrank a sibling claim", async () => {
|
||||
// The bank-list renewal case: the active company's old row (about to be
|
||||
// superseded) and its cash_accounts row still book the IBAN. A sibling
|
||||
// claim on the same IBAN must not win, or a renewal arriving on a fresh
|
||||
// row would switch a working feed off.
|
||||
const { supabase } = makeSupabase({
|
||||
company_members: {
|
||||
data: [{ company_id: 'company-1' }, { company_id: 'company-2' }],
|
||||
},
|
||||
bank_connections: {
|
||||
data: [
|
||||
{
|
||||
id: 'conn-sibling',
|
||||
company_id: 'company-2',
|
||||
accounts_data: [{ uid: 'a1', iban: 'SE11', currency: 'SEK', enabled: true }],
|
||||
},
|
||||
],
|
||||
},
|
||||
cash_accounts: {
|
||||
data: [{ company_id: 'company-1', iban: 'SE11' }],
|
||||
},
|
||||
companies: { data: [] },
|
||||
})
|
||||
|
||||
const context = await fetchCrossCompanyAccountContext(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
'conn-active',
|
||||
)
|
||||
|
||||
expect(context!.claims.has('SE11')).toBe(false)
|
||||
expect(context!.activeCompanyIbans.has('SE11')).toBe(true)
|
||||
expect(context!.deselectedIbans.has('SE11')).toBe(false)
|
||||
})
|
||||
|
||||
it('claims IBANs held by sibling companies via cash_accounts too', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
company_members: {
|
||||
data: [{ company_id: 'company-1' }, { company_id: 'company-2' }],
|
||||
},
|
||||
bank_connections: { data: [] },
|
||||
cash_accounts: { data: [{ company_id: 'company-2', iban: 'SE55' }] },
|
||||
companies: { data: [] },
|
||||
})
|
||||
|
||||
const context = await fetchCrossCompanyAccountContext(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
'conn-active',
|
||||
)
|
||||
|
||||
expect(context!.claims.get('SE55')).toEqual({ companyId: 'company-2', companyName: null })
|
||||
})
|
||||
|
||||
it('lets a claim outrank a remembered deselection for the same IBAN', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
company_members: {
|
||||
data: [{ company_id: 'company-1' }, { company_id: 'company-2' }],
|
||||
},
|
||||
bank_connections: {
|
||||
data: [
|
||||
{
|
||||
id: 'conn-a',
|
||||
company_id: 'company-2',
|
||||
accounts_data: [{ uid: 'a1', iban: 'SE11', currency: 'SEK', enabled: true }],
|
||||
},
|
||||
{
|
||||
id: 'conn-b',
|
||||
company_id: 'company-1',
|
||||
accounts_data: [{ uid: 'a2', iban: 'SE11', currency: 'SEK', enabled: false }],
|
||||
},
|
||||
],
|
||||
},
|
||||
cash_accounts: { data: [] },
|
||||
companies: { data: [] },
|
||||
})
|
||||
|
||||
const context = await fetchCrossCompanyAccountContext(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
'conn-active',
|
||||
)
|
||||
|
||||
expect(context!.claims.has('SE11')).toBe(true)
|
||||
expect(context!.deselectedIbans.has('SE11')).toBe(false)
|
||||
})
|
||||
|
||||
it('treats pending_selection rows asymmetrically: enabled accounts claim, disabled flags are ignored', async () => {
|
||||
// An attach-created row is pending_selection with deliberately-offered
|
||||
// enabled accounts and NO cash rows until its picker is saved: those must
|
||||
// claim, or a second company can take the same physical account inside
|
||||
// that window. Its disabled flags are unconfirmed callback output
|
||||
// (including the guard's own fail-closed writes) and must NOT feed the
|
||||
// deselection memory.
|
||||
const { supabase, chainsByTable } = makeSupabase({
|
||||
company_members: {
|
||||
data: [{ company_id: 'company-1' }, { company_id: 'company-2' }],
|
||||
},
|
||||
bank_connections: {
|
||||
data: [
|
||||
{
|
||||
id: 'conn-attached',
|
||||
company_id: 'company-2',
|
||||
status: 'pending_selection',
|
||||
accounts_data: [
|
||||
{ uid: 'a1', iban: 'SE11', currency: 'SEK', enabled: true },
|
||||
{ uid: 'a2', iban: 'SE22', currency: 'SEK', enabled: false },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
cash_accounts: { data: [] },
|
||||
companies: { data: [] },
|
||||
})
|
||||
|
||||
const context = await fetchCrossCompanyAccountContext(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
'conn-active',
|
||||
)
|
||||
|
||||
expect(context!.claims.has('SE11')).toBe(true)
|
||||
expect(context!.deselectedIbans.has('SE22')).toBe(false)
|
||||
|
||||
const connectionChain = chainsByTable.get('bank_connections')![0]
|
||||
expect(connectionChain.in).toHaveBeenCalledWith('status', [
|
||||
'active',
|
||||
'pending_selection',
|
||||
'expired',
|
||||
'error',
|
||||
])
|
||||
// Paged reads must order on a unique column or rows can be silently
|
||||
// skipped at page boundaries (a skipped row is a missed claim).
|
||||
expect(connectionChain.order).toHaveBeenCalledWith('id')
|
||||
expect(chainsByTable.get('cash_accounts')![0].order).toHaveBeenCalledWith('id')
|
||||
})
|
||||
|
||||
it('reads cash_accounts for ALL member companies (active included)', async () => {
|
||||
const { supabase, chainsByTable } = makeSupabase({
|
||||
company_members: {
|
||||
data: [{ company_id: 'company-1' }, { company_id: 'company-2' }],
|
||||
},
|
||||
bank_connections: { data: [] },
|
||||
cash_accounts: { data: [] },
|
||||
companies: { data: [] },
|
||||
})
|
||||
|
||||
await fetchCrossCompanyAccountContext(supabase, 'user-1', 'company-1', 'conn-active')
|
||||
|
||||
const cashChain = chainsByTable.get('cash_accounts')![0]
|
||||
expect(cashChain.in).toHaveBeenCalledWith('company_id', ['company-1', 'company-2'])
|
||||
})
|
||||
|
||||
it('returns null when a lookup fails, so the caller can fail closed', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
bank_connections: { data: null, error: { message: 'boom' } },
|
||||
})
|
||||
|
||||
const context = await fetchCrossCompanyAccountContext(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
'conn-active',
|
||||
)
|
||||
|
||||
expect(context).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('unclaimedAccountsFor', () => {
|
||||
it('strips stale claimed_by and deselected flags from offered accounts', () => {
|
||||
const accounts: StoredAccount[] = [
|
||||
{
|
||||
uid: 'a1',
|
||||
iban: 'SE11',
|
||||
currency: 'SEK',
|
||||
enabled: false,
|
||||
ledger_account: '1938',
|
||||
claimed_by_company_id: 'company-9',
|
||||
claimed_by_company_name: 'Stale AB',
|
||||
deselected_elsewhere: true,
|
||||
},
|
||||
]
|
||||
|
||||
const offered = unclaimedAccountsFor(accounts, new Set())
|
||||
|
||||
expect(offered).toHaveLength(1)
|
||||
expect(offered[0].enabled).toBe(true)
|
||||
expect(offered[0].ledger_account).toBeUndefined()
|
||||
expect(offered[0].claimed_by_company_id).toBeUndefined()
|
||||
expect(offered[0].claimed_by_company_name).toBeUndefined()
|
||||
expect(offered[0].deselected_elsewhere).toBeUndefined()
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,60 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { deriveTransactionLabel } from '../transaction-label'
|
||||
|
||||
describe('deriveTransactionLabel', () => {
|
||||
it('prefers MCC over the ISO code (most specific signal)', () => {
|
||||
expect(deriveTransactionLabel({ mcc: '6011' })).toBe('Uttag')
|
||||
expect(deriveTransactionLabel({ mcc: 5411 })).toBe('Inköp dagligvaror')
|
||||
// MCC wins even when a (different-meaning) bank code is also present.
|
||||
expect(
|
||||
deriveTransactionLabel({ mcc: '6011', bankTransactionCode: 'PMNT/CCRD' }),
|
||||
).toBe('Uttag')
|
||||
})
|
||||
|
||||
it('maps ISO 20022 Domain/Family codes', () => {
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'PMNT/RCDT' })).toBe('Inbetalning')
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'PMNT/ICDT' })).toBe('Betalning')
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'PMNT/CCRD' })).toBe('Kortköp')
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'PMNT/RDDT' })).toBe('Autogiro')
|
||||
})
|
||||
|
||||
it('parses dash- and dot-separated three-part codes (Domain-Family-SubFamily)', () => {
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'PMNT-CCRD-POSD' })).toBe('Kortköp')
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'pmnt.rcdt.esct' })).toBe('Inbetalning')
|
||||
})
|
||||
|
||||
it('falls back to a keyword scan for proprietary code strings', () => {
|
||||
expect(
|
||||
deriveTransactionLabel({ proprietaryBankTransactionCode: 'INTEREST PAYMENT' }),
|
||||
).toBe('Ränta')
|
||||
expect(
|
||||
deriveTransactionLabel({ proprietaryBankTransactionCode: 'ACCOUNT FEE' }),
|
||||
).toBe('Avgift')
|
||||
expect(
|
||||
deriveTransactionLabel({ proprietaryBankTransactionCode: 'ATM WITHDRAWAL' }),
|
||||
).toBe('Uttag')
|
||||
})
|
||||
|
||||
it('reads the combined Swedish channel wording "Kortköp/uttag" as a card purchase, not a withdrawal', () => {
|
||||
// Enable Banking's flattened code description for ordinary card purchases
|
||||
// at SEB/Swedbank. The card rule must win over the UTTAG keyword.
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'Kortköp/uttag' })).toBe('Kortköp')
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'Card purchase' })).toBe('Kortköp')
|
||||
// A bare withdrawal wording still labels as Uttag.
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'ATM WITHDRAWAL' })).toBe('Uttag')
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'Uttag' })).toBe('Uttag')
|
||||
})
|
||||
|
||||
it('uses the bare PMNT domain + direction as a last generic resort', () => {
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'PMNT', isCredit: true })).toBe('Inbetalning')
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'PMNT', isCredit: false })).toBe('Betalning')
|
||||
})
|
||||
|
||||
it('returns null when nothing is recognized (caller falls through)', () => {
|
||||
expect(deriveTransactionLabel({})).toBeNull()
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'ZZZZ/QQQQ' })).toBeNull()
|
||||
expect(deriveTransactionLabel({ mcc: '0000' })).toBeNull()
|
||||
// Bare unknown domain without isCredit cannot be classified.
|
||||
expect(deriveTransactionLabel({ bankTransactionCode: 'PMNT' })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,281 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
syncAccountTransactions: vi.fn(),
|
||||
updateBalancesFromSync: vi.fn(),
|
||||
emit: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('../sync', () => ({
|
||||
syncAccountTransactions: (...args: unknown[]) => mocks.syncAccountTransactions(...args),
|
||||
}))
|
||||
vi.mock('@/lib/cash-accounts/service', () => ({
|
||||
updateBalancesFromSync: (...args: unknown[]) => mocks.updateBalancesFromSync(...args),
|
||||
}))
|
||||
vi.mock('@/lib/events/bus', () => ({
|
||||
eventBus: { emit: (...args: unknown[]) => mocks.emit(...args) },
|
||||
}))
|
||||
|
||||
import { SessionExpiredError, REAUTH_REQUIRED_MESSAGE, ConnectorSyncError } from '../api-client'
|
||||
import { SYNC_COOLDOWN_MS, triggerConnectionSync } from '../trigger-sync'
|
||||
|
||||
const COMPANY_ID = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const CONNECTION_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const NOW = Date.parse('2026-09-02T09:00:00Z')
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
interface State {
|
||||
connection: Record<string, unknown> | null
|
||||
membershipRole: string | null
|
||||
sieOverlap: boolean
|
||||
updates: Record<string, unknown>[]
|
||||
/**
|
||||
* The durable lease as the database holds it (epoch when never claimed).
|
||||
* The conditional UPDATE the runner issues (`sync_lease_until <= now`) is
|
||||
* reproduced here: a held lease makes the claim return no row.
|
||||
*/
|
||||
leaseUntil: string
|
||||
}
|
||||
|
||||
const EPOCH = '1970-01-01T00:00:00.000Z'
|
||||
|
||||
function makeClient(state: State) {
|
||||
return {
|
||||
from: (table: string) => {
|
||||
let updatePayload: Record<string, unknown> | null = null
|
||||
let lteFilter: { column: string; value: string } | null = null
|
||||
const chain: Record<string, unknown> = {}
|
||||
const passthrough = ['select', 'eq', 'gte', 'order', 'limit', 'in']
|
||||
for (const m of passthrough) chain[m] = vi.fn(() => chain)
|
||||
chain.lte = vi.fn((column: string, value: string) => {
|
||||
lteFilter = { column, value }
|
||||
return chain
|
||||
})
|
||||
chain.update = vi.fn((payload: Record<string, unknown>) => {
|
||||
updatePayload = payload
|
||||
return chain
|
||||
})
|
||||
const resolve = () => {
|
||||
if (updatePayload && 'sync_lease_until' in updatePayload) {
|
||||
// Atomic claim: `.lte('sync_lease_until', <now>)`.
|
||||
if (lteFilter?.column !== 'sync_lease_until') {
|
||||
throw new Error('lease claim must carry the conditional filter')
|
||||
}
|
||||
if (state.leaseUntil > lteFilter.value) return { data: [], error: null }
|
||||
state.leaseUntil = updatePayload.sync_lease_until as string
|
||||
state.updates.push(updatePayload)
|
||||
return { data: [{ id: CONNECTION_ID }], error: null }
|
||||
}
|
||||
if (updatePayload) {
|
||||
state.updates.push(updatePayload)
|
||||
return { data: null, error: null }
|
||||
}
|
||||
if (table === 'bank_connections') return { data: state.connection, error: null }
|
||||
if (table === 'company_members')
|
||||
return { data: state.membershipRole ? { role: state.membershipRole } : null, error: null }
|
||||
if (table === 'sie_imports') return { data: state.sieOverlap ? { id: 'sie-1' } : null, error: null }
|
||||
if (table === 'transactions') return { data: [{ id: 'tx-1' }], error: null }
|
||||
return { data: null, error: null }
|
||||
}
|
||||
chain.maybeSingle = vi.fn(() => Promise.resolve(resolve()))
|
||||
chain.then = (onFulfilled: (v: unknown) => unknown) => Promise.resolve(resolve()).then(onFulfilled)
|
||||
return chain
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function connection(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: CONNECTION_ID,
|
||||
company_id: COMPANY_ID,
|
||||
bank_name: 'Swedbank',
|
||||
status: 'active',
|
||||
accounts_data: [
|
||||
{ uid: 'acc-1', currency: 'SEK', enabled: true, balance: 100 },
|
||||
{ uid: 'acc-2', currency: 'SEK', enabled: false, balance: 5 },
|
||||
],
|
||||
last_synced_at: new Date(NOW - 2 * DAY_MS).toISOString(),
|
||||
error_message: null,
|
||||
sync_lease_until: EPOCH,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
|
||||
let state: State
|
||||
|
||||
function run(now = NOW) {
|
||||
return triggerConnectionSync(makeClient(state) as never, {
|
||||
companyId: COMPANY_ID,
|
||||
userId: 'user-1',
|
||||
connectionId: CONNECTION_ID,
|
||||
log,
|
||||
now,
|
||||
})
|
||||
}
|
||||
|
||||
describe('triggerConnectionSync', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
state = {
|
||||
connection: connection(),
|
||||
membershipRole: 'owner',
|
||||
sieOverlap: false,
|
||||
updates: [],
|
||||
leaseUntil: EPOCH,
|
||||
}
|
||||
mocks.syncAccountTransactions.mockResolvedValue({ imported: 2, duplicates: 5, errors: 0 })
|
||||
mocks.updateBalancesFromSync.mockResolvedValue(undefined)
|
||||
mocks.emit.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
it('syncs only the enabled accounts over the gap-aware window and stamps last_synced_at', async () => {
|
||||
const result = await run()
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result).toMatchObject({ connection_id: CONNECTION_ID, bank: 'Swedbank', imported: 2, duplicates: 5 })
|
||||
// Synced 2 days ago: the 7-day floor applies.
|
||||
expect(result.from_date).toBe(new Date(NOW - 7 * DAY_MS).toISOString().split('T')[0])
|
||||
expect(result.to_date).toBe('2026-09-02')
|
||||
expect(mocks.syncAccountTransactions).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.syncAccountTransactions.mock.calls[0][4]).toMatchObject({ uid: 'acc-1' })
|
||||
expect(state.updates.at(-1)).toMatchObject({ last_synced_at: result.last_synced_at })
|
||||
// Write-back keeps the disabled account so the user's selection survives.
|
||||
expect((state.updates.at(-1)!.accounts_data as unknown[]).length).toBe(2)
|
||||
expect(mocks.updateBalancesFromSync).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.emit).toHaveBeenCalledWith(expect.objectContaining({ type: 'transaction.synced' }))
|
||||
})
|
||||
|
||||
it('widens the window to cover a longer gap and asks for the deepest history past a month', async () => {
|
||||
state.connection = connection({ last_synced_at: new Date(NOW - 40 * DAY_MS).toISOString() })
|
||||
const result = await run()
|
||||
expect(result.ok).toBe(true)
|
||||
if (!result.ok) return
|
||||
expect(result.from_date).toBe(new Date(NOW - 41 * DAY_MS).toISOString().split('T')[0])
|
||||
expect(mocks.syncAccountTransactions.mock.calls[0][8]).toMatchObject({ strategy: 'longest' })
|
||||
})
|
||||
|
||||
it('refuses with a cooldown when the connection synced within 15 minutes', async () => {
|
||||
const syncedAt = NOW - 5 * 60 * 1000
|
||||
state.connection = connection({ last_synced_at: new Date(syncedAt).toISOString() })
|
||||
const result = await run()
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
code: 'BANK_SYNC_COOLDOWN',
|
||||
next_allowed_at: new Date(syncedAt + SYNC_COOLDOWN_MS).toISOString(),
|
||||
retry_after_seconds: 600,
|
||||
})
|
||||
expect(mocks.syncAccountTransactions).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('claims the durable lease before calling the bank', async () => {
|
||||
await run()
|
||||
expect(state.leaseUntil).toBe(new Date(NOW + SYNC_COOLDOWN_MS).toISOString())
|
||||
// The claim is issued before syncAccountTransactions: the lease row
|
||||
// update is the first write recorded.
|
||||
expect(state.updates[0]).toEqual({ sync_lease_until: state.leaseUntil })
|
||||
})
|
||||
|
||||
it('throttles a failing connection by the lease, not only by last_synced_at', async () => {
|
||||
mocks.syncAccountTransactions.mockRejectedValue(new Error('ASPSP 500'))
|
||||
const first = await run()
|
||||
expect(first).toMatchObject({ ok: false, code: 'BANK_SYNC_FAILED' })
|
||||
// A second instance re-reads the row: the lease is now held.
|
||||
state.connection = connection({ sync_lease_until: state.leaseUntil })
|
||||
const second = await run(NOW + 60 * 1000)
|
||||
expect(second).toMatchObject({
|
||||
ok: false,
|
||||
code: 'BANK_SYNC_COOLDOWN',
|
||||
next_allowed_at: state.leaseUntil,
|
||||
retry_after_seconds: 14 * 60,
|
||||
})
|
||||
expect(mocks.syncAccountTransactions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('loses the race to a concurrent claimer and never calls the bank', async () => {
|
||||
// Our read saw no lease; between the read and the claim another
|
||||
// serverless instance took it. The conditional UPDATE returns no row.
|
||||
state.leaseUntil = new Date(NOW + SYNC_COOLDOWN_MS - 1000).toISOString()
|
||||
const result = await run()
|
||||
expect(result).toMatchObject({ ok: false, code: 'BANK_SYNC_COOLDOWN' })
|
||||
expect(mocks.syncAccountTransactions).not.toHaveBeenCalled()
|
||||
expect(mocks.updateBalancesFromSync).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('accepts a sync once a previous lease has expired', async () => {
|
||||
state.leaseUntil = new Date(NOW - 1000).toISOString()
|
||||
state.connection = connection({ sync_lease_until: state.leaseUntil })
|
||||
const result = await run()
|
||||
expect(result.ok).toBe(true)
|
||||
expect(state.leaseUntil).toBe(new Date(NOW + SYNC_COOLDOWN_MS).toISOString())
|
||||
})
|
||||
|
||||
it('answers NOT_FOUND for a connection outside the company or a non-uuid id', async () => {
|
||||
state.connection = null
|
||||
expect(await run()).toMatchObject({ ok: false, code: 'NOT_FOUND' })
|
||||
const bogus = await triggerConnectionSync(makeClient(state) as never, {
|
||||
companyId: COMPANY_ID,
|
||||
userId: 'user-1',
|
||||
connectionId: 'not-a-uuid',
|
||||
log,
|
||||
now: NOW,
|
||||
})
|
||||
expect(bogus).toMatchObject({ ok: false, code: 'NOT_FOUND' })
|
||||
})
|
||||
|
||||
it('answers NOT_FOUND when the caller is not a member of the company, before any lease or bank call', async () => {
|
||||
state.membershipRole = null
|
||||
expect(await run()).toMatchObject({ ok: false, code: 'NOT_FOUND' })
|
||||
expect(state.leaseUntil).toBe(EPOCH)
|
||||
expect(mocks.syncAccountTransactions).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuses an expired or pending connection: only BankID can fix those', async () => {
|
||||
state.connection = connection({ status: 'expired' })
|
||||
expect(await run()).toMatchObject({ ok: false, code: 'BANK_SYNC_NOT_ACTIVE', status: 'expired' })
|
||||
state.connection = connection({ status: 'pending_selection' })
|
||||
expect(await run()).toMatchObject({ ok: false, code: 'BANK_SYNC_NOT_ACTIVE' })
|
||||
expect(mocks.syncAccountTransactions).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('retries an errored connection and recovers it to active on success', async () => {
|
||||
state.connection = connection({ status: 'error', error_message: 'Banksynkningen misslyckades.' })
|
||||
const result = await run()
|
||||
expect(result.ok).toBe(true)
|
||||
expect(state.updates.at(-1)).toMatchObject({ status: 'active', error_message: null })
|
||||
})
|
||||
|
||||
it('refuses when every account is deselected', async () => {
|
||||
state.connection = connection({ accounts_data: [{ uid: 'acc-1', enabled: false }] })
|
||||
expect(await run()).toMatchObject({ ok: false, code: 'BANK_SYNC_NO_ACCOUNTS' })
|
||||
})
|
||||
|
||||
it('answers retryable and leaves the row alone when the connector hop fails', async () => {
|
||||
state.connection = connection({ status: 'error', error_message: 'old' })
|
||||
mocks.syncAccountTransactions.mockRejectedValue(new ConnectorSyncError(null, 'CONNECTOR_TIMEOUT', 'aborted'))
|
||||
const result = await run()
|
||||
expect(result).toMatchObject({ ok: false, code: 'BANK_SYNC_FAILED', status: 'error' })
|
||||
expect(state.updates.some((u) => 'status' in u || 'error_message' in u)).toBe(false)
|
||||
expect(log.warn).toHaveBeenCalledWith(
|
||||
'agent-triggered bank sync: connector hop failed',
|
||||
expect.objectContaining({ code: 'CONNECTOR_TIMEOUT' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('flips the connection to expired when the bank reports the session dead', async () => {
|
||||
mocks.syncAccountTransactions.mockRejectedValue(new SessionExpiredError(401, 'consent closed'))
|
||||
const result = await run()
|
||||
expect(result).toMatchObject({ ok: false, code: 'BANK_SESSION_EXPIRED', status: 'expired' })
|
||||
expect(state.updates.at(-1)).toMatchObject({ status: 'expired', error_message: REAUTH_REQUIRED_MESSAGE })
|
||||
})
|
||||
|
||||
it('suppresses auto-categorisation over a completed SIE import and for viewers', async () => {
|
||||
state.sieOverlap = true
|
||||
state.membershipRole = 'viewer'
|
||||
await run()
|
||||
expect(mocks.syncAccountTransactions.mock.calls[0][8]).toMatchObject({
|
||||
skipAutoCategorization: true,
|
||||
rawInsertOnly: true,
|
||||
})
|
||||
})
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Resolve a user-stated bank name ("swedbank", "SEB", "handelsbanken") to
|
||||
* one ASPSP from the Enable Banking list, so a deep link can start that
|
||||
* bank's consent directly instead of showing the picker.
|
||||
*
|
||||
* Matching is deliberately conservative: exact (case-insensitive) first,
|
||||
* then a UNIQUE prefix match, then a UNIQUE substring match. An ambiguous
|
||||
* or unknown name returns null and the caller falls back to the picker
|
||||
* with the query prefilled: guessing between "Länsförsäkringar Bank" and a
|
||||
* regional "Länsförsäkringar Skåne" would start a consent at the wrong
|
||||
* institution.
|
||||
*/
|
||||
export function matchBankByName<T extends { name: string }>(
|
||||
banks: T[],
|
||||
query: string
|
||||
): T | null {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (!q) return null
|
||||
|
||||
const exact = banks.filter((b) => b.name.toLowerCase() === q)
|
||||
if (exact.length === 1) return exact[0]
|
||||
if (exact.length > 1) return null
|
||||
|
||||
const prefix = banks.filter((b) => b.name.toLowerCase().startsWith(q))
|
||||
if (prefix.length === 1) return prefix[0]
|
||||
if (prefix.length > 1) return null
|
||||
|
||||
const substring = banks.filter((b) => b.name.toLowerCase().includes(q))
|
||||
if (substring.length === 1) return substring[0]
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { StoredAccount } from '../types'
|
||||
|
||||
/**
|
||||
* Split a connection's accounts into the ones that belong in THIS company's
|
||||
* books and the ones the OAuth callback marked as already booked by another
|
||||
* of the user's companies (`claimed_by_company_id`, see lib/session-sharing).
|
||||
*
|
||||
* At one-session banks (SEB) a single BankID consent returns every account the
|
||||
* signer can see across all their companies, so a reconnect from company A
|
||||
* carries company B's accounts too. Since PR #2116 those arrive unchecked and
|
||||
* unmirrored; this helper is what keeps them out of the main list altogether,
|
||||
* so a user working in company A sees company A's accounts. The claimed set is
|
||||
* still returned (never dropped): the picker renders it behind a collapsed
|
||||
* disclosure, because an account that genuinely belongs here must stay
|
||||
* reachable (a claim is a strong hint, not proof of ownership).
|
||||
*
|
||||
* An account counts as claimed elsewhere only while it is BOTH flagged and
|
||||
* disabled here. Every writer keeps those two in step (the callback sets them
|
||||
* together, the selection save clears the flag on enable), but the invariant
|
||||
* is load-bearing: an account that syncs in this company must never be
|
||||
* tucked out of sight, so a flagged-but-enabled row (a future writer, a
|
||||
* support SQL fix) stays in the main list. The callback already lets the
|
||||
* active company's own standing state outrank a sibling claim, so a legacy
|
||||
* account enabled in both companies carries no flag and stays visible too.
|
||||
*/
|
||||
export function partitionByClaim<T extends Pick<StoredAccount, 'claimed_by_company_id' | 'enabled'>>(
|
||||
accounts: readonly T[],
|
||||
): { own: T[]; claimedElsewhere: T[] } {
|
||||
const own: T[] = []
|
||||
const claimedElsewhere: T[] = []
|
||||
for (const account of accounts) {
|
||||
if (account.claimed_by_company_id && account.enabled === false) claimedElsewhere.push(account)
|
||||
else own.push(account)
|
||||
}
|
||||
return { own, claimedElsewhere }
|
||||
}
|
||||
|
||||
/**
|
||||
* One Swedish line summarising the hidden accounts, e.g.
|
||||
* "2 konton synkas i Testbrand AB" or "3 konton synkas i andra bolag" when the
|
||||
* claimants differ (or a name is missing). "Same claimant" is decided on the
|
||||
* company id, not the display name: two companies can share a name. Empty
|
||||
* string for an empty list so callers can render conditionally on the text.
|
||||
*/
|
||||
export function describeClaimedElsewhere(
|
||||
accounts: readonly Pick<StoredAccount, 'claimed_by_company_id' | 'claimed_by_company_name'>[],
|
||||
): string {
|
||||
if (accounts.length === 0) return ''
|
||||
const noun = accounts.length === 1 ? 'konto' : 'konton'
|
||||
const ids = new Set<string>()
|
||||
const names = new Set<string>()
|
||||
let anonymous = false
|
||||
for (const account of accounts) {
|
||||
if (account.claimed_by_company_id) ids.add(account.claimed_by_company_id)
|
||||
if (account.claimed_by_company_name) names.add(account.claimed_by_company_name)
|
||||
else anonymous = true
|
||||
}
|
||||
if (ids.size === 1 && names.size === 1 && !anonymous) {
|
||||
return `${accounts.length} ${noun} synkas i ${[...names][0]}`
|
||||
}
|
||||
return `${accounts.length} ${noun} synkas i ${accounts.length === 1 ? 'ett annat bolag' : 'andra bolag'}`
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user