* fix(security): gate replace_sie_import behind owner/admin membership The RPC was SECURITY DEFINER with EXECUTE granted to PUBLIC and anon, no company_members lookup, no auth.uid() reference and no unauthorized raise, while setting gnubok.allow_delete to disarm the BFL immutability and retention triggers. Any caller holding a company_id and an import id could hard delete another tenant's verifikationer. Confirmed live in production. Applies the same fail closed owner/admin guard that undo_sie_import already carries (migration 20260624120000), resolving the actor from COALESCE(p_user_id, auth.uid()) so it denies when the role is NULL, then revokes EXECUTE from PUBLIC and anon. search_path and the raised statement_timeout are restated, since CREATE OR REPLACE drops settings that are not repeated. userId is a required parameter on replaceSIEImport: the service client has a NULL auth.uid(), so a caller without an explicit actor now fails to compile rather than hitting the closed gate at runtime. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): validate arcim OAuth callback state server side The callback route is skipAuth and decoded the state parameter as plain base64url JSON, trusting consentId and provider from it. A one time code was minted at flow start and never read. An unauthenticated attacker who learned a consent id could run an OAuth flow on their own provider account and post the callback with a forged state, landing their tokens on another tenant's consent, so the victim's next migration imported the attacker's ledger. State is now an opaque randomBytes(32) pointer to a provider_otc row, consumed by a single atomic UPDATE guarded on used_at IS NULL and expires_at, so a replay loses the row lock race and updates nothing. provider is read from provider_consents rather than trusted from the client. provider_otc already existed for exactly this purpose and was never wired up. Also scopes getConsent to an owning company, closing a cross tenant status oracle where the preview and migrate paths echoed a consent's status before the scoped check ran. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): scope documents storage to company_id (phase A) The documents bucket policies matched on auth.uid(), and upload keys were documents/{userId}/..., so company membership was never consulted. Removing a member revoked nothing: their session still authenticated and they kept direct Storage read access to every receipt, supplier invoice and bank statement they had uploaded. The same bug was fixed for sie-files in 20260416120000; this bucket was left behind. Phase A is additive. Company scoped policies are added alongside the uploader scoped ones, uploads move to documents/{companyId}/{userId}/..., and reads accept either layout so nothing breaks mid migration. Phase C, which drops the old policies, is gated on the backfill reporting zero remaining legacy prefix objects. The policy compares the company segment as text rather than casting to uuid the way sie-files does: this bucket holds keys whose second segment is not a uuid (MCP audit packages), and Postgres does not guarantee the bucket prefix qual runs before the cast, so a planner reordering would raise 22P02 and fail the whole query instead of filtering the row out. deleteDocument now removes both candidate keys. Removing only the stored pointer would leave a readable orphan copy of a document the user asked to erase. The backfill script is included but has never been run. It defaults to dry run, refuses .env.local by name, and verifies each copy is readable and SHA-256 identical before repointing the row. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(security): enforce events:read scope and membership on /api/events This was the only one of the three validateApiKey call sites with no downstream guard: v1 and the MCP server both check scope and re-verify company membership, this route did neither. An events:read scope existed and was documented as gating the endpoint but was never called, so a legacy key falling back to DEFAULT_SCOPES read the full log. The bound company id went straight from the api_keys row into a service role query, so a key whose user had been removed from the company kept reading. Adds the scope check before any database access, re-verifies company_members with archived_at IS NULL, honours test mode by stamping X-Gnubok-Mode instead of ignoring it, applies minimisePayload so the pull surface can never return a wider payload than the push surface, and replaces the three flat error strings with the canonical envelope. Test key reads are served rather than blocked: TEST_KEY_WRITE_BLOCKED is gated on mutations in with-api-v1, so a read gets the same treatment as every other v1 read endpoint. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * perf(bookkeeping): sweep remaining journal_entries!inner embeds A previous refactor removed this pattern from lib/reports and introduced fetchEntryLines, but the class was never swept. Seventeen sites remained and had become the top application consumer of production database time: measured across the resulting query shapes, 32,694 calls and 25,848 seconds of execution, mean 790ms, with shapes averaging 2.6s and 3.0s and maxing at 7,962ms against the 8s statement_timeout, which surfaced to users as 500s on the booking path. PostgREST compiles an embed with filters on the embedded side into a correlated INNER JOIN LATERAL with a parameterized LIMIT, which stops Postgres reordering the join, so each query walked the whole journal_entry_lines table across all tenants. Driving from the entries side instead turns that into two indexed round trips. Converted sites keep their existing shape: the helper reattaches the parent entry under the same key the embed produced. Several conversions also remove a latent silent truncation where an unpaginated query was capped at PostgREST's 1000 row ceiling. Two deliberate exceptions. The free text ilike legs of the MCP display query stay on the embed, because each is capped at legLimit and that cap drives the truncation contract the tool reports, while the helper is unbounded. The accounts route moves to the existing get_account_usage_counts RPC instead, since its embed was a head count and the helper returns rows. commitEntry's write path is untouched: the change there is confined to the read query of the pre-commit dimension rule check. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): anchor v1 list cursors on created_at Page two returned page one, forever, while still advertising a fresh next_cursor. The three routes sorted by and encoded a Postgres date column, which serializes as YYYY-MM-DD, but decodeDefaultCursor validates the cursor timestamp as full ISO-8601 and returned null, so the keyset filter was never applied and has_more never went false. An integrator syncing verifikat looped on the newest rows indefinitely. The transactions route already solved this and its comment names the trap; the fix was never ported. All three now order and encode on created_at with an id tie break, matching the transactions keyset predicate exactly. ISO_TIMESTAMP is deliberately left alone: relaxing it would silently change sort semantics on the route that currently works. Default ordering therefore moves from business date to insert order. Every business date is still on the row, and the invoices list gains date_from and date_to filters so a date range is still reachable; the other two already had them. The tests use an in-memory PostgREST that actually evaluates the filters, because the repo's pass-through mock cannot catch this class of bug: the bug is that the filter is never sent. They walk to exhaustion with a hard iteration cap, so an unterminated walk fails instead of hanging. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix(api): separate dry run from commit in the idempotency hash The request hash was built from url.pathname, which excludes the query string, so a dry run and its commit hashed identically. Following the flow documented in dry-run.ts, re-issuing the request with the same Idempotency-Key returned the cached preview with Idempotent-Replayed set and wrote nothing, while reporting 200. An agent or integrator saw success for a write that never happened. dry_run is folded into the hash only when true, not as an unconditional boolean. Including it as false would change the hash of every ordinary write, and with a 24h idempotency TTL any key in flight across the deploy would fail the request_hash comparison and 409 on a legitimate retry. Both hash call sites now go through one shared helper so they cannot drift into a permanent cache miss, and dry run responses are no longer stored at all. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * ci: install the Bedrock SDK out of tree in the compliance review The Swedish accounting compliance gate had failed ten consecutive runs and so was posting nothing. With --no-package-lock npm discarded the lockfile and re-resolved the whole tree from package.json, floating @hookform/resolvers to 5.4.3, whose valibot ^1 peer conflicts with the pinned valibot 0.39.0. Installing into the parent of the checkout resolves only that one package, so an unrelated peer conflict can never take the gate down again. Node still finds it because ESM bare specifiers walk up parent node_modules; NODE_PATH would not have worked, as it is CommonJS only. --legacy-peer-deps was rejected because it masks future genuine peer conflicts and still reifies the full tree. The same step's SDK version is aligned from 0.31.0 back to the 0.29.1 that package.json and check:guards enforce after the streaming outage. That drift went unnoticed because the pin guard only inspects package.json and the lockfile, never workflow files. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * build(docker): generate crontabs from vercel.json vercel.json defines 16 cron jobs; both Docker crontabs carried 9, and were byte identical to each other. Self hosted deployments therefore never sent recurring invoices, never dispatched webhooks and never cleaned up idempotency keys. tax-deadlines also ran once a year on 2 January instead of daily, and documents/verify weekly instead of daily. Extension crons are included rather than excluded. The Dockerfile copies the whole tree before building, so every extension cron route is compiled into the image regardless of the enabled preset, and each returns 200 when its extension is unconfigured, so curl -sf logs no failure. Two such entries were already present in the crontab for extensions absent from the preset, which settles the intent. documents/verify is treated as drift rather than a self hosted concession: the weekly cadence was present in the hosted crontab too, and the run is capped at 200 documents walking a nulls-first queue, so weekly drains the integrity queue seven times slower on a check that exists for BFL retention. webhooks/dispatch keeps its per minute cadence, adding 1,440 requests a day on self hosted. A gentler tick would silently stretch the first retry, since the retry ladder opens at 60 seconds. SCHEDULE_OVERRIDES is the one line place to change that. A parity test asserts the path sets match minus a documented exclusion list, and ratchets three cron routes that are currently scheduled nowhere so they are named rather than silently rotting. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * chore(observability): add a provider agnostic error sink There is no error tracking in this codebase: logs go to console and Vercel retention and nowhere else, nothing alerts on the 16 cron jobs, and seven code comments across lib, app, components and extensions asserted that Sentry captures errors when Sentry is not a dependency. The two most recent bug fixes on this repo were both discovered by customer email. This adds the sink, not a vendor. No dependency is taken: the interface has a no-op default and a registration point, so behaviour is unchanged until an adapter is registered. Releases are tagged from the build id already inlined by next.config.ts. Redaction moved out of lib/logger.ts into a leaf module that both the logger and the sink import, so there is one denylist and no path from application data to a third party can skip the personnummer regex, including direct sink calls that bypass the logger. That matters here because these logs carry personnummer and financial data. verifyCronSecret now reports its own 401s, which covers all 16 jobs without touching a route file and catches the case where CRON_SECRET is rotated without updating the scheduler and every job silently 401s forever. The threshold is one failure rather than the backup alert's three: suppressing the first occurrence is precisely how an outage stays invisible. The seven misleading comments are corrected to describe what the code actually does, including the two cases that still are not covered: the client side one, since the sink is server side, and a warn level call that is not forwarded. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> * fix: remediate the 2026-07-26 similar-sweep findings across all surfaces Resolves the ~150-finding sweep (dev_docs/similar-sweep-2026-07-26.md) with one agent per finding; every behavioural fix carries a regression test proven to fail at HEAD. Full status, corrections to the sweep, refusals and open decisions in dev_docs/similar-sweep-2026-07-26-remediation-status.md. Structural roots closed: - resolveSekAmountOrNull(): honest SEK resolution refuses instead of booking 1:1; four duplicated toSek closures now refuse via INVOICE_FX_RATE_MISSING - ledger-line-amount.ts: journal_entry_lines.currency labels the document, not the amount; SQL pre-filter decoy proven and fixed - sparse-patch.ts: .partial() does not strip .default() in Zod 4.4.3; the exploitable salary payslip-line PATCH and KPI preferences sinks fixed - tests/schema: migration-replay phantom-column guard (13k+ refs, closed CHECK sets, onConflict targets); found 28 real defects, all fixed, all four baselines now empty - three new ratchet guards: sek-labelled-amount, cross-extension-import, ungated-extension-route Highlights: lawful VAT-rate set on all seven invoice surfaces (ML 6 kap), RC input VAT mismatch wired on web + both MCP callers, missing-underlag resource delegates to the shared RPC predicate, push-notifications consent polarity fail-closed, deadlines undo honours requested state, silent-failure and read-side-fabrication classes fixed across settings/KPI/inbox/Stripe/ Arcim/kassaflodesanalys, error-envelope stringification fixed at 10+ sites with isSwedishUserMessage extended. Also includes the parallel session's MCP invoice tools (update_invoice, recurring schedules, invoice deliveries) which share files with the sweep work and are verified green together. 13 new migrations are NOT applied anywhere; they apply via branch merge. 20260726120000 backfills 1247 supplier-invoice rows. pg tests for new DDL are written but unrun (no local Postgres). Verified: 11088 tests / 881 files green, tsc 0 non-test errors, lint 0 errors, check:guards passing, MCP payload 57475/57500. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(migrations): rename replace_sie_import migration off main's 20260726090000 version origin/main shipped 20260726090000_agent_quota_rpc_caller_guard.sql; keeping our replace_sie_import migration on the same version would abort the Supabase apply with a schema_migrations_pkey duplicate at merge time. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): remediate pre-publish deep-review findings across all slices A 13-agent review of the full branch diff surfaced 1 critical, 5 high and ~45 further findings; this commit resolves them in one pass: - replace_sie_import / undo_sie_import: p_user_id honored only for service_role callers; any other caller is pinned to auth.uid() (impersonation gate bypass), authz raise errcode 42501 mapped to a Swedish 403 in the route, new caller-guard migration for undo - bulk_book_transactions refuses homogeneous non-SEK batches instead of writing foreign magnitudes into SEK ledger columns - credit-note cap trigger: company-match on credited_invoice_id, no cross-tenant figures in exception text - link_voucher RPCs resolve NULL invoice currency as SEK end to end - personal-number ciphertext CHECK split into NOT VALID + VALIDATE - same-currency foreign settlements clear 1510 at booking rate and book realized diff to 3960/7960; rate-less foreign write paths refuse - receivables revaluation covers partially_paid and outstanding amounts - period lock guard paginates candidates past the PostgREST 1000 cap - documents: service-client storage removals after authz, dual-layout reads in integrity cron and archive export, backfill delete-source sweep actually deletes with hash verification and shared-key grouping - invoice matching normalizes NULL/lowercase currencies (regression), duplicate candidates stop claiming amount matches they never ran - match-invoice aborts on any booking failure (no paid-without-verifikat) - refresh-exchange-rate reverts on concurrent booking (TOCTOU window) - KPI preferences upsert arbiter aligned to the company-scoped constraint - personnummer_last4 stripped from all salary responses incl. MCP tools - worked-hours batch restores destroyed rows on conflict and error paths - MCP: shared duplicate-claim builder (no more 'null kr'), short-circuit on tag_journal_lines overflow, auto_send schedules stage as high risk - observability sink redacts emails/IBANs/API keys and keeps redacted stacks in prod; assorted small guards (safe-return-to /@, dry_run=True, cursor helper off-by-one, OAuth state TTL 10 min, arcim saveMappings call removed) Full dispositions, deferred items and hand-verified accounting numbers are documented in the PR body and DECISIONS.md. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(personnummer): implement masking and encryption for personal numbers with tests * fix(review): address CI and compliance-bot findings for PR #1215 pg-real: the CI image's auth shim reads the legacy request.jwt.claim.role GUC, so both service-role simulations (runAsServiceRole and the invoice-delivery test's local helper) never satisfied auth.role() = 'service_role' and every legitimate p_user_id path failed closed; the shared helper now sets both GUC shapes plus SET LOCAL ROLE with a fail-loud sanity check, and the delivery test reuses it. The link-voucher migration had recreated both RPCs from pre-rewrite file text, reintroducing the NULL-unsafe membership pattern the null-safe-tenant-guards ratchet bans; both guards now use public.caller_is_company_member() with all currency changes preserved. Compliance bots: the customers export now emits the standard masked form instead of raw AES-256-GCM ciphertext in the Org-/personnummer column, and maskCustomerRow returns a non-round-trippable placeholder on decrypt failure instead of 500ing the list. MCP parity: gnubok_lock_period's staging pre-check now runs the exact countUnbookedInPeriod the commit path enforces (exported from period-service; local mirror deleted), and gnubok_agi_status resolves AGI state run-scoped so a correction run no longer renders as already filed. Declined with evidence: PR-Agent's opening-balances null-zeroing concern (all mergeable columns are NOT NULL with defaults per 20260713101000). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(review): address codex review findings on PR #1215 - restore 20260726140000 to its preview-recorded content and restate the NULL-safe tenant guard under 20260727130000: a recorded migration version never re-runs, so the in-place edit could not reach the preview branch - replace toFixed() with sv-SE two-decimal formatting in the ROT/RUT cap warning texts and update the pinned test expectations - drop the em dash in the fiscal-periods route comment - strip trailing whitespace in import-existing.test.ts Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * test(reports): raise timeout on real PDF render tests renderToBuffer does real @react-pdf layout work and exceeds the 5s default when the full suite saturates the CPU; tests pass in isolation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1082 lines
39 KiB
TypeScript
1082 lines
39 KiB
TypeScript
'use client'
|
|
|
|
import { ENABLED_EXTENSION_IDS } from '@/lib/extensions/_generated/enabled-extensions'
|
|
import React, { useState, useEffect, useCallback } from 'react'
|
|
import { Button } from '@/components/ui/button'
|
|
import { Skeleton } from '@/components/ui/skeleton'
|
|
import {
|
|
DropdownMenu,
|
|
DropdownMenuContent,
|
|
DropdownMenuItem,
|
|
DropdownMenuLabel,
|
|
DropdownMenuSeparator,
|
|
DropdownMenuTrigger,
|
|
} from '@/components/ui/dropdown-menu'
|
|
import {
|
|
DestructiveConfirmDialog,
|
|
useDestructiveConfirm,
|
|
} from '@/components/ui/destructive-confirm-dialog'
|
|
import {
|
|
AlertCircle,
|
|
AlertTriangle,
|
|
CheckCircle2,
|
|
ExternalLink,
|
|
FileCheck,
|
|
Info,
|
|
Link2,
|
|
Loader2,
|
|
MoreHorizontal,
|
|
Send,
|
|
ShieldAlert,
|
|
} from 'lucide-react'
|
|
import type { VatPeriodType } from '@/types'
|
|
import { formatRedovisare, formatRedovisningsperiod } from '@/lib/skatteverket/format'
|
|
import { useCapability } from '@/contexts/CompanyContext'
|
|
import { CAPABILITY } from '@/lib/entitlements/keys'
|
|
import { UpgradeNote } from '@/components/billing/UpgradeNote'
|
|
import { InfoTooltip } from '@/components/ui/info-tooltip'
|
|
|
|
interface SkatteverketStatus {
|
|
connected: boolean
|
|
expired?: boolean
|
|
canRefresh?: boolean
|
|
scope?: string
|
|
expiresAt?: string
|
|
}
|
|
|
|
/**
|
|
* Codes from /lib/api-client.ts's SkatteverketAuthError that mean "the user
|
|
* needs to reconnect with BankID before this action can succeed". When the API
|
|
* returns one of these codes we flip the local status.expired flag so the
|
|
* expired-session attn line with its "Förnya med BankID" action surfaces,
|
|
* even if the upstream /status endpoint hasn't reflected the change yet.
|
|
*/
|
|
const AUTH_RECONNECT_CODES = new Set([
|
|
'NOT_CONNECTED',
|
|
'SESSION_EXPIRED',
|
|
'REFRESH_EXHAUSTED',
|
|
'TOKEN_REVOKED',
|
|
'TOKEN_CORRUPTED',
|
|
'MISSING_SCOPE',
|
|
])
|
|
|
|
// Shape per Skatteverket Momsdeklaration v1.0.24 RAML
|
|
// (kontrollResultat.resultat[].{kod, status, beskrivning})
|
|
interface KontrollResult {
|
|
kod: string
|
|
status: 'ERROR' | 'WARNING'
|
|
beskrivning: string
|
|
}
|
|
|
|
interface SkatteverketPanelProps {
|
|
periodType: VatPeriodType
|
|
year: number
|
|
period: number
|
|
/**
|
|
* Selected räkenskapsår for helårsmoms. The SKV redovisningsperiod for
|
|
* yearly filers is the FY-end month (broken FYs do not end in December),
|
|
* and the `year` prop is not maintained in yearly mode, so both the period
|
|
* id and the fiscal-year end ride along explicitly.
|
|
*/
|
|
fiscalPeriodId?: string
|
|
fiscalYearEnd?: { year: number; month: number }
|
|
hasData: boolean
|
|
/**
|
|
* True when the momsdeklaration's filing gate is closed. Blocks
|
|
* validate/submit: SKV only validates internal arithmetic, so a locally
|
|
* broken declaration would pass their checks and still be materially wrong.
|
|
*
|
|
* The panel deliberately owns NO gate logic of its own. The value is
|
|
* `isFilingBlocked(checks)` (`lib/reports/vat-filing-gate.ts`) computed once
|
|
* in VatDeclarationView over the exact same check array that feeds the
|
|
* "Kontroll av underlaget" banner and the stegen counters, so this button
|
|
* can never be enabled while that section claims (or hides) a problem.
|
|
* Never re-derive it here from a narrower source.
|
|
*/
|
|
localBlocked: boolean
|
|
}
|
|
|
|
/**
|
|
* One feedback slot: exactly one message at a time, replaced at the end of
|
|
* each action. 'info' is for neutral lookups ("inget utkast hittades"):
|
|
* rendering those as success taught users that green means nothing.
|
|
*/
|
|
interface Notice {
|
|
kind: 'error' | 'success' | 'info'
|
|
text: string
|
|
}
|
|
|
|
function formatAmount(amount: number): string {
|
|
return amount.toLocaleString('sv-SE', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
|
}
|
|
|
|
const ORG_NUMBER_MISSING_NOTICE: Notice = {
|
|
kind: 'error',
|
|
text: 'Organisationsnummer saknas. Ange det under Inställningar innan du använder Skatteverket-kopplingen.',
|
|
}
|
|
|
|
function isOrgNumberMissing(err: unknown): boolean {
|
|
return err instanceof Error && err.message === 'Organisationsnummer saknas'
|
|
}
|
|
|
|
/**
|
|
* In-flight labels for actions with no visible button while running (the
|
|
* overflow-menu actions close the menu on select): rendered as a status row
|
|
* so a slow SKV round-trip is never silent.
|
|
*/
|
|
const ACTION_IN_FLIGHT_LABELS: Record<string, string> = {
|
|
validate: 'Validerar deklarationen...',
|
|
draft: 'Sparar utkast...',
|
|
lock: 'Låser utkastet...',
|
|
fetchDraft: 'Hämtar utkast...',
|
|
check: 'Kontrollerar inlämning...',
|
|
fetchDecided: 'Hämtar beslut...',
|
|
unlock: 'Låser upp...',
|
|
delete: 'Raderar utkast...',
|
|
disconnect: 'Kopplar bort Skatteverket...',
|
|
}
|
|
|
|
const SKV_ENABLED = ENABLED_EXTENSION_IDS.has('skatteverket')
|
|
|
|
export function SkatteverketPanel(props: SkatteverketPanelProps) {
|
|
if (!SKV_ENABLED) return null
|
|
return <SkatteverketPanelInner {...props} />
|
|
}
|
|
|
|
function SkatteverketPanelInner({
|
|
periodType,
|
|
year,
|
|
period,
|
|
fiscalPeriodId,
|
|
fiscalYearEnd,
|
|
hasData,
|
|
localBlocked,
|
|
}: SkatteverketPanelProps) {
|
|
// In yearly mode the year picker is replaced by the räkenskapsår selector,
|
|
// so the `year` prop is stale (stuck at the current year). Every SKV call
|
|
// must target the FY-end year instead.
|
|
const effectiveYear = periodType === 'yearly' && fiscalYearEnd ? fiscalYearEnd.year : year
|
|
const hasSkvCapability = useCapability(CAPABILITY.skatteverket)
|
|
const { dialogProps, confirm } = useDestructiveConfirm()
|
|
const [status, setStatus] = useState<SkatteverketStatus | null>(null)
|
|
const [loading, setLoading] = useState(true)
|
|
const [actionLoading, setActionLoading] = useState<string | null>(null)
|
|
const [notice, setNotice] = useState<Notice | null>(null)
|
|
const [kontroller, setKontroller] = useState<KontrollResult[]>([])
|
|
const [signeringslank, setSigneringslank] = useState<string | null>(null)
|
|
const [submitted, setSubmitted] = useState<{
|
|
kvittensnummer?: string
|
|
tidpunkt?: string
|
|
} | null>(null)
|
|
|
|
// Per-period SKV state resets when the picker changes (render-phase
|
|
// adjustment): a signing link, kvittens, or kontrollresultat fetched for
|
|
// one period must never render as if it belonged to another. Without this,
|
|
// the visibilitychange auto-check could stamp "Deklarationen har lämnats
|
|
// in" for a different period than the one being signed.
|
|
const periodKey = `${periodType}:${effectiveYear}:${period}:${fiscalPeriodId ?? ''}`
|
|
const [appliedPeriodKey, setAppliedPeriodKey] = useState(periodKey)
|
|
if (appliedPeriodKey !== periodKey) {
|
|
setAppliedPeriodKey(periodKey)
|
|
setKontroller([])
|
|
setSigneringslank(null)
|
|
setSubmitted(null)
|
|
setNotice(null)
|
|
}
|
|
|
|
/**
|
|
* Apply an API JSON error result. When the error indicates the SKV session
|
|
* has expired/been revoked/lost scope, immediately reflect that in the
|
|
* local status so the "Förnya session" CTA appears next to the message:
|
|
* the user shouldn't have to wait for /status to catch up.
|
|
* Extension routes return a FLAT { error: string, code } shape, unlike the
|
|
* core routes' nested envelope: do not unify the parsers.
|
|
*/
|
|
const applyApiError = useCallback((result: { error?: string; code?: string } | null) => {
|
|
if (!result?.error) return false
|
|
setNotice({ kind: 'error', text: result.error })
|
|
if (result.code && AUTH_RECONNECT_CODES.has(result.code)) {
|
|
setStatus((prev) => prev ? { ...prev, expired: true } : prev)
|
|
}
|
|
return true
|
|
}, [])
|
|
|
|
const fetchStatus = useCallback(async () => {
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/status')
|
|
if (res.ok) {
|
|
const data = await res.json()
|
|
setStatus(data)
|
|
}
|
|
} catch {
|
|
// Extension might not be enabled
|
|
} finally {
|
|
setLoading(false)
|
|
}
|
|
}, [])
|
|
|
|
useEffect(() => {
|
|
fetchStatus()
|
|
|
|
// Check URL params for OAuth callback results
|
|
const params = new URLSearchParams(window.location.search)
|
|
if (params.get('skv_connected') === 'true') {
|
|
setNotice({ kind: 'success', text: 'Ansluten till Skatteverket' })
|
|
fetchStatus()
|
|
// Clean URL
|
|
const url = new URL(window.location.href)
|
|
url.searchParams.delete('skv_connected')
|
|
window.history.replaceState({}, '', url.toString())
|
|
}
|
|
const skvError = params.get('skv_error')
|
|
if (skvError) {
|
|
setNotice({ kind: 'error', text: decodeURIComponent(skvError) })
|
|
const url = new URL(window.location.href)
|
|
url.searchParams.delete('skv_error')
|
|
window.history.replaceState({}, '', url.toString())
|
|
}
|
|
}, [fetchStatus])
|
|
|
|
const handleConnect = () => {
|
|
// return_to brings the user back to the momsdeklaration after the BankID
|
|
// round-trip; the authorize route's default otherwise lands on the report
|
|
// library. The callback appends skv_connected/skv_error itself.
|
|
window.location.href =
|
|
'/api/extensions/ext/skatteverket/authorize?return_to=' +
|
|
encodeURIComponent('/reports/vat-declaration')
|
|
}
|
|
|
|
const handleDisconnect = async () => {
|
|
setActionLoading('disconnect')
|
|
setNotice(null)
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/disconnect', {
|
|
method: 'POST',
|
|
})
|
|
if (res.ok) {
|
|
setStatus({ connected: false })
|
|
setNotice(null)
|
|
setKontroller([])
|
|
setSigneringslank(null)
|
|
setSubmitted(null)
|
|
} else {
|
|
const result = await res.json().catch(() => ({}))
|
|
if (!applyApiError(result)) {
|
|
setNotice({ kind: 'error', text: `Kunde inte koppla bort (${res.status})` })
|
|
}
|
|
}
|
|
} catch {
|
|
setNotice({ kind: 'error', text: 'Kunde inte koppla bort' })
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
const handleValidate = async () => {
|
|
if (localBlocked) {
|
|
setNotice({
|
|
kind: 'error',
|
|
text:
|
|
'Åtgärda felen under Kontroll av underlaget högst upp på sidan innan ' +
|
|
'du skickar till Skatteverket.',
|
|
})
|
|
return
|
|
}
|
|
setActionLoading('validate')
|
|
setNotice(null)
|
|
setKontroller([])
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/declaration/validate', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ periodType, year: effectiveYear, period, fiscalPeriodId }),
|
|
})
|
|
const result = await res.json()
|
|
if (applyApiError(result)) {
|
|
// surfaced + status updated; nothing more to do
|
|
} else {
|
|
const controls: KontrollResult[] = result.data?.kontrollResultat?.resultat || []
|
|
setKontroller(controls)
|
|
if (controls.length === 0) {
|
|
// SKV's OK only confirms arithmetic: it does NOT confirm that the
|
|
// declaration is materially correct. We say so explicitly so the
|
|
// user doesn't read this as a green light for actual filing.
|
|
setNotice({
|
|
kind: 'success',
|
|
text:
|
|
'Skatteverket har inga tekniska invändningar mot deklarationen. ' +
|
|
'Kontrollera siffrorna i förhandsgranskningen innan du skickar in.',
|
|
})
|
|
} else {
|
|
const errors = controls.filter(k => k.status === 'ERROR')
|
|
if (errors.length > 0) {
|
|
setNotice({ kind: 'error', text: `${errors.length} valideringsfel hittades` })
|
|
} else {
|
|
setNotice({
|
|
kind: 'success',
|
|
text: 'Skatteverket har inga tekniska invändningar (med varningar)',
|
|
})
|
|
}
|
|
}
|
|
}
|
|
} catch {
|
|
setNotice({ kind: 'error', text: 'Kunde inte validera deklarationen' })
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
const handleSaveDraft = async () => {
|
|
if (localBlocked) {
|
|
setNotice({
|
|
kind: 'error',
|
|
text:
|
|
'Åtgärda felen under Kontroll av underlaget högst upp på sidan innan ' +
|
|
'du sparar utkastet hos Skatteverket.',
|
|
})
|
|
return
|
|
}
|
|
setActionLoading('draft')
|
|
setNotice(null)
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/declaration/draft', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ periodType, year: effectiveYear, period, fiscalPeriodId }),
|
|
})
|
|
const result = await res.json()
|
|
if (applyApiError(result)) {
|
|
// surfaced + status updated; nothing more to do
|
|
} else {
|
|
const controls: KontrollResult[] = result.data?.kontrollResultat?.resultat || []
|
|
setKontroller(controls)
|
|
const errors = controls.filter(k => k.status === 'ERROR')
|
|
if (errors.length === 0) {
|
|
setNotice({ kind: 'success', text: 'Utkast sparat i Eget utrymme hos Skatteverket' })
|
|
} else {
|
|
setNotice({
|
|
kind: 'error',
|
|
text: `Utkastet sparades men har ${errors.length} valideringsfel`,
|
|
})
|
|
}
|
|
}
|
|
} catch {
|
|
setNotice({ kind: 'error', text: 'Kunde inte spara utkast' })
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
// Helper to get redovisare from settings
|
|
const getRedovisare = useCallback(async (): Promise<string> => {
|
|
const res = await fetch('/api/settings')
|
|
const { data } = await res.json()
|
|
if (!data?.org_number) throw new Error('Organisationsnummer saknas')
|
|
return formatRedovisare(data.org_number, data.entity_type)
|
|
}, [])
|
|
|
|
const getRedovisningsperiod = useCallback((): string => {
|
|
return formatRedovisningsperiod(periodType, year, period, fiscalYearEnd)
|
|
}, [periodType, year, period, fiscalYearEnd])
|
|
|
|
const handleLock = async () => {
|
|
setActionLoading('lock')
|
|
setNotice(null)
|
|
try {
|
|
const res = await fetch(
|
|
`/api/extensions/ext/skatteverket/declaration/lock?redovisare=${encodeURIComponent(
|
|
await getRedovisare()
|
|
)}&redovisningsperiod=${getRedovisningsperiod()}`,
|
|
{ method: 'PUT' }
|
|
)
|
|
const result = await res.json()
|
|
if (applyApiError(result)) {
|
|
// surfaced + status updated; nothing more to do
|
|
} else if (result.data?.signeringsLank) {
|
|
setSigneringslank(result.data.signeringsLank)
|
|
setNotice({
|
|
kind: 'success',
|
|
text: 'Utkastet är låst. Öppna signeringslänken för att signera med BankID.',
|
|
})
|
|
}
|
|
} catch (err) {
|
|
setNotice(
|
|
isOrgNumberMissing(err)
|
|
? ORG_NUMBER_MISSING_NOTICE
|
|
: { kind: 'error', text: 'Kunde inte låsa utkastet' },
|
|
)
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* One-click filing: the server chains kontrollera -> utkast -> lås and
|
|
* returns the signing link. Stage-aware failures come back with a `stage`
|
|
* discriminator: `validation` stopped before anything was written at SKV,
|
|
* `lock` with `draft_saved` means the draft survives in Eget utrymme and
|
|
* only the lock step needs a retry (available under Fler åtgärder).
|
|
*/
|
|
const handleSubmit = async () => {
|
|
if (localBlocked) {
|
|
setNotice({
|
|
kind: 'error',
|
|
text:
|
|
'Åtgärda felen under Kontroll av underlaget högst upp på sidan innan ' +
|
|
'du skickar till Skatteverket.',
|
|
})
|
|
return
|
|
}
|
|
setActionLoading('submit')
|
|
setNotice(null)
|
|
setKontroller([])
|
|
try {
|
|
const res = await fetch('/api/extensions/ext/skatteverket/declaration/submit', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ periodType, year: effectiveYear, period, fiscalPeriodId }),
|
|
})
|
|
const result = await res.json()
|
|
|
|
if (res.ok && result.data?.signeringsLank) {
|
|
const controls: KontrollResult[] = result.data?.kontrollResultat?.resultat || []
|
|
setKontroller(controls)
|
|
setSigneringslank(result.data.signeringsLank)
|
|
setNotice({
|
|
kind: 'success',
|
|
text:
|
|
'Deklarationen är kontrollerad, sparad och låst. Öppna signeringslänken ' +
|
|
'för att signera med BankID.',
|
|
})
|
|
return
|
|
}
|
|
|
|
if (result.stage) {
|
|
const controls: KontrollResult[] = result.kontrollResultat?.resultat || []
|
|
if (controls.length > 0) setKontroller(controls)
|
|
if (result.stage === 'validation') {
|
|
setNotice({
|
|
kind: 'error',
|
|
text: result.error || 'Skatteverket hittade valideringsfel i deklarationen.',
|
|
})
|
|
} else if (result.stage === 'lock' && result.draft_saved) {
|
|
setNotice({
|
|
kind: 'error',
|
|
text:
|
|
'Utkastet är sparat hos Skatteverket men kunde inte låsas för signering. ' +
|
|
'Försök igen med "Lås och signera" under Fler åtgärder.',
|
|
})
|
|
} else {
|
|
setNotice({
|
|
kind: 'error',
|
|
text: result.error || 'Kunde inte skicka deklarationen till Skatteverket',
|
|
})
|
|
}
|
|
return
|
|
}
|
|
|
|
if (!applyApiError(result)) {
|
|
setNotice({
|
|
kind: 'error',
|
|
text: 'Kunde inte skicka deklarationen till Skatteverket',
|
|
})
|
|
}
|
|
} catch {
|
|
setNotice({ kind: 'error', text: 'Kunde inte skicka deklarationen till Skatteverket' })
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
const handleUnlock = async () => {
|
|
setActionLoading('unlock')
|
|
setNotice(null)
|
|
try {
|
|
const res = await fetch(
|
|
`/api/extensions/ext/skatteverket/declaration/lock?redovisare=${encodeURIComponent(
|
|
await getRedovisare()
|
|
)}&redovisningsperiod=${getRedovisningsperiod()}`,
|
|
{ method: 'DELETE' }
|
|
)
|
|
const result = await res.json()
|
|
if (applyApiError(result)) {
|
|
// surfaced + status updated; nothing more to do
|
|
} else {
|
|
setSigneringslank(null)
|
|
setNotice({ kind: 'success', text: 'Utkastet har låsts upp' })
|
|
}
|
|
} catch (err) {
|
|
setNotice(
|
|
isOrgNumberMissing(err)
|
|
? ORG_NUMBER_MISSING_NOTICE
|
|
: { kind: 'error', text: 'Kunde inte låsa upp utkastet' },
|
|
)
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* `silent` suppresses the "inget hittades" notice: used by the automatic
|
|
* re-check when the tab regains focus after the user signed at SKV, where
|
|
* a recurring "nothing found" message would just be noise.
|
|
*/
|
|
const handleCheckSubmitted = useCallback(async (silent = false) => {
|
|
setActionLoading('check')
|
|
setNotice(null)
|
|
try {
|
|
// periodType/year/period let the server complete the period's moms
|
|
// deadline when the filing is confirmed.
|
|
const res = await fetch(
|
|
`/api/extensions/ext/skatteverket/declaration/submitted?redovisare=${encodeURIComponent(
|
|
await getRedovisare()
|
|
)}&redovisningsperiod=${getRedovisningsperiod()}&periodType=${periodType}&year=${effectiveYear}&period=${period}`
|
|
)
|
|
const result = await res.json()
|
|
if (applyApiError(result)) {
|
|
// surfaced + status updated; nothing more to do
|
|
} else if (result.data) {
|
|
setSubmitted(result.data)
|
|
setNotice({ kind: 'success', text: 'Deklarationen har lämnats in' })
|
|
} else if (!silent) {
|
|
setNotice({ kind: 'info', text: 'Ingen inlämnad deklaration hittades för denna period' })
|
|
}
|
|
} catch (err) {
|
|
if (isOrgNumberMissing(err)) {
|
|
setNotice(ORG_NUMBER_MISSING_NOTICE)
|
|
} else if (!silent) {
|
|
setNotice({ kind: 'error', text: 'Kunde inte kontrollera inlämningsstatus' })
|
|
}
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}, [applyApiError, getRedovisare, getRedovisningsperiod, periodType, effectiveYear, period])
|
|
|
|
// While a signing link is outstanding, re-check submission status when the
|
|
// user returns to this tab: signing happens on Skatteverket's site, so the
|
|
// return trip is the natural moment for the kvittens to appear.
|
|
useEffect(() => {
|
|
if (!signeringslank || submitted) return
|
|
const onVisibilityChange = () => {
|
|
if (document.visibilityState === 'visible' && actionLoading === null) {
|
|
handleCheckSubmitted(true)
|
|
}
|
|
}
|
|
document.addEventListener('visibilitychange', onVisibilityChange)
|
|
return () => document.removeEventListener('visibilitychange', onVisibilityChange)
|
|
}, [signeringslank, submitted, actionLoading, handleCheckSubmitted])
|
|
|
|
const handleDeleteDraft = async () => {
|
|
setActionLoading('delete')
|
|
setNotice(null)
|
|
try {
|
|
const res = await fetch(
|
|
`/api/extensions/ext/skatteverket/declaration/draft?redovisare=${encodeURIComponent(
|
|
await getRedovisare()
|
|
)}&redovisningsperiod=${getRedovisningsperiod()}`,
|
|
{ method: 'DELETE' }
|
|
)
|
|
if (res.status === 204 || res.ok) {
|
|
setKontroller([])
|
|
setSigneringslank(null)
|
|
setNotice({ kind: 'success', text: 'Utkastet har raderats från Eget utrymme' })
|
|
} else {
|
|
const result = await res.json().catch(() => ({}))
|
|
if (!applyApiError(result)) {
|
|
setNotice({ kind: 'error', text: `Kunde inte radera utkast (${res.status})` })
|
|
}
|
|
}
|
|
} catch (err) {
|
|
setNotice(
|
|
isOrgNumberMissing(err)
|
|
? ORG_NUMBER_MISSING_NOTICE
|
|
: { kind: 'error', text: 'Kunde inte radera utkast' },
|
|
)
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
const handleFetchDraft = async () => {
|
|
setActionLoading('fetchDraft')
|
|
setNotice(null)
|
|
try {
|
|
const res = await fetch(
|
|
`/api/extensions/ext/skatteverket/declaration/draft?redovisare=${encodeURIComponent(
|
|
await getRedovisare()
|
|
)}&redovisningsperiod=${getRedovisningsperiod()}`
|
|
)
|
|
const result = await res.json()
|
|
if (applyApiError(result)) {
|
|
// surfaced + status updated; nothing more to do
|
|
} else if (!result.data) {
|
|
setNotice({ kind: 'info', text: 'Inget sparat utkast hittades för perioden' })
|
|
} else {
|
|
const locked = result.data?.locked ? ' (låst)' : ''
|
|
const summa = result.data?.momsuppgift?.summaMoms
|
|
const summaLabel = summa !== undefined ? `, summaMoms = ${formatAmount(summa)}` : ''
|
|
setNotice({ kind: 'success', text: `Sparat utkast hittades${locked}${summaLabel}` })
|
|
}
|
|
} catch (err) {
|
|
setNotice(
|
|
isOrgNumberMissing(err)
|
|
? ORG_NUMBER_MISSING_NOTICE
|
|
: { kind: 'error', text: 'Kunde inte hämta utkast' },
|
|
)
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
const handleFetchDecided = async () => {
|
|
setActionLoading('fetchDecided')
|
|
setNotice(null)
|
|
try {
|
|
const res = await fetch(
|
|
`/api/extensions/ext/skatteverket/declaration/decided?redovisare=${encodeURIComponent(
|
|
await getRedovisare()
|
|
)}&redovisningsperiod=${getRedovisningsperiod()}&periodType=${periodType}&year=${effectiveYear}&period=${period}`
|
|
)
|
|
const result = await res.json()
|
|
if (applyApiError(result)) {
|
|
// surfaced + status updated; nothing more to do
|
|
} else if (!result.data) {
|
|
setNotice({ kind: 'info', text: 'Inget beslut hittades för perioden' })
|
|
} else {
|
|
const tid = result.data?.beslutadTidpunkt
|
|
const tidLabel = tid ? ` (beslutad ${new Date(tid).toLocaleDateString('sv-SE')})` : ''
|
|
setNotice({ kind: 'success', text: `Beslut hittades${tidLabel}` })
|
|
}
|
|
} catch (err) {
|
|
setNotice(
|
|
isOrgNumberMissing(err)
|
|
? ORG_NUMBER_MISSING_NOTICE
|
|
: { kind: 'error', text: 'Kunde inte hämta beslutade uppgifter' },
|
|
)
|
|
} finally {
|
|
setActionLoading(null)
|
|
}
|
|
}
|
|
|
|
const handleDeleteDraftConfirmed = async () => {
|
|
const ok = await confirm({
|
|
title: 'Radera utkastet hos Skatteverket?',
|
|
description:
|
|
'Utkastet tas bort från Eget utrymme hos Skatteverket. Detta går inte att ångra.',
|
|
confirmLabel: 'Radera utkast',
|
|
})
|
|
if (!ok) return
|
|
await handleDeleteDraft()
|
|
}
|
|
|
|
const handleDisconnectConfirmed = async () => {
|
|
const ok = await confirm({
|
|
title: 'Koppla bort Skatteverket?',
|
|
description:
|
|
'Anslutningen tas bort och du behöver ansluta med BankID igen för att kunna skicka direkt.',
|
|
confirmLabel: 'Koppla bort',
|
|
})
|
|
if (!ok) return
|
|
await handleDisconnect()
|
|
}
|
|
|
|
if (loading) {
|
|
return (
|
|
<section>
|
|
<div className="space-y-4">
|
|
<Skeleton className="h-5 w-48" />
|
|
<Skeleton className="h-24" />
|
|
</div>
|
|
</section>
|
|
)
|
|
}
|
|
|
|
// Paywall: direct API submission is the paid convenience; manual filing at
|
|
// skatteverket.se stays free and is owned by the "Lämna in" card above.
|
|
// Rendered BEFORE the connected check so a company that connected during
|
|
// trial sees the upsell instead of action buttons that would 403.
|
|
if (!hasSkvCapability) {
|
|
return (
|
|
<section>
|
|
<div className="mb-3">
|
|
<h3 className="flex items-center gap-2 font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
|
<FileCheck className="h-4 w-4" />
|
|
Skicka direkt till Skatteverket (valfritt)
|
|
</h3>
|
|
</div>
|
|
<div className="space-y-4">
|
|
<p className="text-sm text-muted-foreground">
|
|
Med ett abonnemang kan du ansluta med BankID och skicka deklarationen
|
|
direkt härifrån, samt validera, spara utkast och signera.
|
|
</p>
|
|
<UpgradeNote>
|
|
Direktinlämning till Skatteverket kräver ett abonnemang.
|
|
</UpgradeNote>
|
|
</div>
|
|
</section>
|
|
)
|
|
}
|
|
|
|
// Not connected. The momsdeklaration is already complete and can be filed
|
|
// manually at skatteverket.se with no connection (the "Lämna in" card above
|
|
// owns that path). Connecting is an optional convenience for submitting
|
|
// directly from Accounted, so frame it that way.
|
|
if (!status?.connected) {
|
|
return (
|
|
<section>
|
|
<div className="mb-3">
|
|
<h3 className="flex items-center gap-2 font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
|
<FileCheck className="h-4 w-4" />
|
|
Skicka direkt till Skatteverket (valfritt)
|
|
</h3>
|
|
</div>
|
|
<div className="space-y-4">
|
|
{notice?.kind === 'error' && (
|
|
<div
|
|
role="alert"
|
|
className="flex items-start gap-2 text-sm text-destructive bg-destructive/5 rounded-lg p-3"
|
|
>
|
|
<AlertCircle className="h-4 w-4 mt-1 shrink-0" />
|
|
<span>{notice.text}</span>
|
|
</div>
|
|
)}
|
|
<p className="text-sm text-muted-foreground">
|
|
Vill du slippa skriva in siffrorna själv kan du ansluta med BankID och
|
|
skicka deklarationen direkt härifrån, samt validera, spara utkast och
|
|
signera.
|
|
</p>
|
|
<Button onClick={handleConnect} className="gap-2">
|
|
<Link2 className="h-4 w-4" />
|
|
Anslut med BankID
|
|
</Button>
|
|
</div>
|
|
</section>
|
|
)
|
|
}
|
|
|
|
// Connected: show actions
|
|
const hasErrors = kontroller.some(k => k.status === 'ERROR')
|
|
|
|
return (
|
|
<section>
|
|
<div className="mb-3">
|
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
|
<h3 className="flex items-center gap-2 font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
|
<FileCheck className="h-4 w-4" />
|
|
Skicka direkt till Skatteverket
|
|
</h3>
|
|
<div className="flex flex-wrap items-center gap-2">
|
|
{/* Connected is the normal state here (the not-connected branch is
|
|
a different section): muted text, never a chip. The expired
|
|
session is the one exception and gets the attn sentence below
|
|
instead of a badge-and-button cluster. */}
|
|
{!status.expired && (
|
|
<span className="text-xs text-muted-foreground">Ansluten</span>
|
|
)}
|
|
{/* Read-only lookups and recovery actions live in the overflow
|
|
menu: the visible surface stays the forward path (validera,
|
|
spara utkast, lås och signera). */}
|
|
<DropdownMenu>
|
|
<DropdownMenuTrigger asChild>
|
|
<Button variant="ghost" size="icon" aria-label="Fler åtgärder">
|
|
<MoreHorizontal className="h-4 w-4" />
|
|
</Button>
|
|
</DropdownMenuTrigger>
|
|
<DropdownMenuContent align="end" className="w-72">
|
|
{/* The demoted step-by-step actions: the visible surface is
|
|
the one-click "Skicka till Skatteverket" button; these
|
|
remain for partial retries (e.g. lock-only after a lock
|
|
failure) and for users who want to inspect each step. */}
|
|
<DropdownMenuLabel>Steg för steg</DropdownMenuLabel>
|
|
<DropdownMenuItem
|
|
disabled={!hasData || localBlocked || actionLoading !== null}
|
|
onSelect={() => handleValidate()}
|
|
>
|
|
<div>
|
|
<p>Validera</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Kontrollera deklarationen hos Skatteverket utan att spara
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
disabled={!hasData || localBlocked || actionLoading !== null}
|
|
onSelect={() => handleSaveDraft()}
|
|
>
|
|
<div>
|
|
<p>Spara utkast</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Spara deklarationen som utkast i Eget utrymme
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
disabled={!hasData || actionLoading !== null}
|
|
onSelect={() => handleLock()}
|
|
>
|
|
<div>
|
|
<p>Lås och signera</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Lås det sparade utkastet och hämta signeringslänken
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuSeparator />
|
|
<DropdownMenuLabel>Status hos Skatteverket</DropdownMenuLabel>
|
|
<DropdownMenuItem
|
|
disabled={actionLoading !== null}
|
|
onSelect={() => handleFetchDraft()}
|
|
>
|
|
<div>
|
|
<p>Hämta utkast</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Hämta sparat utkast från Eget utrymme
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
disabled={actionLoading !== null}
|
|
onSelect={() => handleCheckSubmitted()}
|
|
>
|
|
<div>
|
|
<p>Kontrollera inlämning</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Kontrollera om en signerad deklaration har lämnats in
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
disabled={actionLoading !== null}
|
|
onSelect={() => handleFetchDecided()}
|
|
>
|
|
<div>
|
|
<p>Hämta beslut</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Hämta Skatteverkets beslut för perioden
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuSeparator />
|
|
<DropdownMenuLabel>Återställning</DropdownMenuLabel>
|
|
<DropdownMenuItem
|
|
disabled={actionLoading !== null}
|
|
onSelect={() => handleUnlock()}
|
|
>
|
|
<div>
|
|
<p>Lås upp</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Lås upp en låst period så att utkastet kan ändras
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuItem
|
|
disabled={actionLoading !== null}
|
|
onSelect={() => handleDeleteDraftConfirmed()}
|
|
>
|
|
<div>
|
|
<p>Radera utkast...</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Radera sparat utkast från Eget utrymme
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
<DropdownMenuSeparator />
|
|
<DropdownMenuItem
|
|
disabled={actionLoading !== null}
|
|
onSelect={() => handleDisconnectConfirmed()}
|
|
className="text-destructive focus:text-destructive"
|
|
>
|
|
<div>
|
|
<p>Koppla bort Skatteverket...</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Kräver ny BankID-anslutning för direktinlämning
|
|
</p>
|
|
</div>
|
|
</DropdownMenuItem>
|
|
</DropdownMenuContent>
|
|
</DropdownMenu>
|
|
</div>
|
|
</div>
|
|
{status.expired && (
|
|
<p className="mt-2 text-[12.5px] leading-5 text-attn">
|
|
Sessionen mot Skatteverket har gått ut.{' '}
|
|
<button
|
|
type="button"
|
|
onClick={handleConnect}
|
|
className="underline underline-offset-2 hover:opacity-80"
|
|
>
|
|
Förnya med BankID
|
|
</button>
|
|
</p>
|
|
)}
|
|
</div>
|
|
<div className="space-y-4">
|
|
{/* In-flight status for overflow-menu actions: their menu closes on
|
|
select, so this row is the only visible sign of work. */}
|
|
{actionLoading && ACTION_IN_FLIGHT_LABELS[actionLoading] && (
|
|
<div
|
|
role="status"
|
|
aria-live="polite"
|
|
className="flex items-center gap-2 text-sm text-muted-foreground"
|
|
>
|
|
<Loader2 className="h-4 w-4 animate-spin" />
|
|
{ACTION_IN_FLIGHT_LABELS[actionLoading]}
|
|
</div>
|
|
)}
|
|
|
|
{/* Single feedback slot: errors are assertive alerts, success/info are
|
|
polite status messages on the neutral surface. */}
|
|
{notice && (
|
|
notice.kind === 'error' ? (
|
|
<div
|
|
role="alert"
|
|
className="flex items-start gap-2 text-sm text-destructive bg-destructive/5 rounded-lg p-3"
|
|
>
|
|
<AlertCircle className="h-4 w-4 mt-1 shrink-0" />
|
|
<span>{notice.text}</span>
|
|
</div>
|
|
) : (
|
|
<div
|
|
role="status"
|
|
aria-live="polite"
|
|
className="flex items-start gap-2 text-sm rounded-lg border border-border bg-muted/30 p-3"
|
|
>
|
|
{notice.kind === 'success' ? (
|
|
<CheckCircle2 className="h-4 w-4 mt-1 shrink-0 text-success" />
|
|
) : (
|
|
<Info className="h-4 w-4 mt-1 shrink-0 text-muted-foreground" />
|
|
)}
|
|
<span>{notice.text}</span>
|
|
</div>
|
|
)
|
|
)}
|
|
|
|
{/* Validation results from Skatteverket */}
|
|
{kontroller.length > 0 && (
|
|
<div className="space-y-2">
|
|
<h3 className="font-sans text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
|
Skatteverkets valideringsresultat
|
|
</h3>
|
|
{kontroller.map((k, i) => (
|
|
<div
|
|
key={`${k.kod}-${i}`}
|
|
className={`flex items-start gap-2 text-sm rounded-lg p-3 ${
|
|
k.status === 'ERROR'
|
|
? 'bg-destructive/5 text-destructive'
|
|
: 'border border-border bg-muted/30'
|
|
}`}
|
|
>
|
|
{k.status === 'ERROR' ? (
|
|
<ShieldAlert className="h-4 w-4 mt-1 shrink-0" />
|
|
) : (
|
|
<AlertTriangle className="h-4 w-4 mt-1 shrink-0 text-warning" />
|
|
)}
|
|
<div>
|
|
<span className="font-mono text-xs mr-2">{k.kod}</span>
|
|
{k.beskrivning}
|
|
</div>
|
|
</div>
|
|
))}
|
|
</div>
|
|
)}
|
|
|
|
{/* Submitted confirmation */}
|
|
{submitted && (
|
|
<div className="rounded-lg border border-border p-3 space-y-1">
|
|
<p className="text-sm font-medium flex items-center gap-2">
|
|
<CheckCircle2 className="h-4 w-4 text-success" />
|
|
Inlämnad
|
|
</p>
|
|
{submitted.kvittensnummer && (
|
|
<p className="text-xs text-muted-foreground">
|
|
Kvittensnummer: <span className="font-mono">{submitted.kvittensnummer}</span>
|
|
</p>
|
|
)}
|
|
{submitted.tidpunkt && (
|
|
<p className="text-xs text-muted-foreground">
|
|
Tidpunkt: {new Date(submitted.tidpunkt).toLocaleString('sv-SE')}
|
|
</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* Signing link */}
|
|
{signeringslank && (
|
|
<div className="rounded-lg border border-border bg-muted/30 p-3 space-y-2">
|
|
<p className="text-sm font-medium">Utkastet är låst och redo att signeras</p>
|
|
<p className="text-xs text-muted-foreground">
|
|
Öppna länken nedan och signera med BankID på Skatteverkets sida. När du
|
|
kommer tillbaka hit kontrolleras inlämningen automatiskt.
|
|
</p>
|
|
<div className="flex flex-wrap gap-2">
|
|
<Button variant="outline" asChild className="gap-2">
|
|
<a href={signeringslank} target="_blank" rel="noopener noreferrer">
|
|
<ExternalLink className="h-4 w-4" />
|
|
Öppna signeringssidan
|
|
</a>
|
|
</Button>
|
|
<Button
|
|
variant="outline"
|
|
onClick={() => handleCheckSubmitted()}
|
|
disabled={actionLoading !== null}
|
|
className="gap-2"
|
|
>
|
|
{actionLoading === 'check' ? (
|
|
<Loader2 className="h-4 w-4 animate-spin" />
|
|
) : (
|
|
<CheckCircle2 className="h-4 w-4" />
|
|
)}
|
|
Kontrollera inlämning
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* Forward lifecycle: one primary action. The individual steps live
|
|
in the overflow menu under "Steg för steg". */}
|
|
<div className="flex flex-wrap items-center gap-2 pt-1">
|
|
<Button
|
|
onClick={handleSubmit}
|
|
disabled={!hasData || localBlocked || actionLoading !== null}
|
|
className="gap-2"
|
|
>
|
|
{actionLoading === 'submit' ? (
|
|
<Loader2 className="h-4 w-4 animate-spin" />
|
|
) : (
|
|
<Send className="h-4 w-4" />
|
|
)}
|
|
Skicka till Skatteverket
|
|
</Button>
|
|
</div>
|
|
|
|
<p className="text-xs text-muted-foreground">
|
|
Deklarationen kontrolleras, sparas som utkast i{' '}
|
|
<InfoTooltip
|
|
variant="help"
|
|
content="Ditt företags privata yta hos Skatteverket. Utkast som sparas där räknas inte som inlämnade förrän de har signerats med BankID."
|
|
>
|
|
<span>Eget utrymme</span>
|
|
</InfoTooltip>{' '}
|
|
och låses för signering med BankID hos Skatteverket. Inget lämnas in
|
|
förrän du har signerat.
|
|
</p>
|
|
|
|
{/* Visible disabled-state explanations: title attributes never show
|
|
on disabled buttons. */}
|
|
{localBlocked && (
|
|
<p className="text-sm text-destructive">
|
|
Åtgärda felen under Kontroll av underlaget högst upp på sidan innan du
|
|
skickar in.
|
|
</p>
|
|
)}
|
|
{hasErrors && !localBlocked && (
|
|
<p className="text-sm text-muted-foreground">
|
|
Valideringsfelen ovan måste åtgärdas innan deklarationen kan lämnas in.
|
|
</p>
|
|
)}
|
|
</div>
|
|
<DestructiveConfirmDialog {...dialogProps} />
|
|
</section>
|
|
)
|
|
}
|