Files
accounted/extensions/general/skatteverket/__tests__/commit-services.test.ts
T
18c20e68e6 fix(scoping): Skatteverket per företag + nåbara startkort + företags-scopade val (#1610)
* fix(scoping): skatteverket per company + true pristine gates + scoped dismissals

Skatteverket connections become per (user, company): the token table
carried BOTH UNIQUE(user_id) and UNIQUE(company_id) (two stacked half
migrations), so one connection leaked "connected" onto every company the
user belongs to, sync ran the token against the wrong orgnr (behorighet
403), and reconnecting from another company silently moved the row and
went dark on the first company's crons. Token reads/writes are now scoped
by company through the whole chain (token-store, api-client refresh
coalescing, skvRequest and its 21 call sites, resolve-auth, crons, MCP),
/skattekonto/saldo answers 401 NOT_CONNECTED for companies without their
own row (which is what the page's startkort keys on), and the dashboard
connect-nudge counts only the active company's row.

Bookkeeping's pristine start card now keys on all-years emptiness via a
count probe instead of "no active filters": the default fiscal-year
selection counted as a filter, which made the card unreachable on
brand-new companies (it showed "inga traffar" instead).

Two browser-global localStorage keys become company-scoped with legacy
fallbacks: the inbox onboarding dismissal (dismissing on one company hid
the card everywhere) and the periodisering auto-detect toggle.

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

* fix(scoping): dedupe cron work per (user, company) + guard the ledger probe

CodeRabbit findings on #1610: the skattekonto sync cron still deduped
token rows by user_id alone, which would drop every company but one for
multi-company operators (the exact scenario the PR fixes); and the
all-years ledger probe could leave a stale false behind on a failed
refetch, letting the pristine card render unconfirmed. The probe now
resets to unknown in flight and carries the fetch generation guard.

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

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-14 08:21:57 +02:00

95 lines
4.3 KiB
TypeScript

/**
* Tests for the extension's registry-exposed commit services: specifically the
* VAT "send for signing" chain (POST /utkast → PUT /las → signeringslänk), the
* SKATTEVERKET_ENABLED flag gate, and SkatteverketAuthError → recoverable
* mapping. The op-lifecycle translation is covered separately in
* lib/pending-operations/__tests__/skatteverket-executors.test.ts.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const mockSkvRequest = vi.fn()
vi.mock('../lib/api-client', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return { ...actual, skvRequest: (...a: unknown[]) => mockSkvRequest(...a) }
})
const mockBuildMomsuppgift = vi.fn()
vi.mock('../lib/declaration-prep', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>
return { ...actual, buildMomsuppgift: (...a: unknown[]) => mockBuildMomsuppgift(...a) }
})
vi.mock('../lib/audit', () => ({ writeSkatteverketAudit: vi.fn() }))
vi.mock('@/lib/extensions/context-factory', () => ({
createExtensionContext: () => ({
supabase: {},
companyId: 'company-1',
userId: 'user-1',
settings: { set: vi.fn().mockResolvedValue(undefined) },
log: { error: vi.fn(), warn: vi.fn(), info: vi.fn() },
}),
}))
import { skatteverketExtension } from '../index'
import { SkatteverketAuthError } from '../lib/api-client'
type SkvSubmitFn = (
supabase: unknown, userId: string, companyId: string, params: Record<string, unknown>,
) => Promise<{ ok: boolean; code?: string; recoverable?: boolean; signing_url?: string }>
const commitSubmitVatDeclaration = skatteverketExtension.services!.commitSubmitVatDeclaration as unknown as SkvSubmitFn
const VAT_PARAMS = { period_type: 'monthly', year: 2025, period: 3 }
let prevEnv: string | undefined
beforeEach(() => {
vi.clearAllMocks()
prevEnv = process.env.SKATTEVERKET_ENABLED
process.env.SKATTEVERKET_ENABLED = 'true'
mockBuildMomsuppgift.mockResolvedValue({
redovisare: '165560000000', redovisningsperiod: '202503', momsuppgift: { summaMoms: 150 },
})
})
afterEach(() => {
if (prevEnv === undefined) delete process.env.SKATTEVERKET_ENABLED
else process.env.SKATTEVERKET_ENABLED = prevEnv
})
describe('commitSubmitVatDeclaration', () => {
it('flag off → recoverable EXTENSION_DISABLED, zero SKV calls', async () => {
delete process.env.SKATTEVERKET_ENABLED
const result = await commitSubmitVatDeclaration({}, 'user-1', 'company-1', VAT_PARAMS)
expect(result).toMatchObject({ ok: false, code: 'EXTENSION_DISABLED', recoverable: true })
expect(mockSkvRequest).not.toHaveBeenCalled()
})
it('happy path: POST /utkast then PUT /las → ok with signing_url', async () => {
mockSkvRequest
.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ kontrollResultat: { status: 'OK' } }) }) // utkast
.mockResolvedValueOnce({ ok: true, status: 200, json: async () => ({ signeringsLank: 'https://skv.test/sign/abc' }) }) // las
const result = await commitSubmitVatDeclaration({}, 'user-1', 'company-1', VAT_PARAMS)
expect(result).toMatchObject({ ok: true, signing_url: 'https://skv.test/sign/abc' })
expect(mockSkvRequest).toHaveBeenCalledTimes(2)
// call order: utkast (POST) before las (PUT)
expect(mockSkvRequest.mock.calls[0][3]).toBe('POST')
expect(mockSkvRequest.mock.calls[0][4]).toMatch(/^\/utkast\/165560000000\/202503$/)
expect(mockSkvRequest.mock.calls[1][3]).toBe('PUT')
expect(mockSkvRequest.mock.calls[1][4]).toMatch(/^\/las\/165560000000\/202503$/)
})
it('utkast rejected by SKV → non-recoverable, no /las call', async () => {
mockSkvRequest.mockResolvedValueOnce({ ok: false, status: 400, text: async () => 'bad rutor' })
const result = await commitSubmitVatDeclaration({}, 'user-1', 'company-1', VAT_PARAMS)
expect(result).toMatchObject({ ok: false, recoverable: false, http_status: 400 })
expect(mockSkvRequest).toHaveBeenCalledTimes(1) // never reached /las
})
it('SkatteverketAuthError → recoverable SKATTEVERKET_NOT_CONNECTED', async () => {
mockSkvRequest.mockRejectedValueOnce(new SkatteverketAuthError('ingen anslutning', 'NOT_CONNECTED'))
const result = await commitSubmitVatDeclaration({}, 'user-1', 'company-1', VAT_PARAMS)
expect(result).toMatchObject({ ok: false, code: 'SKATTEVERKET_NOT_CONNECTED', recoverable: true })
})
})