fix(import): SIE bulk-delete on service client + provider/reporting/b… (#724)

* fix(import): SIE bulk-delete on service client + provider/reporting/banking fixes

Rebuilt branch onto main as a single commit.

- import: run SIE bulk-delete RPCs on the service client to escape the 8s
  statement_timeout; undo_sie_import now takes an explicit actor (p_user_id)
  so its owner/admin gate works when auth.uid() is NULL on the service
  client (migration 20260624120000) + pg-real regression test
- providers: distinguish missing Fortnox license from expired connection;
  provider_consent_tokens PK regression test
- reports: include unmapped BAS expense groups in the income statement
- enable-banking: reconnect closed/expired bank sessions in place
- bookkeeping: surface linked invoices as underlag on the verifikat view
- scripts: track BL cleanup/diagnostic tooling; data files (*.csv) are
  git-ignored and consentId is now a required arg with no silent default

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(import): add Cache-Control header to journal entry references response

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-06-14 23:40:26 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent db8983ba9e
commit 43925bc2d3
37 changed files with 2456 additions and 1152 deletions
@@ -0,0 +1,94 @@
import { describe, it, expect } from 'vitest'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createQueuedMockSupabase } from '@/tests/helpers'
import { getJournalEntryUnderlagReferences } from '../journal-entry-references'
/**
* The resolver issues its queries in a fixed `.from()` order, and the queued
* mock consumes one enqueued result per `.from()` call:
* 1. invoices (direct journal_entry_id link)
* 2. invoice_payments (payment rows → invoice_id)
* 3. invoices (by id — only when step 2 found new ids)
* 4. supplier_invoices (registration_journal_entry_id)
* 5. supplier_invoices (payment_journal_entry_id)
* 6. supplier_invoice_payments (payment rows → supplier_invoice_id)
* 7. supplier_invoices (by id — only when step 6 found new ids)
*/
describe('getJournalEntryUnderlagReferences', () => {
const run = (results: { data: unknown }[]) => {
const { supabase, enqueueMany } = createQueuedMockSupabase()
enqueueMany(results)
return getJournalEntryUnderlagReferences(
supabase as unknown as SupabaseClient,
'company-1',
'je-1',
)
}
it('surfaces a customer invoice linked only via a cash-method payment row', async () => {
// The reported gap: debit 1930 / credit 3001, invoice linked through
// invoice_payments, no document attached and no direct invoice link.
const refs = await run([
{ data: [] }, // 1. invoices direct — none
{ data: [{ invoice_id: 'inv-x' }] }, // 2. invoice_payments
{ data: [{ id: 'inv-x', invoice_number: '003' }] }, // 3. invoices by id
{ data: [] }, // 4. supplier registration
{ data: [] }, // 5. supplier payment
{ data: [] }, // 6. supplier_invoice_payments
])
expect(refs).toEqual([{ type: 'invoice', id: 'inv-x', number: '003' }])
})
it('surfaces a supplier invoice linked via its registration booking', async () => {
const refs = await run([
{ data: [] }, // 1. invoices direct
{ data: [] }, // 2. invoice_payments (empty → step 3 skipped)
{ data: [{ id: 'si-1', supplier_invoice_number: 'LF-001' }] }, // 4. registration
{ data: [] }, // 5. supplier payment
{ data: [] }, // 6. supplier_invoice_payments
])
expect(refs).toEqual([{ type: 'supplier_invoice', id: 'si-1', number: 'LF-001' }])
})
it('returns nothing when no invoice is linked (warning legitimately stays)', async () => {
const refs = await run([
{ data: [] }, // 1. invoices direct
{ data: [] }, // 2. invoice_payments
{ data: [] }, // 4. supplier registration
{ data: [] }, // 5. supplier payment
{ data: [] }, // 6. supplier_invoice_payments
])
expect(refs).toEqual([])
})
it('deduplicates an invoice reachable via both the direct link and a payment row', async () => {
const refs = await run([
{ data: [{ id: 'inv-x', invoice_number: '003' }] }, // 1. invoices direct
{ data: [{ invoice_id: 'inv-x' }] }, // 2. invoice_payments (already known → step 3 skipped)
{ data: [] }, // 4. supplier registration
{ data: [] }, // 5. supplier payment
{ data: [] }, // 6. supplier_invoice_payments
])
expect(refs).toEqual([{ type: 'invoice', id: 'inv-x', number: '003' }])
})
it('returns both a customer and a supplier invoice, customer first', async () => {
const refs = await run([
{ data: [{ id: 'inv-a', invoice_number: 'A1' }] }, // 1. invoices direct
{ data: [] }, // 2. invoice_payments (empty → step 3 skipped)
{ data: [] }, // 4. supplier registration
{ data: [] }, // 5. supplier payment
{ data: [{ supplier_invoice_id: 'si-2' }] }, // 6. supplier_invoice_payments
{ data: [{ id: 'si-2', supplier_invoice_number: 'LF-2' }] }, // 7. supplier by id
])
expect(refs).toEqual([
{ type: 'invoice', id: 'inv-a', number: 'A1' },
{ type: 'supplier_invoice', id: 'si-2', number: 'LF-2' },
])
})
})
@@ -0,0 +1,143 @@
import type { SupabaseClient } from '@supabase/supabase-js'
/**
* A followable reference from a verifikation back to its underlag — the customer
* or supplier invoice that identifies what the affärshändelse avser and who the
* motpart is.
*
* Surfacing these makes the verifieringskedja traceable from the verifikat side,
* not only from the invoice side (BFL 5 kap 7§ — hänvisning till underlag;
* BFNAR 2013:2 — the verification chain must be followable in both directions).
*
* Bank transactions are deliberately excluded: a bank line is the trace of the
* affärshändelse, not its underlag. Counting it as underlag would wrongly silence
* the "saknar underlag" warning for expenses that still genuinely need a kvitto.
*/
export type UnderlagReferenceType = 'invoice' | 'supplier_invoice'
export interface UnderlagReference {
type: UnderlagReferenceType
id: string
/** invoice_number / supplier_invoice_number — the UI builds the label from this. */
number: string
}
interface InvoiceRow {
id: string
invoice_number: string
}
interface SupplierInvoiceRow {
id: string
supplier_invoice_number: string
}
/**
* Resolve every customer/supplier invoice linked to a verifikation, across all
* the deterministic FK paths the engine uses to book one:
* - invoices.journal_entry_id (faktureringsmetod registration / direct)
* - invoice_payments.journal_entry_id (kontantmetod inbetalning / delbetalning)
* - supplier_invoices.registration_journal_entry_id / payment_journal_entry_id
* - supplier_invoice_payments.journal_entry_id (delbetalning)
*
* Every query is company-scoped (defense in depth alongside RLS). Results are
* deduplicated by id, so an invoice reachable via several paths appears once.
*/
export async function getJournalEntryUnderlagReferences(
supabase: SupabaseClient,
companyId: string,
journalEntryId: string,
): Promise<UnderlagReference[]> {
// --- Customer invoices ---------------------------------------------------
const invoices = new Map<string, string>()
// Direct link (faktureringsmetod registration, or invoices.journal_entry_id).
const { data: directInvoices } = await supabase
.from('invoices')
.select('id, invoice_number')
.eq('company_id', companyId)
.eq('journal_entry_id', journalEntryId)
for (const inv of (directInvoices ?? []) as InvoiceRow[]) {
invoices.set(inv.id, inv.invoice_number)
}
// Payment rows (kontantmetod inbetalning, partial payments) → invoice_payments.
const { data: paymentRows } = await supabase
.from('invoice_payments')
.select('invoice_id')
.eq('journal_entry_id', journalEntryId)
const paymentInvoiceIds = new Set<string>()
for (const row of (paymentRows ?? []) as { invoice_id: string | null }[]) {
if (row.invoice_id && !invoices.has(row.invoice_id)) paymentInvoiceIds.add(row.invoice_id)
}
if (paymentInvoiceIds.size > 0) {
const { data: paidInvoices } = await supabase
.from('invoices')
.select('id, invoice_number')
.eq('company_id', companyId)
.in('id', Array.from(paymentInvoiceIds))
for (const inv of (paidInvoices ?? []) as InvoiceRow[]) {
invoices.set(inv.id, inv.invoice_number)
}
}
// --- Supplier invoices ---------------------------------------------------
const supplierInvoices = new Map<string, string>()
// Registration booking (accrual) on the invoice itself.
const { data: registrationLinks } = await supabase
.from('supplier_invoices')
.select('id, supplier_invoice_number')
.eq('company_id', companyId)
.eq('registration_journal_entry_id', journalEntryId)
for (const si of (registrationLinks ?? []) as SupplierInvoiceRow[]) {
supplierInvoices.set(si.id, si.supplier_invoice_number)
}
// Payment booking on the invoice itself.
const { data: paymentLinks } = await supabase
.from('supplier_invoices')
.select('id, supplier_invoice_number')
.eq('company_id', companyId)
.eq('payment_journal_entry_id', journalEntryId)
for (const si of (paymentLinks ?? []) as SupplierInvoiceRow[]) {
supplierInvoices.set(si.id, si.supplier_invoice_number)
}
// Partial-payment rows → supplier_invoice_payments.
const { data: supplierPaymentRows } = await supabase
.from('supplier_invoice_payments')
.select('supplier_invoice_id')
.eq('journal_entry_id', journalEntryId)
const supplierPaymentIds = new Set<string>()
for (const row of (supplierPaymentRows ?? []) as { supplier_invoice_id: string | null }[]) {
if (row.supplier_invoice_id && !supplierInvoices.has(row.supplier_invoice_id)) {
supplierPaymentIds.add(row.supplier_invoice_id)
}
}
if (supplierPaymentIds.size > 0) {
const { data: paidSupplierInvoices } = await supabase
.from('supplier_invoices')
.select('id, supplier_invoice_number')
.eq('company_id', companyId)
.in('id', Array.from(supplierPaymentIds))
for (const si of (paidSupplierInvoices ?? []) as SupplierInvoiceRow[]) {
supplierInvoices.set(si.id, si.supplier_invoice_number)
}
}
// --- Assemble ------------------------------------------------------------
const references: UnderlagReference[] = []
for (const [id, number] of invoices) references.push({ type: 'invoice', id, number })
for (const [id, number] of supplierInvoices) references.push({ type: 'supplier_invoice', id, number })
return references
}
+7
View File
@@ -1861,6 +1861,13 @@ 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.',
},
PROVIDER_LICENSE_MISSING: {
httpStatus: 403,
message_sv:
'Fortnox nekade anslutningen eftersom integrationslicensen inte är aktiv. Aktivera tilläggstjänsten "Fortnox Integration" i ditt Fortnox-konto (Inställningar → Tilläggstjänster) och återanslut sedan. Du kan även importera via SIE-fil under tiden.',
message_en:
'Fortnox refused the connection because the integration license is not active. Activate the "Fortnox Integration" add-on in your Fortnox account, then reconnect. You can also import via SIE file in the meantime.',
},
PROVIDER_RATE_LIMITED: {
httpStatus: 429,
message_sv:
@@ -0,0 +1,156 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool, withUserContext } from '@/tests/pg/setup'
import {
seedCompany,
insertAuthUser,
insertCompanyMember,
insertDraftJournalEntry,
insertBalancedLines,
} from '@/tests/pg/fixtures'
// Migration 20260624120000_undo_sie_import_explicit_actor.sql makes
// undo_sie_import accept the authorising user as p_user_id and resolve the
// owner/admin gate against COALESCE(p_user_id, auth.uid()).
//
// Why: the RPC now runs on the service-role client (to escape the 8s
// statement_timeout on large imports). That client is cookie-less, so inside
// the RPC auth.uid() is NULL — before this fix the role lookup matched nothing
// and the function ALWAYS raised "Only company owners and admins can undo SIE
// imports", breaking undo entirely on hosted.
//
// These tests call the function over the raw pool (no JWT context), which is
// exactly the auth.uid()-is-NULL situation the service client creates.
async function insertCompletedImport(params: {
companyId: string
userId: string
fiscalPeriodId: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO public.sie_imports
(id, user_id, company_id, filename, file_hash, sie_type,
fiscal_year_start, fiscal_year_end, accounts_count, transactions_count,
status, fiscal_period_id, imported_at)
VALUES ($1, $2, $3, 'undo-actor-test.se', $4, 4,
'2026-01-01', '2026-12-31', 0, 1,
'completed', $5, now())`,
[id, params.userId, params.companyId, `hash-${id}`, params.fiscalPeriodId],
)
return id
}
// Seed one posted source_type='import' verifikat so undo has something to
// delete. Insert as draft + balanced lines, then commit the draft→posted
// transition (the balance trigger requires balanced lines on that step).
async function insertPostedImportEntry(params: {
companyId: string
userId: string
fiscalPeriodId: string
}): Promise<string> {
const jeId = await insertDraftJournalEntry({
userId: params.userId,
companyId: params.companyId,
fiscalPeriodId: params.fiscalPeriodId,
sourceType: 'import',
status: 'draft',
voucherNumber: 1,
})
await insertBalancedLines(jeId, 1000)
await getPool().query(
`UPDATE public.journal_entries SET status = 'posted' WHERE id = $1`,
[jeId],
)
return jeId
}
async function callUndo(companyId: string, importId: string, actor: string | null) {
return getPool().query<{ deleted: number }>(
`SELECT public.undo_sie_import($1::uuid, $2::uuid, $3::uuid) AS deleted`,
[companyId, importId, actor],
)
}
describe('undo_sie_import: explicit actor (service-client path)', () => {
it('succeeds with an owner p_user_id even when auth.uid() is NULL', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
const jeId = await insertPostedImportEntry({ companyId, userId, fiscalPeriodId })
const res = await callUndo(companyId, importId, userId)
expect(res.rows[0].deleted).toBe(1)
const { rows: jeRows } = await getPool().query(
`SELECT 1 FROM public.journal_entries WHERE id = $1`,
[jeId],
)
expect(jeRows).toHaveLength(0)
const { rows: impRows } = await getPool().query<{ status: string }>(
`SELECT status FROM public.sie_imports WHERE id = $1`,
[importId],
)
expect(impRows[0].status).toBe('undone')
})
it('raises when no authorising identity is supplied (auth.uid() NULL, p_user_id NULL)', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
await expect(callUndo(companyId, importId, null)).rejects.toThrow(
/owners and admins/i,
)
// The gate fired before any mutation — the import is untouched.
const { rows } = await getPool().query<{ status: string }>(
`SELECT status FROM public.sie_imports WHERE id = $1`,
[importId],
)
expect(rows[0].status).toBe('completed')
})
it('raises when p_user_id is not an owner/admin of the company', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
// A 'member' of the same company is still not allowed to undo.
const memberId = await insertAuthUser()
await insertCompanyMember({ companyId, userId: memberId, role: 'member' })
await expect(callUndo(companyId, importId, memberId)).rejects.toThrow(
/owners and admins/i,
)
// And a complete stranger (no membership) is rejected too.
await expect(callUndo(companyId, importId, randomUUID())).rejects.toThrow(
/owners and admins/i,
)
})
it('still resolves the actor from auth.uid() when p_user_id is omitted (backward compat)', async () => {
const { companyId, userId, fiscalPeriodId } = await seedCompany()
const importId = await insertCompletedImport({ companyId, userId, fiscalPeriodId })
// Seed a posted import verifikat so undo has something to delete. Without it
// the returned count is 0 regardless of behaviour, so the assertion would
// pass even if the function deleted nothing — making the count meaningless.
await insertPostedImportEntry({ companyId, userId, fiscalPeriodId })
// 2-arg shape: p_user_id defaults to NULL, so the gate falls back to
// auth.uid(). withUserContext sets the JWT sub to the owner and runs in a
// transaction; assert inside it (the helper rolls back on return).
const deleted = await withUserContext(userId, async (client) => {
const res = await client.query<{ deleted: number }>(
`SELECT public.undo_sie_import($1::uuid, $2::uuid) AS deleted`,
[companyId, importId],
)
const imp = await client.query<{ status: string }>(
`SELECT status FROM public.sie_imports WHERE id = $1`,
[importId],
)
expect(imp.rows[0].status).toBe('undone')
return res.rows[0].deleted
})
expect(deleted).toBe(1)
})
})
+40 -4
View File
@@ -157,6 +157,29 @@ export async function checkDuplicatePeriodImport(
return data as SIEImport | null
}
/**
* Client for the bulk hard-delete RPCs (replace_sie_import / undo_sie_import).
*
* The authenticated role carries statement_timeout=8s on hosted Supabase,
* and deleting a large import (thousands of journal_entries, each firing
* write_audit_log with a JSONB old_state snapshot, plus cascading lines)
* does not finish inside that budget — the RPC dies with "canceling
* statement due to statement timeout" and rolls back. The service role has
* no statement_timeout, so the RPC runs on it instead.
*
* Safe escalation: callers validate company ownership against the
* RLS-scoped session client BEFORE the RPC, and the RPC itself (SECURITY
* DEFINER) re-filters every statement on p_company_id.
*
* Falls back to the caller's client when the service key is absent
* (unit tests, misconfigured self-hosted) — same behavior as before.
*/
async function rpcClientForBulkDelete(fallback: SupabaseClient): Promise<SupabaseClient> {
if (!process.env.SUPABASE_SERVICE_ROLE_KEY) return fallback
const { createServiceClient } = await import('@/lib/supabase/server')
return createServiceClient()
}
/**
* Replace a completed SIE import so the user can re-import corrected data
* for the same fiscal period.
@@ -210,8 +233,10 @@ export async function replaceSIEImport(
}
}
// 3. Atomically delete entries and mark import as replaced via DB RPC
const { data: deletedCount, error: rpcError } = await supabase.rpc('replace_sie_import', {
// 3. Atomically delete entries and mark import as replaced via DB RPC.
// Runs on the service client — see rpcClientForBulkDelete.
const rpcClient = await rpcClientForBulkDelete(supabase)
const { data: deletedCount, error: rpcError } = await rpcClient.rpc('replace_sie_import', {
p_company_id: companyId,
p_import_id: importId,
})
@@ -231,11 +256,17 @@ export async function replaceSIEImport(
* Pre-flight checks mirror replaceSIEImport so the user gets a Swedish
* error message before the RPC raises. The RPC itself is idempotent on
* status — calling twice surfaces the "not in completed status" error.
*
* `userId` is the authorising user. It is passed to the RPC as p_user_id
* because the RPC may run on the service client (see rpcClientForBulkDelete),
* where auth.uid() is NULL — without it the RPC's owner/admin gate can never
* match and always raises. The RPC enforces owner/admin against this id.
*/
export async function undoSIEImport(
supabase: SupabaseClient,
companyId: string,
importId: string
importId: string,
userId: string
): Promise<{ success: boolean; deletedEntries: number; error?: string }> {
const { data: importRecord } = await supabase
.from('sie_imports')
@@ -265,9 +296,14 @@ export async function undoSIEImport(
}
}
const { data: deletedCount, error: rpcError } = await supabase.rpc('undo_sie_import', {
// Runs on the service client — see rpcClientForBulkDelete. Pass the
// authorising user explicitly: on the service client auth.uid() is NULL,
// so the RPC's owner/admin gate resolves against p_user_id instead.
const rpcClient = await rpcClientForBulkDelete(supabase)
const { data: deletedCount, error: rpcError } = await rpcClient.rpc('undo_sie_import', {
p_company_id: companyId,
p_import_id: importId,
p_user_id: userId,
})
if (rpcError) {
+3 -2
View File
@@ -2550,6 +2550,7 @@ async function commitImportSie(
async function commitUndoSieImport(
supabase: SupabaseClient,
userId: string,
companyId: string,
params: Record<string, unknown>,
): Promise<ExecutorResult> {
@@ -2559,7 +2560,7 @@ async function commitUndoSieImport(
return { error: 'import_id is required', status: 400 }
}
const result = await undoSIEImport(supabase, companyId, importId)
const result = await undoSIEImport(supabase, companyId, importId, userId)
if (!result.success) {
return { error: result.error ?? 'SIE undo failed', status: 400 }
}
@@ -3459,7 +3460,7 @@ async function commitPendingOperationInner(
result = await commitImportSie(supabase, userId, companyId, pendingOp.params)
break
case 'undo_sie_import':
result = await commitUndoSieImport(supabase, companyId, pendingOp.params)
result = await commitUndoSieImport(supabase, userId, companyId, pendingOp.params)
break
case 'create_voucher':
result = await commitCreateVoucher(supabase, userId, companyId, pendingOp.params, opts)
@@ -0,0 +1,63 @@
import { describe, it, expect } from 'vitest'
import { randomUUID } from 'node:crypto'
import { getPool } from '@/tests/pg/setup'
import { seedCompany } from '@/tests/pg/fixtures'
// Regression guard for a destructive bug: resolveConsent()'s optimistic
// concurrency guard ran `UPDATE provider_consent_tokens … .select('id')`, but
// this table's PRIMARY KEY is `consent_id` and it has NO `id` column. Postgres
// rejected the whole statement ("column provider_consent_tokens.id does not
// exist"), which surfaced as updateError AFTER the provider had already rotated
// the refresh token — permanently breaking the consent.
//
// Unit mocks can't catch this (they replay queued data regardless of the
// selected columns), so we assert the real query shapes against real Postgres.
async function seedConsentWithToken(): Promise<{ consentId: string; expiresAt: string }> {
const { companyId } = await seedCompany()
const consentId = randomUUID()
const expiresAt = '2020-01-01T00:00:00.000Z'
await getPool().query(
`INSERT INTO provider_consents (id, company_id, name, status, provider)
VALUES ($1, $2, $3, 1, 'fortnox')`,
[consentId, companyId, `pg-real-${consentId}`],
)
await getPool().query(
`INSERT INTO provider_consent_tokens
(consent_id, provider, access_token, refresh_token, token_expires_at)
VALUES ($1, 'fortnox', 'old-access', 'old-refresh', $2)`,
[consentId, expiresAt],
)
return { consentId, expiresAt }
}
describe('provider_consent_tokens guarded update (pg-real)', () => {
it('the rotation UPDATE … RETURNING consent_id is valid and matches the row', async () => {
const { consentId, expiresAt } = await seedConsentWithToken()
// This mirrors resolveConsent()'s guarded update exactly. `consent_id` is
// the PK; selecting it must succeed and return the matched row.
const { rows } = await getPool().query(
`UPDATE provider_consent_tokens
SET access_token = $1, refresh_token = $2, token_expires_at = $3
WHERE consent_id = $4 AND token_expires_at = $5
RETURNING consent_id`,
['new-access', 'new-refresh', '2030-01-01T00:00:00.000Z', consentId, expiresAt],
)
expect(rows).toHaveLength(1)
expect(rows[0].consent_id).toBe(consentId)
})
it('there is no `id` column to select (proves why the old query broke)', async () => {
const { consentId } = await seedConsentWithToken()
await expect(
getPool().query(
`SELECT id FROM provider_consent_tokens WHERE consent_id = $1`,
[consentId],
),
).rejects.toThrow(/column .*id.* does not exist/i)
})
})
@@ -9,9 +9,15 @@ vi.mock('@/lib/providers/briox/oauth', () => ({
refreshBrioxToken: vi.fn(),
}));
vi.mock('@/lib/providers/fortnox/oauth', () => ({
refreshFortnoxToken: vi.fn(),
}));
import { createServiceClient } from '@/lib/supabase/server';
import { refreshBrioxToken } from '@/lib/providers/briox/oauth';
import { refreshFortnoxToken } from '@/lib/providers/fortnox/oauth';
import { resolveConsent } from '../resolve-consent';
import { ProviderCallError } from '../with-provider-call';
const consentRow = { id: 'c1', company_id: 'co1', provider: 'briox', status: 1 };
@@ -52,7 +58,7 @@ describe('resolveConsent — Briox token refresh concurrency', () => {
it('persists the rotated pair when the guarded update wins the race', async () => {
mock.enqueue({ data: [consentRow] }); // consent lookup
mock.enqueue({ data: [expiredTokens] }); // expired token row
mock.enqueue({ data: [{ id: 't1' }] }); // guarded update matched 1 row
mock.enqueue({ data: [{ consent_id: 'c1' }] }); // guarded update matched 1 row (PK is consent_id, not id)
const result = await resolveConsent('co1', 'c1');
@@ -98,4 +104,63 @@ describe('resolveConsent — Briox token refresh concurrency', () => {
message: expect.stringContaining('re-enter the credentials'),
});
});
it('rethrows a dead refresh token as PROVIDER_AUTH_EXPIRED so callers prompt reconnect', async () => {
mock.enqueue({ data: [consentRow] }); // consent lookup
mock.enqueue({ data: [expiredTokens] }); // expired token row
// Mirrors Fortnox's `400 invalid_grant`: the raw helper throws a plain
// Error whose status lives only in the message string. resolveConsent must
// still classify it as an expired connection, not let it fall through to a
// generic 500 at the route.
vi.mocked(refreshBrioxToken).mockRejectedValueOnce(
new Error('Briox token refresh failed: 400 {"error":"invalid_grant"}'),
);
const err = await resolveConsent('co1', 'c1').catch((e) => e);
expect(err).toBeInstanceOf(ProviderCallError);
expect(err.code).toBe('PROVIDER_AUTH_EXPIRED');
expect(err.provider).toBe('briox');
});
it('maps Fortnox error_missing_license to PROVIDER_LICENSE_MISSING (not a revivable reconnect)', async () => {
const fortnoxConsent = { id: 'c2', company_id: 'co1', provider: 'fortnox', status: 1 };
mock.enqueue({ data: [fortnoxConsent] }); // consent lookup
mock.enqueue({ data: [expiredTokens] }); // expired token row
// Fortnox answers the token endpoint with error_missing_license when the
// customer's integration license has lapsed. Re-auth can't revive it — the
// license must be re-ordered first — so it gets its own code rather than the
// generic "reconnect" PROVIDER_AUTH_EXPIRED.
vi.mocked(refreshFortnoxToken).mockRejectedValueOnce(
new Error(
'Fortnox token refresh failed: 401 {"error":"error_missing_license","error_description":"The client credentials are invalid"}',
),
);
const err = await resolveConsent('co1', 'c2').catch((e) => e);
expect(err).toBeInstanceOf(ProviderCallError);
expect(err.code).toBe('PROVIDER_LICENSE_MISSING');
expect(err.provider).toBe('fortnox');
});
it('keeps a Fortnox invalid_grant as PROVIDER_AUTH_EXPIRED (revivable by reconnect)', async () => {
const fortnoxConsent = { id: 'c2', company_id: 'co1', provider: 'fortnox', status: 1 };
mock.enqueue({ data: [fortnoxConsent] }); // consent lookup
mock.enqueue({ data: [expiredTokens] }); // expired token row
// A plain expired/revoked grant IS revivable by reconnecting — it must not
// be mis-mapped to the license code.
vi.mocked(refreshFortnoxToken).mockRejectedValueOnce(
new Error('Fortnox token refresh failed: 400 {"error":"invalid_grant"}'),
);
const err = await resolveConsent('co1', 'c2').catch((e) => e);
expect(err).toBeInstanceOf(ProviderCallError);
expect(err.code).toBe('PROVIDER_AUTH_EXPIRED');
expect(err.provider).toBe('fortnox');
});
});
+49 -10
View File
@@ -5,6 +5,7 @@ import { refreshFortnoxToken } from './fortnox/oauth';
import { refreshVismaToken } from './visma/oauth';
import { refreshBrioxToken } from './briox/oauth';
import { refreshBjornLundenToken } from './bjornlunden/oauth';
import { ProviderCallError, isMissingLicenseError } from './with-provider-call';
import { createLogger } from '@/lib/logger';
const log = createLogger('providers/resolve-consent');
@@ -98,15 +99,48 @@ export async function resolveConsent(companyId: string, consentId: string): Prom
let refreshed: TokenResponse;
if (consent.provider === 'fortnox') {
refreshed = await refreshFortnoxToken(getOAuthConfig('fortnox'), tokens.refresh_token as string);
} else if (consent.provider === 'briox') {
// Briox /tokenrefresh wants the (expired) access token alongside the
// refresh token; no app-level config involved. Both tokens rotate —
// the new refresh_token is persisted below.
refreshed = await refreshBrioxToken(tokens.refresh_token as string, tokens.access_token as string);
} else {
refreshed = await refreshVismaToken(getOAuthConfig(consent.provider as string), tokens.refresh_token as string);
// A failed refresh is categorically an expired/revoked connection: the
// providers rotate refresh tokens and a dead one (e.g. Fortnox `400
// invalid_grant`) can never be replayed — retrying is pointless. Surface it
// as PROVIDER_AUTH_EXPIRED so callers (preview/sie-data/migrate) report
// "reconnect" (401) instead of a generic 500 that invites a useless retry.
// The raw helpers throw plain Errors with the status only in the message
// string, so classifyProviderError can't see it downstream — we map here,
// at the boundary that knows this is a refresh.
try {
if (consent.provider === 'fortnox') {
refreshed = await refreshFortnoxToken(getOAuthConfig('fortnox'), tokens.refresh_token as string);
} else if (consent.provider === 'briox') {
// Briox /tokenrefresh wants the (expired) access token alongside the
// refresh token; no app-level config involved. Both tokens rotate —
// the new refresh_token is persisted below.
refreshed = await refreshBrioxToken(tokens.refresh_token as string, tokens.access_token as string);
} else {
refreshed = await refreshVismaToken(getOAuthConfig(consent.provider as string), tokens.refresh_token as string);
}
} catch (err) {
const reason = err instanceof Error ? err.message : String(err);
// A missing/inactive integration license (Fortnox `error_missing_license`)
// is NOT a revivable token: re-authorizing loops until the customer
// re-orders the license. Surface it as its own code so the caller shows
// "activate the license, then reconnect" instead of a bare reconnect.
const code = isMissingLicenseError(reason)
? 'PROVIDER_LICENSE_MISSING'
: 'PROVIDER_AUTH_EXPIRED';
log.error(
`Failed to refresh ${consent.provider} token for consent ${consentId} — ` +
(code === 'PROVIDER_LICENSE_MISSING'
? 'the integration license is missing/inactive'
: 'the connection must be re-authorized'),
{ reason },
);
throw new ProviderCallError(
code,
consent.provider as string,
code === 'PROVIDER_LICENSE_MISSING'
? `${consent.provider} integration license missing/inactive; the customer must re-order it before reconnecting`
: `Token refresh failed for ${consent.provider}; the connection must be re-authorized`,
);
}
const newExpiresAt = new Date(Date.now() + refreshed.expires_in * 1000).toISOString();
@@ -126,7 +160,12 @@ export async function resolveConsent(companyId: string, consentId: string): Prom
})
.eq('consent_id', consentId)
.eq('token_expires_at', tokens.token_expires_at as string)
.select('id');
// consent_id is the table's PRIMARY KEY — there is no `id` column.
// Selecting `id` here makes Postgres reject the whole statement
// ("column provider_consent_tokens.id does not exist"), which surfaces as
// updateError and is misreported as "rotated tokens could not be saved"
// AFTER the provider already rotated — permanently breaking the consent.
.select('consent_id');
if (updateError) {
// The provider has ALREADY rotated the tokens but we failed to persist
+26
View File
@@ -13,6 +13,7 @@ import { createLogger, type Logger } from '@/lib/logger'
export type ProviderCallErrorCode =
| 'PROVIDER_AUTH_EXPIRED'
| 'PROVIDER_LICENSE_MISSING'
| 'PROVIDER_RATE_LIMITED'
| 'PROVIDER_UNREACHABLE'
| 'PROVIDER_UPSTREAM_ERROR'
@@ -206,3 +207,28 @@ export function classifyProviderError(error: unknown): ProviderCallErrorCode | n
return null
}
/**
* True when a provider token/OAuth failure means the integration license is
* missing or inactive — NOT an ordinary expired/revoked grant.
*
* Fortnox answers its token endpoint with `error_missing_license` when the
* customer's Fortnox account no longer carries the integration license. The
* stored refresh token cannot be revived by re-authorizing: re-auth loops until
* the customer re-orders the "Fortnox Integration" add-on. Distinguishing this
* from a plain dead token lets callers say "activate the license, then
* reconnect" instead of a bare "reconnect" that just fails again.
*
* Matches on the raw provider message string because the underlying refresh
* helpers bake the body into the Error message; deliberately does NOT match
* `invalid_grant` (that IS a revivable reconnect → PROVIDER_AUTH_EXPIRED).
*/
export function isMissingLicenseError(message: string): boolean {
const haystack = message.toLowerCase()
return (
haystack.includes('error_missing_license') ||
haystack.includes('missing_license') ||
haystack.includes('missing license') ||
haystack.includes('not have enough licenses')
)
}
@@ -6,6 +6,7 @@ vi.mock('../trial-balance', () => ({
import { generateIncomeStatement } from '../income-statement'
import { generateTrialBalance } from '../trial-balance'
import { roundOre } from '@/lib/money'
import type { TrialBalanceRow } from '@/types'
const mockTrialBalance = vi.mocked(generateTrialBalance)
@@ -289,4 +290,71 @@ describe('generateIncomeStatement', () => {
expect(report.financial_sections).toEqual([])
expect(report.total_revenue).toBe(40000)
})
it('includes energikostnader (group 53, e.g. 5310) in expenses and net_result — regression', async () => {
// Regression: group '53' was missing from the expense label map, so 53xx
// accounts (energy costs like 5310 El för drift) were silently dropped from
// total_expenses and net_result. The Resultatrapport (which sums all class
// 3–8 rows directly) stayed correct, which is how the discrepancy surfaced.
mockTrialBalance.mockResolvedValue({
rows: [
makeRow({ account_number: '3001', account_name: 'Revenue', account_class: 3, closing_credit: 100000, closing_debit: 0 }),
makeRow({ account_number: '5310', account_name: 'El för drift', account_class: 5, closing_debit: 18000, closing_credit: 0 }),
],
totalDebit: 18000,
totalCredit: 100000,
isBalanced: false,
})
const report = await generateIncomeStatement(supabase, 'company-1', 'period-1')
expect(report.total_expenses).toBe(18000) // was 0 before the fix
expect(report.net_result).toBe(82000) // was 100000 before the fix
const expenseAccounts = report.expense_sections.flatMap((s) => s.rows.map((r) => r.account_number))
expect(expenseAccounts).toContain('5310')
})
it('routes accounts from every unmapped group (48, 53, 67) into a catch-all, never dropping them', async () => {
mockTrialBalance.mockResolvedValue({
rows: [
makeRow({ account_number: '3001', account_name: 'Revenue', account_class: 3, closing_credit: 100000, closing_debit: 0 }),
makeRow({ account_number: '4810', account_name: 'Energi råvara', account_class: 4, closing_debit: 1000, closing_credit: 0 }),
makeRow({ account_number: '5310', account_name: 'El för drift', account_class: 5, closing_debit: 2000, closing_credit: 0 }),
makeRow({ account_number: '6710', account_name: 'Lämnade bidrag', account_class: 6, closing_debit: 3000, closing_credit: 0 }),
],
totalDebit: 6000,
totalCredit: 100000,
isBalanced: false,
})
const report = await generateIncomeStatement(supabase, 'company-1', 'period-1')
// All three expense accounts must be counted, regardless of label coverage.
expect(report.total_expenses).toBe(6000)
expect(report.net_result).toBe(94000)
const expenseAccounts = report.expense_sections.flatMap((s) => s.rows.map((r) => r.account_number))
expect(expenseAccounts).toEqual(expect.arrayContaining(['4810', '5310', '6710']))
})
it('total_expenses equals the signed sum of every class 4–7 row (no silent drops)', async () => {
// Structural invariant guarding the whole class of "missing group label"
// bug: the sum of expense-section subtotals must equal Σ(debit - credit)
// over all class 4–7 rows, mixing mapped (50, 70) and unmapped (48, 53, 67)
// groups.
const rows = [
makeRow({ account_number: '5010', account_name: 'Lokalhyra', account_class: 5, closing_debit: 8000, closing_credit: 0 }),
makeRow({ account_number: '5310', account_name: 'El för drift', account_class: 5, closing_debit: 2500, closing_credit: 0 }),
makeRow({ account_number: '4810', account_name: 'Energi', account_class: 4, closing_debit: 1500, closing_credit: 0 }),
makeRow({ account_number: '6710', account_name: 'Bidrag', account_class: 6, closing_debit: 500, closing_credit: 0 }),
makeRow({ account_number: '7010', account_name: 'Löner', account_class: 7, closing_debit: 40000, closing_credit: 0 }),
]
mockTrialBalance.mockResolvedValue({ rows, totalDebit: 52500, totalCredit: 0, isBalanced: false })
const report = await generateIncomeStatement(supabase, 'company-1', 'period-1')
const expectedTotal = rows.reduce((sum, r) => sum + (r.closing_debit - r.closing_credit), 0)
const sectionSum = report.expense_sections.reduce((sum, s) => sum + s.subtotal, 0)
expect(report.total_expenses).toBe(expectedTotal) // 52500
expect(roundOre(sectionSum)).toBe(expectedTotal)
})
})
+43 -24
View File
@@ -47,7 +47,8 @@ export async function generateIncomeStatement(
'38': 'Aktiverat arbete',
'39': 'Övriga rörelseintäkter',
},
'credit' // Revenue has credit normal balance
'credit', // Revenue has credit normal balance
'Övriga intäkter',
)
// Expense sections (class 4-7)
@@ -62,10 +63,12 @@ export async function generateIncomeStatement(
'45': 'Inköp utlandet',
'46': 'Underentreprenader och legoarbeten',
'47': 'Erhållna rabatter',
'48': 'Andra produktionskostnader',
'49': 'Lagerförändringar',
'50': 'Lokalkostnader',
'51': 'Fastighetskostnader',
'52': 'Hyra av tillgångar',
'53': 'Energikostnader',
'54': 'Förbrukningsinventarier',
'55': 'Reparation och underhåll',
'56': 'Transportkostnader',
@@ -78,6 +81,7 @@ export async function generateIncomeStatement(
'63': 'Försäkringar och riskkostnader',
'64': 'Förvaltningskostnader',
'65': 'Övriga externa tjänster',
'67': 'Särskilt för ideella föreningar och stiftelser',
'68': 'Inhyrd personal',
'69': 'Övriga kostnader',
'70': 'Löner kollektivanställda',
@@ -90,7 +94,8 @@ export async function generateIncomeStatement(
'78': 'Avskrivningar',
'79': 'Övriga rörelsekostnader',
},
'debit' // Expenses have debit normal balance
'debit', // Expenses have debit normal balance
'Övriga kostnader',
)
// Financial sections (class 8) — exclude 8999 "Årets resultat".
@@ -112,7 +117,8 @@ export async function generateIncomeStatement(
'88': 'Bokslutsdispositioner',
'89': 'Skatter och årets resultat',
},
'mixed'
'mixed',
'Övriga finansiella poster',
)
const totalRevenue = revenueSections.reduce((sum, s) => sum + s.subtotal, 0)
@@ -132,31 +138,29 @@ export async function generateIncomeStatement(
}
/**
* Build report sections from trial balance rows
* Build report sections from trial balance rows.
*
* Every row is assigned to exactly one section: either a known 2-digit group
* (from `groupLabels`) or the `fallbackTitle` catch-all for any group not in
* the map. The catch-all is what keeps the report complete — without it, an
* account whose group code is missing from `groupLabels` (e.g. 53xx
* energikostnader, 48xx, 67xx) would be silently dropped from both the
* breakdown and the computed subtotal/total/net_result.
*/
function buildSections(
rows: TrialBalanceRow[],
groupLabels: Record<string, string>,
normalBalance: 'debit' | 'credit' | 'mixed'
normalBalance: 'debit' | 'credit' | 'mixed',
fallbackTitle: string
): IncomeStatementSection[] {
const sections: IncomeStatementSection[] = []
for (const [groupCode, title] of Object.entries(groupLabels)) {
const groupRows = rows.filter((r) => r.account_number.startsWith(groupCode))
if (groupRows.length === 0) continue
const makeSection = (title: string, groupRows: TrialBalanceRow[]): IncomeStatementSection => {
const sectionRows = groupRows.map((r) => {
let amount: number
if (normalBalance === 'credit') {
// Revenue: credit - debit (positive = revenue)
amount = r.closing_credit - r.closing_debit
} else if (normalBalance === 'debit') {
// Expense: debit - credit (positive = expense)
amount = r.closing_debit - r.closing_credit
} else {
// Mixed: net balance (financial items)
amount = r.closing_credit - r.closing_debit
}
// Expenses (debit) use debit - credit; revenue (credit) and financial
// (mixed) use credit - debit.
const amount =
normalBalance === 'debit'
? r.closing_debit - r.closing_credit
: r.closing_credit - r.closing_debit
return {
account_number: r.account_number,
@@ -167,12 +171,27 @@ function buildSections(
const subtotal = sectionRows.reduce((sum, r) => sum + r.amount, 0)
sections.push({
return {
title,
rows: sectionRows.filter((r) => Math.abs(r.amount) > 0.005),
subtotal: Math.round(subtotal * 100) / 100,
})
}
}
const sections: IncomeStatementSection[] = []
const matched = new Set<string>()
for (const [groupCode, title] of Object.entries(groupLabels)) {
const groupRows = rows.filter((r) => r.account_number.startsWith(groupCode))
if (groupRows.length === 0) continue
for (const r of groupRows) matched.add(r.account_number)
sections.push(makeSection(title, groupRows))
}
// Catch-all: any row whose 2-digit group is not in groupLabels. Guarantees no
// account is ever excluded from the subtotal/total/net_result.
const orphans = rows.filter((r) => !matched.has(r.account_number))
if (orphans.length > 0) sections.push(makeSection(fallbackTitle, orphans))
return sections
}