Files
accounted/extensions/general/arcim-migration/lib/__tests__/arcim-client.test.ts
T
Jakob WennbergandClaude Opus 4.6 cdb40e7af3 feat: resilience fallbacks, Arcim retry logic, and client tests (#52)
* fix: include reversed entries in all reports (general ledger, trial balance, VAT, SIE, NE, INK2)

Reversed entries (storno) must appear alongside their original posted entries
in reports for a complete audit trail. Previously, filtering by status='posted'
excluded them, causing discrepancies when corrections had been made.

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

* feat: semi-manual invoice payment booking with editable journal lines

When marking an invoice as paid, users now see a dialog where they can:
- Choose which bank/cash account the payment goes to (1910, 1920, 1930, etc.)
- Review and edit the proposed journal entry lines before committing
- The happy path remains fast — lines are pre-filled correctly

Implementation:
- Pure proposePaymentLines() function for line computation (accrual + cash)
- PaymentBookingDialog with AccountCombobox, balance validation, date picker
- API accepts optional custom lines, falls back to auto-generation without them
- 18 tests (8 unit + 10 API) all passing

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

* fix: address Greptile review — validation fallback, balance check, error handling

- P1: Return 400 on invalid body instead of silently falling back to
  auto-generated lines (split JSON parse from schema validation)
- P1: Add server-side balance check for custom lines before committing
  (debit must equal credit, totalDebit > 0)
- P2: Wrap PaymentBookingDialog init() in try/catch with toast on
  failure and auto-close instead of silent empty state
- Add 2 new tests: unbalanced lines → 400, invalid schema → 400

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

* fix: OAuth callback redirect for local dev and timeout resilience

- Pass redirectUri dynamically from NEXT_PUBLIC_APP_URL so OAuth
  callbacks work on localhost (not just production)
- Encode consentId/provider in OAuth state (base64url JSON) so the
  callback doesn't depend on session storage
- Add skipAuth flag to extension API routes for OAuth callbacks
  (external provider redirects have no user session cookie)
- Wrap AbortError in descriptive timeout messages in arcim-client
- Make preview endpoint resilient to partial failures (company info
  and SIE fetch are individually non-blocking)
- Simplify login page (remove unused magic link auth mode)

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

* fix: create journal entry before marking invoice as paid

Move journal entry creation before the invoice status update so that
if accounting fails, the invoice is not permanently marked paid without
a corresponding entry. Previously the error was silently swallowed.

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

* fix: update mark-paid tests for journal-first ordering

Reorder mock queue to match new flow (settings before update), update
failure test to expect 500 instead of silent success, add try-catch
with proper error response in route handler.

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

* feat: add reverse charge VAT (ruta 20-32) and improve mobile UX across dashboard

Add full reverse charge (omvänd skattskyldighet) support to the VAT declaration:
- Map accounts 2614/2624/2634 to ruta 30/31/32 for self-assessed output VAT
- Calculate purchase bases (ruta 20-24) from supplier invoices by supplier type
- Include ruta 30-32 in ruta 49 formula and totalOutputVat summary
- Display reverse charge section in reports UI and composition chart
- Add comprehensive test coverage for all reverse charge scenarios

Improve mobile UX across the app:
- Convert nav drawer to bottom sheet with drag handle and safe area padding
- Add mobile card layout for PaymentBookingDialog journal lines
- Replace settings tab pills with dropdown selector on mobile
- Make wizard step indicators responsive (collapsed on mobile)
- Ensure all dialog footers stack buttons full-width on mobile
- Add 44px minimum touch targets throughout
- Make onboarding buttons full-width on mobile

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

* fix: address Greptile review — indentation, query efficiency, tab dedup

- Fix misleading try-block indentation in mark-paid route
- Filter reversed entries at DB level (.eq('status', 'posted')) instead
  of fetching then discarding in memory
- Extract shared settingsTabs array so mobile Select and desktop
  TabsList stay in sync automatically

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

* feat: add resilience fallbacks, Arcim retry logic, and client tests

Add FallbackPrompt component and integrate it across banking and migration
error states so users always have a manual import escape hatch. Add retry
with exponential backoff to Arcim API client for transient failures (429,
502, 503, 504) and timeouts. Expand import page deep-linking with ?mode=
parameter. Add persistent error banner on settings page for bank connection
failures. Include 18 new tests for the Arcim client covering retry, backoff,
pagination, timeout, env validation, and singleton resource unwrapping.

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

* fix: address Greptile review — setActiveTab, test cleanup, redundant clearTimeout

- Add missing setActiveTab('banking') when handling bank_error query
  param so the error banner is actually visible (P1)
- Guard env-var cleanup with try/finally in arcim-client tests to
  prevent state leakage on assertion failure (P2)
- Only mock retry-range setTimeout delays in backoff test, letting
  AbortController timers pass through real setTimeout (P2)
- Remove redundant clearTimeout in catch block — finally handles it (P2)

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 14:15:08 +01:00

358 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
vi.stubEnv('ARCIM_SYNC_GATEWAY_URL', 'https://arcim.test.com')
vi.stubEnv('ARCIM_SYNC_API_KEY', 'test-api-key')
import { getConsent, createConsent, fetchCompanyInfo, fetchCustomers } from '../arcim-client'
describe('arcim-client', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>
let warnSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
vi.clearAllMocks()
fetchSpy = vi.spyOn(globalThis, 'fetch')
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
})
afterEach(() => {
fetchSpy.mockRestore()
warnSpy.mockRestore()
})
// -------------------------------------------------------------------------
// Auth & headers
// -------------------------------------------------------------------------
describe('request headers', () => {
it('sends Authorization and Content-Type headers', async () => {
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify({ id: 'c1', status: 'active' }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
await getConsent('c1')
expect(fetchSpy).toHaveBeenCalledTimes(1)
const [, opts] = fetchSpy.mock.calls[0]
expect(opts?.headers).toMatchObject({
Authorization: 'Bearer test-api-key',
'Content-Type': 'application/json',
})
})
})
// -------------------------------------------------------------------------
// Retry on retryable HTTP status
// -------------------------------------------------------------------------
describe('retry', () => {
it('retries on 503 and succeeds', async () => {
const fail = new Response('Service Unavailable', { status: 503 })
const success = new Response(
JSON.stringify({ id: 'c1', status: 'active' }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
)
fetchSpy
.mockResolvedValueOnce(fail)
.mockResolvedValueOnce(success)
const result = await getConsent('c1')
expect(result).toEqual({ id: 'c1', status: 'active' })
expect(fetchSpy).toHaveBeenCalledTimes(2)
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('returned 503, retrying')
)
})
it('retries on 429 (rate limit) and succeeds', async () => {
const rateLimit = new Response('Too Many Requests', { status: 429 })
const success = new Response(
JSON.stringify({ id: 'c1', status: 'active' }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
)
fetchSpy
.mockResolvedValueOnce(rateLimit)
.mockResolvedValueOnce(success)
const result = await getConsent('c1')
expect(result).toEqual({ id: 'c1', status: 'active' })
expect(fetchSpy).toHaveBeenCalledTimes(2)
})
it('retries on 502 and 504 as well', async () => {
const bad502 = new Response('Bad Gateway', { status: 502 })
const bad504 = new Response('Gateway Timeout', { status: 504 })
const success = new Response(
JSON.stringify({ id: 'c1', status: 'active' }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
)
fetchSpy
.mockResolvedValueOnce(bad502)
.mockResolvedValueOnce(bad504)
.mockResolvedValueOnce(success)
const result = await getConsent('c1')
expect(result).toEqual({ id: 'c1', status: 'active' })
expect(fetchSpy).toHaveBeenCalledTimes(3)
})
it('throws after exhausting all retries on retryable status', async () => {
const fail = new Response('Service Unavailable', { status: 503 })
fetchSpy
.mockResolvedValueOnce(fail.clone())
.mockResolvedValueOnce(fail.clone())
.mockResolvedValueOnce(fail.clone())
await expect(getConsent('c1')).rejects.toThrow('Arcim API 503')
expect(fetchSpy).toHaveBeenCalledTimes(3) // 1 original + 2 retries
})
it('does not retry on 400 errors', async () => {
const badRequest = new Response('Bad Request', { status: 400 })
fetchSpy.mockResolvedValueOnce(badRequest)
await expect(getConsent('c1')).rejects.toThrow('Arcim API 400')
expect(fetchSpy).toHaveBeenCalledTimes(1)
})
it('does not retry on 404 errors', async () => {
const notFound = new Response('Not Found', { status: 404 })
fetchSpy.mockResolvedValueOnce(notFound)
await expect(getConsent('c1')).rejects.toThrow('Arcim API 404')
expect(fetchSpy).toHaveBeenCalledTimes(1)
})
})
// -------------------------------------------------------------------------
// Retry on timeout (AbortError)
// -------------------------------------------------------------------------
describe('timeout retry', () => {
it('retries on AbortError and succeeds', async () => {
const abortError = new DOMException('Aborted', 'AbortError')
const success = new Response(
JSON.stringify({ id: 'c1', status: 'active' }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
)
fetchSpy
.mockRejectedValueOnce(abortError)
.mockResolvedValueOnce(success)
const result = await getConsent('c1')
expect(result).toEqual({ id: 'c1', status: 'active' })
expect(fetchSpy).toHaveBeenCalledTimes(2)
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining('timed out, retrying')
)
})
it('throws timeout error after exhausting retries on AbortError', async () => {
const abortError = new DOMException('Aborted', 'AbortError')
fetchSpy
.mockRejectedValueOnce(abortError)
.mockRejectedValueOnce(abortError)
.mockRejectedValueOnce(abortError)
await expect(getConsent('c1')).rejects.toThrow('Arcim API timeout')
expect(fetchSpy).toHaveBeenCalledTimes(3)
})
it('does not retry on non-abort network errors', async () => {
const networkError = new TypeError('fetch failed')
fetchSpy.mockRejectedValueOnce(networkError)
await expect(getConsent('c1')).rejects.toThrow('fetch failed')
expect(fetchSpy).toHaveBeenCalledTimes(1)
})
})
// -------------------------------------------------------------------------
// Exponential backoff
// -------------------------------------------------------------------------
describe('backoff', () => {
it('increases delay on successive retries', async () => {
const delays: number[] = []
const realSetTimeout = globalThis.setTimeout
// Only intercept retry delays (1000–10000ms range), pass abort timers through
vi.spyOn(globalThis, 'setTimeout').mockImplementation((fn, ms) => {
if (ms && ms >= 1000 && ms < 120_000) {
delays.push(ms as number)
// Execute retry delay callback immediately
if (typeof fn === 'function') fn()
return 0 as unknown as ReturnType<typeof setTimeout>
}
// Let abort controller timers run through real setTimeout
return realSetTimeout(fn, ms)
})
const fail = new Response('Service Unavailable', { status: 503 })
const success = new Response(
JSON.stringify({ id: 'c1', status: 'active' }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
)
fetchSpy
.mockResolvedValueOnce(fail.clone())
.mockResolvedValueOnce(fail.clone())
.mockResolvedValueOnce(success)
await getConsent('c1')
// attempt 0 → delay = 1000 * (0+1) = 1000
// attempt 1 → delay = 1000 * (1+1) = 2000
expect(delays).toEqual([1000, 2000])
vi.restoreAllMocks()
// Re-set our spies since restoreAllMocks clears them
fetchSpy = vi.spyOn(globalThis, 'fetch')
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
})
})
// -------------------------------------------------------------------------
// POST body
// -------------------------------------------------------------------------
describe('request body', () => {
it('sends JSON body for POST requests', async () => {
fetchSpy.mockResolvedValueOnce(
new Response(
JSON.stringify({ id: 'c1', status: 'pending', provider: 'fortnox' }),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
)
)
await createConsent('fortnox' as any, 'Test', '5591234567', 'Test AB')
const [url, opts] = fetchSpy.mock.calls[0]
expect(url).toBe('https://arcim.test.com/api/v1/consents')
expect(opts?.method).toBe('POST')
expect(JSON.parse(opts?.body as string)).toEqual({
name: 'Test',
provider: 'fortnox',
orgNumber: '5591234567',
companyName: 'Test AB',
})
})
})
// -------------------------------------------------------------------------
// Pagination (fetchAllPages)
// -------------------------------------------------------------------------
describe('pagination', () => {
it('fetches all pages until hasMore is false', async () => {
const page1 = { data: [{ id: 'c1' }, { id: 'c2' }], hasMore: true }
const page2 = { data: [{ id: 'c3' }], hasMore: false }
fetchSpy
.mockResolvedValueOnce(
new Response(JSON.stringify(page1), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
.mockResolvedValueOnce(
new Response(JSON.stringify(page2), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
const result = await fetchCustomers('consent-1')
expect(result).toHaveLength(3)
expect(result.map((c: any) => c.id)).toEqual(['c1', 'c2', 'c3'])
expect(fetchSpy).toHaveBeenCalledTimes(2)
})
it('stops when page returns empty data', async () => {
const page1 = { data: [{ id: 'c1' }], hasMore: true }
const page2 = { data: [], hasMore: true }
fetchSpy
.mockResolvedValueOnce(
new Response(JSON.stringify(page1), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
.mockResolvedValueOnce(
new Response(JSON.stringify(page2), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
const result = await fetchCustomers('consent-1')
expect(result).toHaveLength(1)
expect(fetchSpy).toHaveBeenCalledTimes(2)
})
})
// -------------------------------------------------------------------------
// Singleton resource (fetchCompanyInfo)
// -------------------------------------------------------------------------
describe('singleton resource', () => {
it('unwraps { data } envelope for company info', async () => {
const company = { orgNumber: '5591234567', name: 'Test AB' }
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify({ data: company }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
const result = await fetchCompanyInfo('consent-1')
expect(result).toEqual(company)
})
it('returns null when data is undefined', async () => {
fetchSpy.mockResolvedValueOnce(
new Response(JSON.stringify({}), {
status: 200,
headers: { 'Content-Type': 'application/json' },
})
)
const result = await fetchCompanyInfo('consent-1')
expect(result).toBeNull()
})
})
// -------------------------------------------------------------------------
// Missing env vars
// -------------------------------------------------------------------------
describe('environment validation', () => {
it('throws when ARCIM_SYNC_GATEWAY_URL is missing', async () => {
const orig = process.env.ARCIM_SYNC_GATEWAY_URL
delete process.env.ARCIM_SYNC_GATEWAY_URL
try {
await expect(getConsent('c1')).rejects.toThrow(
'ARCIM_SYNC_GATEWAY_URL is not configured'
)
} finally {
process.env.ARCIM_SYNC_GATEWAY_URL = orig
}
})
it('throws when ARCIM_SYNC_API_KEY is missing', async () => {
const orig = process.env.ARCIM_SYNC_API_KEY
delete process.env.ARCIM_SYNC_API_KEY
try {
await expect(getConsent('c1')).rejects.toThrow(
'ARCIM_SYNC_API_KEY is not configured'
)
} finally {
process.env.ARCIM_SYNC_API_KEY = orig
}
})
})
})