Files
accounted/extensions/general/arcim-migration/lib/__tests__/arcim-client.test.ts
T
MattssonandClaude Fable 5 288915c152 Fix/fdb fr usrs (#1125)
* fix(invoices): return attachment filename in delivery history summaries

The 20260723003000 hardening dropped attachment_filename from
list_invoice_delivery_summaries, so the delivery history UI always fell
back to the generic "faktura.pdf" label. Recreate the RPC with the
filename included: it is derived from company name, customer name,
invoice number, and date, all already visible to every company member,
so the minimization boundary is unchanged. Addresses stay masked and
message content, BCC, and checksums stay server-side.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(reconciliation): surface own-account transfer legs in match-to-voucher by default

The second (incoming) leg of a transfer between two of the company's own
bank accounts was hidden in the 'Matcha mot befintlig verifikation' dialog
because the voucher counted as 'already matched' once its outgoing leg was
linked, even though the incoming account's line had no settling transaction.
Users read the empty default list as 'the app won't let me link this'.

get_account_gl_lines_for_matching now counts links per settlement account:
a transaction provably on another cash account no longer marks the voucher
as matched for the requested account, so the unsettled transfer leg surfaces
by default (and auto-selects on an exact match). Same-account N:1 stays
behind the 'Visa aven matchade verifikationer' opt-in, and transactions
without a resolvable cash account conservatively keep counting everywhere.
get_unlinked_gl_lines is deliberately untouched (feeds auto-reconcile).

Companion guard: mark_entry_as_opening_balance now refuses entries with
linked bank transactions, since half-settled transfer vouchers became
reachable in the reconciliation view's unmatched table where 'Mark som IB'
renders; re-tagging one would strand its transaction against a movement-
excluded entry. getReconciliationStatus counts unmatched GL lines with the
account-scoped RPC so the status card agrees with the table.

Fixes #1026

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf(api): cut prod p95 latency via local JWT auth, single-RT company resolution, and report aggregate RPCs

Baseline 2026-07-23 (487 prod samples): p50 160ms, p95 480ms, 13% of
requests over 300ms. Target: p95 under 300ms.

- requireAuth: verify JWTs locally via getClaims (ES256/JWKS) instead of
  a second network getUser per request; getUser fallback keeps HS256
  self-hosted and existing test mocks working; middleware still
  revocation-checks every /api request
- resolve_active_company RPC (20260723161000): one round trip replaces
  2-3 queries in getActiveCompanyId and middleware; PGRST202/42501 fall
  back to the legacy query path
- arsredovisning build-data: ~33 sequential round trips down to ~7,
  output byte-identical (snapshot-proven)
- currency rate route: stop bypassing the exchange_rates cache (missing
  supabase arg caused an external Riksbanken call on every request)
- document.get: parallelize row fetch, signed URL and audit event
- list_company_accounts RPC (20260723170000): accounts list in one round
  trip instead of paging past PostgREST's 1000-row cap
- vat-declaration route: drop a dead sequential company_settings query
- get_kpi_report_aggregates RPC (20260723180000): KPI report's three
  full-period line scans collapsed into one aggregate call; dimension-
  filtered path unchanged
- lint: fix 9 baseline errors, downgrade 4 react-hooks compiler rules to
  warn, zero the eslint baseline ratchet

All four gates green: lint 0 errors, 9163 tests, check:guards, build.
Migrations applied idempotently to staging only; prod receives them via
Supabase branching on merge.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(review): resolve PR review findings across auth, VAT declaration, and IB retag

- requireAuth getClaims fast path: pin iss (project URL) and aud
  ('authenticated'), log every fallback to getUser (ASVS V9.1 finding)
- remove the ignored accountingMethod parameter from calculateVatDeclaration
  and the dead company_settings.accounting_method reads in xlsx/pdf/eskd
  routes; v1 API keeps accepting the query param but documents it as a no-op
- close the mark_entry_as_opening_balance TOCTOU race with a transactions
  trigger (20260723190000, FOR KEY SHARE on journal_entries) + pg tests;
  applied to staging and smoke-verified both directions
- re-add the 42501 tenant guard to branch-local migration 20260723160000
  (function body had silently reverted to the pre-20260619130100 definition)
- document the buildK3Noter tbFullRows full-TB contract (uppskjuten skatt
  opening balance per BFNAR 2012:1 ch.29)
- add KPI VAT-liability test covering reduced-rate output accounts 2621/2631

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(db): use NULL-safe caller_is_company_member in opening-balance retag guard

The re-added tenant guard carried the pre-20260703180000 raw
NOT IN (SELECT user_company_ids()) pattern, which the
null-safe-tenant-guards ratchet blocks. Staging re-synced.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-23 16:16:55 +02:00

358 lines
12 KiB
TypeScript

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', '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) => 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
}
})
})
})