diff --git a/DECISIONS.md b/DECISIONS.md index e982a5fb..8ecb550b 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -190,6 +190,10 @@ One line per decision: `[YYYY-MM-DD] : `. Appended by agents and [2026-07-17] Settings PUT keeps update(body) without a pick() allow-list: UpdateSettingsSchema is the write boundary (z.object strips unknown keys; company_id/onboarding_complete are not in the schema, org_number is deleted post-onboarding), so the mass-assignment finding does not apply. [2026-07-17] Turning vat_registered off (or vat_has_eu_trade off) now coerces the dependent flags (vat_taxable_base_over_40m, vat_has_eu_trade, periodisk_sammanstallning_enabled) to false server-side instead of 400-ing on the stale stored combination; explicitly enabling PS without registration or EU trade still 400s. PS period/filing-method preferences are deliberately preserved while PS is disabled (they are inert until re-enabled). [2026-07-17] Kept the cron's cross-tenant company_settings/deadlines scans on the service client: a daily all-company repair job is inherently cross-tenant, is cron-secret-gated, and per-company scoping would turn one paginated query into N queries; the per-company writes remain scoped by company_id inside the generator. +[2026-07-17] Skatteverket OAuth callback no longer awaits runPostConnectRefresh (eager promise + next/server after(), mirroring the enable-banking finalize decoupling): awaiting held the redirect open up to ~40s while the popup kept showing SKV's consumed consent page, which users read as a hung connect; the connect panels compensate with a delayed (15s) status refetch. The 2026-07-12 "awaited on purpose" rationale is superseded. +[2026-07-17] Skatteverket connect switched from a 600x750 named popup to window.open(url, '_blank') (new tab): SKV's consent page did not fit the popup (approve button below the fold; prod logs show authorize attempts with no callback ever arriving), and the named-window reuse made retry clicks appear dead. Parallel flows are prevented UI-side (button disabled while the tab lives) because each /authorize overwrites oauth_state + the PKCE verifier. +[2026-07-17] MCP kontoplan + verifikat-note tools stage at LOW risk and tools/list ceiling bumped 54K to 56K: create/update_account are reference data with no journal impact (update_article precedent), set_voucher_note is trigger-guaranteed notes-only (20260608120000 carve-out); the 3 tools inline STAGED_OPERATION_SCHEMA which is wire contract, descriptions were trimmed first. +[2026-07-17] Stale-tab recovery for Skatteverket/bank connections uses throttled visibilitychange refetches (settings connect panel, banking panel, /skattekonto not-connected state) instead of listening for the skatteverket-connection-updated CustomEvent on /skattekonto: that event only propagates within one window, and the connect flow always lives on another route or tab, so a listener there is dead code; cross-tab push (BroadcastChannel) was rejected as disproportionate since a tab switch necessarily precedes the user looking at the stale view. [2026-07-17] YearEndPreview.netResult now derived from the closing-lines totals (the signed 2099/2010 transfer) instead of generateIncomeStatement: the income statement excludes source_type='year_end' entries, so bokslut-flow depreciation/dispositioner were missing from the preview summary card while the bokslutsverifikation table included them (issue #766); patching the income statement instead was rejected because its exclusion is load-bearing (post-closing RR would collapse to zero) and executeYearEndClosing never reads netResult. [2026-07-17] Issue #310 vat_rate normalizer lives in lib/vat/supplier-invoice-line-checks.ts (shared by MCP staging and the pending-operation executor) instead of a local helper in mcp-server/server.ts: core cannot import extensions, and the legal-rate set (LEGAL_VAT_RATES) already lives there; duplicating the statutory set in two files invites drift. [2026-07-09] Billing checkout/portal guard BOTH is_anonymous and is_sandbox: a sandbox-company user created a live Stripe customer via POST /api/billing/checkout (no subscription, so never charged) because neither route checked either flag and withRouteContext admits anonymous users. Both conditions are checked even though they co-occur today (they are orthogonal), the anon check runs first (no DB round trip), and GET /api/billing/status exposes isDemo so the client hides the upgrade CTA instead of showing a button that 403s. One orphan Stripe customer and its company_subscriptions row left for manual cleanup (external destructive action, not done unilaterally). @@ -200,4 +204,5 @@ One line per decision: `[YYYY-MM-DD] : `. Appended by agents and [2026-07-10] Reopened the no-LLM call for account intelligence (founder directive): dev_docs/data_quality_master.md v2.1 revises D6. AI is scoped to where the deterministic engine has zero signal (supplier cold-start classification, no-hard-key residue, fleet-cluster naming) under D8 guardrails: persist-first (no model calls on booking hot paths), approval-gated suggest-band only (never preselect, never auto-book), AI priors in a sidecar table not categorization_templates, reuse the existing eu-north-1 Bedrock client (BFL residency), self-hosted/no-creds degrades to deterministic. The deterministic floor still ships first in every workstream; the AI-subsystem removal migration stays valid for what it removed (the auto-booking agent), not for AI as such. [2026-07-12] Issue #988 (transaction stuck on a removed verifikat): root cause was predicate divergence, the re-booking guards treated ANY non-null transactions.journal_entry_id as linked while the UI counts only status='posted'. Fix is a shared hasLiveJournalEntryLink() so stale pointers (reversed/cancelled/missing) are re-linkable, failing CLOSED on read errors, plus optimistic locks on the exact previous pointer instead of always .is(null). Chose guard self-heal over a null-on-reverse DB trigger because a trigger would fight correctEntry's re-point-to-correction behavior and race the correction insert; reverseEntry/correctEntry re-links stay best-effort. match-invoice/match-supplier-invoice untouched (they key on invoice ids; prod had zero dangling there). [2026-07-15] Issue #735 result-appropriation: did NOT run the mass 2099-to-2098 backfill. Prod audit showed the script read the FROZEN opening-balance 2099, not the CURRENT posted balance: 202 of 360 planned periods already carried their own disposition (mostly via SIE import) and 43 would have double-moved equity (worst case tens of MSEK on a single company), while periods without an OB entry fabricated balances via the cumulative-history fallback. Posted ONE verified entry for the reporting company (unblocking their arsredovisning) and rewrote the script to a current-balance-safe backfill: eligibility decided from current posted 2099, explicit OB entry required, already-disposed and ambiguous periods skipped to a manual-review report. planResultAppropriation/generateResultAppropriation untouched (steady-state year-end path, covered by pg-real tests); the safety lives in the sweep. +[2026-07-17] create_account now enforces first-digit vs account_type consistency (superRefine at the commit boundary + fail-fast in the MCP tool): class 8 legitimately allows both revenue and expense (financial items per the BAS catalog), classes 0/9 stay unconstrained (free-use per the BAS standard); prevents contradictory rows like 2999+expense whose derived account_class would misclassify balance sheet vs income statement. PR-review findings on set_voucher_note (posted-entry immutability, BFL 5:5 audit trail) were refuted, not fixed: the notes-only carve-out is migration 20260608120000's whole-row to_jsonb diff and audit_journal_entries already records old/new on every UPDATE. [2026-07-17] Assistenten settings opens on Kunskap (konteringskarta) instead of Minne; dropped the nested Kompetens/Minne tab row inside Kunskap: it duplicated the top-level tabs one row above. diff --git a/app/(dashboard)/articles/[id]/page.tsx b/app/(dashboard)/articles/[id]/page.tsx index 074b66da..cc65fa71 100644 --- a/app/(dashboard)/articles/[id]/page.tsx +++ b/app/(dashboard)/articles/[id]/page.tsx @@ -344,6 +344,7 @@ export default function ArticleDetailPage({ onSubmit={handleUpdate} isLoading={isUpdating} initialData={{ + article_number: article.article_number || undefined, name: article.name, name_en: article.name_en || undefined, type: article.type, diff --git a/app/(dashboard)/pending/page.tsx b/app/(dashboard)/pending/page.tsx index abc2ad0d..25e4415f 100644 --- a/app/(dashboard)/pending/page.tsx +++ b/app/(dashboard)/pending/page.tsx @@ -78,6 +78,8 @@ const OPERATION_LABEL_KEYS: Record = { create_supplier: 'type_create_supplier', create_article: 'type_create_article', update_article: 'type_update_article', + create_account: 'type_create_account', + update_account: 'type_update_account', create_dimension_value: 'type_create_dimension_value', // Supplier invoices create_supplier_invoice_from_inbox: 'type_create_supplier_invoice_from_inbox', @@ -95,6 +97,7 @@ const OPERATION_LABEL_KEYS: Record = { link_transaction_journal_entry: 'type_link_transaction_journal_entry', uncategorize_transaction: 'type_uncategorize_transaction', retag_line_dimensions: 'type_retag_line_dimensions', + set_voucher_note: 'type_set_voucher_note', // Bulk booking / allocation match_batch_allocate: 'type_match_batch_allocate', bulk_book_transactions: 'type_bulk_book_transactions', diff --git a/app/(dashboard)/skattekonto/page.tsx b/app/(dashboard)/skattekonto/page.tsx index bccdfccc..43507ea5 100644 --- a/app/(dashboard)/skattekonto/page.tsx +++ b/app/(dashboard)/skattekonto/page.tsx @@ -1,6 +1,6 @@ 'use client' -import { useCallback, useEffect, useState } from 'react' +import { useCallback, useEffect, useRef, useState } from 'react' import Link from 'next/link' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' @@ -101,6 +101,10 @@ export default function SkattekontoPage() { setNotConnected(true) return } + // A non-401 response proves a connection now exists: clear a stale + // not-connected state so a reload after connecting (in another tab or + // via the visibility refetch below) actually flips the page over. + setNotConnected(false) // A non-auth failure must NOT fall through to the "inget saldo hämtat // ännu"-tomvy — that reads as "not configured" when the truth is "the @@ -128,6 +132,30 @@ export default function SkattekontoPage() { void reload() }, [reload]) + // Auto-recover from the "inte anslutet" empty state when the user returns + // to this tab: the connect flow lives in Inställningar (often completed in + // another tab or after a mobile BankID app-switch), so no in-window signal + // can reach this page. Only fires while notConnected is showing: a routine + // tab switch on a healthy page must not flash the loading state. Throttled + // so rapid tab toggling doesn't hammer the API. + const notConnectedRef = useRef(false) + useEffect(() => { + notConnectedRef.current = notConnected + }, [notConnected]) + const lastVisibilityReloadRef = useRef(0) + useEffect(() => { + function onVisible() { + if (document.visibilityState !== 'visible') return + if (!notConnectedRef.current) return + const now = Date.now() + if (now - lastVisibilityReloadRef.current < 5_000) return + lastVisibilityReloadRef.current = now + void reload() + } + document.addEventListener('visibilitychange', onVisible) + return () => document.removeEventListener('visibilitychange', onVisible) + }, [reload]) + async function syncNow() { setSyncing(true) try { diff --git a/components/articles/ArticleForm.tsx b/components/articles/ArticleForm.tsx index 9f88af1d..9b98dc97 100644 --- a/components/articles/ArticleForm.tsx +++ b/components/articles/ArticleForm.tsx @@ -131,6 +131,7 @@ export default function ArticleForm({ const schema = useMemo( () => z.object({ + article_number: z.string().trim().max(64, t('number_too_long')).optional(), name: z.string().min(1, t('name_required')), name_en: z.string().optional(), type: z.enum(['vara', 'tjanst']), @@ -161,6 +162,7 @@ export default function ArticleForm({ } = useForm({ resolver: zodResolver(schema), defaultValues: { + article_number: initialData?.article_number || '', name: initialData?.name || '', name_en: initialData?.name_en || '', type: initialData?.type || 'tjanst', @@ -180,6 +182,7 @@ export default function ArticleForm({ const onFormSubmit = (data: FormData) => { onSubmit({ + article_number: data.article_number?.trim() || null, name: data.name, name_en: data.name_en || null, type: data.type, @@ -197,24 +200,39 @@ export default function ArticleForm({ return (
- {/* Type */} -
- - ( - + {/* Type + article number */} +
+
+ + ( + + )} + /> +
+
+ + + {errors.article_number ? ( +

{errors.article_number.message}

+ ) : ( +

{t('number_hint')}

)} - /> +
{/* Name */} diff --git a/components/salary/AGIPanel.tsx b/components/salary/AGIPanel.tsx index cc7e85e9..d96a99f0 100644 --- a/components/salary/AGIPanel.tsx +++ b/components/salary/AGIPanel.tsx @@ -150,6 +150,11 @@ export function AGIPanel(props: AGIPanelProps) { const [success, setSuccess] = useState(null) const [chain, setChain] = useState(null) const [showAdvanced, setShowAdvanced] = useState(false) + // True while an OAuth tab opened from this panel is still alive. Disables + // the connect buttons so a second click cannot start a parallel flow: each + // /authorize call overwrites the stored oauth_state + PKCE verifier, so a + // parallel flow guarantees a CSRF failure for whichever tab finishes last. + const [connecting, setConnecting] = useState(false) // "2026-06" for user-facing copy; the period prop is compact YYYYMM. const prettyPeriod = `${period.slice(0, 4)}-${period.slice(4)}` @@ -213,9 +218,26 @@ export function AGIPanel(props: AGIPanelProps) { fetchStatus() }, [fetchStatus]) - // Handle of the OAuth popup opened by handleConnect: used to verify the - // sender identity of incoming postMessages. + // Handle of the OAuth tab opened by handleConnect: used to verify the + // sender identity of incoming postMessages and to detect abandonment. const popupRef = useRef(null) + const watchTimerRef = useRef | null>(null) + const delayedRefetchRef = useRef | null>(null) + + const stopWatchingOauthTab = useCallback(() => { + if (watchTimerRef.current) { + clearInterval(watchTimerRef.current) + watchTimerRef.current = null + } + setConnecting(false) + }, []) + + useEffect(() => { + return () => { + if (watchTimerRef.current) clearInterval(watchTimerRef.current) + if (delayedRefetchRef.current) clearTimeout(delayedRefetchRef.current) + } + }, []) // Listen for OAuth completion from the BankID popup. When the popup posts // back a success/error message we re-fetch status so the panel flips from @@ -228,6 +250,7 @@ export function AGIPanel(props: AGIPanelProps) { // same-origin scripts. if (!popupRef.current || event.source !== popupRef.current) return if (event.data?.type === 'skatteverket-oauth-success') { + stopWatchingOauthTab() setError(null) setSuccess(t('oauth_success')) fetchStatus() @@ -235,7 +258,18 @@ export function AGIPanel(props: AGIPanelProps) { // consumers (e.g. the salary page) can react without trusting raw // postMessage. window.dispatchEvent(new CustomEvent('skatteverket-connection-updated')) + // The post-connect refresh (skattekonto sync, AGI settle, token + // health) now runs server-side AFTER the callback responds, so the + // status fetched above predates it. Refetch once more when it has + // plausibly settled so synced data and health flags show up + // without a manual reload. + if (delayedRefetchRef.current) clearTimeout(delayedRefetchRef.current) + delayedRefetchRef.current = setTimeout(() => { + fetchStatus() + window.dispatchEvent(new CustomEvent('skatteverket-connection-updated')) + }, 15_000) } else if (event.data?.type === 'skatteverket-oauth-error') { + stopWatchingOauthTab() const reason = typeof event.data.reason === 'string' && event.data.reason ? event.data.reason @@ -245,7 +279,7 @@ export function AGIPanel(props: AGIPanelProps) { } window.addEventListener('message', handleMessage) return () => window.removeEventListener('message', handleMessage) - }, [fetchStatus, t]) + }, [fetchStatus, stopWatchingOauthTab, t]) // Drop a stale "AGI-XML saknas" error once the run's AGI is (re)generated. // That error is set when "Skicka in underlag" runs before the XML exists; if @@ -377,6 +411,9 @@ export function AGIPanel(props: AGIPanelProps) { }, [submission?.status, checkKvittens]) const handleDisconnect = useCallback(async () => { + // No disconnect while an OAuth tab is in flight: the callback completing + // right after the disconnect would silently recreate the tokens. + if (connecting) return setActionLoading('disconnect') setError(null) setSuccess(null) @@ -397,35 +434,43 @@ export function AGIPanel(props: AGIPanelProps) { } finally { setActionLoading(null) } - }, [fetchStatus, onRefreshSubmission, t]) + }, [connecting, fetchStatus, onRefreshSubmission, t]) const handleConnect = () => { - // Open the BankID OAuth flow in a centered popup. The callback page + // Open the BankID OAuth flow in a NEW TAB, not a popup. The old 600x750 + // popup could not fit Skatteverket's consent page: the approve button + // sat below the fold and users got stranded mid-consent. A tab gets the + // full viewport (and behaves natively on mobile). The callback page // detects `window.opener` and posts back a `skatteverket-oauth-success` // (or `-error`) message, then closes itself: see the postMessage - // listener below. `return_to` is still passed so the popup-less fallback - // path (e.g. popup blockers) lands on the salary run page rather than - // the default /reports tab. + // listener below. `return_to` is still passed so the tab-blocked + // fallback path lands on the salary run page rather than the default + // /reports tab. const returnTo = typeof window !== 'undefined' ? window.location.pathname + window.location.search : '' const url = `/api/extensions/ext/skatteverket/authorize${ returnTo ? `?return_to=${encodeURIComponent(returnTo)}` : '' }` - const w = 600 - const h = 750 - const left = window.screenX + (window.outerWidth - w) / 2 - const top = window.screenY + (window.outerHeight - h) / 2 - const popup = window.open( - url, - 'skatteverket-oauth', - `width=${w},height=${h},left=${left},top=${top}`, - ) - popupRef.current = popup - if (!popup) { - // Popup blocked: fall back to a full-page navigation. + const tab = window.open(url, '_blank') + popupRef.current = tab + if (!tab) { + // Tab blocked: fall back to a full-page navigation. window.location.href = url + return } + setConnecting(true) + // Detect abandonment: if the tab goes away without posting a message + // (closed manually, stranded on Skatteverket's side), re-enable the + // buttons and refresh status. This also fires after a successful + // self-close; the extra status fetch is harmless. + if (watchTimerRef.current) clearInterval(watchTimerRef.current) + watchTimerRef.current = setInterval(() => { + if (popupRef.current?.closed) { + stopWatchingOauthTab() + fetchStatus() + } + }, 1000) } /** @@ -803,9 +848,9 @@ export function AGIPanel(props: AGIPanelProps) { {t('connect_description')}

{!readOnly && ( - )} @@ -851,7 +896,7 @@ export function AGIPanel(props: AGIPanelProps) {
)} @@ -1076,9 +1121,9 @@ export function AGIPanel(props: AGIPanelProps) { {error} {sessionExpired && !readOnly && (
-
)} diff --git a/components/settings/SkatteverketConnectPanel.tsx b/components/settings/SkatteverketConnectPanel.tsx index 6f61ad40..d84bdf4f 100644 --- a/components/settings/SkatteverketConnectPanel.tsx +++ b/components/settings/SkatteverketConnectPanel.tsx @@ -45,9 +45,31 @@ function SkatteverketPersonalConnectionCard() { const [status, setStatus] = useState(null) const [loading, setLoading] = useState(true) const [disconnecting, setDisconnecting] = useState(false) - // Handle of the OAuth popup opened by startConnect: used to verify the - // sender identity of incoming postMessages. + // True while an OAuth tab opened from this panel is still alive. Disables + // the connect button so a second click cannot start a parallel flow: each + // /authorize call overwrites the stored oauth_state + PKCE verifier, so a + // parallel flow guarantees a CSRF failure for whichever tab finishes last. + const [connecting, setConnecting] = useState(false) + // Handle of the OAuth tab opened by startConnect: used to verify the + // sender identity of incoming postMessages and to detect abandonment. const popupRef = useRef(null) + const watchTimerRef = useRef | null>(null) + const delayedRefetchRef = useRef | null>(null) + + const stopWatchingOauthTab = useCallback(() => { + if (watchTimerRef.current) { + clearInterval(watchTimerRef.current) + watchTimerRef.current = null + } + setConnecting(false) + }, []) + + useEffect(() => { + return () => { + if (watchTimerRef.current) clearInterval(watchTimerRef.current) + if (delayedRefetchRef.current) clearTimeout(delayedRefetchRef.current) + } + }, []) // docs: https://www7.skatteverket.se/portal-wapi/open/apier-och-oppna-data/utvecklarportalen/v1/getFile/tjanstebeskrivning-skattekonto-hamta-huvudmans-saldo-och-transaktioner-v101 const SCOPE_LABELS: Record = { @@ -58,8 +80,12 @@ function SkatteverketPersonalConnectionCard() { agd: t('scope_agd'), } + // Only the first load blanks the card to the loading state: later refetches + // (postMessage, closed-tab watcher, delayed sync refetch, visibility) update + // in the background so the panel doesn't flash on every signal. + const hasLoadedRef = useRef(false) const loadStatus = useCallback(async () => { - setLoading(true) + if (!hasLoadedRef.current) setLoading(true) try { const res = await fetch('/api/extensions/ext/skatteverket/status') if (res.status === 503) { @@ -71,6 +97,7 @@ function SkatteverketPersonalConnectionCard() { } catch { setStatus({ connected: false }) } finally { + hasLoadedRef.current = true setLoading(false) } }, []) @@ -79,6 +106,24 @@ function SkatteverketPersonalConnectionCard() { loadStatus() }, [loadStatus]) + // Safety net for completion signals that never reach this tab: a mobile + // BankID app-switch can land the OAuth return in a different browser tab, + // and a bfcache-restored page shows a pre-connection snapshot. Refetch + // status whenever the tab regains visibility, throttled so rapid tab + // toggling doesn't hammer the API. + const lastVisibilityFetchRef = useRef(0) + useEffect(() => { + function onVisible() { + if (document.visibilityState !== 'visible') return + const now = Date.now() + if (now - lastVisibilityFetchRef.current < 5_000) return + lastVisibilityFetchRef.current = now + loadStatus() + } + document.addEventListener('visibilitychange', onVisible) + return () => document.removeEventListener('visibilitychange', onVisible) + }, [loadStatus]) + // Listen for OAuth completion from the BankID popup (same pattern as // AGIPanel): the callback page posts success/error and closes itself, so // the settings page never navigates and we just re-fetch the status. @@ -90,6 +135,7 @@ function SkatteverketPersonalConnectionCard() { // same-origin scripts. if (!popupRef.current || event.source !== popupRef.current) return if (event.data?.type === 'skatteverket-oauth-success') { + stopWatchingOauthTab() toast({ title: tOauth('connected_title'), description: tOauth('connected_description'), @@ -99,7 +145,18 @@ function SkatteverketPersonalConnectionCard() { // consumers (e.g. the salary page) can react without trusting raw // postMessage. window.dispatchEvent(new CustomEvent('skatteverket-connection-updated')) + // The post-connect refresh (skattekonto sync, AGI settle, token + // health) now runs server-side AFTER the callback responds, so the + // status fetched above predates it. Refetch once more when it has + // plausibly settled so synced data and health flags (e.g. + // MISSING_SCOPE) show up without a manual reload. + if (delayedRefetchRef.current) clearTimeout(delayedRefetchRef.current) + delayedRefetchRef.current = setTimeout(() => { + loadStatus() + window.dispatchEvent(new CustomEvent('skatteverket-connection-updated')) + }, 15_000) } else if (event.data?.type === 'skatteverket-oauth-error') { + stopWatchingOauthTab() toast({ title: tOauth('connect_failed_title'), description: @@ -112,35 +169,46 @@ function SkatteverketPersonalConnectionCard() { } window.addEventListener('message', handleMessage) return () => window.removeEventListener('message', handleMessage) - }, [loadStatus, toast, tOauth]) + }, [loadStatus, stopWatchingOauthTab, toast, tOauth]) function startConnect() { - // Open the BankID OAuth flow in a centered popup. The callback page + // Open the BankID OAuth flow in a NEW TAB, not a popup. The old 600x750 + // popup could not fit Skatteverket's consent page: the approve button + // sat below the fold and users got stranded mid-consent. A tab gets the + // full viewport (and behaves natively on mobile). The callback page // detects `window.opener`, posts back a message and closes itself: the // settings page never navigates, so browser history stays clean and // closing the settings afterwards cannot walk Back into the consumed // OAuth chain (the "redirected to Skatteverket again" bug). const returnTo = encodeURIComponent('/settings/tax') const url = `/api/extensions/ext/skatteverket/authorize?return_to=${returnTo}` - const w = 600 - const h = 750 - const left = window.screenX + (window.outerWidth - w) / 2 - const top = window.screenY + (window.outerHeight - h) / 2 - const popup = window.open( - url, - 'skatteverket-oauth', - `width=${w},height=${h},left=${left},top=${top}`, - ) - popupRef.current = popup - if (!popup) { - // Popup blocked: fall back to the full-page flow. The callback then + const tab = window.open(url, '_blank') + popupRef.current = tab + if (!tab) { + // Tab blocked: fall back to the full-page flow. The callback then // lands on /settings/tax?skv_connected=true, handled by // TaxSettingsContent's query-param effect. window.location.href = url + return } + setConnecting(true) + // Detect abandonment: if the tab goes away without posting a message + // (closed manually, stranded on Skatteverket's side), re-enable the + // button and refresh status. This also fires after a successful + // self-close; the extra status fetch is harmless. + if (watchTimerRef.current) clearInterval(watchTimerRef.current) + watchTimerRef.current = setInterval(() => { + if (popupRef.current?.closed) { + stopWatchingOauthTab() + loadStatus() + } + }, 1000) } async function disconnect() { + // No disconnect while an OAuth tab is in flight: the callback completing + // right after the disconnect would silently recreate the tokens. + if (connecting) return setDisconnecting(true) try { const res = await fetch('/api/extensions/ext/skatteverket/disconnect', { @@ -206,11 +274,11 @@ function SkatteverketPersonalConnectionCard() { )} @@ -245,7 +313,14 @@ function SkatteverketPersonalConnectionCard() { {status.needsReconsent && (
-

{t('needs_reconsent_message')}

+ {/* MISSING_SCOPE right after a connect means the user skipped a + behörighet on SKV's consent page; tell them exactly that + instead of the generic "session expired" prompt. */} +

+ {status.lastErrorCode === 'MISSING_SCOPE' + ? t('missing_scope_message') + : t('needs_reconsent_message')} +

)}
@@ -306,17 +381,17 @@ function SkatteverketPersonalConnectionCard() { {(status.expired || status.needsReconsent || !status.canRefresh || !(scopes.includes('skahmst') || scopes.includes('skattekonto')) || !scopes.includes('agd')) && ( )}