fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
masterplan-lock / check (push) Successful in 19s
ci / sonar (push) Failing after 21s
security / scan (push) Failing after 1m37s

Å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:
2026-11-10 09:37:22 +01:00
parent 077251ac94
commit e7f0070e84
6135 changed files with 1718997 additions and 4 deletions
@@ -0,0 +1,24 @@
# Example branding extension
Copy this folder to start a whitelabel fork:
```bash
cp -r extensions/general/_example-branding extensions/general/your-brand
```
Then:
1. Edit `your-brand/manifest.json`: set `id`, `exportName`, `entryPoint`, name, description.
2. Edit `your-brand/index.ts`: uncomment and set the branding values you want to override.
3. Drop your assets in `your-brand/assets/` (logo.svg, favicon.ico, og.png, etc.). Wire up an extension API route to serve them, or set the asset paths in `index.ts` to external CDN URLs.
4. Enable the extension in `extensions.config.json`:
```json
{ "id": "your-brand", "enabled": true }
```
5. Run `npm run setup:extensions && npm run dev`.
See `docs/WHITELABEL.md` for the full fork checklist (env vars, sync workflow, what NOT to change).
## Why a separate extension instead of just env vars?
Both work. Env vars are simpler for scalar overrides (app name, support email). An extension lets you bundle assets (logos, icons) and override values that don't fit cleanly into env vars. You can use both: extension overrides win over env vars.
@@ -0,0 +1,29 @@
import type { Extension } from '@/lib/extensions/types'
import { registerBrandingService } from '@/lib/branding/service'
// Register the whitelabel branding values immediately when this extension is loaded.
// Edit the values below to match your brand. Any field omitted falls back to the
// Accounted default (and to whatever you've set via env vars). See docs/WHITELABEL.md.
registerBrandingService({
// appName: 'YourBrand',
// appDescription: 'Bokföring & redovisning',
// legalEntity: 'YourBrand AB',
// supportEmail: '[email protected]',
// privacyEmail: '[email protected]',
// securityEmail: '[email protected]',
// appUrl: 'https://app.yourbrand.se',
// logoPath: '/api/extensions/ext/_example-branding/assets/logo.svg',
// faviconPath: '/api/extensions/ext/_example-branding/assets/favicon.ico',
// appleTouchIconPath: '/api/extensions/ext/_example-branding/assets/apple-touch-icon-192.png',
// pwaIconBasePath: '/api/extensions/ext/_example-branding/assets/icons',
// themeColor: '#000000',
// manifestThemeColor: '#000000',
// manifestBackgroundColor: '#ffffff',
// hiddenNavHrefs: ['/salary', '/salary/employees', '/customers'],
})
export const exampleBrandingExtension: Extension = {
id: '_example-branding',
name: 'Whitelabel branding (example)',
version: '1.0.0',
}
@@ -0,0 +1,19 @@
{
"id": "_example-branding",
"sector": "general",
"exportName": "exampleBrandingExtension",
"entryPoint": "@/extensions/general/_example-branding",
"workspace": null,
"requiredEnvVars": [],
"optionalEnvVars": [],
"npmDependencies": [],
"definition": {
"name": "Whitelabel branding (example)",
"category": "operations",
"icon": "Palette",
"dataPattern": "core",
"readsCoreTables": [],
"description": "Copy-paste starter for a whitelabel fork. Disabled by default.",
"longDescription": "Template extension for forks that want to rebrand the app. Copy this folder, rename it, edit index.ts with your brand values, drop your logo into assets/, and enable it in extensions.config.json. See docs/WHITELABEL.md for the full fork checklist."
}
}
@@ -0,0 +1,274 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { createMockRequest } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
import { getErrorEntry } from '@/lib/errors/structured-errors'
/**
* Björn Lundén through Lundify's activation redirect (issue #2323).
*
* BL sends the customer back to our callback as
* `?publicKey={User-Key}&extra={state}` instead of OAuth's code/state. The
* callback folds that into the same server-written state row the OAuth
* providers use, then runs the User-Key through the SAME probe-then-store
* path as the manual field (submitProviderToken), owned by the consent's own
* company. These tests pin that nothing about the state handling loosened for
* BL, and that the activation URL /connect hands out follows BL's format.
*/
vi.mock('../lib/migration-orchestrator', () => ({
executeMigration: vi.fn().mockResolvedValue({}),
}))
vi.mock('../lib/provider-client', () => ({
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
mintHandoff: vi.fn(),
consumeHandoff: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn(),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
ProviderTokenInvalidError: class ProviderTokenInvalidError extends Error {
constructor(message: string, public readonly kind: string = 'credentials') {
super(message)
}
},
ProviderCompanyMismatchError: class ProviderCompanyMismatchError extends Error {},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}))
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: vi.fn(),
}))
vi.mock('@/lib/branding/resolve', () => ({ resolveBrandByHost: vi.fn().mockResolvedValue(null) }))
vi.mock('@/lib/auth/oauth-flow-binding', () => ({
requireFlowInitiator: vi.fn(),
FLOW_INITIATOR_MISMATCH_MESSAGE: 'initiator mismatch',
}))
import { arcimMigrationExtension } from '../index'
import { requireFlowInitiator } from '@/lib/auth/oauth-flow-binding'
import {
consumeOAuthState,
exchangeAuthToken,
submitProviderToken,
createConsent,
listConsents,
generateOtc,
getAuthUrl,
ProviderTokenInvalidError,
} from '../lib/provider-client'
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const findRoute = (method: string, path: string) =>
(arcimMigrationExtension.apiRoutes ?? []).find(
(r) => r.method === method && r.path === path,
)!
const callbackHandler = findRoute('GET', '/callback').handler as RouteHandler
const connectHandler = findRoute('POST', '/connect').handler as RouteHandler
const APP_URL = 'https://app.example.test'
const CALLBACK_PATH = '/api/extensions/ext/arcim-migration/callback'
const ACTIVATION_KEY = '36b2bf61-0514-4825-a8a5-08cf151176f2'
const USER_KEY = '1f0e2d3c-4b5a-4c6d-8e7f-0a1b2c3d4e5f'
const blState = {
consentId: 'consent-bl',
provider: 'bjornlunden',
companyId: 'company-1',
userId: 'user-1',
origin: APP_URL,
} as const
const ctxFor = (userId: string) => ({
companyId: 'company-1',
supabase: { auth: { getUser: vi.fn().mockResolvedValue({ data: { user: { id: userId } } }) } },
}) as unknown as ExtensionContext
beforeEach(() => {
vi.clearAllMocks()
vi.stubEnv('NEXT_PUBLIC_APP_URL', APP_URL)
vi.stubEnv('FORTNOX_REDIRECT_URI', '')
vi.stubEnv('VISMA_REDIRECT_URI', '')
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.mocked(requireFlowInitiator).mockResolvedValue({ ok: true, userId: 'user-1' })
vi.mocked(consumeOAuthState).mockResolvedValue(blState)
vi.mocked(submitProviderToken).mockResolvedValue({ success: true, consentId: 'consent-bl' })
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
describe('POST /connect for Björn Lundén', () => {
beforeEach(() => {
vi.mocked(listConsents).mockResolvedValue([])
vi.mocked(createConsent).mockResolvedValue({ id: 'consent-bl' } as Awaited<ReturnType<typeof createConsent>>)
vi.mocked(generateOtc).mockResolvedValue({ code: 'otc-code', consentId: 'consent-bl', expiresAt: '' })
})
const connect = (body: Record<string, unknown>) =>
connectHandler(
createMockRequest(`${APP_URL}/api/extensions/ext/arcim-migration/connect`, { method: 'POST', body }),
ctxFor('user-1'),
)
it('hands out a Lundify activation URL bound to a fresh state row when BL issued a key', async () => {
vi.stubEnv('BJORN_LUNDEN_ACTIVATION_KEY', ACTIVATION_KEY)
const response = await connect({ provider: 'bjornlunden' })
const body = await response.json()
expect(response.status).toBe(200)
expect(body.authType).toBe('token')
expect(body.consentId).toBe('consent-bl')
// The state is minted for THIS consent and user, like the OAuth providers.
expect(generateOtc).toHaveBeenCalledWith('consent-bl', 'user-1', APP_URL)
expect(body.activationUrl).toBe(
`https://lundify.com/activate-integration/${ACTIVATION_KEY}/${encodeURIComponent(`${APP_URL}${CALLBACK_PATH}`)}?extra=otc-code`,
)
// Not an OAuth provider: no authorization URL is built.
expect(getAuthUrl).not.toHaveBeenCalled()
})
it('keeps the manual User-Key path only when no activation key is configured', async () => {
vi.stubEnv('BJORN_LUNDEN_ACTIVATION_KEY', '')
const body = await (await connect({ provider: 'bjornlunden' })).json()
expect(body.authType).toBe('token')
expect(body).not.toHaveProperty('activationUrl')
expect(generateOtc).not.toHaveBeenCalled()
})
it('offers the activation URL on reconnect against the stale consent', async () => {
vi.stubEnv('BJORN_LUNDEN_ACTIVATION_KEY', ACTIVATION_KEY)
vi.mocked(listConsents).mockResolvedValue([
{ id: 'consent-stale', provider: 'bjornlunden', status: 1 },
] as Awaited<ReturnType<typeof listConsents>>)
vi.mocked(generateOtc).mockResolvedValue({ code: 'otc-2', consentId: 'consent-stale', expiresAt: '' })
const body = await (await connect({ provider: 'bjornlunden', reconnect: true })).json()
expect(body).toMatchObject({ consentId: 'consent-stale', authType: 'token', reconnect: true })
expect(generateOtc).toHaveBeenCalledWith('consent-stale', 'user-1', APP_URL)
expect(body.activationUrl).toContain('?extra=otc-2')
expect(createConsent).not.toHaveBeenCalled()
})
it('does not hand other token providers an activation URL', async () => {
vi.stubEnv('BJORN_LUNDEN_ACTIVATION_KEY', ACTIVATION_KEY)
const body = await (await connect({ provider: 'bokio' })).json()
expect(body.authType).toBe('token')
expect(body).not.toHaveProperty('activationUrl')
expect(generateOtc).not.toHaveBeenCalled()
})
})
describe('GET /callback from Lundify (publicKey + extra)', () => {
const request = (params: Record<string, string>) =>
createMockRequest(`${APP_URL}${CALLBACK_PATH}`, { searchParams: params })
it('resolves the consent from the state row and stores the User-Key through submitProviderToken', async () => {
const req = request({ publicKey: USER_KEY, extra: 'otc-code' })
const response = await callbackHandler(req)
const html = await response.text()
expect(response.status).toBe(200)
// `extra` IS the state: the same atomic consumption as OAuth's `state`.
expect(consumeOAuthState).toHaveBeenCalledWith('otc-code')
// The completing session must be the initiator, exactly like OAuth.
expect(requireFlowInitiator).toHaveBeenCalledWith(req, 'user-1', { flow: 'arcim-migration.callback' })
// Same probe-then-store as the manual field; owner = the consent's company
// read server-side, never anything from the query string.
expect(submitProviderToken).toHaveBeenCalledWith(
'consent-bl',
'bjornlunden',
'client_credentials',
USER_KEY,
'company-1',
)
expect(exchangeAuthToken).not.toHaveBeenCalled()
expect(html).toContain('arcim-oauth-success')
expect(html).toContain(`${APP_URL}/import?migration=connected&consentId=consent-bl`)
})
it('shows the registry sentence when the company has not activated the integration', async () => {
vi.mocked(submitProviderToken).mockRejectedValue(
new ProviderTokenInvalidError('no scopes', 'integration-not-activated'),
)
const html = await (await callbackHandler(request({ publicKey: USER_KEY, extra: 'otc-code' }))).text()
expect(html).toContain('arcim-oauth-error')
expect(html).toContain(getErrorEntry('BL_INTEGRATION_NOT_ACTIVATED')!.message_sv)
expect(html).not.toContain('no scopes')
})
it('shows the registry sentence when BL knows no company for the key', async () => {
vi.mocked(submitProviderToken).mockRejectedValue(
new ProviderTokenInvalidError('HTTP 500', 'company-key-not-found'),
)
const html = await (await callbackHandler(request({ publicKey: USER_KEY, extra: 'otc-code' }))).text()
expect(html).toContain(getErrorEntry('BL_COMPANY_KEY_NOT_FOUND')!.message_sv)
})
it('rejects a publicKey without our state before touching any row', async () => {
const html = await (await callbackHandler(request({ publicKey: USER_KEY }))).text()
expect(html).toContain('saknade code eller state')
expect(consumeOAuthState).not.toHaveBeenCalled()
expect(submitProviderToken).not.toHaveBeenCalled()
})
it('rejects a forged or replayed extra with the generic message and stores nothing', async () => {
vi.mocked(consumeOAuthState).mockResolvedValue(null)
const html = await (await callbackHandler(request({ publicKey: USER_KEY, extra: 'forged' }))).text()
expect(html).toContain('Ingen giltig migrationssession hittades')
expect(submitProviderToken).not.toHaveBeenCalled()
expect(requireFlowInitiator).not.toHaveBeenCalled()
})
it('refuses a completing session that is not the initiator', async () => {
vi.mocked(requireFlowInitiator).mockResolvedValue({
ok: false,
reason: 'mismatch',
response: new Response(null, { status: 403 }),
sessionUserId: 'other-user',
})
const html = await (await callbackHandler(request({ publicKey: USER_KEY, extra: 'otc-code' }))).text()
expect(html).toContain('initiator mismatch')
expect(submitProviderToken).not.toHaveBeenCalled()
})
it('does not let a publicKey override an OAuth code on the same request', async () => {
vi.mocked(consumeOAuthState).mockResolvedValue({ ...blState, provider: 'fortnox' })
await callbackHandler(request({ code: 'oauth-code', state: 'otc-code', publicKey: USER_KEY, extra: 'other' }))
expect(consumeOAuthState).toHaveBeenCalledWith('otc-code')
expect(exchangeAuthToken).toHaveBeenCalledWith('consent-bl', 'fortnox', 'oauth-code', `${APP_URL}${CALLBACK_PATH}`)
expect(submitProviderToken).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,255 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { PartyDto, SalesInvoiceDto, SupplierInvoiceDto } from '@/lib/providers/dto'
/**
* Guards the SEK conversion of migrated invoices.
*
* The provider DTOs carry NO exchange rate and NO SEK amount, only a currency
* code and amounts already expressed in it. The mapper used to write
* `exchange_rate: dto.currencyCode === 'SEK' ? null : null`: a ternary that
* returned null on BOTH branches, so every foreign-currency invoice the
* migration imported arrived unconverted, together with null subtotal_sek /
* vat_amount_sek / total_sek.
*
* An imported invoice is räkenskapsinformation (BFL 7 kap): its SEK value is
* part of the record. So the rate must come from the invoice's OWN issue date
* (not today), and when no rate can be established the invoice must be
* REPORTED, never silently nulled and never posted at a fabricated 1:1.
*/
vi.mock('@/lib/currency/riksbanken', () => ({
fetchExchangeRate: vi.fn(),
}))
import { fetchExchangeRate } from '@/lib/currency/riksbanken'
import { buildFxRateIndex, mapSalesInvoice, mapSupplierInvoice } from '../lib/entity-mapper'
const party: PartyDto = { name: 'Motpart AB', identifications: [] }
function salesDto(over: { currencyCode?: string; issueDate?: string } = {}): SalesInvoiceDto {
const currencyCode = over.currencyCode ?? 'SEK'
return {
id: 'inv-1',
invoiceNumber: 'F-100',
issueDate: over.issueDate ?? '2024-03-15',
dueDate: '2024-04-15',
currencyCode,
status: 'sent',
supplier: party,
customer: party,
lines: [
{
id: '1',
description: 'Konsultarvode',
lineExtensionAmount: { value: 1000, currencyCode },
taxPercent: 25,
taxAmount: { value: 250, currencyCode },
},
],
taxTotal: { taxAmount: { value: 250, currencyCode } },
legalMonetaryTotal: {
lineExtensionAmount: { value: 1000, currencyCode },
payableAmount: { value: 1250, currencyCode },
},
paymentStatus: { paid: false, balance: { value: 1250, currencyCode } },
}
}
function supplierDto(over: { currencyCode?: string; issueDate?: string } = {}): SupplierInvoiceDto {
const currencyCode = over.currencyCode ?? 'SEK'
return {
id: 'sinv-1',
invoiceNumber: 'L-200',
issueDate: over.issueDate ?? '2024-03-15',
dueDate: '2024-04-15',
currencyCode,
status: 'booked',
supplier: party,
buyer: party,
lines: [
{
id: '1',
description: 'Licens',
lineExtensionAmount: { value: 1000, currencyCode },
taxPercent: 25,
taxAmount: { value: 250, currencyCode },
},
],
taxTotal: { taxAmount: { value: 250, currencyCode } },
legalMonetaryTotal: {
lineExtensionAmount: { value: 1000, currencyCode },
payableAmount: { value: 1250, currencyCode },
},
paymentStatus: { paid: false, balance: { value: 1250, currencyCode } },
}
}
const supabase = {} as SupabaseClient
beforeEach(() => {
vi.clearAllMocks()
})
describe('invoice item VAT-rate units', () => {
it('keeps customer items in percent and supplier items in decimal fractions', () => {
const sales = mapSalesInvoice(salesDto(), 'user-1', 'company-1', 'customer-1')
const supplier = mapSupplierInvoice(supplierDto(), 'user-1', 'company-1', 'supplier-1')
expect(sales.items[0]?.vat_rate).toBe(25)
expect(supplier.items[0]?.vat_rate).toBe(0.25)
})
it('preserves a foreign supplier rate while converting its unit', () => {
const dto = supplierDto()
dto.lines[0]!.taxPercent = 19
const supplier = mapSupplierInvoice(dto, 'user-1', 'company-1', 'supplier-1')
expect(supplier.items[0]?.vat_rate).toBe(0.19)
})
})
describe('buildFxRateIndex', () => {
it('fetches the rate for each document DATE, not today, and caches per pair', async () => {
;(fetchExchangeRate as Mock).mockImplementation(async (currency: string, date: Date) => ({
currency,
rate: 11.5,
date: date.toISOString().split('T')[0],
}))
const index = await buildFxRateIndex(supabase, [
{ currencyCode: 'EUR', issueDate: '2024-03-15' },
// Same (currency, date) pair: must NOT trigger a second fetch.
{ currencyCode: 'EUR', issueDate: '2024-03-15' },
{ currencyCode: 'EUR', issueDate: '2022-11-02' },
// SEK needs no rate at all.
{ currencyCode: 'SEK', issueDate: '2024-03-15' },
])
expect(fetchExchangeRate).toHaveBeenCalledTimes(2)
// The document's own date is what is asked for.
const askedDates = (fetchExchangeRate as Mock).mock.calls
.map((c) => (c[1] as Date).toISOString().split('T')[0])
.sort()
expect(askedDates).toEqual(['2022-11-02', '2024-03-15'])
// The supabase client is passed so the exchange_rates cache is consulted.
expect((fetchExchangeRate as Mock).mock.calls[0][2]).toBe(supabase)
expect(index.get('EUR|2024-03-15')?.rate).toBe(11.5)
expect(index.get('EUR|2022-11-02')?.rate).toBe(11.5)
})
it('leaves a pair unset when the rate cannot be fetched: never a made-up rate', async () => {
;(fetchExchangeRate as Mock).mockResolvedValue(null)
const index = await buildFxRateIndex(supabase, [{ currencyCode: 'EUR', issueDate: '2024-03-15' }])
expect(index.size).toBe(0)
})
it('skips currencies with no Riksbanken series instead of fetching them', async () => {
const index = await buildFxRateIndex(supabase, [{ currencyCode: 'JPY', issueDate: '2024-03-15' }])
expect(fetchExchangeRate).not.toHaveBeenCalled()
expect(index.size).toBe(0)
})
})
describe.each([
['mapSalesInvoice', (dto: SalesInvoiceDto, fx?: Map<string, never>) =>
mapSalesInvoice(dto, 'user-1', 'company-1', 'customer-1', fx as never), salesDto],
['mapSupplierInvoice', (dto: SupplierInvoiceDto, fx?: Map<string, never>) =>
mapSupplierInvoice(dto, 'user-1', 'company-1', 'supplier-1', fx as never), supplierDto],
] as const)('%s: SEK conversion', (_name, map, makeDto) => {
it('SEK invoice: no exchange rate, SEK amounts equal the invoice amounts', () => {
// A domestic invoice has no rate to record; that null is honest, and the
// *_sek columns still carry the value.
const { invoice, fxUnresolved } = map(makeDto({ currencyCode: 'SEK' }) as never)
expect(invoice.exchange_rate).toBeNull()
expect(invoice.exchange_rate_date).toBeNull()
expect(invoice.subtotal_sek).toBe(1000)
expect(invoice.vat_amount_sek).toBe(250)
expect(invoice.total_sek).toBe(1250)
expect(fxUnresolved).toBeNull()
})
it('EUR invoice with a resolved rate: rate and SEK amounts are populated', () => {
const fx = new Map([
['EUR|2024-03-15', { currency: 'EUR', rate: 11.32, date: '2024-03-15' }],
])
const { invoice, fxUnresolved } = map(
makeDto({ currencyCode: 'EUR', issueDate: '2024-03-15' }) as never,
fx as never
)
expect(invoice.currency).toBe('EUR')
expect(invoice.exchange_rate).toBe(11.32)
expect(invoice.exchange_rate_date).toBe('2024-03-15')
// Rounded to öre through the mapper's round2 helper, never toFixed.
expect(invoice.subtotal_sek).toBe(11320)
expect(invoice.vat_amount_sek).toBe(2830)
expect(invoice.total_sek).toBe(14150)
// Foreign-currency amounts themselves stay in the invoice currency.
expect(invoice.subtotal).toBe(1000)
expect(invoice.total).toBe(1250)
expect(fxUnresolved).toBeNull()
})
it('uses the rate for the invoice DATE, not another date in the index', () => {
const fx = new Map([
['EUR|2024-03-15', { currency: 'EUR', rate: 11.32, date: '2024-03-15' }],
['EUR|2022-11-02', { currency: 'EUR', rate: 10.75, date: '2022-11-02' }],
])
const { invoice } = map(
makeDto({ currencyCode: 'EUR', issueDate: '2022-11-02' }) as never,
fx as never
)
expect(invoice.exchange_rate).toBe(10.75)
expect(invoice.total_sek).toBe(13437.5)
})
it('EUR invoice with no obtainable rate: reported, not silently nulled', () => {
const { invoice, fxUnresolved } = map(
makeDto({ currencyCode: 'EUR', issueDate: '2024-03-15' }) as never,
new Map() as never
)
// Still imported (the record is räkenskapsinformation) but explicitly
// unconverted, so the booking paths refuse it instead of posting at 1:1.
expect(invoice.exchange_rate).toBeNull()
expect(invoice.subtotal_sek).toBeNull()
expect(invoice.vat_amount_sek).toBeNull()
expect(invoice.total_sek).toBeNull()
expect(fxUnresolved).toEqual({ currency: 'EUR', date: '2024-03-15', reason: 'rate_unavailable' })
})
it('currency with no rate source at all is reported as unsupported', () => {
const { invoice, fxUnresolved } = map(
makeDto({ currencyCode: 'JPY', issueDate: '2024-03-15' }) as never,
new Map() as never
)
expect(invoice.exchange_rate).toBeNull()
expect(invoice.total_sek).toBeNull()
expect(fxUnresolved).toEqual({
currency: 'JPY',
date: '2024-03-15',
reason: 'unsupported_currency',
})
})
it('never converts a foreign invoice when no rate index is supplied', () => {
// The regression this locks: a caller that forgets to resolve rates must
// get a REPORT, never a 1:1 conversion.
const { invoice, fxUnresolved } = map(makeDto({ currencyCode: 'EUR' }) as never)
expect(invoice.exchange_rate).toBeNull()
expect(invoice.total_sek).toBeNull()
expect(fxUnresolved?.reason).toBe('rate_unavailable')
})
})
@@ -0,0 +1,333 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import { createMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
/**
* Issues #2211 / #2238: the direct provider connection used to fetch three
* fiscal years as a silent cap (getAllowedFiscalYears in lib/sie-fetcher).
* A first, broken year 2022/2023 simply never arrived and the user asked
* whether they had done something wrong. The cap is a default selection
* now: the preview step renders every source year as a picker, /sie-data
* fetches the ticked years, and the result step names the rest.
*
* These tests lock the plumbing the wizard reads: GET /preview carries
* `sourceYears` (with the default flag), GET /sie-data honours `years` and
* carries `omittedYears`.
*/
vi.mock('../lib/migration-orchestrator', () => ({
executeMigration: vi.fn(),
}))
vi.mock('../lib/provider-client', () => ({
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn(),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
ProviderTokenInvalidError: class ProviderTokenInvalidError extends Error {},
ProviderCompanyMismatchError: class ProviderCompanyMismatchError extends Error {},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}))
vi.mock('../lib/sie-fetcher', () => ({
providerSupportsSie: vi.fn().mockReturnValue(true),
fetchProviderSieFiles: vi.fn(),
getAllowedFiscalYears: vi.fn(),
FiscalYearSelectionError: class FiscalYearSelectionError extends Error {
constructor(public readonly unknownYears: number[]) {
super(`unknown ${unknownYears.join(', ')}`)
}
},
MAX_SELECTED_FISCAL_YEARS: 6,
}))
// The Fortnox asset preview would otherwise go to the network.
vi.mock('../lib/import-assets', () => ({
fetchFortnoxAssetPreview: vi.fn().mockResolvedValue(null),
}))
vi.mock('../lib/mapping-targets', () => ({
buildMappingTargets: vi.fn().mockResolvedValue([]),
}))
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: vi.fn(),
}))
import { arcimMigrationExtension } from '../index'
import { getConsent, resolveConsent, fetchCompanyInfoDirect } from '../lib/provider-client'
import {
fetchProviderSieFiles,
getAllowedFiscalYears,
FiscalYearSelectionError,
MAX_SELECTED_FISCAL_YEARS,
} from '../lib/sie-fetcher'
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
function handler(path: string): RouteHandler {
return (arcimMigrationExtension.apiRoutes ?? []).find((r) => r.method === 'GET' && r.path === path)!
.handler as RouteHandler
}
const CY = new Date().getFullYear()
// One fiscal year inside the window, enough SIE for the parser and the
// validator (#SIETYP + #RAR) so /sie-data reaches its response.
const SIE_IN_WINDOW = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "Bolaget AB"',
`#RAR 0 ${CY}0101 ${CY}1231`,
'#KONTO 1930 "Företagskonto"',
'',
].join('\n')
const BROKEN_FIRST_YEAR = {
year: CY - 4,
fromDate: `${CY - 4}-09-01`,
toDate: `${CY - 3}-12-31`,
inDefaultSelection: false,
}
const CURRENT_YEAR = { year: CY, fromDate: `${CY}-01-01`, toDate: `${CY}-12-31`, inDefaultSelection: true }
const SOURCE_YEARS = [BROKEN_FIRST_YEAR, CURRENT_YEAR]
const OMITTED = [BROKEN_FIRST_YEAR]
function buildCtx(): ExtensionContext {
const { supabase, mockResult } = createMockSupabase()
// Every query in these routes reads lists or counts: none, everywhere.
mockResult({ data: [], count: 0 })
;(supabase as unknown as { auth: unknown }).auth = {
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } } }),
}
return { supabase, companyId: 'company-1' } as unknown as ExtensionContext
}
function request(path: string, consentId = 'consent-1') {
return createMockRequest(`http://localhost/api/extensions/ext/arcim-migration${path}`, {
searchParams: { consentId },
})
}
beforeEach(() => {
vi.clearAllMocks()
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
;(resolveConsent as Mock).mockResolvedValue({
consent: { provider: 'fortnox' },
accessToken: 'tok',
providerCompanyId: undefined,
})
;(fetchCompanyInfoDirect as Mock).mockResolvedValue(null)
;(getAllowedFiscalYears as Mock).mockReturnValue(new Set([CY - 2, CY - 1, CY]))
;(fetchProviderSieFiles as Mock).mockResolvedValue({
files: [{ fiscalYear: CY, rawContent: SIE_IN_WINDOW }],
availableYears: [CY],
sourceYears: SOURCE_YEARS,
failedYears: [],
omittedYears: OMITTED,
})
})
describe('GET /preview: every source year, with the default selection marked (#2211)', () => {
it('answers 401 without a user', async () => {
const ctx = buildCtx()
;(ctx.supabase as unknown as { auth: { getUser: Mock } }).auth.getUser.mockResolvedValue({
data: { user: null },
})
const res = await handler('/preview')(request('/preview'), ctx)
expect(res.status).toBe(401)
})
it('carries every source year with its bounds and default flag, on the default selection', async () => {
const res = await handler('/preview')(request('/preview'), buildCtx())
const { status, body } = await parseJsonResponse<{
sieAvailable: boolean
sieStats: { fiscalYears: number[] }
sourceYears: typeof SOURCE_YEARS
}>(res)
expect(status).toBe(200)
expect(body.sieAvailable).toBe(true)
expect(body.sieStats.fiscalYears).toEqual([CY])
// The bounds as the provider reports them: a broken year is named as
// "2022-09-01 till 2023-12-31", not as a wrong calendar year, and it is
// unticked by default rather than absent.
expect(body.sourceYears).toEqual(SOURCE_YEARS)
// The preview never sends a selection: its stats are the default's.
expect((fetchProviderSieFiles as Mock).mock.calls[0][3]).toBeUndefined()
})
it('hands the picker the same cap /sie-data enforces', async () => {
const res = await handler('/preview')(request('/preview'), buildCtx())
const { body } = await parseJsonResponse<{ maxSelectedYears: number }>(res)
expect(body.maxSelectedYears).toBe(MAX_SELECTED_FISCAL_YEARS)
})
it('still lists the source years when nothing inside the default selection came back', async () => {
;(fetchProviderSieFiles as Mock).mockResolvedValue({
files: [],
availableYears: [],
sourceYears: [BROKEN_FIRST_YEAR],
failedYears: [],
omittedYears: [BROKEN_FIRST_YEAR],
})
const res = await handler('/preview')(request('/preview'), buildCtx())
const { status, body } = await parseJsonResponse<{ sieAvailable: boolean; sourceYears: unknown[] }>(res)
expect(status).toBe(200)
expect(body.sieAvailable).toBe(false)
expect(body.sourceYears).toEqual([BROKEN_FIRST_YEAR])
})
})
describe('GET /sie-data: the ticked years are fetched, the rest are named (#2211, #2238)', () => {
it('answers 400 without a consentId', async () => {
const res = await handler('/sie-data')(
createMockRequest('http://localhost/api/extensions/ext/arcim-migration/sie-data'),
buildCtx(),
)
expect(res.status).toBe(400)
})
it('answers 400 VALIDATION_ERROR on a malformed years selection, before touching the provider', async () => {
const res = await handler('/sie-data')(
createMockRequest('http://localhost/api/extensions/ext/arcim-migration/sie-data', {
searchParams: { consentId: 'consent-1', years: `${CY},abc` },
}),
buildCtx(),
)
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(400)
expect(body.error.code).toBe('VALIDATION_ERROR')
expect(fetchProviderSieFiles).not.toHaveBeenCalled()
})
it('falls back to the default selection without a years param and returns omittedYears', async () => {
const res = await handler('/sie-data')(request('/sie-data'), buildCtx())
const { status, body } = await parseJsonResponse<{
fileStatuses: { fiscalYear: number }[]
failedYears: unknown[]
omittedYears: typeof OMITTED
}>(res)
expect(status).toBe(200)
expect((fetchProviderSieFiles as Mock).mock.calls[0][3]).toBeUndefined()
expect(body.fileStatuses.map((f) => f.fiscalYear)).toEqual([CY])
expect(body.failedYears).toEqual([])
expect(body.omittedYears).toEqual(OMITTED)
})
it('passes the ticked years to the fetcher, deduplicated and oldest first', async () => {
;(fetchProviderSieFiles as Mock).mockResolvedValue({
files: [
{ fiscalYear: CY - 4, rawContent: SIE_IN_WINDOW.replace(`#RAR 0 ${CY}0101 ${CY}1231`, `#RAR 0 ${CY - 4}0901 ${CY - 3}1231`) },
{ fiscalYear: CY, rawContent: SIE_IN_WINDOW },
],
availableYears: [CY - 4, CY],
sourceYears: SOURCE_YEARS,
failedYears: [],
omittedYears: [],
})
const res = await handler('/sie-data')(
createMockRequest('http://localhost/api/extensions/ext/arcim-migration/sie-data', {
searchParams: { consentId: 'consent-1', years: `${CY},${CY - 4},${CY}` },
}),
buildCtx(),
)
const { status, body } = await parseJsonResponse<{
fileStatuses: { fiscalYear: number }[]
omittedYears: unknown[]
}>(res)
expect(status).toBe(200)
expect((fetchProviderSieFiles as Mock).mock.calls[0][3]).toEqual({ years: [CY - 4, CY] })
expect(body.fileStatuses.map((f) => f.fiscalYear)).toEqual([CY - 4, CY])
expect(body.omittedYears).toEqual([])
})
it('accepts a selection at the cap and rejects one over it before any provider call', async () => {
const atCap = Array.from({ length: MAX_SELECTED_FISCAL_YEARS }, (_, i) => CY - i)
const overCap = [...atCap, CY - MAX_SELECTED_FISCAL_YEARS]
const ok = await handler('/sie-data')(
createMockRequest('http://localhost/api/extensions/ext/arcim-migration/sie-data', {
searchParams: { consentId: 'consent-1', years: atCap.join(',') },
}),
buildCtx(),
)
expect(ok.status).toBe(200)
expect((fetchProviderSieFiles as Mock).mock.calls[0][3]).toEqual({
years: [...atCap].sort((a, b) => a - b),
})
vi.clearAllMocks()
const rejected = await handler('/sie-data')(
createMockRequest('http://localhost/api/extensions/ext/arcim-migration/sie-data', {
searchParams: { consentId: 'consent-1', years: overCap.join(',') },
}),
buildCtx(),
)
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(rejected)
expect(status).toBe(400)
expect(body.error.code).toBe('VALIDATION_ERROR')
expect(body.error.message).toContain(String(MAX_SELECTED_FISCAL_YEARS))
// Refused before the consent is even resolved: no provider work at all.
expect(fetchProviderSieFiles).not.toHaveBeenCalled()
expect(resolveConsent).not.toHaveBeenCalled()
})
it('rejects a ticked year the source does not have, as the fetcher reports it before any export', async () => {
;(fetchProviderSieFiles as Mock).mockRejectedValue(new FiscalYearSelectionError([CY - 7]))
const res = await handler('/sie-data')(
createMockRequest('http://localhost/api/extensions/ext/arcim-migration/sie-data', {
searchParams: { consentId: 'consent-1', years: `${CY},${CY - 7}` },
}),
buildCtx(),
)
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
expect(status).toBe(400)
expect(body.error.code).toBe('VALIDATION_ERROR')
expect(body.error.message).toContain(String(CY - 7))
})
it('names the selection in PROVIDER_SIE_NO_YEARS when none of the ticked years exist at the source', async () => {
;(fetchProviderSieFiles as Mock).mockResolvedValue({
files: [],
availableYears: [],
sourceYears: SOURCE_YEARS,
failedYears: [],
omittedYears: SOURCE_YEARS,
})
const res = await handler('/sie-data')(
createMockRequest('http://localhost/api/extensions/ext/arcim-migration/sie-data', {
searchParams: { consentId: 'consent-1', years: `${CY - 7}` },
}),
buildCtx(),
)
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
expect(status).toBe(404)
expect(body.error.code).toBe('PROVIDER_SIE_NO_YEARS')
expect(body.error.message).toContain(String(CY - 7))
})
})
@@ -0,0 +1,80 @@
import { describe, it, expect, vi } from 'vitest'
/**
* The voucher-attachment scopes (Arkivplats + Koppla filer) are opt-in per
* authorize call rather than part of every Fortnox connect. Two reasons, both
* of which have already cost us once:
*
* 1. Fortnox derives its customer licence requirements from what the
* integration requests, so asking every customer for Arkivplats would put
* a licence in front of people who never import a receipt.
* 2. A scope the registered app lacks makes authorize reject with
* invalid_scope before login. Keeping it off the ordinary connect means
* the blast radius of getting it wrong is the underlag flow, not every
* Fortnox connection in production (incident 2026-08-13).
*/
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => ({ from: vi.fn() }),
createServiceClientNoCookies: () => ({ from: vi.fn() }),
}))
vi.mock('@/lib/providers/oauth-config', () => ({
getOAuthConfig: () => ({
clientId: 'client-id',
clientSecret: 'client-secret',
redirectUri: 'https://accounted.example.test/callback',
}),
}))
import {
fortnoxConsentScopes,
FORTNOX_DOCUMENT_SCOPES,
} from '@/lib/providers/fortnox/oauth'
import { getAuthUrl } from '../lib/provider-client'
const scopesOf = (url: string) =>
new URL(url).searchParams.get('scope')?.split(' ') ?? []
describe('Fortnox document scopes are opt-in', () => {
it('leaves the attachment scopes out of an ordinary consent', () => {
expect(fortnoxConsentScopes()).not.toContain('archive')
expect(fortnoxConsentScopes()).not.toContain('connectfile')
})
// The OAuth callback overwrites the consent's tokens in place, so a document
// consent that dropped the base scopes would silently revoke the migration's
// own access to the ledger it just imported.
it('never drops the base scopes when asking for the attachment scopes', () => {
const base = fortnoxConsentScopes()
const withDocuments = fortnoxConsentScopes({ documents: true })
for (const scope of base) {
expect(withDocuments).toContain(scope)
}
expect(withDocuments.length).toBeGreaterThanOrEqual(base.length)
expect(new Set(withDocuments).size).toBe(withDocuments.length)
})
it('names both attachment scopes, so the portal registration has a source of truth', () => {
expect(FORTNOX_DOCUMENT_SCOPES).toEqual(['archive', 'connectfile'])
})
it('builds the ordinary connect URL without the attachment scopes', async () => {
const { url } = await getAuthUrl('fortnox', 'state-1', 'https://cb.test')
expect(scopesOf(url)).toEqual(fortnoxConsentScopes())
expect(scopesOf(url)).not.toContain('archive')
})
it('builds the underlag reconnect URL from the document consent scopes', async () => {
const { url } = await getAuthUrl('fortnox', 'state-2', 'https://cb.test', {
documentScopes: true,
})
expect(scopesOf(url)).toEqual(fortnoxConsentScopes({ documents: true }))
for (const scope of fortnoxConsentScopes()) {
expect(scopesOf(url)).toContain(scope)
}
})
})
@@ -0,0 +1,43 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { decryptHandoffValue, encryptHandoffValue } from '../lib/handoff-crypto'
describe('handoff encryption', () => {
const context = JSON.stringify(['token', 'consent', 'user', 'https://brand.example', 'provider_code'])
beforeEach(() => vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'test-only-server-secret'))
afterEach(() => vi.unstubAllEnvs())
it('encrypts identical values differently and preserves Unicode error text', () => {
const plaintext = 'Återanrop: känsligt fel <script>'
const first = encryptHandoffValue(plaintext, context)
expect(first).not.toContain(plaintext)
expect(first).not.toBe(encryptHandoffValue(plaintext, context))
expect(decryptHandoffValue(first, context)).toBe(plaintext)
})
it('authenticates the ciphertext and rejects tampering', () => {
const encrypted = encryptHandoffValue('provider-code', context)
const bytes = Buffer.from(encrypted.slice(3), 'base64url')
bytes[bytes.length - 1] ^= 1
expect(() => decryptHandoffValue('v1:' + bytes.toString('base64url'), context)).toThrow()
})
it.each([0, 1, 2, 3, 4])('rejects swapping context component %s', (index) => {
const encrypted = encryptHandoffValue('provider-code', context)
const modified = JSON.parse(context) as string[]
modified[index] += '-different'
expect(() => decryptHandoffValue(encrypted, JSON.stringify(modified))).toThrow()
})
it('rejects plaintext and a different server secret', () => {
expect(() => decryptHandoffValue('provider-code', context)).toThrow()
const encrypted = encryptHandoffValue('provider-code', context)
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'different-server-secret')
expect(() => decryptHandoffValue(encrypted, context)).toThrow()
})
it('refuses to store credentials when the server secret is missing', () => {
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', '')
expect(() => encryptHandoffValue('provider-code', context)).toThrow('SUPABASE_SERVICE_ROLE_KEY is required')
})
})
@@ -0,0 +1,339 @@
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import { createMockRequest, createMockSupabase, parseJsonResponse } from '@/tests/helpers'
import { eventBus } from '@/lib/events/bus'
import type { ExtensionContext } from '@/lib/extensions/types'
vi.mock('../lib/import-documents', () => {
class FortnoxDocumentScopesRequiredError extends Error {
readonly code = 'PROVIDER_DOCUMENT_SCOPES_REQUIRED'
constructor() {
super('Fortnox consent lacks archive/connectfile scope: reconnect required')
}
}
return {
FortnoxDocumentScopesRequiredError,
importProviderDocuments: vi.fn(),
}
})
const fortnoxOAuth = vi.hoisted(() => ({ documentScopesApproved: false }))
vi.mock('@/lib/providers/fortnox/oauth', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@/lib/providers/fortnox/oauth')>()
return {
...actual,
get FORTNOX_DOCUMENT_SCOPES_APPROVED() {
return fortnoxOAuth.documentScopesApproved
},
}
})
vi.mock('../lib/provider-client', () => {
class ProviderTokenInvalidError extends Error {
constructor(
message: string,
readonly kind:
| 'credentials'
| 'company-not-found'
| 'integration-not-activated'
| 'company-key-not-found' = 'credentials',
) {
super(message)
}
}
return {
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn(),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
ProviderTokenInvalidError,
ProviderCompanyMismatchError: class ProviderCompanyMismatchError extends Error {},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}
})
import { arcimMigrationExtension } from '../index'
import {
FortnoxDocumentScopesRequiredError,
importProviderDocuments,
} from '../lib/import-documents'
import {
ProviderTokenInvalidError,
submitProviderToken,
} from '../lib/provider-client'
const route = (arcimMigrationExtension.apiRoutes ?? []).find(
(candidate) =>
candidate.method === 'POST' && candidate.path === '/import-documents',
)!
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const handler = route.handler as RouteHandler
const submitTokenRoute = (arcimMigrationExtension.apiRoutes ?? []).find(
(candidate) => candidate.method === 'POST' && candidate.path === '/submit-token',
)!
const submitTokenHandler = submitTokenRoute.handler as RouteHandler
function buildContext(): ExtensionContext {
const { supabase } = createMockSupabase()
;(supabase as unknown as { auth: unknown }).auth = {
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } } }),
}
return { supabase, companyId: 'company-1' } as unknown as ExtensionContext
}
function request(dryRun: boolean) {
return createMockRequest(
'http://localhost/api/extensions/ext/arcim-migration/import-documents',
{
method: 'POST',
body: { consentId: 'consent-1', dryRun },
},
)
}
function submitTokenRequest() {
return createMockRequest(
'http://localhost/api/extensions/ext/arcim-migration/submit-token',
{
method: 'POST',
body: {
consentId: 'consent-1',
provider: 'bokio',
apiToken: 'not-a-real-token',
companyId: '9b408943-7a1e-47ac-85a7-ac52b2c210d3',
},
},
)
}
describe('POST /import-documents', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
fortnoxOAuth.documentScopesApproved = false
})
it('passes dry-run discovery through without storing documents', async () => {
;(importProviderDocuments as Mock).mockResolvedValue({
provider: 'fortnox',
scanned: 4,
linked: 3,
skipped: 0,
unmatched: 1,
failed: 0,
dryRun: true,
unmatchedSamples: [],
})
const response = await handler(request(true), buildContext())
const { status, body } = await parseJsonResponse<{
success: boolean
dryRun: boolean
result: { scanned: number }
}>(response)
expect(status).toBe(200)
expect(body).toMatchObject({ success: true, dryRun: true, result: { scanned: 4 } })
expect(importProviderDocuments).toHaveBeenCalledWith(
expect.objectContaining({
companyId: 'company-1',
consentId: 'consent-1',
dryRun: true,
}),
)
})
it('passes a non-empty string cursor through and restarts from the top for anything else', async () => {
;(importProviderDocuments as Mock).mockResolvedValue({
provider: 'fortnox',
scanned: 1,
linked: 1,
skipped: 0,
unmatched: 0,
failed: 0,
dryRun: false,
unmatchedSamples: [],
total: 113,
partial: true,
nextCursor: 'file-18',
})
const withCursor = createMockRequest(
'http://localhost/api/extensions/ext/arcim-migration/import-documents',
{ method: 'POST', body: { consentId: 'consent-1', dryRun: false, cursor: 'file-17' } },
)
const { status, body } = await parseJsonResponse<{
result: { partial: boolean; nextCursor: string | null }
}>(await handler(withCursor, buildContext()))
expect(status).toBe(200)
expect(body.result).toMatchObject({ partial: true, nextCursor: 'file-18' })
expect(importProviderDocuments).toHaveBeenLastCalledWith(
expect.objectContaining({ consentId: 'consent-1', dryRun: false, cursor: 'file-17' }),
)
const garbage = createMockRequest(
'http://localhost/api/extensions/ext/arcim-migration/import-documents',
{ method: 'POST', body: { consentId: 'consent-1', cursor: 17 } },
)
await handler(garbage, buildContext())
expect(importProviderDocuments).toHaveBeenLastCalledWith(
expect.objectContaining({ cursor: null }),
)
})
it('asks the user to reconnect only once the connect request carries the scopes', async () => {
fortnoxOAuth.documentScopesApproved = true
;(importProviderDocuments as Mock).mockRejectedValue(
new FortnoxDocumentScopesRequiredError(),
)
const response = await handler(request(false), buildContext())
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en?: string }
}>(response)
expect(status).toBe(403)
expect(body.error.code).toBe('PROVIDER_DOCUMENT_SCOPES_REQUIRED')
expect(body.error.message).toContain('Koppla om Fortnox')
expect(body.error.message_en).toContain('Reconnect Fortnox')
})
// Klura AB, 2026-08-20: the connect request does not ask Fortnox for Arkiv
// and Koppla fil at all, so the reconnect advice sent the user around a loop
// four times (and to buy the Fortnox Arkiv module) for nothing.
it('says the permission is missing on our side while the scopes are unapproved', async () => {
fortnoxOAuth.documentScopesApproved = false
;(importProviderDocuments as Mock).mockRejectedValue(
new FortnoxDocumentScopesRequiredError(),
)
const response = await handler(request(false), buildContext())
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en?: string }
}>(response)
expect(status).toBe(403)
expect(body.error.code).toBe('PROVIDER_DOCUMENT_SCOPES_UNAVAILABLE')
expect(body.error.message).not.toContain('Koppla om Fortnox')
expect(body.error.message).toContain('Att koppla om hjälper inte')
expect(body.error.message_en).toContain('Reconnecting will not help')
})
})
describe('POST /submit-token Bokio error mapping', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
it('reports a 401/403 authentication verdict as rejected integration details', async () => {
;(submitProviderToken as Mock).mockRejectedValue(
new ProviderTokenInvalidError('Bokio rejected the integration token (HTTP 403)'),
)
const response = await submitTokenHandler(submitTokenRequest(), buildContext())
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en?: string }
}>(response)
expect(status).toBe(422)
expect(body.error.code).toBe('PROVIDER_TOKEN_INVALID')
expect(body.error.message).toContain('avvisade autentiseringen')
expect(body.error.message_en).toContain('rejected the authentication')
})
it('reports a Bokio 404 as a company-ID failure instead of rejected credentials', async () => {
;(submitProviderToken as Mock).mockRejectedValue(
new ProviderTokenInvalidError(
'Bokio does not know that company id',
'company-not-found',
),
)
const response = await submitTokenHandler(submitTokenRequest(), buildContext())
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en?: string }
}>(response)
expect(status).toBe(422)
expect(body.error.code).toBe('BOKIO_COMPANY_NOT_FOUND')
expect(body.error.message).toContain('företags-ID')
expect(body.error.message_en).toContain('company ID')
})
it('keeps an unclassified provider/configuration failure generic', async () => {
;(submitProviderToken as Mock).mockRejectedValue(
new Error('Bokio company-information response is missing companyInformation'),
)
const response = await submitTokenHandler(submitTokenRequest(), buildContext())
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en?: string }
}>(response)
expect(status).toBe(500)
expect(body.error.code).toBe('PROVIDER_TOKEN_SUBMIT_FAILED')
expect(body.error.message).toContain('kontrollera integrationsuppgifterna')
expect(body.error.message_en).toContain('verify the integration details')
})
})
describe('POST /submit-token Björn Lundén error mapping', () => {
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
it('reports a valid key whose company never activated the integration as an activation problem, not bad credentials', async () => {
;(submitProviderToken as Mock).mockRejectedValue(
new ProviderTokenInvalidError(
'Björn Lundén: the company behind this User-Key has not activated the integration',
'integration-not-activated',
),
)
const response = await submitTokenHandler(submitTokenRequest(), buildContext())
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en?: string }
}>(response)
expect(status).toBe(422)
expect(body.error.code).toBe('BL_INTEGRATION_NOT_ACTIVATED')
expect(body.error.message).toContain('Aktivera integrationen')
expect(body.error.message).not.toContain('avvisade autentiseringen')
expect(body.error.message_en).toContain('Activate the integration')
})
it('reports an unknown User-Key as a key problem with the place to copy it from', async () => {
;(submitProviderToken as Mock).mockRejectedValue(
new ProviderTokenInvalidError(
'Björn Lundén found no company for the key (HTTP 500)',
'company-key-not-found',
),
)
const response = await submitTokenHandler(submitTokenRequest(), buildContext())
const { status, body } = await parseJsonResponse<{
error: { code: string; message: string; message_en?: string }
}>(response)
expect(status).toBe(422)
expect(body.error.code).toBe('BL_COMPANY_KEY_NOT_FOUND')
expect(body.error.message).toContain('hittade inget företag')
expect(body.error.message_en).toContain('found no company')
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,146 @@
/**
* Tests for the CP1252-mojibake tripwire on POST /import-sie.
*
* This handler receives SIE as an ALREADY-DECODED string (rawContent in JSON),
* so an upstream that decoded CP437 bytes as windows-1252 has baked the
* corruption in before the repo's own encoding detection could run: exactly
* what the retired Arcim Sync gateway did on 2026-03-17, landing mojibake
* ("L”neutbetalning", "BANKTJŽNSTER") in posted entries with no warning.
*
* The tripwire must WARN and NEVER BLOCK: the import proceeds untouched and
* the warning rides on result.warnings, which the migration workspace UI
* already renders. The mojibake literals below are the subject under test and
* must stay byte-exact.
*/
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
vi.mock('@/lib/import/sie-import', () => ({
loadMappings: vi.fn(),
generateImportPreview: vi.fn(),
executeSIEImport: vi.fn(),
}))
import { arcimMigrationExtension } from '../index'
import { executeSIEImport } from '@/lib/import/sie-import'
const importSieRoute = (arcimMigrationExtension.apiRoutes ?? []).find(
(r) => r.method === 'POST' && r.path === '/import-sie',
)!
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const handler = importSieRoute.handler as RouteHandler
const MOJIBAKE_SIE = [
'#FLAGGA 0',
'#SIETYP 4',
'#FNAMN "Migrerad AB"',
'#RAR 0 20240101 20241231',
'#KONTO 1930 "F”retagskonto"',
'#KONTO 4056 "Ink”p tj„nster inom EU"',
'#VER A 1 20240115 "L”neutbetalning"',
'{',
'#TRANS 1930 {} -100.00',
'#TRANS 4056 {} 100.00',
'}',
].join('\n')
const CLEAN_SIE = MOJIBAKE_SIE
.replace('F”retagskonto', 'Företagskonto')
.replace('Ink”p tj„nster inom EU', 'Inköp tjänster inom EU')
.replace('L”neutbetalning', 'Löneutbetalning')
const MAPPINGS = [
{ sourceAccount: '1930', sourceName: 'Företagskonto', targetAccount: '1930' },
{ sourceAccount: '4056', sourceName: 'Inköp tjänster inom EU', targetAccount: '4056' },
]
function buildCtx(userId: string | null) {
const log = { info: vi.fn(), warn: vi.fn(), error: vi.fn() }
const supabase = {
auth: {
getUser: vi.fn().mockResolvedValue({ data: { user: userId ? { id: userId } : null } }),
},
}
const ctx = { supabase, companyId: 'company-1', log } as unknown as ExtensionContext
return { ctx, log }
}
function importRequest(body: Record<string, unknown>) {
return createMockRequest('http://localhost/api/extensions/ext/arcim-migration/import-sie', {
method: 'POST',
body,
})
}
describe('POST /import-sie: mojibake tripwire', () => {
beforeEach(() => {
vi.clearAllMocks()
// Fresh result object per call: the handler pushes onto result.warnings.
;(executeSIEImport as Mock).mockImplementation(async () => ({
success: true,
journalEntriesCreated: 1,
errors: [],
warnings: [],
}))
})
it('returns 401 when unauthenticated', async () => {
const { ctx } = buildCtx(null)
const response = await handler(
importRequest({ rawContent: CLEAN_SIE, mappings: MAPPINGS, options: {} }),
ctx,
)
expect(response.status).toBe(401)
expect(executeSIEImport).not.toHaveBeenCalled()
})
it('returns 400 when rawContent is missing', async () => {
const { ctx } = buildCtx('user-1')
const response = await handler(importRequest({ mappings: MAPPINGS, options: {} }), ctx)
expect(response.status).toBe(400)
expect(executeSIEImport).not.toHaveBeenCalled()
})
it('surfaces a Swedish warning on mojibaked content WITHOUT blocking the import', async () => {
const { ctx, log } = buildCtx('user-1')
const response = await handler(
importRequest({ rawContent: MOJIBAKE_SIE, mappings: MAPPINGS, options: {} }),
ctx,
)
const { status, body } = await parseJsonResponse<{ warnings: string[] }>(response)
expect(status).toBe(200)
// Warn, never block: the import ran despite the flagged content.
expect(executeSIEImport).toHaveBeenCalledTimes(1)
const tripwire = body.warnings.find((w) => w.includes('felaktigt teckenkodad'))
expect(tripwire).toBeDefined()
// The first flagged string (accounts are scanned first) is the example.
expect(tripwire).toContain('F”retagskonto')
// Must dodge the workspace UI's structured-card filters, or the warning
// silently disappears from the "Remaining warnings" card.
expect(tripwire).not.toContain('hoppades över')
expect(tripwire).not.toContain('förts om till eget kapital')
expect(log.warn).toHaveBeenCalledWith(
'import-sie: CP1252 mojibake artifacts in SIE text',
expect.objectContaining({ artifactCount: 3 }),
)
})
it('adds no warning for clean content', async () => {
const { ctx, log } = buildCtx('user-1')
const response = await handler(
importRequest({ rawContent: CLEAN_SIE, mappings: MAPPINGS, options: {} }),
ctx,
)
const { status, body } = await parseJsonResponse<{ warnings: string[] }>(response)
expect(status).toBe(200)
expect(executeSIEImport).toHaveBeenCalledTimes(1)
expect(body.warnings.some((w) => w.includes('felaktigt teckenkodad'))).toBe(false)
expect(log.warn).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,32 @@
/**
* Guard against re-adding a direct saveMappings() call to the migration
* wizard's /import-sie handler.
*
* The handler used to run `await saveMappings(supabase, user.id, mappings)`
* before executeSIEImport: user.id in the companyId slot. Once saveMappings
* started surfacing upsert failures (and filling user_id), that call threw on
* RLS/FK on every request, 500ing every provider-migration import before a
* single voucher was written. The call was also redundant: executeSIEImport
* saves the mappings itself (lib/import/sie-import.ts), with the correct
* companyId + userId and non-fatal warning handling.
*
* A source-level assertion is deliberate: the handler builds its Supabase
* client inline and the failure mode is "a future refactor re-imports the
* helper", which this catches regardless of how the handler is wired.
*/
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
const indexSource = readFileSync(fileURLToPath(new URL('../index.ts', import.meta.url)), 'utf8')
describe('arcim-migration /import-sie handler', () => {
it('does not call saveMappings directly (executeSIEImport persists mappings itself)', () => {
expect(indexSource).not.toMatch(/\bsaveMappings\s*\(/)
expect(indexSource).not.toMatch(/import\s*\{[^}]*\bsaveMappings\b[^}]*\}/)
})
it('still routes the import through executeSIEImport, which owns mapping persistence', () => {
expect(indexSource).toContain('executeSIEImport(supabase, companyId, user.id, parsed, mappings')
})
})
@@ -0,0 +1,97 @@
/**
* Issue #2212: the guided import's mapping step offered no target for a
* Fortnox account that exists in neither the company chart nor BAS (4599),
* and the user could not tell whether the import handled it.
*
* These tests run the exact resolution /sie-data runs (buildMappingTargets
* then suggestMappings) and pin the contract the mapping step now renders:
* - an in-range source account the chart lacks resolves to ITSELF and is
* created on import with the class and type the importer derives from
* the number (classifyAccount: the same helper syncMappedAccounts uses);
* - that holds with or without a #KONTO name;
* - a number outside 1000-8999 stays unresolved and blocks the step.
*/
import { describe, expect, it } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { buildMappingTargets } from '../lib/mapping-targets'
import { suggestMappings, validateMappings, isValidBASRange } from '@/lib/import/account-mapper'
import { classifyAccount } from '@/lib/bookkeeping/account-classifier'
import { getBASReference } from '@/lib/bookkeeping/bas-reference'
/** A company whose chart holds only the given rows (one page, then empty). */
function supabaseWithChart(rows: Array<Record<string, unknown>>): SupabaseClient {
let served = false
const builder = {
select: () => builder,
eq: () => builder,
order: () => builder,
range: () => Promise.resolve({ data: served ? [] : ((served = true), rows), error: null }),
}
return { from: () => builder } as unknown as SupabaseClient
}
describe('guided import: resolving a source account the target chart lacks', () => {
it('4599 is in neither BAS nor an empty chart, so no dropdown target exists for it', async () => {
expect(getBASReference('4599')).toBeUndefined()
const targets = await buildMappingTargets(supabaseWithChart([]), 'company-1')
expect(targets.find((t) => t.account_number === '4599')).toBeUndefined()
})
// The user's case: a #KONTO row with a name and no postings in any exported
// year. It resolves to itself; the import creates it under the file's name.
it('self-maps a named #KONTO-only account onto its own number', async () => {
const targets = await buildMappingTargets(supabaseWithChart([]), 'company-1')
const [mapping] = suggestMappings([{ number: '4599', name: 'Justering inköp' }], targets)
expect(mapping.targetAccount).toBe('4599')
expect(mapping.targetName).toBe('Justering inköp')
expect(mapping.matchType).toBe('bas_range')
expect(validateMappings([mapping]).valid).toBe(true)
})
// The other route to the same screen: an account referenced by #TRANS/#IB
// without a #KONTO row arrives nameless. It must resolve the same way; the
// importer names it "Konto 4599" (account-sync fallback, tested there).
it('self-maps a nameless account referenced only by transactions', async () => {
const targets = await buildMappingTargets(supabaseWithChart([]), 'company-1')
const [mapping] = suggestMappings([{ number: '4599', name: '' }], targets)
expect(mapping.targetAccount).toBe('4599')
expect(mapping.matchType).toBe('bas_range')
expect(validateMappings([mapping]).valid).toBe(true)
})
// The type the created account gets is derived from the number range by
// the importer's own classifier, never asked of the user.
it('derives the created account type from the number range', () => {
expect(classifyAccount('4599')).toEqual({ account_type: 'expense', normal_balance: 'debit' })
expect(classifyAccount('1932')).toEqual({ account_type: 'asset', normal_balance: 'debit' })
expect(classifyAccount('2093')).toEqual({ account_type: 'equity', normal_balance: 'credit' })
})
// Nothing can be created for a number outside BAS: the step must block and
// the user must pick a chart account for its postings.
it('leaves an out-of-range account unresolved so the step blocks', async () => {
const targets = await buildMappingTargets(supabaseWithChart([]), 'company-1')
const [mapping] = suggestMappings([{ number: '9100', name: 'Internt konto' }], targets)
expect(mapping.targetAccount).toBe('')
expect(isValidBASRange('9100')).toBe(false)
expect(validateMappings([mapping])).toMatchObject({ valid: false, unmappedAccounts: ['9100'] })
})
// A company that already renamed the account keeps its own row as the
// target (exact match on the chart), so nothing is created twice.
it('prefers the company row when the account already exists in the chart', async () => {
const targets = await buildMappingTargets(
supabaseWithChart([{ account_number: '4599', account_name: 'Eget namn', account_class: 4 }]),
'company-1',
)
const [mapping] = suggestMappings([{ number: '4599', name: 'Justering inköp' }], targets)
expect(mapping.targetAccount).toBe('4599')
expect(mapping.targetName).toBe('Eget namn')
expect(mapping.matchType).toBe('exact')
})
})
@@ -0,0 +1,82 @@
import { describe, expect, it } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { buildMappingTargets } from '../lib/mapping-targets'
/**
* A chart_of_accounts read that returns the given rows for any range, which is
* all fetchAllRows needs: one page, then an empty one.
*/
function supabaseWith(rows: Array<Record<string, unknown>> | Error): SupabaseClient {
let served = false
const range = () =>
rows instanceof Error
? Promise.resolve({ data: null, error: { message: rows.message } })
: Promise.resolve({ data: served ? [] : ((served = true), rows), error: null })
const builder = {
select: () => builder,
eq: () => builder,
order: () => builder,
range,
}
return { from: () => builder } as unknown as SupabaseClient
}
describe('buildMappingTargets', () => {
// The bug this file exists for: BAS defines 3000-3004 and stops, so a
// company account like 3005 was active in the chart, visible everywhere else
// in the app, and still absent from the migration's mapping dropdown.
it('offers a company account that BAS does not define', async () => {
const targets = await buildMappingTargets(
supabaseWith([
{ account_number: '3005', account_name: 'Provisioner inom Sverige', account_class: 3 },
]),
'company-1',
)
const found = targets.find((t) => t.account_number === '3005')
expect(found?.account_name).toBe('Provisioner inom Sverige')
})
it('still offers standard accounts the company has not created', async () => {
const targets = await buildMappingTargets(supabaseWith([]), 'company-1')
expect(targets.find((t) => t.account_number === '1930')).toBeTruthy()
expect(targets.length).toBeGreaterThan(1000)
})
// The user renamed it; that is the label they will look for.
it('prefers the company name over the BAS name on a collision', async () => {
const targets = await buildMappingTargets(
supabaseWith([
{ account_number: '3001', account_name: 'Försäljning konsulttjänster', account_class: 3 },
]),
'company-1',
)
const matches = targets.filter((t) => t.account_number === '3001')
expect(matches).toHaveLength(1)
expect(matches[0].account_name).toBe('Försäljning konsulttjänster')
})
it('derives the class from the number when the row has none', async () => {
const targets = await buildMappingTargets(
supabaseWith([{ account_number: '3005', account_name: 'X', account_class: null }]),
'company-1',
)
expect(targets.find((t) => t.account_number === '3005')?.account_class).toBe(3)
})
it('sorts by account number so the dropdown groups read in order', async () => {
const targets = await buildMappingTargets(
supabaseWith([{ account_number: '3005', account_name: 'X', account_class: 3 }]),
'company-1',
)
const numbers = targets.map((t) => t.account_number)
expect(numbers).toEqual([...numbers].sort((a, b) => a.localeCompare(b)))
})
// An incomplete list still lets the migration run; an exception stops it.
it('falls back to BAS when the chart cannot be read', async () => {
const targets = await buildMappingTargets(supabaseWith(new Error('boom')), 'company-1')
expect(targets.length).toBeGreaterThan(1000)
expect(targets.find((t) => t.account_number === '3005')).toBeUndefined()
})
})
@@ -0,0 +1,241 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import { createMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
/**
* Guards the server-side "SIE import required first" rule on the entity-migration
* route (POST /migrate).
*
* Provider API import only ever writes subledger entities (customers, suppliers,
* invoices): it never posts to the general ledger. The GL (kontoplan, ingående
* balanser, verifikationer) arrives via SIE. Importing entities without the
* SIE-derived ledger leaves an incomplete bokföring under BFL, so the route MUST
* refuse to run for EVERY provider until a completed SIE import exists for the
* company. Fortnox used to be exempt (it pulls SIE itself via API), but the
* wizard lets the user uncheck "Bokföringsdata (SIE)" while keeping entities
* checked (#2000), so the exemption is gone. The rule is "must exist", not "must
* be part of this run": an entities-only re-run after a full migration passes.
*
* Previously this was only an advisory banner + step-gating in the React wizard,
* which a direct API call or a stale client could bypass. This test locks the
* enforcement at the authoritative seam: the route handler.
*/
vi.mock('../lib/migration-orchestrator', () => ({
executeMigration: vi.fn().mockResolvedValue({ customers: { total: 0, imported: 0, skipped: 0 } }),
}))
// index.ts imports many helpers from provider-client at module load; stub the
// whole module and give getConsent/acceptConsent controllable behaviour.
vi.mock('../lib/provider-client', () => ({
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn().mockResolvedValue(undefined),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
// Real classes: index.ts branches on `instanceof` in the catch blocks.
ProviderTokenInvalidError: class ProviderTokenInvalidError extends Error {},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}))
import { arcimMigrationExtension } from '../index'
import { executeMigration } from '../lib/migration-orchestrator'
import { getConsent } from '../lib/provider-client'
const migrateRoute = (arcimMigrationExtension.apiRoutes ?? []).find(
(r) => r.method === 'POST' && r.path === '/migrate',
)!
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const handler = migrateRoute.handler as RouteHandler
function buildCtx(count: number | null): ExtensionContext {
const { supabase, mockResult } = createMockSupabase()
// The guard awaits `from('sie_imports').select(..,{count,head}).eq().eq()`.
mockResult({ count })
;(supabase as unknown as { auth: unknown }).auth = {
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } } }),
}
return { supabase, companyId: 'company-1' } as unknown as ExtensionContext
}
function migrateRequest(body: Record<string, unknown> = { consentId: 'consent-1' }) {
return createMockRequest('http://localhost/api/extensions/ext/arcim-migration/migrate', {
method: 'POST',
body,
})
}
type GuardErrorBody = { error: { code: string; message: string; message_en?: string } }
describe('POST /migrate: SIE-import-required guard', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns 401 when there is no authenticated user', async () => {
const ctx = buildCtx(0)
;(ctx.supabase as unknown as { auth: { getUser: Mock } }).auth.getUser
.mockResolvedValue({ data: { user: null } })
const res = await handler(migrateRequest(), ctx)
expect(res.status).toBe(401)
expect(getConsent).not.toHaveBeenCalled()
expect(executeMigration).not.toHaveBeenCalled()
})
it('returns 400 when consentId is missing', async () => {
const res = await handler(migrateRequest({}), buildCtx(1))
expect(res.status).toBe(400)
expect(getConsent).not.toHaveBeenCalled()
expect(executeMigration).not.toHaveBeenCalled()
})
it('blocks a non-Fortnox provider when no completed SIE import exists', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'visma' })
const res = await handler(migrateRequest(), buildCtx(0))
const { status, body } = await parseJsonResponse<GuardErrorBody>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('PROVIDER_SIE_IMPORT_REQUIRED')
// Visma has no SIE-over-API: the static registry text ("ladda upp en
// SIE-fil") is the right instruction and must stay.
expect(body.error.message).toMatch(/ladda upp en SIE-fil/i)
expect(executeMigration).not.toHaveBeenCalled()
})
it('allows a non-Fortnox provider once a completed SIE import exists', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'visma' })
const res = await handler(migrateRequest(), buildCtx(1))
expect(res.status).toBe(200)
expect(executeMigration).toHaveBeenCalledTimes(1)
})
it('blocks Fortnox when no completed SIE import exists (SIE step unchecked in the wizard)', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
const res = await handler(migrateRequest(), buildCtx(0))
const { status, body } = await parseJsonResponse<GuardErrorBody>(res)
expect(status).toBe(409)
expect(body.error.code).toBe('PROVIDER_SIE_IMPORT_REQUIRED')
expect(executeMigration).not.toHaveBeenCalled()
})
it('tells SIE-over-API providers to tick the wizard checkbox, not to upload a file', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
const res = await handler(migrateRequest(), buildCtx(0))
const { body } = await parseJsonResponse<GuardErrorBody>(res)
expect(body.error.message).toContain('Bokföringsdata (SIE)')
expect(body.error.message).not.toMatch(/ladda upp/i)
expect(body.error.message_en).toContain('Bokföringsdata (SIE)')
expect(body.error.message_en).not.toMatch(/upload/i)
})
it('allows a company-info-only run with no SIE import (writes no ledger data)', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
const res = await handler(
migrateRequest({
consentId: 'consent-1',
importCompanyInfo: true,
importCustomers: false,
importSuppliers: false,
importSalesInvoices: false,
importSupplierInvoices: false,
importAssets: false,
}),
buildCtx(0),
)
expect(res.status).toBe(200)
expect(executeMigration).toHaveBeenCalledTimes(1)
})
// The asset register is entity data too: its rows carry BAS account triples
// and depreciation plans that only mean something against an imported chart
// of accounts, so an assets-only run is gated like any other entity import.
it('blocks an assets-only run with no SIE import', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
const res = await handler(
migrateRequest({
consentId: 'consent-1',
importCompanyInfo: false,
importCustomers: false,
importSuppliers: false,
importSalesInvoices: false,
importSupplierInvoices: false,
importAssets: true,
}),
buildCtx(0),
)
expect(res.status).toBe(409)
expect(executeMigration).not.toHaveBeenCalled()
})
// Backward compatibility: a client written before the asset option existed
// omits the field entirely. That request must behave as it did then, so the
// omitted option neither imports assets nor trips this guard.
it('allows a company-info-only run that omits importAssets entirely', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
const res = await handler(
migrateRequest({
consentId: 'consent-1',
importCompanyInfo: true,
importCustomers: false,
importSuppliers: false,
importSalesInvoices: false,
importSupplierInvoices: false,
}),
buildCtx(0),
)
expect(res.status).toBe(200)
expect(executeMigration).toHaveBeenCalledTimes(1)
})
it('still blocks when company info is combined with any entity flag', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
const res = await handler(
migrateRequest({
consentId: 'consent-1',
importCompanyInfo: true,
importCustomers: false,
importSuppliers: true,
importSalesInvoices: false,
importSupplierInvoices: false,
}),
buildCtx(0),
)
expect(res.status).toBe(409)
expect(executeMigration).not.toHaveBeenCalled()
})
it('allows Fortnox once a completed SIE import exists (entities-only re-run)', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
const res = await handler(migrateRequest(), buildCtx(1))
expect(res.status).toBe(200)
expect(executeMigration).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,114 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import { createMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
/**
* Locks the /migrate route's mapping of a doomed provider run to a structured
* error response. When the orchestrator rethrows a connection-level failure
* (here: Visma's "No access to module: api_standard"), the route must answer
* with PROVIDER_API_MODULE_INACTIVE and its remediation, not a generic
* PROVIDER_MIGRATE_FAILED or a misleading success envelope.
*/
vi.mock('../lib/migration-orchestrator', () => ({
executeMigration: vi.fn(),
}))
vi.mock('../lib/provider-client', () => ({
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn().mockResolvedValue(undefined),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
ProviderTokenInvalidError: class ProviderTokenInvalidError extends Error {},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}))
import { arcimMigrationExtension } from '../index'
import { executeMigration } from '../lib/migration-orchestrator'
import { getConsent } from '../lib/provider-client'
const migrateRoute = (arcimMigrationExtension.apiRoutes ?? []).find(
(r) => r.method === 'POST' && r.path === '/migrate',
)!
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const handler = migrateRoute.handler as RouteHandler
function buildCtx(): ExtensionContext {
const { supabase, mockResult } = createMockSupabase()
// The SIE guard awaits `from('sie_imports').select(..,{count,head}).eq().eq()`.
mockResult({ count: 1 })
;(supabase as unknown as { auth: unknown }).auth = {
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } } }),
}
return { supabase, companyId: 'company-1' } as unknown as ExtensionContext
}
function migrateRequest() {
return createMockRequest('http://localhost/api/extensions/ext/arcim-migration/migrate', {
method: 'POST',
body: { consentId: 'consent-1' },
})
}
function vismaModuleError(): Error {
const e = new Error('Visma API error: 403 Forbidden') as Error & {
statusCode: number
body: string
}
e.statusCode = 403
e.body =
'{"ErrorCode":4002,"DeveloperErrorMessage":"ForbiddenRequestException - No access to module: api_standard","ErrorId":"x","Errors":[]}'
return e
}
describe('POST /migrate: provider error mapping', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('answers 403 PROVIDER_API_MODULE_INACTIVE when the orchestrator hits an inactive Visma API module', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'visma' })
;(executeMigration as Mock).mockRejectedValue(vismaModuleError())
const res = await handler(migrateRequest(), buildCtx())
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
expect(status).toBe(403)
expect(body.error.code).toBe('PROVIDER_API_MODULE_INACTIVE')
expect(body.error.message).toContain('Appar och tillägg')
})
it('still returns success with stepErrors passed through for non-fatal partial failures', async () => {
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'visma' })
;(executeMigration as Mock).mockResolvedValue({
customers: { total: 5, imported: 5, updated: 0, skipped: 0, skipReasons: {} },
stepErrors: [
{
step: 'suppliers',
code: 'PROVIDER_UPSTREAM_ERROR',
message: 'Leverantören svarade med ett fel. Försök igen om en stund.',
},
],
})
const res = await handler(migrateRequest(), buildCtx())
const { status, body } = await parseJsonResponse<{
success: boolean
results: { stepErrors?: { step: string; code: string | null }[] }
}>(res)
expect(status).toBe(200)
expect(body.success).toBe(true)
expect(body.results.stepErrors).toHaveLength(1)
expect(body.results.stepErrors![0].step).toBe('suppliers')
})
})
@@ -0,0 +1,161 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import { createMockSupabase } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
/**
* Locks the /migrate NDJSON streaming contract (opt-in via
* `Accept: application/x-ndjson`):
*
* - each orchestrator onProgress call becomes one `progress` line with the
* real step label and anchor (the wizard's fake 55→100 jump is dead)
* - success ends with a terminal `done` line carrying the results, after
* acceptConsent ran
* - an orchestrator failure ends with a terminal `error` line carrying the
* SAME structured envelope the JSON path answers with (the 200 status is
* already committed when the stream opens)
* - a request WITHOUT the Accept header keeps the original JSON contract
*/
vi.mock('../lib/migration-orchestrator', () => ({
executeMigration: vi.fn(),
}))
vi.mock('../lib/provider-client', () => ({
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn().mockResolvedValue(undefined),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
ProviderTokenInvalidError: class ProviderTokenInvalidError extends Error {},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}))
import { arcimMigrationExtension } from '../index'
import { executeMigration } from '../lib/migration-orchestrator'
import { getConsent, acceptConsent } from '../lib/provider-client'
const migrateRoute = (arcimMigrationExtension.apiRoutes ?? []).find(
(r) => r.method === 'POST' && r.path === '/migrate',
)!
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const handler = migrateRoute.handler as RouteHandler
function buildCtx(): ExtensionContext {
const { supabase, mockResult } = createMockSupabase()
// The SIE guard awaits `from('sie_imports').select(..,{count,head}).eq().eq()`.
mockResult({ count: 1 })
;(supabase as unknown as { auth: unknown }).auth = {
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } } }),
}
return { supabase, companyId: 'company-1' } as unknown as ExtensionContext
}
function streamRequest() {
return new Request('http://localhost/api/extensions/ext/arcim-migration/migrate', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/x-ndjson' },
body: JSON.stringify({ consentId: 'consent-1' }),
})
}
async function readNdjson(res: Response): Promise<Record<string, unknown>[]> {
const text = await res.text()
return text
.split('\n')
.filter((line) => line.trim())
.map((line) => JSON.parse(line))
}
describe('POST /migrate: NDJSON streaming', () => {
beforeEach(() => {
vi.clearAllMocks()
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'visma' })
})
it('streams one progress line per orchestrator event, then a terminal done line with results', async () => {
const results = {
customers: { total: 5, imported: 5, updated: 0, skipped: 0, skipReasons: {} },
stepErrors: [],
}
;(executeMigration as Mock).mockImplementation(
async (opts: { onProgress?: (p: { status: string; currentStep?: string; progress: number }) => void }) => {
opts.onProgress?.({ status: 'fetching', currentStep: 'Ansluter till Visma eEkonomi...', progress: 5 })
opts.onProgress?.({ status: 'importing', currentStep: 'Importerar kunder...', progress: 20 })
opts.onProgress?.({ status: 'completed', currentStep: 'Klart!', progress: 100 })
return results
},
)
const res = await handler(streamRequest(), buildCtx())
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toContain('application/x-ndjson')
const events = await readNdjson(res)
expect(events).toHaveLength(4)
expect(events[0]).toEqual({
kind: 'progress',
status: 'fetching',
currentStep: 'Ansluter till Visma eEkonomi...',
progress: 5,
})
expect(events[1]).toMatchObject({ kind: 'progress', currentStep: 'Importerar kunder...', progress: 20 })
expect(events[3]).toEqual({ kind: 'done', success: true, results })
expect(acceptConsent).toHaveBeenCalledWith('consent-1')
})
it('ends with a terminal error line carrying the structured envelope when the orchestrator fails', async () => {
const vismaError = new Error('Visma API error: 403 Forbidden') as Error & {
statusCode: number
body: string
}
vismaError.statusCode = 403
vismaError.body =
'{"ErrorCode":4002,"DeveloperErrorMessage":"ForbiddenRequestException - No access to module: api_standard","ErrorId":"x","Errors":[]}'
;(executeMigration as Mock).mockImplementation(
async (opts: { onProgress?: (p: { status: string; progress: number }) => void }) => {
opts.onProgress?.({ status: 'fetching', progress: 5 })
throw vismaError
},
)
const res = await handler(streamRequest(), buildCtx())
expect(res.status).toBe(200)
const events = await readNdjson(res)
const terminal = events[events.length - 1] as {
kind: string
error: { code: string; message: string }
}
expect(terminal.kind).toBe('error')
expect(terminal.error.code).toBe('PROVIDER_API_MODULE_INACTIVE')
expect(terminal.error.message).toContain('Appar och tillägg')
expect(acceptConsent).not.toHaveBeenCalled()
})
it('keeps the single-JSON contract when the Accept header is absent', async () => {
const results = { customers: { total: 1, imported: 1, updated: 0, skipped: 0, skipReasons: {} } }
;(executeMigration as Mock).mockResolvedValue(results)
const res = await handler(
new Request('http://localhost/api/extensions/ext/arcim-migration/migrate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ consentId: 'consent-1' }),
}),
buildCtx(),
)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toContain('application/json')
expect(await res.json()).toEqual({ success: true, results })
})
})
@@ -0,0 +1,236 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createQueuedMockSupabase } from '@/tests/helpers'
/**
* Locks the registration-voucher link step of the migration (#1463): the
* orchestrator collects the id of every invoice it inserted together with the
* voucher ref the provider named, hands that list to the core linker once,
* after both invoice steps, and carries the counts into the results. A
* linker failure is recorded as a step error and never discards the invoices
* that were already persisted.
*/
vi.mock('@/lib/providers/resolve-consent', () => ({
resolveConsent: vi.fn().mockResolvedValue({
consent: { provider: 'visma' },
accessToken: 'tok',
providerCompanyId: null,
}),
}))
vi.mock('@/lib/providers/provider-data-fetcher', () => ({
fetchCompanyInfoDirect: vi.fn(),
fetchCustomersDirect: vi.fn(),
fetchSuppliersDirect: vi.fn(),
fetchSalesInvoicesHydrated: vi.fn(),
fetchSupplierInvoicesHydrated: vi.fn(),
}))
vi.mock('@/lib/invoices/bulk-reconcile-supplier-vouchers', () => ({
reconcileSupplierInvoiceVouchers: vi.fn(),
}))
vi.mock('@/lib/invoices/link-migrated-registration-vouchers', () => ({
linkMigratedRegistrationVouchers: vi.fn(),
}))
vi.mock('@/lib/supabase/fetch-all', () => ({
fetchAllRows: vi.fn().mockResolvedValue([]),
}))
// Inserts answer with deterministic ids so the collected inputs can be
// asserted; the per-row fallback itself has its own suite.
vi.mock('../lib/insert-fallback', () => ({
insertWithPerRowFallback: vi.fn(async (_supabase: unknown, table: string, rows: Record<string, unknown>[]) => ({
returned: rows.map((row, i) => ({
id: `${table}-${i + 1}`,
org_number: row.org_number ?? null,
name: row.name ?? null,
})),
failedCount: 0,
firstError: null,
})),
}))
import { executeMigration } from '../lib/migration-orchestrator'
import {
fetchSalesInvoicesHydrated,
fetchSupplierInvoicesHydrated,
} from '@/lib/providers/provider-data-fetcher'
import { linkMigratedRegistrationVouchers } from '@/lib/invoices/link-migrated-registration-vouchers'
import type { SalesInvoiceDto, SupplierInvoiceDto } from '@/lib/providers/dto'
const mLink = linkMigratedRegistrationVouchers as Mock
const HYDRATION = { needed: 0, hydrated: 0, failed: 0, skippedForBudget: 0 }
function party(name: string) {
return { name, identifications: [] }
}
function salesDto(over: Partial<SalesInvoiceDto> & { invoiceNumber: string }): SalesInvoiceDto {
return {
id: over.invoiceNumber,
issueDate: '2025-03-14',
dueDate: '2025-04-13',
currencyCode: 'SEK',
status: 'sent',
supplier: party(''),
customer: party('Kund AB'),
lines: [],
legalMonetaryTotal: { payableAmount: { value: 1000, currencyCode: 'SEK' } },
taxTotal: { taxAmount: { value: 200, currencyCode: 'SEK' } },
paymentStatus: { paid: false, balance: { value: 1000, currencyCode: 'SEK' } },
...over,
}
}
function supplierDto(over: Partial<SupplierInvoiceDto> & { invoiceNumber: string }): SupplierInvoiceDto {
return {
id: over.invoiceNumber,
issueDate: '2025-05-02',
dueDate: '2025-06-01',
currencyCode: 'SEK',
status: 'booked',
supplier: party('Leverantör AB'),
buyer: party(''),
lines: [],
legalMonetaryTotal: { payableAmount: { value: 2500, currencyCode: 'SEK' } },
taxTotal: { taxAmount: { value: 500, currencyCode: 'SEK' } },
paymentStatus: { paid: false, balance: { value: 2500, currencyCode: 'SEK' } },
...over,
}
}
const LINK_COUNTS = {
scanned: 2, linked: 1, noRef: 1, refNotFetched: 0, unresolved: 0, ambiguous: 0, amountMismatch: 0, alreadyLinked: 0, reports: [],
}
function baseOptions(overrides: Record<string, unknown> = {}) {
const { supabase } = createQueuedMockSupabase()
return {
consentId: 'consent-1',
companyId: 'company-1',
userId: 'user-1',
supabase: supabase as unknown as SupabaseClient,
createHistoryClient: async () => ({ from: vi.fn() }) as unknown as Pick<SupabaseClient, 'from'>,
importCompanyInfo: false,
importCustomers: false,
importSuppliers: false,
importSalesInvoices: false,
importSupplierInvoices: false,
reconcileVouchers: false,
...overrides,
}
}
describe('executeMigration: registration voucher links', () => {
beforeEach(() => {
vi.clearAllMocks()
mLink.mockResolvedValue(LINK_COUNTS)
})
it('hands every inserted invoice, with its provider voucher ref, to the linker once and reports the counts', async () => {
;(fetchSalesInvoicesHydrated as Mock).mockResolvedValue({
invoices: [
salesDto({ invoiceNumber: '1001', sourceVoucher: { series: 'A', number: 329 } }),
salesDto({ invoiceNumber: '1002' }),
salesDto({ invoiceNumber: '1003', currencyCode: 'EUR' }),
],
hydration: { ...HYDRATION, needed: 1, skippedForBudget: 1 },
// 1003's detail form was never fetched: its ref is unknown, not absent.
unhydratedIds: new Set(['1003']),
})
;(fetchSupplierInvoicesHydrated as Mock).mockResolvedValue({
invoices: [supplierDto({ invoiceNumber: 'L-77', sourceVoucher: { series: 'B', number: 5 } })],
hydration: HYDRATION,
unhydratedIds: new Set(),
})
const results = await executeMigration(
baseOptions({ importSalesInvoices: true, importSupplierInvoices: true }),
)
expect(mLink).toHaveBeenCalledTimes(1)
const call = mLink.mock.calls[0][0]
expect(call.companyId).toBe('company-1')
expect(call.invoices).toEqual([
{
invoiceId: 'invoices-1',
kind: 'customer',
sourceVoucher: { series: 'A', number: 329 },
refNotFetched: false,
invoiceDate: '2025-03-14',
totalSek: 1000,
currencyCode: 'SEK',
invoiceNumber: '1001',
},
{
invoiceId: 'invoices-2',
kind: 'customer',
sourceVoucher: null,
refNotFetched: false,
invoiceDate: '2025-03-14',
totalSek: 1000,
currencyCode: 'SEK',
invoiceNumber: '1002',
},
{
invoiceId: 'invoices-3',
kind: 'customer',
sourceVoucher: null,
refNotFetched: true,
invoiceDate: '2025-03-14',
// The SEK total comes from the run's rate index; the linker gets the
// currency so a mismatch can be explained as a rate difference.
totalSek: expect.any(Number),
currencyCode: 'EUR',
invoiceNumber: '1003',
},
{
invoiceId: 'supplier_invoices-1',
kind: 'supplier',
sourceVoucher: { series: 'B', number: 5 },
refNotFetched: false,
invoiceDate: '2025-05-02',
totalSek: 2500,
currencyCode: 'SEK',
invoiceNumber: 'L-77',
},
])
expect(results.registrationLinks).toEqual({
scanned: 2, linked: 1, noRef: 1, refNotFetched: 0, unresolved: 0, ambiguous: 0, amountMismatch: 0, alreadyLinked: 0,
})
expect(results.salesInvoices?.imported).toBe(3)
expect(results.supplierInvoices?.imported).toBe(1)
expect(results.stepErrors).toBeUndefined()
})
it('skips the linker entirely when no invoice was inserted', async () => {
;(fetchSalesInvoicesHydrated as Mock).mockResolvedValue({ invoices: [], hydration: HYDRATION, unhydratedIds: new Set() })
const results = await executeMigration(baseOptions({ importSalesInvoices: true }))
expect(mLink).not.toHaveBeenCalled()
expect(results.registrationLinks).toBeUndefined()
})
it('records a linker failure as a step error and keeps the imported invoices', async () => {
;(fetchSalesInvoicesHydrated as Mock).mockResolvedValue({
invoices: [salesDto({ invoiceNumber: '1001', sourceVoucher: { series: 'A', number: 1 } })],
hydration: HYDRATION,
unhydratedIds: new Set(),
})
mLink.mockRejectedValue(new Error('db down'))
const results = await executeMigration(baseOptions({ importSalesInvoices: true }))
expect(results.salesInvoices?.imported).toBe(1)
expect(results.registrationLinks).toBeUndefined()
expect(results.stepErrors).toEqual([
expect.objectContaining({ step: 'registrationLinks' }),
])
})
})
@@ -0,0 +1,253 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
/**
* Locks the orchestrator's error surfacing.
*
* Before this, every step's catch was log-and-continue, so a migration where
* every provider call failed (e.g. Visma's "No access to module: api_standard"
* when the customer's plan lacks the API module) reported success with zero
* rows. The user saw "Allt är uppdaterat", retried, reconnected, and finally
* filed the config issue as a bug.
*
* Contract:
* - Connection-level failures (auth expired, license missing, API module
* inactive) doom every remaining call: the orchestrator RETHROWS so the
* route answers with the structured code and its remediation.
* - Other failures stay non-fatal (one bad step must not discard the other
* steps' persisted rows) but are recorded on results.stepErrors so the
* result UI renders them instead of implying success.
* - A 403 on ONE register once the same token has already answered earlier in
* the run is not a connection-level failure at all: the Fortnox account
* that lacks leverantörsregister rights imported customers seconds before,
* so the run continues and the provider's own reason is what the user
* reads. Reconnecting could never have helped.
*/
vi.mock('@/lib/providers/resolve-consent', () => ({
resolveConsent: vi.fn().mockResolvedValue({
consent: { provider: 'visma' },
accessToken: 'tok',
providerCompanyId: null,
}),
}))
vi.mock('@/lib/providers/provider-data-fetcher', () => ({
fetchCompanyInfoDirect: vi.fn(),
fetchCustomersDirect: vi.fn(),
fetchSuppliersDirect: vi.fn(),
// The orchestrator consumes the HYDRATED variants: mocking only the
// Direct ones left the invoice steps calling undefined, which the step's
// own try/catch swallowed into a recorded error, so the tests stayed green
// while exercising nothing.
fetchSalesInvoicesHydrated: vi.fn(),
fetchSupplierInvoicesHydrated: vi.fn(),
}))
vi.mock('@/lib/invoices/bulk-reconcile-supplier-vouchers', () => ({
reconcileSupplierInvoiceVouchers: vi.fn(),
}))
vi.mock('@/lib/supabase/fetch-all', () => ({
fetchAllRows: vi.fn().mockResolvedValue([]),
}))
import { executeMigration } from '../lib/migration-orchestrator'
import {
fetchCompanyInfoDirect,
fetchCustomersDirect,
fetchSuppliersDirect,
fetchSalesInvoicesHydrated,
} from '@/lib/providers/provider-data-fetcher'
import { FortnoxApiError } from '@/lib/providers/fortnox/client'
const VISMA_MODULE_BODY =
'{"ErrorCode":4002,"DeveloperErrorMessage":"ForbiddenRequestException - No access to module: api_standard","ErrorId":"x","Errors":[]}'
/** The live Fortnox answer for a supplier read the account may not make. */
const FORTNOX_SUPPLIER_BODY =
'{"ErrorInformation":{"Error":1,"Message":"Saknar beh\u00f6righet f\u00f6r leverant\u00f6rsregister.","Code":2003275}}'
function vismaError(statusCode: number, body?: string): Error {
const e = new Error(`Visma API error: ${statusCode}`) as Error & {
statusCode: number
body?: string
}
e.statusCode = statusCode
e.body = body
return e
}
function baseOptions(overrides: Record<string, unknown> = {}) {
return {
consentId: 'consent-1',
companyId: 'company-1',
userId: 'user-1',
supabase: {} as unknown as SupabaseClient,
createHistoryClient: async () => ({ from: vi.fn() }) as unknown as Pick<SupabaseClient, 'from'>,
importCompanyInfo: false,
importCustomers: false,
importSuppliers: false,
importSalesInvoices: false,
importSupplierInvoices: false,
reconcileVouchers: false,
...overrides,
}
}
describe('executeMigration: step error surfacing', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('rethrows when a step fails with an inactive API module (Visma 4002): the run is doomed', async () => {
;(fetchCustomersDirect as Mock).mockRejectedValue(vismaError(403, VISMA_MODULE_BODY))
await expect(
executeMigration(baseOptions({ importCustomers: true })),
).rejects.toMatchObject({ statusCode: 403 })
})
it('rethrows a doomed company-info step too, instead of settling for imported:false', async () => {
;(fetchCompanyInfoDirect as Mock).mockRejectedValue(vismaError(403, VISMA_MODULE_BODY))
await expect(
executeMigration(baseOptions({ importCompanyInfo: true })),
).rejects.toMatchObject({ statusCode: 403 })
})
it('records a non-fatal classified failure on results.stepErrors with the registry Swedish message', async () => {
;(fetchCustomersDirect as Mock).mockRejectedValue(vismaError(500))
const results = await executeMigration(baseOptions({ importCustomers: true }))
expect(results.stepErrors).toEqual([
{
step: 'customers',
code: 'PROVIDER_UPSTREAM_ERROR',
message: 'Leverantören svarade med ett fel. Försök igen om en stund.',
},
])
// The step failed before producing a result: no customers section.
expect(results.customers).toBeUndefined()
})
it('records an unclassified failure with a generic Swedish sentence carrying the raw reason', async () => {
;(fetchCustomersDirect as Mock).mockRejectedValue(new Error('boom'))
const results = await executeMigration(baseOptions({ importCustomers: true }))
expect(results.stepErrors).toEqual([
{ step: 'customers', code: null, message: 'Leverantören svarade med ett fel: boom' },
])
})
it('keeps going when one register is closed on a token that already worked', async () => {
// Customers came back fine, so the grant is provably alive: the suppliers
// 403 is Fortnox refusing leverantörsregistret, not the connection dying.
// Aborting here is what left sales invoices, supplier invoices, vouchers
// and payment reconciliation unimported behind an "Återanslut" the user
// could follow forever.
;(fetchCustomersDirect as Mock).mockResolvedValue([])
;(fetchSuppliersDirect as Mock).mockRejectedValue(
new FortnoxApiError('Fortnox API error: 403', 403, FORTNOX_SUPPLIER_BODY),
)
;(fetchSalesInvoicesHydrated as Mock).mockResolvedValue({
invoices: [],
hydration: undefined,
unhydratedIds: new Set<string>(),
})
const results = await executeMigration(
baseOptions({ importCustomers: true, importSuppliers: true, importSalesInvoices: true }),
)
expect(results.stepErrors).toHaveLength(1)
expect(results.stepErrors![0].step).toBe('suppliers')
expect(results.stepErrors![0].code).toBe('PROVIDER_RESOURCE_FORBIDDEN')
// The provider's own sentence is the only part that names the register.
expect(results.stepErrors![0].message).toContain('Saknar behörighet för leverantörsregister.')
expect(results.stepErrors![0].message).not.toContain('Återanslut')
// The steps after the closed register still ran.
expect(fetchSalesInvoicesHydrated).toHaveBeenCalledTimes(1)
expect(results.salesInvoices).toBeDefined()
})
it('does not treat a step that never called the provider as proof of the grant', async () => {
// fetchCustomersDirect answers [] WITHOUT issuing any request when the
// provider needs a company id the consent has none of (Bokio, Björn
// Lundén) or does not expose the register (WINT suppliers). Reading that
// resolved promise as "the token works" would downgrade a genuine auth
// expiry on the next step to a per-register denial, and the run would
// finish "successfully" with every section empty.
;(fetchCustomersDirect as Mock).mockResolvedValue([])
;(fetchSuppliersDirect as Mock).mockRejectedValue(vismaError(403))
await expect(
executeMigration(baseOptions({ importCustomers: true, importSuppliers: true })),
).rejects.toMatchObject({ statusCode: 403 })
})
it('lets rows fetched earlier prove the grant for an opaque 403 later in the run', async () => {
// Rows can only come from a real answer on this token, so the Bokio 403
// that follows (empty body, nothing to read) is one closed register.
;(fetchCustomersDirect as Mock).mockResolvedValue([
{ id: 'cust-1', active: false, party: { name: 'Kund AB' } },
])
;(fetchSuppliersDirect as Mock).mockRejectedValue(vismaError(403))
const results = await executeMigration(
baseOptions({ importCustomers: true, importSuppliers: true }),
)
expect(results.customers).toMatchObject({ total: 1, imported: 0 })
expect(results.stepErrors).toHaveLength(1)
expect(results.stepErrors![0].step).toBe('suppliers')
expect(results.stepErrors![0].code).toBe('PROVIDER_RESOURCE_FORBIDDEN')
expect(results.stepErrors![0].message).not.toContain('Återanslut för att fortsätta')
})
it('still rethrows a 403 on the first provider call of the run: that one can be a dead grant', async () => {
// Bokio answers with an empty body, so nothing distinguishes a revoked
// grant from a closed register here. "Reconnect" stays the answer.
;(fetchCustomersDirect as Mock).mockRejectedValue(vismaError(403))
await expect(
executeMigration(baseOptions({ importCustomers: true })),
).rejects.toMatchObject({ statusCode: 403 })
})
it('does not let an opaque 403 on the company-info probe abort the run', async () => {
// Step 1 is the opening call, so nothing can have proven the grant yet.
// Company information is optional metadata (this fetch used to swallow
// every error and return null); a grant that really is dead says so on the
// next step, which is still fatal.
;(fetchCompanyInfoDirect as Mock).mockRejectedValue(vismaError(403))
;(fetchCustomersDirect as Mock).mockResolvedValue([])
const results = await executeMigration(
baseOptions({ importCompanyInfo: true, importCustomers: true }),
)
expect(results.companyInfo).toEqual({ imported: false })
expect(results.stepErrors).toHaveLength(1)
expect(results.stepErrors![0].step).toBe('companyInfo')
expect(results.stepErrors![0].code).toBe('PROVIDER_RESOURCE_FORBIDDEN')
expect(fetchCustomersDirect).toHaveBeenCalledTimes(1)
})
it('returns no stepErrors when every enabled step succeeds', async () => {
;(fetchCustomersDirect as Mock).mockResolvedValue([])
const results = await executeMigration(baseOptions({ importCustomers: true }))
expect(results.stepErrors).toBeUndefined()
expect(results.customers).toEqual({
total: 0,
imported: 0,
updated: 0,
skipped: 0,
skipReasons: {},
})
})
})
@@ -0,0 +1,255 @@
import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest'
import { createMockRequest } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
/**
* Binds the OAuth callback to the user who STARTED the flow.
*
* oauth-callback-state.test.ts pins that the callback trusts nothing but the
* server-written state row. That row proves the callback belongs to a flow we
* started; it does not say who is finishing it. The authorize URL is
* shareable, so a victim lured into approving a Fortnox/Visma consent that an
* attacker started would have their provider account bound to the attacker's
* consent, and the attacker's next migration would import the victim's ledger.
*
* The state row now records the initiator (provider_otc.user_id, written by
* generateOtc from /connect) and the callback requires the completing
* browser's own session to be that user before the code is exchanged. The
* binding helper is the real one; only the cookie session behind it is faked.
*/
vi.mock('../lib/migration-orchestrator', () => ({
executeMigration: vi.fn().mockResolvedValue({}),
}))
vi.mock('../lib/provider-client', () => ({
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn(),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
ProviderTokenInvalidError: class ProviderTokenInvalidError extends Error {},
// Mirrors the real constructor and message so the callback's mapping from
// this error to the Swedish registry sentence is exercised for real.
ProviderCompanyMismatchError: class ProviderCompanyMismatchError extends Error {
constructor(
public readonly expectedOrgNumber: string,
public readonly actualOrgNumber: string,
public readonly actualCompanyName: string | null,
) {
super(
`Provider company mismatch: credentials open ${actualOrgNumber}, ` +
`but the target company is ${expectedOrgNumber}`,
)
}
},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}))
const { mockCreateClient } = vi.hoisted(() => ({ mockCreateClient: vi.fn() }))
vi.mock('@/lib/supabase/server', () => ({
createClient: mockCreateClient,
createServiceClient: vi.fn(),
}))
import { arcimMigrationExtension } from '../index'
import {
consumeOAuthState,
exchangeAuthToken,
generateOtc,
getAuthUrl,
listConsents,
createConsent,
ProviderCompanyMismatchError,
} from '../lib/provider-client'
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const findRoute = (method: string, path: string) =>
(arcimMigrationExtension.apiRoutes ?? []).find((r) => r.method === method && r.path === path)!
const callbackHandler = findRoute('GET', '/callback').handler as RouteHandler
const connectHandler = findRoute('POST', '/connect').handler as RouteHandler
const APP_URL = 'https://app.example.test'
const STATE_REJECTED = 'Ingen giltig migrationssession hittades'
/** The browser completing the callback is signed in as `userId` (or nobody). */
function useSession(userId: string | null) {
mockCreateClient.mockResolvedValue({
auth: {
getUser: vi.fn().mockResolvedValue({
data: { user: userId ? { id: userId } : null },
error: null,
}),
},
})
}
function callbackRequest(params: Record<string, string>) {
return createMockRequest(`${APP_URL}/api/extensions/ext/arcim-migration/callback`, {
searchParams: params,
})
}
function connectCtx(userId = 'user-1'): ExtensionContext {
return {
supabase: { auth: { getUser: vi.fn().mockResolvedValue({ data: { user: { id: userId } } }) } },
companyId: 'company-1',
userId,
} as unknown as ExtensionContext
}
describe('GET /callback: the completing session must be the initiator', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubEnv('NEXT_PUBLIC_APP_URL', APP_URL)
vi.stubEnv('FORTNOX_REDIRECT_URI', '')
vi.stubEnv('VISMA_REDIRECT_URI', '')
vi.spyOn(console, 'error').mockImplementation(() => {})
vi.spyOn(console, 'warn').mockImplementation(() => {})
;(consumeOAuthState as Mock).mockResolvedValue({
consentId: 'consent-1',
provider: 'fortnox',
userId: 'user-1',
})
;(exchangeAuthToken as Mock).mockResolvedValue({ success: true, consentId: 'consent-1' })
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('finalises when the browser session belongs to the user who started the flow', async () => {
useSession('user-1')
const res = await callbackHandler(callbackRequest({ code: 'provider-auth-code', state: 'otc' }))
const html = await res.text()
expect(exchangeAuthToken).toHaveBeenCalledTimes(1)
expect(exchangeAuthToken).toHaveBeenCalledWith(
'consent-1',
'fortnox',
'provider-auth-code',
`${APP_URL}/api/extensions/ext/arcim-migration/callback`,
)
expect(html).toContain('Anslutningen lyckades')
})
it('refuses a completion by a different signed-in user without exchanging the code', async () => {
// The victim (user-2) was lured into approving user-1's consent.
useSession('user-2')
const res = await callbackHandler(callbackRequest({ code: 'provider-auth-code', state: 'otc' }))
const html = await res.text()
expect(exchangeAuthToken).not.toHaveBeenCalled()
expect(html).toContain('Anslutningen misslyckades')
expect(html).toContain('annat användarkonto')
// The refused party learns nothing about the consent it tried to complete.
expect(html).not.toContain('consent-1')
// Error popups stay open (see oauth-callback-state.test.ts).
expect(html).not.toContain('window.close')
})
it('refuses a completion with no session at all and asks for a fresh connect', async () => {
useSession(null)
const res = await callbackHandler(callbackRequest({ code: 'provider-auth-code', state: 'otc' }))
const html = await res.text()
expect(exchangeAuthToken).not.toHaveBeenCalled()
// The state is already spent (consumed atomically before the check), so
// the only way forward is a new connect, not a login-and-retry.
expect(consumeOAuthState).toHaveBeenCalledWith('otc')
expect(html).toContain('Logga in och starta om anslutningen')
expect(html).not.toContain('consent-1')
})
it('refuses a state row that records no initiator, with the generic state rejection', async () => {
// Rows minted before provider_otc.user_id existed: nobody to bind to.
;(consumeOAuthState as Mock).mockResolvedValue({
consentId: 'consent-1',
provider: 'fortnox',
userId: null,
})
useSession('user-1')
const res = await callbackHandler(callbackRequest({ code: 'provider-auth-code', state: 'otc' }))
const html = await res.text()
expect(exchangeAuthToken).not.toHaveBeenCalled()
expect(mockCreateClient).not.toHaveBeenCalled()
expect(html).toContain(STATE_REJECTED)
})
it('reports valid tokens for the WRONG company in Swedish and never claims success', async () => {
useSession('user-1')
;(exchangeAuthToken as Mock).mockRejectedValue(
new ProviderCompanyMismatchError('5560160680', '5567037485', 'Annat Bolag AB'),
)
const res = await callbackHandler(callbackRequest({ code: 'provider-auth-code', state: 'otc' }))
const html = await res.text()
expect(html).toContain('Anslutningen misslyckades')
expect(html).toContain('Uppgifterna gäller ett annat företag')
expect(html).not.toContain('Provider company mismatch')
expect(html).not.toContain('Anslutningen lyckades')
})
})
describe('POST /connect: the state row records who started the flow', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubEnv('NEXT_PUBLIC_APP_URL', APP_URL)
vi.stubEnv('FORTNOX_REDIRECT_URI', '')
vi.spyOn(console, 'error').mockImplementation(() => {})
;(generateOtc as Mock).mockResolvedValue({ code: 'otc-code-1' })
;(getAuthUrl as Mock).mockResolvedValue({ url: 'https://apps.fortnox.se/oauth-v1/auth?x=1' })
})
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
it('binds a first connect to the caller', async () => {
;(listConsents as Mock).mockResolvedValue([])
;(createConsent as Mock).mockResolvedValue({ id: 'consent-new' })
const res = await connectHandler(
createMockRequest(`${APP_URL}/api/extensions/ext/arcim-migration/connect`, {
method: 'POST',
body: { provider: 'fortnox' },
}),
connectCtx('user-1'),
)
expect(res.status).toBe(200)
expect(generateOtc).toHaveBeenCalledWith('consent-new', 'user-1', APP_URL)
})
it('binds a reconnect of an existing consent to the caller too', async () => {
;(listConsents as Mock).mockResolvedValue([{ id: 'consent-1', provider: 'fortnox', status: 1 }])
const res = await connectHandler(
createMockRequest(`${APP_URL}/api/extensions/ext/arcim-migration/connect`, {
method: 'POST',
body: { provider: 'fortnox', reconnect: true },
}),
connectCtx('user-1'),
)
expect(res.status).toBe(200)
expect(generateOtc).toHaveBeenCalledWith('consent-1', 'user-1', APP_URL)
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,126 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import { createMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
/**
* Locks what GET /preview does with a company-info failure.
*
* fetchCompanyInfoDirect used to swallow every provider error and return null,
* which made the handler's classify-and-rethrow unreachable code: a Visma
* company whose api_standard module is off got a 200 preview with
* companyInfo: null, connected happily, and only discovered the problem when
* the migration came back empty. The remediation text ("Appar och tillägg")
* existed the whole time and never reached anyone.
*
* The other half matters just as much: a transient provider failure must stay
* soft. The preview is still useful without the company card, and turning a
* hiccup into a hard error would block the connect step for no reason.
*/
vi.mock('../lib/migration-orchestrator', () => ({
executeMigration: vi.fn(),
}))
vi.mock('../lib/provider-client', () => ({
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn(),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
ProviderTokenInvalidError: class ProviderTokenInvalidError extends Error {},
ProviderCompanyMismatchError: class ProviderCompanyMismatchError extends Error {},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}))
// Visma serves no SIE over the API, but keep the fetcher stubbed so no test
// here can reach a provider over the network.
vi.mock('../lib/sie-fetcher', () => ({
providerSupportsSie: vi.fn().mockReturnValue(false),
fetchProviderSieFiles: vi.fn(),
getAllowedFiscalYears: vi.fn().mockReturnValue([]),
FiscalYearSelectionError: class FiscalYearSelectionError extends Error {},
MAX_SELECTED_FISCAL_YEARS: 6,
}))
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
createServiceClient: vi.fn(),
}))
import { arcimMigrationExtension } from '../index'
import { getConsent, resolveConsent, fetchCompanyInfoDirect } from '../lib/provider-client'
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const previewHandler = (arcimMigrationExtension.apiRoutes ?? []).find(
(r) => r.method === 'GET' && r.path === '/preview',
)!.handler as RouteHandler
const VISMA_MODULE_BODY =
'{"ErrorCode":4002,"DeveloperErrorMessage":"ForbiddenRequestException - No access to module: api_standard","ErrorId":"x","Errors":[]}'
function vismaError(statusCode: number, body?: string): Error {
const e = new Error(`Visma API error: ${statusCode}`) as Error & {
statusCode: number
body?: string
}
e.statusCode = statusCode
e.body = body
return e
}
function buildCtx(): ExtensionContext {
const { supabase, mockResult } = createMockSupabase()
// The handler counts completed SIE imports at the end of the happy path.
mockResult({ count: 0 })
;(supabase as unknown as { auth: unknown }).auth = {
getUser: vi.fn().mockResolvedValue({ data: { user: { id: 'user-1' } } }),
}
return { supabase, companyId: 'company-1' } as unknown as ExtensionContext
}
function previewRequest() {
return createMockRequest('http://localhost/api/extensions/ext/arcim-migration/preview', {
searchParams: { consentId: 'consent-1' },
})
}
describe('GET /preview: company-info failures', () => {
beforeEach(() => {
vi.clearAllMocks()
;(getConsent as Mock).mockResolvedValue({ id: 'consent-1', status: 1, provider: 'visma' })
;(resolveConsent as Mock).mockResolvedValue({
consent: { provider: 'visma' },
accessToken: 'tok',
providerCompanyId: null,
})
})
it('answers 403 PROVIDER_API_MODULE_INACTIVE with the remediation instead of a silent empty preview', async () => {
;(fetchCompanyInfoDirect as Mock).mockRejectedValue(vismaError(403, VISMA_MODULE_BODY))
const res = await previewHandler(previewRequest(), buildCtx())
const { status, body } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
expect(status).toBe(403)
expect(body.error.code).toBe('PROVIDER_API_MODULE_INACTIVE')
expect(body.error.message).toContain('Appar och tillägg')
})
it('keeps a transient provider failure soft: the preview still answers 200', async () => {
;(fetchCompanyInfoDirect as Mock).mockRejectedValue(vismaError(503))
const res = await previewHandler(previewRequest(), buildCtx())
const { status, body } = await parseJsonResponse<{ companyInfo: unknown }>(res)
expect(status).toBe(200)
expect(body.companyInfo).toBeNull()
})
})
@@ -0,0 +1,164 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import { createQueuedMockSupabase } from '@/tests/helpers'
/**
* exchangeAuthToken() must refuse valid OAuth tokens that open the WRONG
* company.
*
* Bokio and WINT already had this guard in submitProviderToken: a token that
* works plus the wrong company imports a foreign legal entity's customers,
* suppliers and invoices into this ledger with no error at all. The OAuth
* providers (Fortnox, Visma) had nothing: whichever company the user (or
* whoever lured them) signed in to at the provider was bound to the consent.
*
* Rule under test: only a confident mismatch blocks. A missing org number on
* either side, or a failed company-information call, is not evidence and the
* exchange completes as before.
*/
vi.mock('@/lib/providers/oauth-config', () => ({
getOAuthConfig: vi.fn(() => ({
clientId: 'client-id',
clientSecret: 'client-secret',
redirectUri: 'https://app.example/api/extensions/ext/arcim-migration/callback',
})),
}))
vi.mock('@/lib/providers/fortnox/oauth', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/providers/fortnox/oauth')>()),
exchangeFortnoxCode: vi.fn(),
}))
vi.mock('@/lib/providers/provider-data-fetcher', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/providers/provider-data-fetcher')>()),
fetchCompanyInfoDirect: vi.fn(),
}))
let serviceClient: ReturnType<typeof createQueuedMockSupabase>
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceClient.supabase,
createClient: vi.fn(),
}))
import { exchangeAuthToken, ProviderCompanyMismatchError } from '../lib/provider-client'
import { exchangeFortnoxCode } from '@/lib/providers/fortnox/oauth'
import { fetchCompanyInfoDirect } from '@/lib/providers/provider-data-fetcher'
// Both pass normalizeOrgNumber's Luhn check: Spotify AB and Ericsson.
const TARGET_ORG = '5560160680'
const OTHER_ORG = '5567037485'
const TOKENS = { access_token: 'access-1', refresh_token: 'refresh-1', expires_in: 3600 }
/**
* Queue results in exchangeAuthToken's `from` order: provider_consents
* (company_id), companies (org_number), then the token upsert and the status
* update (whose results are not read).
*/
function useDb(consentCompanyId: string | null, targetOrgNumber: string | null) {
serviceClient = createQueuedMockSupabase()
serviceClient.enqueueMany([
{ data: consentCompanyId ? { company_id: consentCompanyId } : null },
{ data: { org_number: targetOrgNumber } },
])
return serviceClient
}
describe('exchangeAuthToken: provider company must match the consent company', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(console, 'error').mockImplementation(() => {})
;(exchangeFortnoxCode as Mock).mockResolvedValue(TOKENS)
})
it('refuses tokens for a different company and stores nothing', async () => {
const db = useDb('company-1', '556016-0680')
;(fetchCompanyInfoDirect as Mock).mockResolvedValue({
companyName: 'Annat Bolag AB',
organizationNumber: '556703-7485',
})
const error = await exchangeAuthToken('consent-1', 'fortnox', 'code', 'https://cb').catch((e) => e)
expect(error).toBeInstanceOf(ProviderCompanyMismatchError)
expect((error as ProviderCompanyMismatchError).expectedOrgNumber).toBe(TARGET_ORG)
expect((error as ProviderCompanyMismatchError).actualOrgNumber).toBe(OTHER_ORG)
expect((error as ProviderCompanyMismatchError).actualCompanyName).toBe('Annat Bolag AB')
// The one-shot code was exchanged (that is how we learned the company),
// but nothing about the result may land in the database.
expect(db.findCall('provider_consent_tokens', 'upsert')).toBeUndefined()
expect(db.findCall('provider_consents', 'update')).toBeUndefined()
})
it('checks the company the token opens, using the fresh access token', async () => {
useDb('company-1', TARGET_ORG)
;(fetchCompanyInfoDirect as Mock).mockResolvedValue({
companyName: 'Rätt Bolag AB',
organizationNumber: TARGET_ORG,
})
await exchangeAuthToken('consent-1', 'fortnox', 'code', 'https://cb')
expect(fetchCompanyInfoDirect).toHaveBeenCalledWith('fortnox', 'access-1')
})
it('stores the tokens and accepts the consent when the org numbers agree', async () => {
const db = useDb('company-1', '556016-0680')
;(fetchCompanyInfoDirect as Mock).mockResolvedValue({
companyName: 'Rätt Bolag AB',
organizationNumber: TARGET_ORG,
})
await expect(exchangeAuthToken('consent-1', 'fortnox', 'code', 'https://cb')).resolves.toEqual({
success: true,
consentId: 'consent-1',
})
const upsert = db.findCall('provider_consent_tokens', 'upsert')?.[0] as Record<string, unknown>
expect(upsert).toMatchObject({
consent_id: 'consent-1',
provider: 'fortnox',
access_token: 'access-1',
refresh_token: 'refresh-1',
})
expect(db.findCall('provider_consents', 'update')?.[0]).toEqual({ status: 1 })
})
it('does not block when the provider reports no org number', async () => {
const db = useDb('company-1', TARGET_ORG)
;(fetchCompanyInfoDirect as Mock).mockResolvedValue({ companyName: 'Namnlöst AB' })
await exchangeAuthToken('consent-1', 'fortnox', 'code', 'https://cb')
expect(db.findCall('provider_consent_tokens', 'upsert')).toBeDefined()
// Nothing to compare against: the target company is not even looked up.
expect(db.findCall('companies', 'select')).toBeUndefined()
})
it('does not block when the Accounted company has no org number', async () => {
const db = useDb('company-1', null)
;(fetchCompanyInfoDirect as Mock).mockResolvedValue({
companyName: 'Annat Bolag AB',
organizationNumber: OTHER_ORG,
})
await exchangeAuthToken('consent-1', 'fortnox', 'code', 'https://cb')
expect(db.findCall('provider_consent_tokens', 'upsert')).toBeDefined()
})
it('does not block when the company-information call fails', async () => {
// A scope the app registration lacks, or a provider hiccup, is not a
// verdict on identity. The tokens are valid (the exchange succeeded).
const db = useDb('company-1', TARGET_ORG)
;(fetchCompanyInfoDirect as Mock).mockRejectedValue(new Error('403 forbidden'))
await expect(exchangeAuthToken('consent-1', 'fortnox', 'code', 'https://cb')).resolves.toEqual({
success: true,
consentId: 'consent-1',
})
expect(db.findCall('provider_consent_tokens', 'upsert')).toBeDefined()
})
})
@@ -0,0 +1,364 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { encryptHandoffValue } from '../lib/handoff-crypto'
/**
* Unit-level guard on the two tenant boundaries in provider-client:
*
* 1. consumeOAuthState() must consume the OAuth state row with a SINGLE
* conditional UPDATE (`used_at IS NULL` + `expires_at > now` in the WHERE
* clause). A read-then-write would leave a window where two concurrent
* callbacks both see an unused row and both bind tokens.
* 2. getConsent() must filter on company_id. It runs on the service client,
* which bypasses RLS, so that predicate is the only thing stopping an
* authenticated user from reading another tenant's consent status.
*/
type QueryResult = { data?: unknown; error?: unknown }
type RecordedCall = { table: string; ops: [string, unknown[]][] }
/**
* Chainable Supabase stub that RECORDS the predicates it was given. The shared
* helper in tests/helpers.ts intentionally discards arguments; here the
* arguments are the thing under test.
*/
function createRecordingSupabase(results: QueryResult[]) {
const calls: RecordedCall[] = []
let index = 0
const from = (table: string) => {
const result = results[index++] ?? {}
const record: RecordedCall = { table, ops: [] }
calls.push(record)
const chain: unknown = new Proxy(
{},
{
get(_target, prop) {
if (prop === 'then') {
return (resolve: (v: unknown) => void) =>
resolve({ data: result.data ?? null, error: result.error ?? null })
}
return (...args: unknown[]) => {
record.ops.push([String(prop), args])
return chain
}
},
},
)
return chain
}
return { supabase: { from: vi.fn(from) }, calls }
}
const findOp = (call: RecordedCall, name: string, firstArg?: unknown) =>
call.ops.find(([op, args]) => op === name && (firstArg === undefined || args[0] === firstArg))
let serviceClient: { from: ReturnType<typeof vi.fn> }
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => serviceClient,
createServiceClientNoCookies: () => serviceClient,
createClient: vi.fn(),
}))
import {
consumeOAuthState,
mintHandoff,
consumeHandoff,
generateOtc,
getConsent,
ConsentNotFoundError,
} from '../lib/provider-client'
function useResults(results: QueryResult[]) {
const recording = createRecordingSupabase(results)
serviceClient = recording.supabase
return recording
}
describe('consumeOAuthState', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('consumes the state row with one conditional UPDATE, not a read then a write', async () => {
const { calls } = useResults([
{ data: { consent_id: 'consent-1', user_id: 'user-1' } },
{ data: { provider: 'fortnox', company_id: 'company-1' } },
])
await consumeOAuthState('state-token')
const otcCall = calls[0]
expect(otcCall.table).toBe('provider_otc')
// The very first thing done to the row is the UPDATE: there is no
// select-then-decide window for a concurrent replay to slip through.
expect(otcCall.ops[0][0]).toBe('update')
expect(findOp(otcCall, 'eq', 'code')?.[1]).toEqual(['code', 'state-token'])
// Single-use: the row is only claimed while it is still unclaimed.
expect(findOp(otcCall, 'is', 'used_at')?.[1]).toEqual(['used_at', null])
// Expiry is enforced in the same statement, not in JavaScript afterwards.
expect(findOp(otcCall, 'gt', 'expires_at')).toBeDefined()
expect(findOp(otcCall, 'select', 'consent_id, user_id, origin')).toBeDefined()
expect(findOp(otcCall, 'is', 'provider_code')?.[1]).toEqual(['provider_code', null])
expect(findOp(otcCall, 'is', 'provider_error')?.[1]).toEqual(['provider_error', null])
})
it('returns the consent and the provider read from the server-side rows', async () => {
useResults([{ data: { consent_id: 'consent-1', user_id: 'user-1' } }, { data: { provider: 'visma', company_id: 'company-1' } }])
await expect(consumeOAuthState('state-token')).resolves.toEqual({
consentId: 'consent-1',
provider: 'visma',
companyId: 'company-1',
userId: 'user-1',
origin: null,
})
})
it('reads the provider from provider_consents, never from the caller', async () => {
const { calls } = useResults([
{ data: { consent_id: 'consent-1', user_id: 'user-1' } },
{ data: { provider: 'fortnox', company_id: 'company-1' } },
])
await consumeOAuthState('state-token')
expect(calls[1].table).toBe('provider_consents')
expect(findOp(calls[1], 'eq', 'id')?.[1]).toEqual(['id', 'consent-1'])
})
it('returns null for an unknown or forged state token', async () => {
// No row matched the code: PostgREST answers with no representation.
useResults([{ data: null }])
await expect(consumeOAuthState('forged-token')).resolves.toBeNull()
})
it('returns null for an expired state token', async () => {
// The `expires_at > now` predicate excluded the row, so 0 rows updated.
useResults([{ data: null }])
await expect(consumeOAuthState('expired-token')).resolves.toBeNull()
})
it('returns null on replay: the second consume of the same token loses', async () => {
useResults([{ data: { consent_id: 'consent-1', user_id: 'user-1' } }, { data: { provider: 'fortnox', company_id: 'company-1' } }])
await expect(consumeOAuthState('one-time-token')).resolves.toEqual({
consentId: 'consent-1',
provider: 'fortnox',
companyId: 'company-1',
userId: 'user-1',
origin: null,
})
// Replay: used_at is now set, so `is('used_at', null)` matches nothing.
useResults([{ data: null }])
await expect(consumeOAuthState('one-time-token')).resolves.toBeNull()
})
it('returns userId null for a row minted before the initiator column existed', async () => {
// The callback refuses these (nobody to bind the completion to); this
// function only has to report the absence honestly, never invent a user.
useResults([{ data: { consent_id: 'consent-1', user_id: null } }, { data: { provider: 'fortnox', company_id: 'company-1' } }])
await expect(consumeOAuthState('state-token')).resolves.toEqual({
consentId: 'consent-1',
provider: 'fortnox',
companyId: 'company-1',
userId: null,
origin: null,
})
})
it('returns null when the consent behind a valid token is gone', async () => {
useResults([{ data: { consent_id: 'consent-1', user_id: 'user-1' } }, { data: null }])
await expect(consumeOAuthState('state-token')).resolves.toBeNull()
})
it('returns null when the update itself errors', async () => {
useResults([{ data: null, error: { message: 'boom' } }])
await expect(consumeOAuthState('state-token')).resolves.toBeNull()
})
})
describe('generateOtc', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('defaults the OAuth state lifetime to 10 minutes', async () => {
// The state only has to survive the round trip to the provider's login
// page. The old 60-minute default left a phished or leaked state
// consumable for an hour.
const { calls } = useResults([{ data: null }])
const before = Date.now()
const { expiresAt } = await generateOtc('consent-1', 'user-1', 'https://solbo.accounted.se')
const after = Date.now()
expect(calls[0].table).toBe('provider_otc')
const inserted = findOp(calls[0], 'insert')?.[1][0] as { consent_id: string; user_id: string; expires_at: string }
expect(inserted.consent_id).toBe('consent-1')
// The initiator travels with the row: the callback binds the completing
// session to it, so it must be written here and nowhere else.
expect(inserted.user_id).toBe('user-1')
expect(inserted).toHaveProperty('origin', 'https://solbo.accounted.se')
const tenMinutes = 10 * 60 * 1000
const expiry = new Date(expiresAt).getTime()
expect(expiry).toBeGreaterThanOrEqual(before + tenMinutes)
expect(expiry).toBeLessThanOrEqual(after + tenMinutes)
expect(new Date(inserted.expires_at).getTime()).toBe(expiry)
})
})
describe('OAuth handoff storage', () => {
const origin = 'https://solbo.accounted.se'
beforeEach(() => {
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'test-only-handoff-encryption-key')
})
afterEach(() => vi.unstubAllEnvs())
it.each([{ providerCode: 'auth-code' }, { providerError: 'access denied' }])(
'mints a fresh two-minute handoff holding %j', async (result) => {
const { calls } = useResults([{}, {}])
const before = Date.now()
const first = await mintHandoff('consent-1', 'user-1', origin, result)
const second = await mintHandoff('consent-1', 'user-1', origin, result)
expect(first.code).toMatch(/^[A-Za-z0-9_-]{43}$/)
expect(first.code).not.toBe(second.code)
expect(Date.parse(first.expiresAt)).toBeGreaterThanOrEqual(before + 120_000)
expect(Date.parse(first.expiresAt)).toBeLessThanOrEqual(Date.now() + 120_000)
const inserted = findOp(calls[0], 'insert')?.[1][0] as Record<string, unknown>
expect(inserted).toEqual({
code: first.code, consent_id: 'consent-1', user_id: 'user-1', origin,
expires_at: first.expiresAt,
provider_code: result.providerCode ? expect.stringMatching(/^v1:/) : null,
provider_error: result.providerError ? expect.stringMatching(/^v1:/) : null,
})
expect(JSON.stringify(inserted)).not.toContain(result.providerCode ?? result.providerError)
useResults([{ data: inserted }, { data: { provider: 'fortnox', company_id: 'company-1' } }])
await expect(consumeHandoff(first.code, origin)).resolves.toMatchObject({
providerCode: result.providerCode ?? null, providerError: result.providerError ?? null,
})
},
)
it('deletes atomically, binding origin, expiry, unused status and handoff purpose', async () => {
const { calls } = useResults([
{ data: {
consent_id: 'consent-1', user_id: 'user-1', origin, provider_error: null,
provider_code: encryptHandoffValue('stored-code', JSON.stringify(['handoff-token', 'consent-1', 'user-1', origin, 'provider_code'])),
} },
{ data: { provider: 'visma', company_id: 'company-1' } },
])
await expect(consumeHandoff('handoff-token', origin)).resolves.toEqual({
consentId: 'consent-1', userId: 'user-1', origin, provider: 'visma', companyId: 'company-1',
providerCode: 'stored-code', providerError: null,
})
expect(calls[0].ops[0][0]).toBe('delete')
expect(findOp(calls[0], 'eq', 'code')?.[1]).toEqual(['code', 'handoff-token'])
expect(findOp(calls[0], 'eq', 'origin')?.[1]).toEqual(['origin', origin])
expect(findOp(calls[0], 'is', 'used_at')?.[1]).toEqual(['used_at', null])
expect(findOp(calls[0], 'gt', 'expires_at')).toBeDefined()
expect(findOp(calls[0], 'or')?.[1]).toEqual(['provider_code.not.is.null,provider_error.not.is.null'])
expect(calls[1].table).toBe('provider_consents')
expect(findOp(calls[1], 'eq', 'id')?.[1]).toEqual(['id', 'consent-1'])
})
it('rejects unmatched or already consumed handoffs without reading a consent', async () => {
const { calls } = useResults([{ data: null }])
await expect(consumeHandoff('spent-token', origin)).resolves.toBeNull()
expect(calls).toHaveLength(1)
})
it('fails closed when the delete errors or the consent no longer exists', async () => {
useResults([{ error: { message: 'unavailable' } }])
await expect(consumeHandoff('token', origin)).resolves.toBeNull()
useResults([{ data: { consent_id: 'deleted-consent' } }, { data: null }])
await expect(consumeHandoff('token', origin)).resolves.toBeNull()
})
it('fails the flow if the handoff cannot be stored', async () => {
useResults([{ error: { message: 'unavailable' } }])
await expect(mintHandoff('consent-1', 'user-1', origin, { providerCode: 'code' }))
.rejects.toThrow('Failed to mint OAuth handoff')
})
it('rejects unencrypted or corrupted handoff credentials after deleting the row', async () => {
const { calls } = useResults([
{ data: { consent_id: 'consent-1', user_id: 'user-1', origin, provider_code: 'plaintext-code', provider_error: null } },
{ data: { provider: 'fortnox', company_id: 'company-1' } },
])
await expect(consumeHandoff('token', origin)).resolves.toBeNull()
expect(calls[0].ops[0][0]).toBe('delete')
})
})
describe('getConsent', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('filters on the owning company', async () => {
const { calls } = useResults([
{ data: { id: 'consent-1', name: 'n', provider: 'fortnox', status: 1 } },
])
await getConsent('consent-1', 'company-1')
expect(calls[0].table).toBe('provider_consents')
expect(findOp(calls[0], 'eq', 'id')?.[1]).toEqual(['id', 'consent-1'])
expect(findOp(calls[0], 'eq', 'company_id')?.[1]).toEqual(['company_id', 'company-1'])
})
it('throws ConsentNotFoundError when the consent belongs to another company', async () => {
// The company_id predicate excluded the row: indistinguishable from a
// consent id that does not exist at all, which is the point.
useResults([{ data: null }])
await expect(getConsent('other-tenants-consent', 'company-1')).rejects.toBeInstanceOf(
ConsentNotFoundError,
)
})
it('leaks no consent state in the not-found error', async () => {
useResults([{ data: null }])
const error = await getConsent('other-tenants-consent', 'company-1').catch((e) => e)
expect(error).toBeInstanceOf(ConsentNotFoundError)
expect((error as Error).message).toBe('Consent not found')
expect((error as Error).message).not.toContain('other-tenants-consent')
})
it('returns the consent when the caller owns it', async () => {
useResults([
{
data: {
id: 'consent-1',
name: 'gnubok-migration-user-1',
provider: 'fortnox',
status: 1,
org_number: '5566778899',
company_name: 'Test AB',
},
},
])
await expect(getConsent('consent-1', 'company-1')).resolves.toEqual({
id: 'consent-1',
name: 'gnubok-migration-user-1',
provider: 'fortnox',
status: 1,
orgNumber: '5566778899',
companyName: 'Test AB',
})
})
})
@@ -0,0 +1,158 @@
import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest'
import { createMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
import type { ExtensionContext } from '@/lib/extensions/types'
/**
* POST /reconcile (#1463): the payment reconcile runs as before, and
* `{ consentId }` adds the registration-voucher relink. The consent is
* validated company-scoped BEFORE the payment reconcile writes anything (a
* wrong id is a clean 404, not a 500 after a write), and a relink failure is
* reported beside the payment result that was already persisted instead of
* discarding it.
*/
vi.mock('../lib/migration-orchestrator', () => ({
executeMigration: vi.fn(),
}))
vi.mock('../lib/provider-client', () => ({
createConsent: vi.fn(),
getConsent: vi.fn(),
listConsents: vi.fn(),
generateOtc: vi.fn(),
consumeOAuthState: vi.fn(),
getAuthUrl: vi.fn(),
exchangeAuthToken: vi.fn(),
submitProviderToken: vi.fn(),
acceptConsent: vi.fn(),
deleteConsent: vi.fn(),
resolveConsent: vi.fn(),
fetchCompanyInfoDirect: vi.fn(),
ProviderTokenInvalidError: class ProviderTokenInvalidError extends Error {},
ConsentNotFoundError: class ConsentNotFoundError extends Error {},
}))
vi.mock('@/lib/invoices/bulk-reconcile-supplier-vouchers', () => ({
reconcileSupplierInvoiceVouchers: vi.fn(),
}))
vi.mock('../lib/relink-registration-vouchers', () => ({
relinkRegistrationVouchers: vi.fn(),
}))
import { arcimMigrationExtension } from '../index'
import { getConsent, ConsentNotFoundError } from '../lib/provider-client'
import { reconcileSupplierInvoiceVouchers } from '@/lib/invoices/bulk-reconcile-supplier-vouchers'
import { relinkRegistrationVouchers } from '../lib/relink-registration-vouchers'
const route = (arcimMigrationExtension.apiRoutes ?? []).find(
(r) => r.method === 'POST' && r.path === '/reconcile',
)!
type RouteHandler = (request: Request, ctx?: ExtensionContext) => Promise<Response>
const handler = route.handler as RouteHandler
const mReconcile = reconcileSupplierInvoiceVouchers as Mock
const mRelink = relinkRegistrationVouchers as Mock
const mGetConsent = getConsent as Mock
const PAYMENT_RESULT = { scanned: 3, autoLinked: 2, ambiguous: 0, unmatched: 1, items: [] }
const LINK_RESULT = {
scanned: 2, linked: 1, noRef: 0, refNotFetched: 1, unresolved: 0, ambiguous: 0, amountMismatch: 0, alreadyLinked: 0,
reports: [], providerInvoices: 2, matched: 2, unmatched: 0,
hydration: {
sales: { needed: 1, hydrated: 0, failed: 0, skippedForBudget: 1 },
supplier: { needed: 0, hydrated: 0, failed: 0, skippedForBudget: 0 },
},
}
function buildCtx(user: { id: string } | null = { id: 'user-1' }): ExtensionContext {
const { supabase } = createMockSupabase()
;(supabase as unknown as { auth: unknown }).auth = {
getUser: vi.fn().mockResolvedValue({ data: { user } }),
}
return { supabase, companyId: 'company-1', log: { info: vi.fn(), error: vi.fn(), warn: vi.fn() } } as unknown as ExtensionContext
}
function reconcileRequest(body?: Record<string, unknown>) {
return createMockRequest('http://localhost/api/extensions/ext/arcim-migration/reconcile', {
method: 'POST',
...(body ? { body } : {}),
})
}
describe('POST /reconcile', () => {
beforeEach(() => {
vi.clearAllMocks()
mReconcile.mockResolvedValue(PAYMENT_RESULT)
mRelink.mockResolvedValue(LINK_RESULT)
mGetConsent.mockResolvedValue({ id: 'consent-1', status: 1, provider: 'fortnox' })
})
it('returns 401 without a user and touches nothing', async () => {
const res = await handler(reconcileRequest({ consentId: 'consent-1' }), buildCtx(null))
expect(res.status).toBe(401)
expect(mGetConsent).not.toHaveBeenCalled()
expect(mReconcile).not.toHaveBeenCalled()
expect(mRelink).not.toHaveBeenCalled()
})
it('without consentId runs the payment reconcile only and answers as before', async () => {
const res = await handler(reconcileRequest({ dryRun: true }), buildCtx())
const { status, body } = await parseJsonResponse<Record<string, unknown>>(res)
expect(status).toBe(200)
expect(body).toEqual({ success: true, dryRun: true, result: PAYMENT_RESULT })
expect(mReconcile).toHaveBeenCalledWith(expect.objectContaining({ companyId: 'company-1', userId: 'user-1', dryRun: true }))
expect(mGetConsent).not.toHaveBeenCalled()
expect(mRelink).not.toHaveBeenCalled()
})
it('with consentId validates the consent, runs both passes and returns the link counts', async () => {
const res = await handler(reconcileRequest({ consentId: 'consent-1', dryRun: true }), buildCtx())
const { status, body } = await parseJsonResponse<Record<string, unknown>>(res)
expect(status).toBe(200)
expect(body).toEqual({ success: true, dryRun: true, result: PAYMENT_RESULT, registrationLinks: LINK_RESULT })
expect(mGetConsent).toHaveBeenCalledWith('consent-1', 'company-1')
expect(mRelink).toHaveBeenCalledWith(expect.objectContaining({ companyId: 'company-1', consentId: 'consent-1', dryRun: true }))
})
it('answers 404 PROVIDER_CONSENT_NOT_FOUND for a foreign or unknown consent, before any write', async () => {
mGetConsent.mockRejectedValue(new ConsentNotFoundError())
const res = await handler(reconcileRequest({ consentId: 'consent-x' }), buildCtx())
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(status).toBe(404)
expect(body.error.code).toBe('PROVIDER_CONSENT_NOT_FOUND')
expect(mReconcile).not.toHaveBeenCalled()
expect(mRelink).not.toHaveBeenCalled()
})
it('keeps the persisted payment result when the relink itself fails, and names the failure', async () => {
mRelink.mockRejectedValue({ status: 404, message: 'Consent not found' })
const res = await handler(reconcileRequest({ consentId: 'consent-1' }), buildCtx())
const { status, body } = await parseJsonResponse<Record<string, unknown>>(res)
expect(status).toBe(200)
expect(body).toEqual({
success: true,
dryRun: false,
result: PAYMENT_RESULT,
registrationLinks: null,
registrationLinksError: { code: 'PROVIDER_CONSENT_NOT_FOUND' },
})
})
it('classifies an unknown relink error as PROVIDER_MIGRATE_FAILED without leaking its message', async () => {
mRelink.mockRejectedValue(new Error('socket hang up at 10.0.0.1'))
const res = await handler(reconcileRequest({ consentId: 'consent-1' }), buildCtx())
const { body } = await parseJsonResponse<{ registrationLinksError: { code: string } }>(res)
expect(body.registrationLinksError).toEqual({ code: 'PROVIDER_MIGRATE_FAILED' })
expect(JSON.stringify(body)).not.toContain('10.0.0.1')
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,74 @@
import { describe, it, expect, vi } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
/**
* The count the cron sizes and orders its run by. It must be the pass's own
* predicate (non-draft sales invoices of this company with no rows) evaluated
* in the database as a HEAD count, so a company with thousands of complete
* invoices costs one indexed query and no rows. The grammar itself
* (`invoice_items=is.null` on a to-many embed) is proven against a real
* PostgREST in complete-invoice-lines-count.tool.test.ts; this file pins the
* query shape and the error contract.
*/
vi.mock('@/lib/providers/resolve-consent', () => ({ resolveConsent: vi.fn() }))
vi.mock('@/lib/providers/provider-data-fetcher', () => ({
fetchSalesInvoicesDirect: vi.fn(),
hydrateSalesInvoices: vi.fn(),
}))
vi.mock('@/lib/supabase/fetch-all', () => ({ fetchAllRows: vi.fn() }))
import { countRowlessInvoices } from '../complete-invoice-lines'
interface Call { method: string; args: unknown[] }
/** Thenable query-builder stand-in that records the chain and answers with `response`. */
function makeSupabase(response: { count: number | null; error: { message: string } | null }) {
const calls: Call[] = []
const tables: string[] = []
const builder: Record<string, unknown> = {}
for (const method of ['select', 'eq', 'neq', 'is']) {
builder[method] = (...args: unknown[]) => {
calls.push({ method, args })
return builder
}
}
builder.then = (resolve: (v: unknown) => void, reject: (e: unknown) => void) =>
Promise.resolve(response).then(resolve, reject)
const from = vi.fn((table: string) => {
tables.push(table)
return builder
})
return { supabase: { from } as unknown as SupabaseClient, calls, tables }
}
describe('countRowlessInvoices', () => {
it('counts non-draft sales invoices with no rows in the database, loading none of them', async () => {
const { supabase, calls, tables } = makeSupabase({ count: 155, error: null })
await expect(countRowlessInvoices(supabase, 'co-1')).resolves.toBe(155)
expect(tables).toEqual(['invoices'])
expect(calls).toEqual([
{ method: 'select', args: ['id, invoice_items(id)', { count: 'exact', head: true }] },
{ method: 'eq', args: ['company_id', 'co-1'] },
{ method: 'eq', args: ['document_type', 'invoice'] },
{ method: 'neq', args: ['status', 'draft'] },
{ method: 'is', args: ['invoice_items', null] },
])
})
it('throws on a failed count rather than reporting the company as done', async () => {
const { supabase } = makeSupabase({ count: null, error: { message: 'canceling statement due to statement timeout' } })
await expect(countRowlessInvoices(supabase, 'co-1')).rejects.toThrow(
'invoices count failed: canceling statement due to statement timeout',
)
})
it('reads a missing count as nothing to do', async () => {
const { supabase } = makeSupabase({ count: null, error: null })
await expect(countRowlessInvoices(supabase, 'co-1')).resolves.toBe(0)
})
})
@@ -0,0 +1,94 @@
import { randomUUID } from 'node:crypto'
import { describe, it, expect, beforeAll } from 'vitest'
import { getPool } from '@/tests/pg/setup'
import { seedCompany } from '@/tests/pg/fixtures'
import { createToolPgClient } from '@/tests/tool-pg/client'
import { countRowlessInvoices } from '../complete-invoice-lines'
/**
* `invoice_items=is.null` on a to-many embed is resolved by PostgREST, not by
* Postgres and not by the type system, and a HEAD count on top of it is one
* more thing a mocked client answers whatever the grammar means. The cron
* skips every register this count reports as empty, so a count that came
* back 0 for everyone would switch the whole cron off, and a count that
* ignored the embed filter would size registers by their whole history. Both
* pass unit tests. This asserts on the real thing that the count is the
* anti-join the pass's own `loadCandidates` evaluates client-side.
*/
async function insertInvoice(input: {
userId: string
companyId: string
status?: string
documentType?: string
rows?: number
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.invoices
(id, user_id, company_id, invoice_number, invoice_date, due_date, status, document_type, total)
VALUES ($1, $2, $3, $4, '2026-03-14', '2026-04-13', $5, $6, 1250)`,
[id, input.userId, input.companyId, `F-${randomUUID()}`, input.status ?? 'sent', input.documentType ?? 'invoice'],
)
for (let i = 0; i < (input.rows ?? 0); i++) {
await getPool().query(
`INSERT INTO public.invoice_items (invoice_id, sort_order, description, quantity, unit_price, line_total)
VALUES ($1, $2, 'Konsulttid', 1, 1000, 1000)`,
[id, i + 1],
)
}
return id
}
describe('countRowlessInvoices against a real PostgREST', () => {
let client: ReturnType<typeof createToolPgClient>
let companyId: string
let otherCompanyId: string
beforeAll(async () => {
client = createToolPgClient()
const a = await seedCompany()
const b = await seedCompany()
companyId = a.companyId
otherCompanyId = b.companyId
// Three the pass would complete...
await insertInvoice({ userId: a.userId, companyId })
await insertInvoice({ userId: a.userId, companyId, status: 'paid' })
await insertInvoice({ userId: a.userId, companyId, status: 'overdue' })
// ...and four it would not: rows already there, a draft, a proforma.
await insertInvoice({ userId: a.userId, companyId, status: 'paid', rows: 1 })
await insertInvoice({ userId: a.userId, companyId, rows: 3 })
await insertInvoice({ userId: a.userId, companyId, status: 'draft' })
await insertInvoice({ userId: a.userId, companyId, documentType: 'proforma' })
// Another company's row-less invoice must not leak into the count.
await insertInvoice({ userId: b.userId, companyId: otherCompanyId })
}, 30_000)
it('counts exactly the non-draft sales invoices with no rows, per company', async () => {
expect(await countRowlessInvoices(client, companyId)).toBe(3)
expect(await countRowlessInvoices(client, otherCompanyId)).toBe(1)
})
it('agrees with the predicate the pass evaluates client-side', async () => {
const { data, error } = await client
.from('invoices')
.select('id, invoice_items(id)')
.eq('company_id', companyId)
.eq('document_type', 'invoice')
.neq('status', 'draft')
expect(error).toBeNull()
const rows = (data ?? []) as { id: string; invoice_items: { id: string }[] | null }[]
const rowless = rows.filter((row) => (row.invoice_items?.length ?? 0) === 0)
expect(rows).toHaveLength(5)
expect(rowless).toHaveLength(await countRowlessInvoices(client, companyId))
})
it('reports zero for a company whose invoices all have rows', async () => {
const c = await seedCompany()
await insertInvoice({ userId: c.userId, companyId: c.companyId, rows: 2 })
await insertInvoice({ userId: c.userId, companyId: c.companyId, status: 'paid', rows: 1 })
expect(await countRowlessInvoices(client, c.companyId)).toBe(0)
})
})
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest'
import { buildCustomerMetadataEnrichment } from '../customer-metadata'
describe('buildCustomerMetadataEnrichment', () => {
const mapped = {
contact_person: 'Anna Andersson',
invoice_email_cc_addresses: ['[email protected]'],
invoice_email_bcc_addresses: ['[email protected]'],
}
it('fills metadata that was never configured', () => {
expect(buildCustomerMetadataEnrichment({
contact_person: null,
invoice_email_cc_addresses: null,
invoice_email_bcc_addresses: null,
}, mapped)).toEqual(mapped)
})
it('does not overwrite existing values or explicit clears', () => {
expect(buildCustomerMetadataEnrichment({
contact_person: '',
invoice_email_cc_addresses: [],
invoice_email_bcc_addresses: ['[email protected]'],
}, mapped)).toBeNull()
})
it('does not turn unknown provider metadata into explicit empty values', () => {
expect(buildCustomerMetadataEnrichment({
contact_person: null,
invoice_email_cc_addresses: null,
invoice_email_bcc_addresses: null,
}, {
contact_person: null,
invoice_email_cc_addresses: [],
invoice_email_bcc_addresses: null,
})).toBeNull()
})
})

Some files were not shown because too many files have changed in this diff Show More