db8983ba9e
* feat(arcim-migration): Briox provider with SIE-over-API import - Briox auth via account ID + application token (no app-level credentials); both tokens rotate on refresh and are persisted - New sie-fetcher pulls the general ledger as SIE through the provider API for Fortnox, Briox and Bjorn Lunden - Wizard stops on a failed SIE import and surfaces the real errors instead of proceeding to the misleading migrate-guard message - PROVIDER_SIE_ONLY_FORTNOX renamed to PROVIDER_SIE_NOT_SUPPORTED; new PROVIDER_TOKEN_INVALID for rejected provider credentials Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bookkeeping): per-line accruals (periodisering) on invoices and supplier invoices Defer revenue/costs per invoice line to 29xx/17xx interim accounts with automatic monthly dissolution (nightly cron + catch-up at registration), schedule cancellation on credit, year-end auto-detect exclusion for already-scheduled invoices, invoice-inbox service-period extraction for prefill, and an MCP tool to list schedules. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(bokslut): iXBRL arsredovisning generation and Bolagsverket digital filing Generate the annual report as iXBRL from a generated taxonomy registry (K2 element lists, taxonomy:generate/check scripts + CI guard), expose it via the fiscal-period API, and add the bolagsverket extension for digital submission to eget utrymme with webhook-driven status tracking (submissions table + pg tests, lifecycle events, year-end wizard UI). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(mcp): raise origin-guard test timeout to 20s The dynamic import pulls in the full server module; the parse alone flirts with the 5s default under full-suite parallel load. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Add new scripts and documentation for K2 AB taxonomy generation and validation - Introduced `generate-taxonomy-registry.ts` to automate the generation of the iXBRL taxonomy concept registry from official element lists and tuple models. - Added `validate-ixbrl.mjs` for validating generated iXBRL reports against the official taxonomy package using Arelle. - Included new documentation files: - `k2-ab-arsredovisning-elementlista-2024-09-12_rev20250312_sv.xlsx` - `tuple-innehallsmodell-arsredovisning-k2-2024-09-12.xlsx` - `taxonomi-paket-2024-09-12_rev20250312.zip` * Add tests for bookkeeping accruals dissolution and supplier invoices - Implement tests for the POST /api/bookkeeping/accruals/[id]/dissolve route, covering success and error scenarios. - Add tests for the DELETE /api/supplier-invoices/[id] route, including authentication checks and validation of invoice deletion conditions. - Introduce tests for the Arcim migration provider client, ensuring token handling and error classification. - Create tests for the Bolagsverket extension, validating submission role enforcement and environment settings. - Add Zod schemas for Bolagsverket response payloads to ensure proper validation. - Implement tests for MCP server's list accrual schedules, confirming registration and scope mapping. - Add consistency tests for IXBRL document generation, ensuring duplicate facts and XML escaping are handled correctly. - Introduce typed domain errors for accrual schedules to improve error handling in the service. - Add tests for resolving consent with Briox token refresh concurrency, ensuring proper token management and error handling. * fix(tests): update payload size guard comments to reflect recent changes in tool descriptions and ceiling adjustments * fix(gitattributes): mark generated JSON files in bokslut taxonomy as linguist-generated * feat(migrations): add backfill for invoices.journal_entry_id and fallback for next_voucher_number user_id * feat(bokslut): enhance compliance and financial processing features with new submission details and security measures --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
159 lines
6.0 KiB
TypeScript
159 lines
6.0 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
import { createQueuedMockSupabase } from '@/tests/helpers'
|
|
|
|
const { mockBlGet } = vi.hoisted(() => ({ mockBlGet: vi.fn() }))
|
|
|
|
vi.mock('@/lib/supabase/server', () => ({
|
|
createServiceClient: vi.fn(),
|
|
createClient: vi.fn(),
|
|
}))
|
|
|
|
vi.mock('@/lib/providers/bjornlunden/oauth', () => ({
|
|
refreshBjornLundenToken: vi.fn().mockResolvedValue({
|
|
access_token: 'bl-app-token',
|
|
token_type: 'Bearer',
|
|
expires_in: 3600,
|
|
}),
|
|
}))
|
|
|
|
// Keep the real BjornLundenApiError (instanceof checks in provider-client)
|
|
// but replace the client so the /details probe is controllable per test.
|
|
vi.mock('@/lib/providers/bjornlunden/client', async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import('@/lib/providers/bjornlunden/client')>()
|
|
return {
|
|
...actual,
|
|
// Must be a `function` (not an arrow) so `new BjornLundenClient()` works.
|
|
BjornLundenClient: vi.fn().mockImplementation(function mockClient() {
|
|
return { get: mockBlGet }
|
|
}),
|
|
}
|
|
})
|
|
|
|
import { createServiceClient } from '@/lib/supabase/server'
|
|
import { BjornLundenApiError } from '@/lib/providers/bjornlunden/client'
|
|
import {
|
|
submitProviderToken,
|
|
ProviderTokenInvalidError,
|
|
ConsentNotFoundError,
|
|
} from '../provider-client'
|
|
|
|
describe('submitProviderToken', () => {
|
|
let mock: ReturnType<typeof createQueuedMockSupabase>
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
mock = createQueuedMockSupabase()
|
|
vi.mocked(createServiceClient).mockReturnValue(mock.supabase as never)
|
|
})
|
|
|
|
const tablesTouched = () => vi.mocked(mock.supabase.from).mock.calls.map((c) => c[0])
|
|
|
|
// ── Consent ownership (IDOR guard) ────────────────────────────────
|
|
|
|
it('throws ConsentNotFoundError and writes NOTHING when the consent belongs to another company', async () => {
|
|
// Ownership check finds no row for (consentId, ownerCompanyId) — the same
|
|
// result whether the consent does not exist or belongs to another tenant.
|
|
mock.enqueue({ data: [] })
|
|
|
|
await expect(
|
|
submitProviderToken('consent-other-tenant', 'bokio', 'tok', 'bokio-guid', 'company-A'),
|
|
).rejects.toBeInstanceOf(ConsentNotFoundError)
|
|
|
|
// Only the ownership read happened — no token upsert, no consent update.
|
|
expect(tablesTouched()).toEqual(['provider_consents'])
|
|
})
|
|
|
|
it('stores tokens when the consent belongs to the caller company', async () => {
|
|
mock.enqueue({ data: [{ id: 'consent-1' }] }) // ownership check
|
|
mock.enqueue({ data: null }) // token upsert
|
|
|
|
const result = await submitProviderToken('consent-1', 'bokio', 'tok', 'bokio-guid', 'company-A')
|
|
|
|
expect(result).toEqual({ success: true, consentId: 'consent-1' })
|
|
expect(tablesTouched()).toEqual(['provider_consents', 'provider_consent_tokens'])
|
|
})
|
|
|
|
// ── BL /details probe error classification ────────────────────────
|
|
|
|
it('does NOT map a 429 from the BL probe to ProviderTokenInvalidError', async () => {
|
|
mock.enqueue({ data: [{ id: 'consent-1' }] }) // ownership check
|
|
mockBlGet.mockRejectedValueOnce(new BjornLundenApiError('Björn Lunden API error: 429', 429))
|
|
|
|
const err: unknown = await submitProviderToken(
|
|
'consent-1',
|
|
'bjornlunden',
|
|
'client_credentials',
|
|
'user-key-guid',
|
|
'company-A',
|
|
).catch((e: unknown) => e)
|
|
|
|
expect(err).toBeInstanceOf(BjornLundenApiError)
|
|
expect(err).not.toBeInstanceOf(ProviderTokenInvalidError)
|
|
// The transient failure must not store the unverified key either.
|
|
expect(tablesTouched()).not.toContain('provider_consent_tokens')
|
|
})
|
|
|
|
it('does NOT map gateway-style 5xx (503) from the BL probe to ProviderTokenInvalidError', async () => {
|
|
mock.enqueue({ data: [{ id: 'consent-1' }] })
|
|
mockBlGet.mockRejectedValueOnce(new BjornLundenApiError('Björn Lunden API error: 503', 503))
|
|
|
|
const err: unknown = await submitProviderToken(
|
|
'consent-1',
|
|
'bjornlunden',
|
|
'client_credentials',
|
|
'user-key-guid',
|
|
'company-A',
|
|
).catch((e: unknown) => e)
|
|
|
|
expect(err).toBeInstanceOf(BjornLundenApiError)
|
|
expect(err).not.toBeInstanceOf(ProviderTokenInvalidError)
|
|
})
|
|
|
|
it('maps 500 from the BL probe to invalid credentials (sandbox-verified bad-key signal) and disables probe retries', async () => {
|
|
mock.enqueue({ data: [{ id: 'consent-1' }] })
|
|
mockBlGet.mockRejectedValueOnce(new BjornLundenApiError('Björn Lunden API error: 500', 500))
|
|
|
|
await expect(
|
|
submitProviderToken('consent-1', 'bjornlunden', 'client_credentials', 'user-key-guid', 'company-A'),
|
|
).rejects.toBeInstanceOf(ProviderTokenInvalidError)
|
|
|
|
// The probe must fail fast: a typo'd key answers 500, which the client's
|
|
// retry policy treats as retryable — retry is disabled per call.
|
|
expect(mockBlGet).toHaveBeenCalledTimes(1)
|
|
expect(mockBlGet).toHaveBeenCalledWith('bl-app-token', 'user-key-guid', '/details', {
|
|
retry: false,
|
|
})
|
|
})
|
|
|
|
it('maps 404 from the BL probe to invalid credentials', async () => {
|
|
mock.enqueue({ data: [{ id: 'consent-1' }] })
|
|
mockBlGet.mockRejectedValueOnce(new BjornLundenApiError('Björn Lunden API error: 404', 404))
|
|
|
|
await expect(
|
|
submitProviderToken('consent-1', 'bjornlunden', 'client_credentials', 'user-key-guid', 'company-A'),
|
|
).rejects.toBeInstanceOf(ProviderTokenInvalidError)
|
|
})
|
|
|
|
it('stores BL tokens (and labels the consent) when the probe succeeds', async () => {
|
|
mock.enqueue({ data: [{ id: 'consent-1' }] }) // ownership check
|
|
mock.enqueue({ data: null }) // consent company_name update
|
|
mock.enqueue({ data: null }) // token upsert
|
|
mockBlGet.mockResolvedValueOnce({ name: 'Testbolaget AB' })
|
|
|
|
const result = await submitProviderToken(
|
|
'consent-1',
|
|
'bjornlunden',
|
|
'client_credentials',
|
|
'user-key-guid',
|
|
'company-A',
|
|
)
|
|
|
|
expect(result).toEqual({ success: true, consentId: 'consent-1' })
|
|
expect(tablesTouched()).toEqual([
|
|
'provider_consents',
|
|
'provider_consents',
|
|
'provider_consent_tokens',
|
|
])
|
|
})
|
|
})
|