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>
This commit is contained in:
Jakob Wennberg
2026-09-01 14:57:48 +02:00
committed by GitHub
co-authored by Claude Opus 5
parent 1c04262e06
commit f1d76deaba
25 changed files with 1356 additions and 134 deletions
+26 -1
View File
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest'
import { getErrorMessage } from '../get-error-message'
import { getErrorMessage, getProviderResourceForbiddenMessage } from '../get-error-message'
import { getErrorEntry } from '../structured-errors'
import {
AccountsNotInChartError,
BookkeepingDatabaseError,
@@ -538,3 +539,27 @@ describe('getErrorMessage: GoTrue auth error patterns', () => {
)
})
})
describe('getProviderResourceForbiddenMessage', () => {
it('builds on the registry copy and appends the provider\'s own sentence', () => {
const entry = getErrorEntry('PROVIDER_RESOURCE_FORBIDDEN')!
const msg = getProviderResourceForbiddenMessage('Saknar behörighet för leverantörsregister.')
// One copy of the sentence, in the registry: the toast, the API envelope
// and the public error catalogue all have to say the same thing.
expect(msg.startsWith(entry.message_sv)).toBe(true)
// The provider's own words are the only part that names the register.
expect(msg).toContain('Leverantörens svar: "Saknar behörighet för leverantörsregister."')
})
it('falls back to the base sentence alone when the provider sent an opaque body', () => {
const entry = getErrorEntry('PROVIDER_RESOURCE_FORBIDDEN')!
expect(getProviderResourceForbiddenMessage(null)).toBe(entry.message_sv)
expect(getProviderResourceForbiddenMessage(' ')).toBe(entry.message_sv)
expect(getProviderResourceForbiddenMessage(null, 'en')).toBe(entry.message_en)
})
it('never tells the user to reconnect: the same grant meets the same 403', () => {
expect(getProviderResourceForbiddenMessage(null)).not.toMatch(/återanslut för att fortsätta/i)
})
})
@@ -70,6 +70,25 @@ describe('structured-errors registry', () => {
expect(entry?.retryable).toBeFalsy()
})
it('registers PROVIDER_RESOURCE_FORBIDDEN as a 403 that never tells the user to reconnect', () => {
// The provider refused one register on a grant that keeps working, so
// "Återanslut" is the one thing this message must not say: reconnecting
// re-mints the same grant and meets the same 403. This entry is also the
// single source of that copy (get-error-message.ts reads it for the toast,
// lib/docs/content/errors.ts publishes it), so it has to exist.
const entry = getErrorEntry('PROVIDER_RESOURCE_FORBIDDEN')
expect(entry).toBeDefined()
expect(entry?.httpStatus).toBe(403)
// Says reconnecting does not help; never the "Återanslut för att
// fortsätta" imperative PROVIDER_AUTH_EXPIRED carries.
expect(entry?.message_sv).toMatch(/återansluta hjälper inte/i)
expect(entry?.message_sv).not.toMatch(/återanslut för att fortsätta/i)
expect(entry?.message_sv).toMatch(/behörighet/i)
expect(entry?.message_en).toBeTruthy()
// Retrying the same call hits the same permission gap: not transient.
expect(entry?.retryable).toBeFalsy()
})
it('listErrorCodes returns at least the bookkeeping + generic + provider codes', () => {
const codes = listErrorCodes()
expect(codes.length).toBeGreaterThan(20)
+32
View File
@@ -643,6 +643,38 @@ export function getBankConnectionErrorMessage(
return description && description !== code ? `${base} (${description})` : base
}
const PROVIDER_REASON_PREFIX: Bilingual = {
sv: 'Leverantörens svar',
en: 'Provider response',
}
/**
* The provider refused ONE register while the grant itself keeps working: a
* Fortnox account without rights to leverantörsregistret, a Bokio token with a
* narrower scope. Never say "återanslut" here, the reconnect re-mints the same
* grant and hits the same 403.
*
* The base copy is the registry's PROVIDER_RESOURCE_FORBIDDEN entry, not a
* second copy of it: the same sentence has to reach the toast, the API
* envelope and the public error catalogue (lib/docs/content/errors.ts renders
* the registry verbatim). The entry's existence is locked by
* lib/errors/__tests__/structured-errors.test.ts.
*
* `reason` is the provider's own sentence (e.g. Fortnox'
* "Saknar behörighet för leverantörsregister."), appended verbatim because it
* is the only part that names the register. Omitted when the provider sent an
* opaque body, which Bokio does.
*/
export function getProviderResourceForbiddenMessage(
reason?: string | null,
locale: ErrorLocale = 'sv',
): string {
const entry = getErrorEntry('PROVIDER_RESOURCE_FORBIDDEN')!
const base = pick({ sv: entry.message_sv, en: entry.message_en }, locale)
const detail = reason?.trim()
return detail ? `${base} ${pick(PROVIDER_REASON_PREFIX, locale)}: "${detail}"` : base
}
/**
* Helper that parses a Response body and returns a user-friendly error message.
*/
+11
View File
@@ -3167,6 +3167,17 @@ const PROVIDER: Record<string, StructuredErrorEntry> = {
message_sv: 'Anslutningen till leverantören har gått ut. Återanslut för att fortsätta.',
message_en: 'Provider authentication expired or refresh failed.',
},
// The provider refused ONE register while the same access token keeps
// answering for the rest (Fortnox: "Saknar behörighet för
// leverantörsregister.", code 2003275). Never "återanslut" here: the
// reconnect re-mints the same grant and meets the same 403.
PROVIDER_RESOURCE_FORBIDDEN: {
httpStatus: 403,
message_sv:
'Leverantören nekade åtkomst till en del av uppgifterna, men anslutningen fungerar. Att återansluta hjälper inte: kontrollera behörigheterna för det registret hos leverantören (i Fortnox användarens rättigheter och licens, i Bokio rättigheterna på integrationstoken) och försök igen.',
message_en:
'The provider refused access to part of the data, but the connection itself works. Reconnecting will not help: check that register\'s permissions with the provider (in Fortnox the user rights and licence, in Bokio the integration token rights) and try again.',
},
PROVIDER_LICENSE_MISSING: {
httpStatus: 403,
message_sv:
@@ -0,0 +1,75 @@
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()
})
})
@@ -3,7 +3,9 @@ import {
classifyProviderError,
isApiModuleInactiveError,
ProviderCallError,
type ProviderCallErrorCode,
} from '../with-provider-call'
import { FortnoxApiError } from '../fortnox/client'
import { getErrorEntry } from '@/lib/errors/structured-errors'
/**
@@ -19,6 +21,10 @@ import { getErrorEntry } from '@/lib/errors/structured-errors'
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}}'
/** Mirror of VismaApiError's shape: statusCode + body on a plain Error. */
function vismaError(statusCode: number, body?: string): Error {
const e = new Error(`Visma API error: ${statusCode}`) as Error & {
@@ -37,8 +43,71 @@ describe('classifyProviderError', () => {
)
})
it('keeps a bare 403 (no module body) as PROVIDER_AUTH_EXPIRED', () => {
it('keeps a bare 403 on the first call of a run as PROVIDER_AUTH_EXPIRED', () => {
// Nothing has proven the grant yet and the body says nothing: a revoked
// grant and a closed register look identical, so "reconnect" stays.
expect(classifyProviderError(vismaError(403))).toBe('PROVIDER_AUTH_EXPIRED')
expect(classifyProviderError(vismaError(403), { grantProven: false })).toBe(
'PROVIDER_AUTH_EXPIRED',
)
})
it('reads a bare 403 as PROVIDER_RESOURCE_FORBIDDEN once the run has proven the grant', () => {
// Bokio sends an empty 403 body. The same token answered an earlier step
// in this run, so the grant is alive and one register is closed: aborting
// the run and telling the user to reconnect can never help.
expect(classifyProviderError(vismaError(403), { grantProven: true })).toBe(
'PROVIDER_RESOURCE_FORBIDDEN',
)
})
it('reads the Fortnox per-register 403 as PROVIDER_RESOURCE_FORBIDDEN even on the first call', () => {
// Fortnox answers 401 for a dead token and 403 only for a resource the
// account may not read, so its own 403 is proof enough. Classified off the
// typed error, not off the Swedish sentence in the body: the same denial
// in another locale, or reworded, must classify identically.
const err = new FortnoxApiError('Fortnox API error: 403', 403, FORTNOX_SUPPLIER_BODY)
expect(classifyProviderError(err)).toBe('PROVIDER_RESOURCE_FORBIDDEN')
const localised = new FortnoxApiError(
'Fortnox API error: 403',
403,
'{"ErrorInformation":{"Error":1,"Message":"No permission for the supplier register.","Code":2003275}}',
)
expect(classifyProviderError(localised)).toBe('PROVIDER_RESOURCE_FORBIDDEN')
// Fortnox sometimes answers with no body at all; still a per-resource 403.
expect(classifyProviderError(new FortnoxApiError('Fortnox API error: 403', 403))).toBe(
'PROVIDER_RESOURCE_FORBIDDEN',
)
})
it('does not read a Fortnox 401 as a per-resource denial', () => {
// 401 IS the dead token: the migration must keep aborting on it.
expect(classifyProviderError(new FortnoxApiError('Fortnox API error: 401', 401))).toBe(
'PROVIDER_AUTH_EXPIRED',
)
})
it('does not read another provider\'s "saknar behörighet" body as a per-resource denial', () => {
// The Swedish sentence alone proves nothing: only Fortnox is known to
// reserve 403 for the resource, and the run's own history covers the rest.
expect(classifyProviderError(vismaError(403, FORTNOX_SUPPLIER_BODY))).toBe(
'PROVIDER_AUTH_EXPIRED',
)
})
it('never downgrades a 401: a dead token is a dead token, proven grant or not', () => {
expect(classifyProviderError(vismaError(401))).toBe('PROVIDER_AUTH_EXPIRED')
expect(classifyProviderError(vismaError(401), { grantProven: true })).toBe(
'PROVIDER_AUTH_EXPIRED',
)
})
it('keeps a module/licence 403 fatal even after the grant is proven', () => {
expect(classifyProviderError(vismaError(403, VISMA_MODULE_BODY), { grantProven: true })).toBe(
'PROVIDER_API_MODULE_INACTIVE',
)
})
it('maps a Fortnox missing-license message to PROVIDER_LICENSE_MISSING', () => {
@@ -57,6 +126,19 @@ describe('classifyProviderError', () => {
expect(classifyProviderError(err)).toBe('PROVIDER_API_MODULE_INACTIVE')
})
it('re-reads a ProviderCallError 403 with the run context mapResponseError lacked', () => {
const err = new ProviderCallError('PROVIDER_AUTH_EXPIRED', 'bokio', 'Forbidden', {
status: 403,
})
expect(classifyProviderError(err)).toBe('PROVIDER_AUTH_EXPIRED')
expect(classifyProviderError(err, { grantProven: true })).toBe('PROVIDER_RESOURCE_FORBIDDEN')
const unauthorized = new ProviderCallError('PROVIDER_AUTH_EXPIRED', 'bokio', 'Unauthorized', {
status: 401,
})
expect(classifyProviderError(unauthorized, { grantProven: true })).toBe('PROVIDER_AUTH_EXPIRED')
})
it('returns null for an unclassifiable error', () => {
expect(classifyProviderError(new Error('boom'))).toBeNull()
expect(classifyProviderError('not an error')).toBeNull()
@@ -82,4 +164,27 @@ describe('structured error registry wiring', () => {
expect(entry!.message_sv).toContain('Appar och tillägg')
expect(entry!.message_en).toBeTruthy()
})
it('every code classifyProviderError can return has a registry entry', () => {
// A code with no entry falls through entryFor() to INTERNAL_ERROR and the
// route answers 500 with "Något gick fel", which is how
// PROVIDER_RESOURCE_FORBIDDEN shipped the first time. Keyed by the union
// rather than listed in an array, so the next code added to
// ProviderCallErrorCode fails to compile until it is checked here too.
const codes: Record<ProviderCallErrorCode, true> = {
PROVIDER_AUTH_EXPIRED: true,
PROVIDER_RESOURCE_FORBIDDEN: true,
PROVIDER_LICENSE_MISSING: true,
PROVIDER_API_MODULE_INACTIVE: true,
PROVIDER_RATE_LIMITED: true,
PROVIDER_UNREACHABLE: true,
PROVIDER_UPSTREAM_ERROR: true,
}
for (const code of Object.keys(codes) as ProviderCallErrorCode[]) {
const entry = getErrorEntry(code)
expect(entry, `missing registry entry for ${code}`).toBeDefined()
expect(entry!.message_sv).toBeTruthy()
expect(entry!.message_en).toBeTruthy()
}
})
})
+63 -46
View File
@@ -74,60 +74,77 @@ async function blPaginate<T>(
// ── Public fetch functions ──────────────────────────────────────────
/**
* Company information straight from the provider.
*
* Throws whatever the provider client threw. It used to catch everything and
* return null, which made a Visma company whose api_standard module is off
* look like a company with no details: the preview answered 200 with
* companyInfo: null and its classify-and-rethrow remediation was unreachable
* code. Callers decide what is soft (the preview keeps transient failures
* soft, the migration records a step error). `null` still means "nothing to
* fetch here" (no resource config, or no provider company id), never "the
* call failed".
*/
export async function fetchCompanyInfoDirect(
provider: ProviderName,
accessToken: string,
providerCompanyId?: string,
): Promise<CompanyInformationDto | null> {
try {
if (provider === 'fortnox') {
const config = FORTNOX_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
const response = await fortnoxClient.get<Record<string, unknown>>(accessToken, config.listEndpoint);
const data = response[config.detailKey];
return data ? config.mapper(data as Record<string, unknown>) as CompanyInformationDto : null;
}
if (provider === 'visma') {
const config = VISMA_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
const response = await vismaClient.get<Record<string, unknown>>(accessToken, config.listEndpoint);
return config.mapper(response) as CompanyInformationDto;
}
if (provider === 'briox') {
const config = BRIOX_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
const response = await brioxClient.get<Record<string, unknown>>(accessToken, config.listEndpoint);
return config.mapper(response) as CompanyInformationDto;
}
if (provider === 'bokio') {
const config = BOKIO_RESOURCE_CONFIGS[ResourceType.CompanyInformation];
if (!config || !providerCompanyId) return null;
const response = await bokioClient.getCompany<Record<string, unknown>>(accessToken, providerCompanyId);
return response ? config.mapper(response) as CompanyInformationDto : null;
}
if (provider === 'bjornlunden') {
const config = BL_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
if (!providerCompanyId) return null;
const response = await bjornLundenClient.get<Record<string, unknown>>(accessToken, providerCompanyId, config.listEndpoint);
return config.mapper(response) as CompanyInformationDto;
}
if (provider === 'wint') {
// The WINT token is company-scoped: GET /api/Auth describes the company
// the token opens, no providerCompanyId needed on the request.
const config = WINT_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
const response = await wintClient.get<Record<string, unknown>>(accessToken, config.listEndpoint);
return config.mapper(response) as CompanyInformationDto;
}
return null;
} catch (error) {
console.error(`[provider-data-fetcher] Failed to fetch company info from ${provider}:`, error);
return null;
if (provider === 'fortnox') {
const config = FORTNOX_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
const response = await fortnoxClient.get<Record<string, unknown>>(accessToken, config.listEndpoint);
const data = response[config.detailKey];
return data ? config.mapper(data as Record<string, unknown>) as CompanyInformationDto : null;
}
if (provider === 'visma') {
const config = VISMA_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
const response = await vismaClient.get<Record<string, unknown>>(accessToken, config.listEndpoint);
return config.mapper(response) as CompanyInformationDto;
}
if (provider === 'briox') {
const config = BRIOX_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
const response = await brioxClient.get<Record<string, unknown>>(accessToken, config.listEndpoint);
return config.mapper(response) as CompanyInformationDto;
}
if (provider === 'bokio') {
const config = BOKIO_RESOURCE_CONFIGS[ResourceType.CompanyInformation];
if (!config || !providerCompanyId) return null;
const response = await bokioClient.getCompany<Record<string, unknown>>(accessToken, providerCompanyId);
return response ? config.mapper(response) as CompanyInformationDto : null;
}
if (provider === 'bjornlunden') {
const config = BL_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
if (!providerCompanyId) return null;
const response = await bjornLundenClient.get<Record<string, unknown>>(accessToken, providerCompanyId, config.listEndpoint);
return config.mapper(response) as CompanyInformationDto;
}
if (provider === 'wint') {
// The WINT token is company-scoped: GET /api/Auth describes the company
// the token opens, no providerCompanyId needed on the request.
const config = WINT_RESOURCE_CONFIGS[ResourceType.CompanyInformation]!;
const response = await wintClient.get<Record<string, unknown>>(accessToken, config.listEndpoint);
return config.mapper(response) as CompanyInformationDto;
}
return null;
}
/**
* List fetches. Every one of them can answer `[]` WITHOUT issuing a request:
* Bokio and Björn Lundén key their list endpoints on a provider company id
* this consent may not carry, WINT has no supplier register, and Bokio's
* supplier 404 is swallowed on purpose. So an empty array means "nothing to
* import", never "the provider answered nothing", and callers must not read a
* resolved promise as proof that the access token works (see the migration
* orchestrator's ProviderRunState.grantProven, which counts rows instead).
* A failed request still throws; only genuinely absent resources return [].
*/
export async function fetchCustomersDirect(
provider: ProviderName,
accessToken: string,
+44 -2
View File
@@ -10,9 +10,16 @@
*/
import { createLogger, type Logger } from '@/lib/logger'
// Fortnox is the one provider with a typed predicate for "this account may not
// read this resource" (403, or 400 with a permission body). classifyProviderError
// reuses it instead of pattern-matching the Swedish sentence in the body, which
// changes with the provider's locale and copy; import-documents.ts already
// treats a Fortnox 403 the same way.
import { isFortnoxPermissionError } from './fortnox/client'
export type ProviderCallErrorCode =
| 'PROVIDER_AUTH_EXPIRED'
| 'PROVIDER_RESOURCE_FORBIDDEN'
| 'PROVIDER_LICENSE_MISSING'
| 'PROVIDER_API_MODULE_INACTIVE'
| 'PROVIDER_RATE_LIMITED'
@@ -172,12 +179,31 @@ function isNetworkError(err: Error): boolean {
return false
}
export interface ClassifyProviderErrorOptions {
/**
* True when an earlier provider call in the same run already returned data.
* The access token is then provably alive, so a 403 after that point is the
* provider closing ONE resource, not the grant dying. Leave it false (the
* default) when the failing call is the first one: an opaque 403 there is
* indistinguishable from a revoked grant and must keep saying "reconnect".
*
* Data returned, not a promise that resolved: several fetchers answer with
* an empty list before issuing any request (a provider company id we do not
* have, a register the provider does not expose), and those prove nothing.
*/
grantProven?: boolean
}
/**
* Classify an error from a provider client (Fortnox/Bokio/Visma/Briox/BL) into
* a structured error code. Reads `statusCode` (Fortnox client) or `status`
* (other clients) off the thrown error and maps:
*
* 401/403 → PROVIDER_AUTH_EXPIRED
* 401 → PROVIDER_AUTH_EXPIRED
* 403 → PROVIDER_RESOURCE_FORBIDDEN when the provider answers 403 only
* for the resource (Fortnox, see isFortnoxPermissionError), or
* when `options.grantProven` says an earlier call in the same run
* already succeeded on this token; otherwise PROVIDER_AUTH_EXPIRED
* 429 → PROVIDER_RATE_LIMITED
* 5xx → PROVIDER_UPSTREAM_ERROR
* network → PROVIDER_UNREACHABLE
@@ -189,8 +215,16 @@ function isNetworkError(err: Error): boolean {
* gått ut. Återanslut för att fortsätta." vs. "Försök igen om en stund.")
* instead of the same generic message for every cause.
*/
export function classifyProviderError(error: unknown): ProviderCallErrorCode | null {
export function classifyProviderError(
error: unknown,
options: ClassifyProviderErrorOptions = {},
): ProviderCallErrorCode | null {
if (error instanceof ProviderCallError) {
// mapResponseError() sees one response and cannot know the run's history,
// so a 403 it already labelled AUTH_EXPIRED is re-read here with it.
if (error.code === 'PROVIDER_AUTH_EXPIRED' && error.status === 403 && options.grantProven) {
return 'PROVIDER_RESOURCE_FORBIDDEN'
}
return error.code
}
if (!(error instanceof Error)) return null
@@ -212,6 +246,14 @@ export function classifyProviderError(error: unknown): ProviderCallErrorCode | n
if (isMissingLicenseError(haystack)) return 'PROVIDER_LICENSE_MISSING'
if (typeof status === 'number') {
// A 403 is only a dead grant when nothing else says otherwise: a provider
// that reserves 403 for the resource and answers 401 for a dead token
// (Fortnox), or the same token having already answered earlier in this
// run, both mean the grant is alive and one register is closed. 401 is
// never downgraded: that IS a dead token.
if (status === 403 && (options.grantProven || isFortnoxPermissionError(error))) {
return 'PROVIDER_RESOURCE_FORBIDDEN'
}
if (status === 401 || status === 403) return 'PROVIDER_AUTH_EXPIRED'
if (status === 429) return 'PROVIDER_RATE_LIMITED'
if (status >= 500) return 'PROVIDER_UPSTREAM_ERROR'