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>
This commit is contained in:
Jakob Wennberg
2026-08-14 08:21:57 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent 4e14182a00
commit 18c20e68e6
28 changed files with 317 additions and 145 deletions
@@ -410,7 +410,7 @@ describe('AGI kvittenser cron', () => {
expect(body.expired).toBe(1)
expect(body.apigwConfig).toBe(0)
expect(body.results[0]).toMatchObject({ status: 'expired_token', error: 'SESSION_EXPIRED' })
expect(mockMarkNeedsReconsent).toHaveBeenCalledWith(expect.anything(), 'user-1', 'SESSION_EXPIRED')
expect(mockMarkNeedsReconsent).toHaveBeenCalledWith(expect.anything(), 'user-1', 'comp-1', 'SESSION_EXPIRED')
expect(errorSpy).not.toHaveBeenCalled()
expect(errorRecorder).not.toHaveBeenCalled()
expect(warnSpy).not.toHaveBeenCalled()
@@ -172,7 +172,7 @@ export async function GET(request: Request) {
.eq('company_id', companyId)
.maybeSingle()
if (tokenRow?.user_id) {
await markNeedsReconsent(supabase, tokenRow.user_id as string, err.code)
await markNeedsReconsent(supabase, tokenRow.user_id as string, companyId, err.code)
}
results.push({ declarationId, period, status: 'expired_token', error: err.code })
continue
@@ -82,7 +82,9 @@ export async function GET(request: Request) {
.order('expires_at', { ascending: true })
.order('user_id', { ascending: true })
.range(from, to),
{ dedupeBy: token => token.user_id },
// One row per (user, company) since tokens went per-company: deduping by
// user alone would drop every company but one for multi-company operators.
{ dedupeBy: token => `${token.user_id}:${token.company_id}` },
)
} catch (error) {
console.error('[skattekonto-sync-cron] Failed to fetch tokens', {
@@ -213,7 +215,7 @@ export async function GET(request: Request) {
const ctx = createExtensionContext(supabase, userId, companyId, 'skatteverket')
const auth: SkvAuth =
source === 'system' ? { mode: 'system' } : { mode: 'user', supabase, userId }
source === 'system' ? { mode: 'system' } : { mode: 'user', supabase, userId, companyId }
const syncResult = await syncSkattekonto(ctx, auth)
// Drift check: compare the fresh SKV saldo against GL 1630 sum. Emits
@@ -271,7 +273,7 @@ export async function GET(request: Request) {
err instanceof SkatteverketAuthError &&
(RECONSENT_ERROR_CODES as readonly string[]).includes(err.code)
) {
await markNeedsReconsent(supabase, userId, err.code)
await markNeedsReconsent(supabase, userId, companyId, err.code)
results.push({ userId, companyId, source, status: 'expired', error: err.code })
continue
}
@@ -287,7 +287,7 @@ describe('VAT kvittenser cron', () => {
expect(body.expired).toBe(1)
expect(body.results[0]).toMatchObject({ status: 'expired_token', error: 'SESSION_EXPIRED' })
expect(mockMarkNeedsReconsent).toHaveBeenCalledWith(expect.anything(), 'user-1', 'SESSION_EXPIRED')
expect(mockMarkNeedsReconsent).toHaveBeenCalledWith(expect.anything(), 'user-1', 'comp-1', 'SESSION_EXPIRED')
})
it('records error for generic failures without aborting the run', async () => {
@@ -266,7 +266,7 @@ export async function GET(request: Request) {
.eq('company_id', companyId)
.maybeSingle()
if (tokenRow?.user_id) {
await markNeedsReconsent(supabase, tokenRow.user_id as string, err.code)
await markNeedsReconsent(supabase, tokenRow.user_id as string, companyId, err.code)
}
} catch (reconsentErr) {
console.warn('[vat-kvittenser-cron] Failed to persist reconsent flag', {