Files
accounted/lib/providers/__tests__/provider-data-fetcher.test.ts
T
Jakob WennbergandClaude Opus 5 f1d76deaba fix(providers): stop dead-ending on a resource 403, and stop dropping every migrated kreditfaktura (#2113)
* fix(providers): stop dead-ending on a resource 403, and stop dropping every migrated kreditfaktura

Two independent defects in the provider migration, both customer-visible.

A per-resource 403 was classified as a dead grant. classifyProviderError mapped
any 401 or 403 to PROVIDER_AUTH_EXPIRED, which is fatal, so a Fortnox account
without leverantorsregister permission aborted the whole migration at the
suppliers step with "Anslutningen har gatt ut. Ateranslut" even though the same
token had just succeeded on the previous step. Reconnecting can never fix that,
and steps 4 and later never ran. The provider's own reason ("Saknar behorighet
for leverantorsregister.") never reached the user. A 403 is now non-fatal once
the same token has already succeeded in the run, the migration continues, and
the provider's reason is surfaced. A 401, or a 403 on the first call, keeps the
auth-expired path.

fetchCompanyInfoDirect swallowed every error and returned null, which made the
existing PROVIDER_API_MODULE_INACTIVE remediation unreachable: a Visma customer
whose api_standard module is off got a silent 200 with an empty company card
instead of the precise Swedish explanation that was already written.

Kreditfakturor were dropped entirely. entity-mapper wrote document_type
'credit_note', but invoices_document_type_check allows only invoice, proforma
and delivery_note, and credit notes are modelled by credited_invoice_id. Every
migrated kreditfaktura was rejected and counted as skipped. One customer
imported 255 sales invoices and 0 credit notes on 2026-08-31; AR and revenue
are overstated by the credited amounts, and kreditfakturor are
rakenskapsinformation. They now import as invoice rows with reversed amounts
and status 'credited', following the in-app credit convention. They import
unlinked: no provider DTO carries a reference to the invoice being credited, so
there is nothing to match on and guessing would corrupt the AR ledger. The
wizard says so instead of burying them in skipped.

Also makes the OAuth callback non-replayable from browser history (no-store
plus history replacement), which is what the "state rejected" events were: a
replay of a callback that had already succeeded seconds earlier. No
already-connected page, so consumed-vs-unknown state stays unobservable to an
unauthenticated caller. Expected PSD2 session expiry drops from error to warn.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016ifKg6Ec67A39oxfGPU1yc

* fix(arcim): entity line needs the failed flag

The unlinked-credit-note row omitted `failed`, which the entityLines element
type requires. Caught by the zero-extensions build, not by vitest: the unit
suite does not typecheck.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016ifKg6Ec67A39oxfGPU1yc

* fix(arcim): write the missing-reference disclosure onto the credit note itself

Review finding (swedish-compliance-review-bot): ML 17 kap 22-23 § wants a
kreditfaktura to reference the invoice it credits, and BFL 5 kap 6-7 § wants a
verifikation to reference its underlag. No provider DTO carries that reference,
so the pairing cannot be resolved at import and guessing it would corrupt the
AR ledger. Reporting the count in the migration wizard is not enough: a result
screen is not rakenskapsinformation, and the gap has to be legible on the
record itself years later.

The disclosure now goes into invoices.notes and supplier_invoices.notes,
preserving whatever note the provider sent.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016ifKg6Ec67A39oxfGPU1yc

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-01 14:57:48 +02:00

76 lines
2.4 KiB
TypeScript

import { describe, it, expect, beforeEach, vi } from 'vitest'
/**
* Locks fetchCompanyInfoDirect's failure contract.
*
* It used to wrap the whole body in try/catch and return null on ANY error, so
* a Visma company whose api_standard module is off looked exactly like a
* company with no details: /preview answered 200 with companyInfo: null and
* its classify-and-rethrow remediation (PROVIDER_API_MODULE_INACTIVE, with the
* "Appar och tillägg" instructions) was unreachable code. The customer read
* "connected" and only found out after an empty migration.
*
* Contract now: provider errors propagate, and null keeps its one meaning,
* "there is nothing to fetch here".
*/
const { vismaGet, bokioGetCompany } = vi.hoisted(() => ({
vismaGet: vi.fn(),
bokioGetCompany: vi.fn(),
}))
vi.mock('../visma/client', () => ({
VismaClient: class {
get = vismaGet
},
}))
vi.mock('../bokio/client', () => ({
BokioClient: class {
getCompany = bokioGetCompany
},
BokioApiError: class BokioApiError extends Error {},
}))
import { fetchCompanyInfoDirect } from '../provider-data-fetcher'
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
}
describe('fetchCompanyInfoDirect', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('propagates a provider failure instead of swallowing it into null', async () => {
vismaGet.mockRejectedValue(vismaError(403, VISMA_MODULE_BODY))
await expect(fetchCompanyInfoDirect('visma', 'tok')).rejects.toMatchObject({
statusCode: 403,
body: VISMA_MODULE_BODY,
})
})
it('propagates transient failures too: the caller decides what is soft', async () => {
vismaGet.mockRejectedValue(vismaError(500))
await expect(fetchCompanyInfoDirect('visma', 'tok')).rejects.toMatchObject({ statusCode: 500 })
})
it('still returns null when there is nothing to fetch, without calling the provider', async () => {
// Bokio needs the provider company id to address the company endpoint.
await expect(fetchCompanyInfoDirect('bokio', 'tok')).resolves.toBeNull()
expect(bokioGetCompany).not.toHaveBeenCalled()
})
})