fix: similar-sweep currency remediation, security hardening and v1 API fixes (#1215)
* 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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) <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> * 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 <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5
parent
a43a8b03cf
commit
f24b26a139
File diff suppressed because one or more lines are too long
@@ -52,3 +52,21 @@ CRON_SECRET=generate-a-random-secret
|
||||
# NEXT_PUBLIC_BOLAGSVERKET_FILING_ENABLED=false
|
||||
# BOLAGSVERKET_ARELLE_VALIDATOR_URL=
|
||||
# BOLAGSVERKET_ARELLE_VALIDATOR_TOKEN=
|
||||
|
||||
# ── Optional: error tracking / observability ──────────────
|
||||
# The app routes every error-level log line, and anything flagged
|
||||
# `alert: true`, to a provider-agnostic sink (lib/observability). No vendor is
|
||||
# wired up: the sink is a NO-OP until an adapter is registered with
|
||||
# registerObservabilitySink(). Setting these variables alone changes nothing,
|
||||
# and self-hosted installs can leave them unset forever.
|
||||
#
|
||||
# Names are generic placeholders. When a provider is picked, either keep these
|
||||
# and read them in the adapter, or replace them with the vendor's own names.
|
||||
# OBSERVABILITY_DSN= # server-side ingest endpoint / key
|
||||
# NEXT_PUBLIC_OBSERVABILITY_DSN= # browser ingest endpoint / key, if used
|
||||
# Optional overrides. Both have sensible defaults: the environment falls back
|
||||
# to VERCEL_ENV then NODE_ENV, and the release falls back to
|
||||
# NEXT_PUBLIC_BUILD_ID (the commit sha next.config.ts inlines at build time)
|
||||
# then VERCEL_GIT_COMMIT_SHA. Set them only when tagging must differ.
|
||||
# OBSERVABILITY_ENVIRONMENT=
|
||||
# OBSERVABILITY_RELEASE=
|
||||
|
||||
@@ -68,6 +68,12 @@ jobs:
|
||||
ignore-unfixed: true
|
||||
format: sarif
|
||||
output: trivy-results.sarif
|
||||
# Without this, trivy-action unsets TRIVY_SEVERITY when format is
|
||||
# sarif (entrypoint.sh: "Building SARIF report with all severities"),
|
||||
# silently discarding the CRITICAL,HIGH filter above. The exit code
|
||||
# then fires on any fixable CVE down to LOW, which is not the policy
|
||||
# documented here and turns routine low-severity noise into a red run.
|
||||
limit-severities-for-sarif: true
|
||||
|
||||
- name: Upload Trivy results to GitHub Security tab
|
||||
# if: always() so findings still reach the Security tab even though the
|
||||
|
||||
@@ -65,12 +65,23 @@ jobs:
|
||||
# OCI attestations, queryable via `docker buildx imagetools inspect`.
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
# Per-branch cache scope so a PR branch can't poison main's cache
|
||||
# layers. Fall back to main's cache on first build of a new branch.
|
||||
cache-from: |
|
||||
type=gha,scope=${{ github.ref_name }}
|
||||
type=gha,scope=main
|
||||
cache-to: type=gha,scope=${{ github.ref_name }},mode=max
|
||||
# Layer cache lives in GHCR, not the GitHub Actions cache. Two
|
||||
# platforms x mode=max is ~7 GB, which alone ate 70% of the repo's
|
||||
# 10 GB Actions cache quota and, because buildx refreshes every blob's
|
||||
# access time on each run, never aged out under LRU: it starved the
|
||||
# other workflows' caches instead. GHCR storage is free for public
|
||||
# repos and off that quota. mode=max is kept deliberately: mode=min
|
||||
# would drop the deps/builder stages and make every push redo
|
||||
# `npm ci` + `next build`.
|
||||
#
|
||||
# A single stable cache tag is safe here: this workflow only runs on
|
||||
# main and v*.*.* tags, and tags are cut from main, so there is no
|
||||
# untrusted ref that could poison the layers.
|
||||
#
|
||||
# image-manifest=true,oci-mediatypes=true is required by GHCR, which
|
||||
# rejects buildkit's default cache manifest media type.
|
||||
cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache
|
||||
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:buildcache,mode=max,image-manifest=true,oci-mediatypes=true
|
||||
|
||||
- name: Install cosign
|
||||
uses: sigstore/[email protected]
|
||||
|
||||
@@ -57,10 +57,23 @@ jobs:
|
||||
fi
|
||||
echo "number=$NUM" >> "$GITHUB_OUTPUT"
|
||||
- name: Install Anthropic Bedrock SDK
|
||||
# Pinned exact version + --ignore-scripts: this is the privileged job
|
||||
# (write token in env), so no floating @latest and no dependency
|
||||
# lifecycle scripts may execute here.
|
||||
run: npm install --no-save --no-package-lock --ignore-scripts @anthropic-ai/[email protected]
|
||||
# Installed ONE DIRECTORY ABOVE the checkout on purpose. Running this
|
||||
# inside the repo makes npm re-resolve the whole dependency tree from
|
||||
# package.json (--no-package-lock throws away the pinned resolutions),
|
||||
# and that re-resolution dies on an unrelated floating peer conflict
|
||||
# (@hookform/resolvers -> valibot), which silently killed this review on
|
||||
# every PR. Out of tree npm resolves this one package and nothing else,
|
||||
# so an unrelated peer conflict can never take the compliance gate down
|
||||
# again. Node still finds it: ESM bare specifiers walk up the parent
|
||||
# directories' node_modules. NODE_PATH is not an alternative here, the
|
||||
# ESM loader ignores it (CommonJS only).
|
||||
# Version tracks the exact package.json pin: 0.32.0 broke Bedrock
|
||||
# streaming in prod (DECISIONS.md 2026-07-08) and check:guards enforces
|
||||
# 0.29.1 repo-wide, so this job must not be the one place running an
|
||||
# unvetted build. Pinned exact + --ignore-scripts because this is the
|
||||
# privileged job (write token in env): no floating @latest, and no
|
||||
# dependency lifecycle scripts may execute here.
|
||||
run: npm install --prefix "$GITHUB_WORKSPACE/.." --no-save --no-package-lock --ignore-scripts @anthropic-ai/[email protected]
|
||||
- name: Run compliance review
|
||||
env:
|
||||
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
|
||||
|
||||
@@ -52,10 +52,16 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
# Deliberately no `cache: npm` here. This workflow runs on pull_request
|
||||
# only, so the cache is never written on main, and GitHub scopes caches
|
||||
# by ref: every PR uploaded its own 284 MB copy under an identical key
|
||||
# that no other PR could ever restore. Fourteen dead copies (4 GB, 40% of
|
||||
# the repo quota) accumulated in a single day. If this is ever worth
|
||||
# caching again, it has to be actions/cache/save on main plus
|
||||
# actions/cache/restore here, which is the only shape that gets hits.
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- run: npm ci
|
||||
|
||||
|
||||
+168
File diff suppressed because one or more lines are too long
+29
-41
@@ -17,6 +17,10 @@ import { isBankIdEnabled } from '@/lib/auth/bankid'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { detectWebmailHint } from '@/lib/auth/webmail-search'
|
||||
import { safeReturnTo } from '@/lib/auth/safe-return-to'
|
||||
import {
|
||||
consumeInviteCookie,
|
||||
INVITE_PROBLEM_MESSAGE_KEYS,
|
||||
} from '@/lib/auth/consume-invite-cookie'
|
||||
import { AuthPageSkeleton } from '@/components/auth/AuthPageSkeleton'
|
||||
|
||||
const branding = getBranding()
|
||||
@@ -59,8 +63,27 @@ function LoginPageContent() {
|
||||
const bankIdEnabled = isBankIdEnabled()
|
||||
const tAuth = useTranslations('auth')
|
||||
const tCommon = useTranslations('common')
|
||||
const tInvite = useTranslations('invite')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
|
||||
// Accept a pending invite, if any, and report a non-definitive failure.
|
||||
// Returns true when the caller should land the user in the app directly.
|
||||
// The invite cookie survives anything that is not a settled outcome, so
|
||||
// /onboarding and /select-company can retry acceptance server-side.
|
||||
const acceptPendingInvite = async (): Promise<boolean> => {
|
||||
const invite = await consumeInviteCookie()
|
||||
if (invite.accepted) return true
|
||||
if (invite.problem) {
|
||||
const keys = INVITE_PROBLEM_MESSAGE_KEYS[invite.problem]
|
||||
toast({
|
||||
title: tInvite(keys.title),
|
||||
description: tInvite(keys.body),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Reset cooldown timer
|
||||
useEffect(() => {
|
||||
if (!resetCooldownUntil) return
|
||||
@@ -114,26 +137,9 @@ function LoginPageContent() {
|
||||
}
|
||||
|
||||
// Check for pending invite token
|
||||
const bankIdCookieMatch = document.cookie.match(/gnubok-invite-token=([^;]+)/)
|
||||
const bankIdInviteToken = bankIdCookieMatch?.[1]
|
||||
|
||||
if (bankIdInviteToken) {
|
||||
try {
|
||||
const res = await fetch('/api/team/accept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: bankIdInviteToken }),
|
||||
})
|
||||
|
||||
if (res.ok) {
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
window.location.href = '/'
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[login] invite acceptance failed:', err)
|
||||
}
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
if (await acceptPendingInvite()) {
|
||||
window.location.href = '/'
|
||||
return
|
||||
}
|
||||
|
||||
if (nextPath !== '/') {
|
||||
@@ -196,27 +202,9 @@ function LoginPageContent() {
|
||||
}
|
||||
|
||||
// Check for pending invite token
|
||||
const cookieMatch = document.cookie.match(/gnubok-invite-token=([^;]+)/)
|
||||
const inviteToken = cookieMatch?.[1]
|
||||
|
||||
if (inviteToken) {
|
||||
try {
|
||||
const res = await fetch('/api/team/accept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: inviteToken }),
|
||||
})
|
||||
|
||||
if (res.ok) {
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
window.location.href = '/'
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[login] invite acceptance failed:', err)
|
||||
}
|
||||
// Clear cookie even on failure to avoid retrying stale tokens
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
if (await acceptPendingInvite()) {
|
||||
window.location.href = '/'
|
||||
return
|
||||
}
|
||||
|
||||
if (nextPath !== '/') {
|
||||
|
||||
@@ -11,6 +11,10 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, ShieldCheck, LogOut } from 'lucide-react'
|
||||
import { SupportLink } from '@/components/ui/support-link'
|
||||
import { safeReturnTo } from '@/lib/auth/safe-return-to'
|
||||
import {
|
||||
consumeInviteCookie,
|
||||
INVITE_PROBLEM_MESSAGE_KEYS,
|
||||
} from '@/lib/auth/consume-invite-cookie'
|
||||
|
||||
export default function MfaVerifyPage() {
|
||||
return (
|
||||
@@ -23,6 +27,7 @@ export default function MfaVerifyPage() {
|
||||
function MfaVerifyContent() {
|
||||
const t = useTranslations('mfa')
|
||||
const tCommon = useTranslations('common')
|
||||
const tInvite = useTranslations('invite')
|
||||
const [code, setCode] = useState('')
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [factorId, setFactorId] = useState<string | null>(null)
|
||||
@@ -68,6 +73,24 @@ function MfaVerifyContent() {
|
||||
return () => clearInterval(interval)
|
||||
}, [lockoutUntil])
|
||||
|
||||
// Accept a pending invite, if any, and report a non-definitive failure.
|
||||
// Returns true when the caller should land the user in the app directly.
|
||||
// The invite cookie survives anything that is not a settled outcome, so
|
||||
// /onboarding and /select-company can retry acceptance server-side.
|
||||
const acceptPendingInvite = async (): Promise<boolean> => {
|
||||
const invite = await consumeInviteCookie()
|
||||
if (invite.accepted) return true
|
||||
if (invite.problem) {
|
||||
const keys = INVITE_PROBLEM_MESSAGE_KEYS[invite.problem]
|
||||
toast({
|
||||
title: tInvite(keys.title),
|
||||
description: tInvite(keys.body),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const handleVerify = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault()
|
||||
if (!factorId || code.length !== 6) return
|
||||
@@ -116,26 +139,9 @@ function MfaVerifyContent() {
|
||||
return
|
||||
}
|
||||
|
||||
const cookieMatch = document.cookie.match(/gnubok-invite-token=([^;]+)/)
|
||||
const inviteToken = cookieMatch?.[1]
|
||||
|
||||
if (inviteToken) {
|
||||
try {
|
||||
const res = await fetch('/api/team/accept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: inviteToken }),
|
||||
})
|
||||
|
||||
if (res.ok) {
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
window.location.href = '/'
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[mfa/verify] invite acceptance failed:', err)
|
||||
}
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
if (await acceptPendingInvite()) {
|
||||
window.location.href = '/'
|
||||
return
|
||||
}
|
||||
|
||||
if (returnTo.startsWith('/api/')) {
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
/**
|
||||
* Two findings on the signup page, both about an address travelling (or not)
|
||||
* with the user.
|
||||
*
|
||||
* 1. The BankID signup form left its email field blank and editable while the
|
||||
* password form on the very same page pre-filled and locked it from the
|
||||
* invitation. An invitee who chose BankID therefore typed their private
|
||||
* address, POST /api/team/accept answered 403 on its email equality check,
|
||||
* and they landed on /select-company with no membership. The token now
|
||||
* survives that 403 (lib/auth/consume-invite-cookie.ts retains it on
|
||||
* `wrong_email`, and /select-company re-runs acceptance server-side), so the
|
||||
* dead end is recoverable; the signup still should not walk into it.
|
||||
* 2. The duplicate-email screen linked to `/login?email=...`, which
|
||||
* app/(auth)/login/page.tsx never reads. The address rode along in the URL,
|
||||
* the browser history, the Referer header and every proxy access log, and
|
||||
* arrived nowhere.
|
||||
*
|
||||
* The page is a client component and this repo deliberately has no component
|
||||
* test harness (CLAUDE.md: scope is lib/ + app/api/), so these assert on the
|
||||
* page source, the same pattern used by
|
||||
* app/(auth)/reset-password/__tests__/invite-handoff.test.ts and
|
||||
* app/invite/[token]/__tests__/invite-cookie.test.ts.
|
||||
*/
|
||||
const SRC = fs.readFileSync(path.resolve(__dirname, '../page.tsx'), 'utf8')
|
||||
|
||||
/** The page source with comment lines dropped, so prose about a pattern is never mistaken for the pattern. */
|
||||
const CODE = SRC.split('\n')
|
||||
.filter((line) => !/^\s*(\*|\/\/|\/\*)/.test(line))
|
||||
.join('\n')
|
||||
|
||||
/** The props of one `<Input>`, located by its id. */
|
||||
function inputProps(id: string): string {
|
||||
const anchor = SRC.indexOf(`id="${id}"`)
|
||||
expect(anchor, `no <Input id="${id}"> on the page`).toBeGreaterThan(-1)
|
||||
return SRC.slice(SRC.lastIndexOf('<Input', anchor), SRC.indexOf('/>', anchor) + 2)
|
||||
}
|
||||
|
||||
/** A whole labelled field group (Label + Input + hint), located by the input's id. */
|
||||
function fieldGroup(id: string): string {
|
||||
const anchor = SRC.indexOf(`id="${id}"`)
|
||||
expect(anchor, `no <Input id="${id}"> on the page`).toBeGreaterThan(-1)
|
||||
return SRC.slice(
|
||||
SRC.lastIndexOf('<div className="space-y-2">', anchor),
|
||||
SRC.indexOf('</div>', anchor) + '</div>'.length,
|
||||
)
|
||||
}
|
||||
|
||||
/** The body of the effect that resolves `?invite=` into the invited address. */
|
||||
function inviteEffect(): string {
|
||||
const start = SRC.indexOf("searchParams.get('invite')")
|
||||
expect(start).toBeGreaterThan(-1)
|
||||
return SRC.slice(start, SRC.indexOf('}, [searchParams])', start))
|
||||
}
|
||||
|
||||
/**
|
||||
* Just the duplicate-email screen. Scoped, because the page footer carries its
|
||||
* own bare `/login` link and would satisfy an unscoped assertion.
|
||||
*/
|
||||
function duplicateScreen(): string {
|
||||
const start = CODE.indexOf('if (duplicateEmail) {')
|
||||
expect(start).toBeGreaterThan(-1)
|
||||
const end = CODE.indexOf('if (isRegistered) {', start)
|
||||
expect(end).toBeGreaterThan(start)
|
||||
return CODE.slice(start, end)
|
||||
}
|
||||
|
||||
describe('an invited signup', () => {
|
||||
it('pre-fills the BankID email field from the invitation, not just the password one', () => {
|
||||
const effect = inviteEffect()
|
||||
expect(effect).toContain('setEmail(data.data.email)')
|
||||
expect(effect).toContain('setBankIdEmail(data.data.email)')
|
||||
})
|
||||
|
||||
it('locks the BankID email field exactly the way the password field is locked', () => {
|
||||
// Same invitation, same page: one behaviour. The divergence was the bug.
|
||||
for (const id of ['email', 'bankid_email']) {
|
||||
const props = inputProps(id)
|
||||
expect(props, id).toContain('disabled={isLoading || !!inviteEmail}')
|
||||
expect(props, id).toContain('readOnly={!!inviteEmail}')
|
||||
}
|
||||
})
|
||||
|
||||
it('tells the invitee where the locked address came from', () => {
|
||||
expect(fieldGroup('bankid_email')).toContain("t('invite_email_hint')")
|
||||
expect(fieldGroup('email')).toContain("t('invite_email_hint')")
|
||||
})
|
||||
|
||||
it('still submits the invited address although a disabled input is not in the FormData', () => {
|
||||
// `disabled` (unlike `readOnly`) excludes a field from FormData, so the
|
||||
// locked value only reaches the request through the state fallback. Both
|
||||
// handlers rely on it; dropping either fallback would POST an empty email.
|
||||
expect(CODE).toContain("(formData.get('bankid_email') as string) || bankIdEmail")
|
||||
expect(CODE).toContain("(formData.get('email') as string) || email")
|
||||
})
|
||||
})
|
||||
|
||||
describe('a signup that did not come from an invitation', () => {
|
||||
// The overwhelming majority. Nothing may lock or pre-fill for these users.
|
||||
it('starts with no invited address', () => {
|
||||
expect(CODE).toContain('const [inviteEmail, setInviteEmail] = useState<string | null>(null)')
|
||||
expect(CODE).toContain("const [bankIdEmail, setBankIdEmail] = useState('')")
|
||||
})
|
||||
|
||||
it('never resolves an invitation when the link carries no token', () => {
|
||||
expect(inviteEffect()).toContain('if (!inviteToken) return')
|
||||
})
|
||||
|
||||
it('leaves both email fields editable, gating every lock on the invitation', () => {
|
||||
for (const id of ['email', 'bankid_email']) {
|
||||
const props = inputProps(id)
|
||||
// No unconditional lock: every disabled/readOnly here names inviteEmail.
|
||||
const locks = props.match(/(disabled|readOnly)=\{[^}]*\}/g) ?? []
|
||||
expect(locks.length, id).toBeGreaterThan(0)
|
||||
for (const lock of locks) {
|
||||
expect(lock, `${id}: ${lock} is not conditional on the invitation`).toContain('inviteEmail')
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the BankID field its own hint when there is no invitation', () => {
|
||||
expect(fieldGroup('bankid_email')).toContain("t('bankid_email_hint')")
|
||||
})
|
||||
})
|
||||
|
||||
describe('the duplicate-email screen', () => {
|
||||
it('sends the user to plain /login', () => {
|
||||
expect(duplicateScreen()).toContain('<Link href="/login">')
|
||||
})
|
||||
|
||||
it('does not put the address in the URL of a page that never reads it', () => {
|
||||
expect(duplicateScreen()).not.toMatch(/\/login\?/)
|
||||
expect(CODE).not.toContain('encodeURIComponent(duplicateEmail)')
|
||||
})
|
||||
|
||||
it('still shows the address, so nothing is lost by dropping the parameter', () => {
|
||||
expect(duplicateScreen()).toContain('{duplicateEmail}')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the post-auth destination parameter', () => {
|
||||
it('does not read `next`', () => {
|
||||
// Nothing links to /register with one: bounceToAuth (lib/supabase/
|
||||
// middleware.ts) targets /login and the two MFA pages, and
|
||||
// app/invite/[token]/page.tsx sends `?invite=`. An unread parameter cannot
|
||||
// redirect anyone.
|
||||
expect(CODE).not.toContain("searchParams.get('next')")
|
||||
})
|
||||
|
||||
it('would have to sanitize a destination through safeReturnTo if one is ever added', () => {
|
||||
// The ratchet, not a restatement of today's behaviour: the moment someone
|
||||
// reads a destination off this URL, the shared validator has to be the
|
||||
// thing that vets it. Hand-rolled checks here emitted
|
||||
// `Location: http://evil.com/`. Rejection of absolute and
|
||||
// protocol-relative values is covered by
|
||||
// lib/auth/__tests__/safe-return-to.test.ts.
|
||||
const readsDestination = /searchParams\.get\('(next|returnTo|redirect|redirectTo)'\)/.test(CODE)
|
||||
if (readsDestination) {
|
||||
expect(CODE).toContain("from '@/lib/auth/safe-return-to'")
|
||||
expect(CODE).toMatch(/safeReturnTo\(\s*searchParams\.get\('(next|returnTo|redirect|redirectTo)'\)/)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('the wording the locked field renders', () => {
|
||||
const messages = (locale: 'sv' | 'en') =>
|
||||
JSON.parse(
|
||||
fs.readFileSync(path.resolve(__dirname, `../../../../messages/${locale}.json`), 'utf8'),
|
||||
) as { register: Record<string, string> }
|
||||
|
||||
for (const locale of ['sv', 'en'] as const) {
|
||||
it(`has both email hints in ${locale}.json`, () => {
|
||||
const register = messages(locale).register
|
||||
expect(register.invite_email_hint).toBeTruthy()
|
||||
expect(register.bankid_email_hint).toBeTruthy()
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -17,6 +17,10 @@ import { isBankIdEnabled } from '@/lib/auth/bankid'
|
||||
import type { BankIdResult } from '@/components/auth/BankIdAuth'
|
||||
import { getBranding } from '@/lib/branding/service'
|
||||
import { detectWebmailHint } from '@/lib/auth/webmail-search'
|
||||
import {
|
||||
consumeInviteCookie,
|
||||
INVITE_PROBLEM_MESSAGE_KEYS,
|
||||
} from '@/lib/auth/consume-invite-cookie'
|
||||
import { AuthPageSkeleton } from '@/components/auth/AuthPageSkeleton'
|
||||
|
||||
const branding = getBranding()
|
||||
@@ -35,6 +39,17 @@ export default function RegisterPage() {
|
||||
}
|
||||
|
||||
function RegisterPageContent() {
|
||||
// `invite` is the only query parameter this page reads. It deliberately does
|
||||
// NOT read `next`: nothing links here with one (bounceToAuth in
|
||||
// lib/supabase/middleware.ts targets /login and the two MFA pages only, and
|
||||
// app/invite/[token]/page.tsx sends `?invite=`), the already-signed-in case
|
||||
// is handled in the middleware behind safeReturnTo, and neither signup path
|
||||
// has a destination to spend it on: the password path leaves through the
|
||||
// confirmation mail and /auth/callback, and the BankID path must land a
|
||||
// brand-new account on '/' or /select-company rather than a deep link it has
|
||||
// no membership for. If a destination is ever wanted here it MUST go through
|
||||
// safeReturnTo (lib/auth/safe-return-to.ts); a hand-rolled check on this
|
||||
// value is an open redirect.
|
||||
const searchParams = useSearchParams()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
@@ -51,10 +66,35 @@ function RegisterPageContent() {
|
||||
const supabase = createClient()
|
||||
const bankIdEnabled = isBankIdEnabled()
|
||||
const t = useTranslations('register')
|
||||
const tInvite = useTranslations('invite')
|
||||
const errorLocale = useLocale() as ErrorLocale
|
||||
|
||||
// Accept a pending invite, if any, and report a non-definitive failure.
|
||||
// Returns true when the caller should land the user in the app directly.
|
||||
// The invite cookie survives anything that is not a settled outcome, so
|
||||
// /onboarding and /select-company can retry acceptance server-side.
|
||||
const acceptPendingInvite = async (): Promise<boolean> => {
|
||||
const invite = await consumeInviteCookie()
|
||||
if (invite.accepted) return true
|
||||
if (invite.problem) {
|
||||
const keys = INVITE_PROBLEM_MESSAGE_KEYS[invite.problem]
|
||||
toast({
|
||||
title: tInvite(keys.title),
|
||||
description: tInvite(keys.body),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// When arriving from an invite link, fetch the invite info to pre-fill
|
||||
// and lock the email field so the user registers with the correct address.
|
||||
// BOTH signup forms are pre-filled: the BankID form used to be left blank
|
||||
// and editable, so an invitee who signed up with BankID typed their private
|
||||
// address, POST /api/team/accept answered 403 on the email equality check,
|
||||
// and they landed on /select-company with no membership. The token now
|
||||
// survives that 403 (lib/auth/consume-invite-cookie.ts) so it is recoverable
|
||||
// rather than terminal, but the signup should not walk into it at all.
|
||||
useEffect(() => {
|
||||
const inviteToken = searchParams.get('invite')
|
||||
if (!inviteToken) return
|
||||
@@ -65,6 +105,7 @@ function RegisterPageContent() {
|
||||
if (data?.data?.email) {
|
||||
setInviteEmail(data.data.email)
|
||||
setEmail(data.data.email)
|
||||
setBankIdEmail(data.data.email)
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
@@ -156,27 +197,9 @@ function RegisterPageContent() {
|
||||
// invitee who registers with BankID lands on /select-company with no
|
||||
// membership and gets funneled into creating a company instead of
|
||||
// joining the one they were invited to.
|
||||
const inviteCookieMatch = document.cookie.match(/gnubok-invite-token=([^;]+)/)
|
||||
const inviteToken = inviteCookieMatch?.[1]
|
||||
|
||||
if (inviteToken) {
|
||||
try {
|
||||
const res = await fetch('/api/team/accept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: inviteToken }),
|
||||
})
|
||||
|
||||
if (res.ok) {
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
window.location.href = '/'
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[register] invite acceptance failed:', err instanceof Error ? err.message : String(err))
|
||||
}
|
||||
// Clear cookie even on failure to avoid retrying stale tokens
|
||||
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
|
||||
if (await acceptPendingInvite()) {
|
||||
window.location.href = '/'
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/select-company')
|
||||
@@ -326,8 +349,15 @@ function RegisterPageContent() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{/*
|
||||
Plain /login, no `email` parameter: app/(auth)/login/page.tsx
|
||||
reads only `error`, `flow` and `next`, so the address was
|
||||
travelling in the URL (browser history, Referer, every proxy
|
||||
access log) and arriving nowhere. The address is already on
|
||||
screen above, so nothing is lost by dropping it.
|
||||
*/}
|
||||
<Button className="w-full" asChild>
|
||||
<Link href={`/login?email=${encodeURIComponent(duplicateEmail)}`}>
|
||||
<Link href="/login">
|
||||
{t('sign_in')}
|
||||
</Link>
|
||||
</Button>
|
||||
@@ -452,11 +482,12 @@ function RegisterPageContent() {
|
||||
value={bankIdEmail}
|
||||
onChange={(e) => setBankIdEmail(e.target.value)}
|
||||
required
|
||||
disabled={isLoading}
|
||||
disabled={isLoading || !!inviteEmail}
|
||||
readOnly={!!inviteEmail}
|
||||
className="h-11"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('bankid_email_hint')}
|
||||
{inviteEmail ? t('invite_email_hint') : t('bankid_email_hint')}
|
||||
</p>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11" disabled={isLoading}>
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import {
|
||||
INVITE_COOKIE_NAME,
|
||||
INVITE_PROBLEM_MESSAGE_KEYS,
|
||||
} from '@/lib/auth/consume-invite-cookie'
|
||||
import {
|
||||
handoffPendingInvite,
|
||||
INVITE_ACCEPTED_DESTINATION,
|
||||
INVITE_RETRY_DESTINATION,
|
||||
type InviteHandoffDeps,
|
||||
} from '../invite-handoff'
|
||||
|
||||
/**
|
||||
* The finding: `/reset-password` was the only session-establishing path that
|
||||
* never consumed the pre-auth invite cookie, and the server-side safety nets
|
||||
* (`acceptPendingInviteByToken()` on `/onboarding` and `/select-company`) do
|
||||
* not cover it, because `/onboarding` is only ever reached by a user with zero
|
||||
* companies. A consultant who already had a company of their own could not
|
||||
* recover the invitation at all.
|
||||
*
|
||||
* The flow lives in `../invite-handoff.ts` so it is reachable from the node
|
||||
* test env: the page itself is a client component and this repo deliberately
|
||||
* has no component harness (CLAUDE.md: scope is lib/ + app/api/). The wiring
|
||||
* inside the page is asserted against its source, the same pattern used by
|
||||
* app/invite/[token]/__tests__/invite-cookie.test.ts.
|
||||
*/
|
||||
|
||||
const TOKEN = 'gnubok_inv_Zm9vYmFyLXRva2Vu'
|
||||
|
||||
/**
|
||||
* Minimal document.cookie stand-in (node env has no DOM). Models the one
|
||||
* behaviour the shared helper depends on: assigning `name=; max-age=0` removes
|
||||
* the entry.
|
||||
*/
|
||||
function installCookieJar(initial: Record<string, string> = {}) {
|
||||
const jar = new Map(Object.entries(initial))
|
||||
|
||||
Object.defineProperty(globalThis, 'document', {
|
||||
configurable: true,
|
||||
value: {
|
||||
get cookie() {
|
||||
return [...jar.entries()].map(([k, v]) => `${k}=${v}`).join('; ')
|
||||
},
|
||||
set cookie(raw: string) {
|
||||
const [pair, ...attrs] = raw.split(';').map((s) => s.trim())
|
||||
const eq = pair.indexOf('=')
|
||||
const name = pair.slice(0, eq)
|
||||
const value = pair.slice(eq + 1)
|
||||
if (attrs.some((a) => /^max-age=0$/i.test(a)) || value === '') {
|
||||
jar.delete(name)
|
||||
} else {
|
||||
jar.set(name, value)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return jar
|
||||
}
|
||||
|
||||
let fetchMock: ReturnType<typeof vi.fn>
|
||||
let reportProblem: Mock<InviteHandoffDeps['reportProblem']>
|
||||
let getUser: Mock<InviteHandoffDeps['getUser']>
|
||||
let getAssuranceLevel: Mock<InviteHandoffDeps['getAssuranceLevel']>
|
||||
|
||||
/** An ordinary hosted user: no BankID link, no TOTP step-up owed. */
|
||||
function deps(overrides: Partial<InviteHandoffDeps> = {}): InviteHandoffDeps {
|
||||
return {
|
||||
getUser,
|
||||
getAssuranceLevel,
|
||||
reportProblem,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
reportProblem = vi.fn<InviteHandoffDeps['reportProblem']>()
|
||||
getUser = vi
|
||||
.fn<InviteHandoffDeps['getUser']>()
|
||||
.mockResolvedValue({ app_metadata: {} })
|
||||
getAssuranceLevel = vi
|
||||
.fn<InviteHandoffDeps['getAssuranceLevel']>()
|
||||
.mockResolvedValue({ currentLevel: 'aal1', nextLevel: 'aal1' })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
vi.unstubAllEnvs()
|
||||
Reflect.deleteProperty(globalThis, 'document')
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
function respondWith(status: number) {
|
||||
fetchMock.mockResolvedValue({ status, ok: status >= 200 && status < 300 })
|
||||
}
|
||||
|
||||
describe('invite handoff after a password reset', () => {
|
||||
// The core of the finding: the invitee resets their password and is a member
|
||||
// when they land in the app.
|
||||
it('joins the invited company and lands the user in the app', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(200)
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/team/accept', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: TOKEN }),
|
||||
})
|
||||
expect(destination).toBe(INVITE_ACCEPTED_DESTINATION)
|
||||
expect(reportProblem).not.toHaveBeenCalled()
|
||||
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
|
||||
})
|
||||
|
||||
/**
|
||||
* The user shape that motivated the fix. Acceptance is inline and reads no
|
||||
* membership state, so a user who already has a company of their own goes
|
||||
* through the identical single POST: exactly one request, no company lookup
|
||||
* that could branch them away, and never a bounce through `/onboarding`
|
||||
* (which they would never be sent to).
|
||||
*/
|
||||
it('joins a user who already has a company of their own too', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(200)
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(destination).toBe(INVITE_ACCEPTED_DESTINATION)
|
||||
expect(destination).not.toBe('/onboarding')
|
||||
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
|
||||
})
|
||||
|
||||
it('treats already-a-member (409) as joined', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(409)
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(destination).toBe(INVITE_ACCEPTED_DESTINATION)
|
||||
expect(reportProblem).not.toHaveBeenCalled()
|
||||
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
|
||||
})
|
||||
|
||||
it('retains the token on a transient failure, reports it, and asks for a server-side retry', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(500)
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(jar.get(INVITE_COOKIE_NAME)).toBe(TOKEN)
|
||||
expect(reportProblem).toHaveBeenCalledWith('retryable')
|
||||
// /select-company re-runs acceptPendingInviteByToken() server-side and is
|
||||
// reachable for a user who already has a company; /onboarding is not.
|
||||
expect(destination).toBe(INVITE_RETRY_DESTINATION)
|
||||
expect(destination).not.toBe('/onboarding')
|
||||
})
|
||||
|
||||
it('retains the token when the request never reaches the server', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(jar.get(INVITE_COOKIE_NAME)).toBe(TOKEN)
|
||||
expect(reportProblem).toHaveBeenCalledWith('retryable')
|
||||
expect(destination).toBe(INVITE_RETRY_DESTINATION)
|
||||
})
|
||||
|
||||
it('retains the token on an email mismatch (403) without a futile retry', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(403)
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(jar.get(INVITE_COOKIE_NAME)).toBe(TOKEN)
|
||||
expect(reportProblem).toHaveBeenCalledWith('wrong_email')
|
||||
// The server-side email equality check would fail identically for this
|
||||
// account, so there is nothing for /select-company to retry.
|
||||
expect(destination).toBeNull()
|
||||
})
|
||||
|
||||
it('clears a spent token (410) and reports it', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(410)
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
|
||||
expect(reportProblem).toHaveBeenCalledWith('spent')
|
||||
expect(destination).toBeNull()
|
||||
})
|
||||
|
||||
it('does nothing at all when there is no invite cookie', async () => {
|
||||
installCookieJar({ 'sb-access-token': 'x' })
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(getUser).not.toHaveBeenCalled()
|
||||
expect(reportProblem).not.toHaveBeenCalled()
|
||||
expect(destination).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* A recovery session is AAL1, and POST /api/team/accept is NOT in
|
||||
* `apiPathSkipsMfaGate`, so the middleware answers a pending step-up with a
|
||||
* bare 403. The shared classifier reads 403 as `wrong_email`, so attempting the
|
||||
* acceptance there would tell a legitimate invitee their invitation belongs to
|
||||
* someone else. Defer instead, on exactly the middleware's own condition.
|
||||
*/
|
||||
describe('a session that still owes an MFA step-up', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', '')
|
||||
getAssuranceLevel.mockResolvedValue({
|
||||
currentLevel: 'aal1',
|
||||
nextLevel: 'aal2',
|
||||
})
|
||||
})
|
||||
|
||||
it('defers without touching the token or claiming the wrong address', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(403)
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
expect(reportProblem).not.toHaveBeenCalled()
|
||||
// The same predicate bounces the user to /mfa/verify, which consumes the
|
||||
// surviving cookie once the second factor is in.
|
||||
expect(jar.get(INVITE_COOKIE_NAME)).toBe(TOKEN)
|
||||
expect(destination).toBeNull()
|
||||
})
|
||||
|
||||
it('does not defer a BankID-linked user, whom nothing would bounce', async () => {
|
||||
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(200)
|
||||
|
||||
const destination = await handoffPendingInvite(
|
||||
deps({ getUser: async () => ({ app_metadata: { bankid_linked: true } }) }),
|
||||
)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(destination).toBe(INVITE_ACCEPTED_DESTINATION)
|
||||
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not defer on self-hosted, where MFA is never enforced', async () => {
|
||||
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
|
||||
installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(200)
|
||||
|
||||
const destination = await handoffPendingInvite(deps())
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(destination).toBe(INVITE_ACCEPTED_DESTINATION)
|
||||
})
|
||||
|
||||
it('still attempts when the assurance level cannot be read', async () => {
|
||||
installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(200)
|
||||
|
||||
const destination = await handoffPendingInvite(
|
||||
deps({ getAssuranceLevel: async () => null }),
|
||||
)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(destination).toBe(INVITE_ACCEPTED_DESTINATION)
|
||||
})
|
||||
|
||||
// A throw here must never surface as "could not save password": the password
|
||||
// was saved before this ran.
|
||||
it('still attempts, without throwing, when the session read fails outright', async () => {
|
||||
installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
|
||||
respondWith(200)
|
||||
|
||||
const destination = await handoffPendingInvite(
|
||||
deps({
|
||||
getUser: async () => {
|
||||
throw new TypeError('Failed to fetch')
|
||||
},
|
||||
}),
|
||||
)
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
expect(destination).toBe(INVITE_ACCEPTED_DESTINATION)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The page wiring. Against HEAD every assertion here fails: the page never
|
||||
* mentioned the invite at all.
|
||||
*/
|
||||
describe('reset-password page wiring', () => {
|
||||
const SRC = fs.readFileSync(path.resolve(__dirname, '../page.tsx'), 'utf8')
|
||||
|
||||
it('calls the shared handoff rather than carrying its own copy', () => {
|
||||
expect(SRC).toContain("import { handoffPendingInvite } from './invite-handoff'")
|
||||
expect(SRC).toContain('await handoffPendingInvite({')
|
||||
// The acceptance POST and the cookie writes belong to the shared helper.
|
||||
expect(SRC).not.toContain('/api/team/accept')
|
||||
expect(SRC).not.toContain('document.cookie')
|
||||
})
|
||||
|
||||
it('runs the handoff only after the password has actually been saved', () => {
|
||||
const passwordPost = SRC.indexOf("'/api/account/password'")
|
||||
const failureGuard = SRC.indexOf('if (!res.ok)')
|
||||
const handoff = SRC.indexOf('await handoffPendingInvite({')
|
||||
|
||||
expect(passwordPost).toBeGreaterThan(-1)
|
||||
expect(failureGuard).toBeGreaterThan(passwordPost)
|
||||
expect(handoff).toBeGreaterThan(failureGuard)
|
||||
})
|
||||
|
||||
it('hard-navigates to whatever the handoff returns', () => {
|
||||
expect(SRC).toContain('window.location.href = inviteDestination')
|
||||
})
|
||||
|
||||
it('never routes invite recovery through /onboarding', () => {
|
||||
// /onboarding heals a missed invite server-side but is unreachable for a
|
||||
// user who already has a company: that is the whole finding. Comment lines
|
||||
// are dropped so prose about it is not mistaken for a navigation.
|
||||
const code = SRC.split('\n').filter(
|
||||
(line) => !/^\s*(\*|\/\/|\/\*)/.test(line),
|
||||
)
|
||||
expect(code.join('\n')).not.toContain('/onboarding')
|
||||
})
|
||||
|
||||
it('renders the shared invite wording instead of inventing its own', () => {
|
||||
expect(SRC).toContain(
|
||||
"import { INVITE_PROBLEM_MESSAGE_KEYS } from '@/lib/auth/consume-invite-cookie'",
|
||||
)
|
||||
expect(SRC).toContain("useTranslations('invite')")
|
||||
})
|
||||
})
|
||||
|
||||
/** The toast the page now renders must exist in both locales. */
|
||||
describe('invite problem wording', () => {
|
||||
const messages = (locale: 'sv' | 'en') =>
|
||||
JSON.parse(
|
||||
fs.readFileSync(
|
||||
path.resolve(__dirname, `../../../../messages/${locale}.json`),
|
||||
'utf8',
|
||||
),
|
||||
) as { invite: Record<string, string> }
|
||||
|
||||
for (const locale of ['sv', 'en'] as const) {
|
||||
it(`has every problem title and body in ${locale}.json`, () => {
|
||||
const invite = messages(locale).invite
|
||||
for (const { title, body } of Object.values(INVITE_PROBLEM_MESSAGE_KEYS)) {
|
||||
expect(invite[title]).toBeTruthy()
|
||||
expect(invite[body]).toBeTruthy()
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import {
|
||||
consumeInviteCookie,
|
||||
readInviteCookie,
|
||||
type InviteAcceptProblem,
|
||||
} from '@/lib/auth/consume-invite-cookie'
|
||||
import { shouldEnforceMfa } from '@/lib/auth/mfa'
|
||||
|
||||
/**
|
||||
* Invite handoff for the password-recovery flow.
|
||||
*
|
||||
* `/reset-password` was the only session-establishing path that never picked
|
||||
* the pre-auth invite cookie back up. Login, register and `/mfa/verify` all
|
||||
* call `consumeInviteCookie()`; the recovery flow did not, and the server-side
|
||||
* safety nets do not cover it. `acceptPendingInviteByToken()`
|
||||
* (lib/company/pending-invites.ts) runs only on `/onboarding` and
|
||||
* `/select-company`, and `/onboarding` is reachable only for a user with zero
|
||||
* companies. A consultant who already has a company of their own therefore had
|
||||
* no route back to the invitation at all after resetting their password.
|
||||
*
|
||||
* This module holds the decision only. The POST, the status classification and
|
||||
* the "clear the cookie on a definitive outcome, keep it otherwise" rule all
|
||||
* stay in `lib/auth/consume-invite-cookie.ts`: this is the fifth caller of that
|
||||
* helper, not a fifth copy of it.
|
||||
*
|
||||
* It lives beside `page.tsx` rather than inside it because a Next.js page file
|
||||
* may not export anything but the page component and the route segment config,
|
||||
* which would leave the flow untestable in a repo with no component harness.
|
||||
*/
|
||||
|
||||
/** Only the field the MFA predicate reads off the authenticated user. */
|
||||
export interface InviteHandoffUser {
|
||||
app_metadata?: Record<string, unknown>
|
||||
}
|
||||
|
||||
/** Current vs required assurance level for the live session. */
|
||||
export interface InviteHandoffAssuranceLevel {
|
||||
currentLevel: string | null
|
||||
nextLevel: string | null
|
||||
}
|
||||
|
||||
export interface InviteHandoffDeps {
|
||||
/** The authenticated user, or null when it could not be read. */
|
||||
getUser: () => Promise<InviteHandoffUser | null>
|
||||
/** The session's assurance levels, or null when they could not be read. */
|
||||
getAssuranceLevel: () => Promise<InviteHandoffAssuranceLevel | null>
|
||||
/** Show the user a non-definitive outcome. */
|
||||
reportProblem: (problem: InviteAcceptProblem) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a user whose invite survived an inconclusive attempt is sent so the
|
||||
* server can retry it. `/select-company` re-runs `acceptPendingInviteByToken()`
|
||||
* on every load and, unlike `/onboarding`, is reachable for a user who already
|
||||
* has a company (lib/supabase/middleware.ts lets it through with a resolved
|
||||
* active company). That makes it the only healing surface for the user shape
|
||||
* this whole handoff exists for.
|
||||
*/
|
||||
export const INVITE_RETRY_DESTINATION = '/select-company'
|
||||
|
||||
/** Where a settled invite lands the user. */
|
||||
export const INVITE_ACCEPTED_DESTINATION = '/'
|
||||
|
||||
/**
|
||||
* Accept a pending invitation once the password reset itself is finished.
|
||||
*
|
||||
* MUST be called only after `POST /api/account/password` has returned 2xx.
|
||||
* That route runs `requireAuth()`, so its success proves a server-validated
|
||||
* session exists, and waiting for it means no membership is ever created off a
|
||||
* half-completed recovery. Authorization is not this function's business:
|
||||
* `/api/team/accept` re-authorizes every attempt with `requireAuth()` plus an
|
||||
* email equality check against the invitation.
|
||||
*
|
||||
* Returns the path to hard-navigate to, or null to keep the caller's normal
|
||||
* post-reset navigation. Null covers every case where nothing changed
|
||||
* server-side: no invitation in flight, a step-up still owed, a spent token, or
|
||||
* an invitation belonging to another address.
|
||||
*
|
||||
* Never throws, so a hiccup in the invite handoff can never be mistaken for a
|
||||
* failed password reset by the caller's error path.
|
||||
*/
|
||||
export async function handoffPendingInvite(
|
||||
deps: InviteHandoffDeps,
|
||||
): Promise<string | null> {
|
||||
// No invitation in flight: no requests, no toast, untouched flow.
|
||||
if (!readInviteCookie()) return null
|
||||
|
||||
if (await mfaStepUpOwed(deps)) return null
|
||||
|
||||
const invite = await consumeInviteCookie()
|
||||
if (invite.problem) deps.reportProblem(invite.problem)
|
||||
|
||||
if (invite.accepted) return INVITE_ACCEPTED_DESTINATION
|
||||
|
||||
// Retain-and-retry, for transient failures only. `wrong_email` is
|
||||
// deterministic for this account (the server-side email equality check would
|
||||
// fail identically), and `spent` already destroyed the token, so neither
|
||||
// gains anything from the server-side retry: both just show the toast and
|
||||
// keep the normal flow.
|
||||
if (invite.disposition === 'retryable') return INVITE_RETRY_DESTINATION
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the middleware would reject the acceptance for want of a step-up.
|
||||
*
|
||||
* `POST /api/team/accept` sits BEHIND the middleware MFA gate: it is not in
|
||||
* `apiPathSkipsMfaGate` (lib/auth/api-mfa-gate.ts), and a recovery session is
|
||||
* AAL1. Attempting the acceptance while a step-up is owed returns a bare 403,
|
||||
* which the shared classifier cannot tell apart from an email mismatch, so a
|
||||
* legitimate invitee would be told their invitation belongs to someone else.
|
||||
*
|
||||
* The predicate mirrors the middleware's own condition exactly
|
||||
* (`shouldEnforceMfa` plus aal1-with-aal2-required), which makes "we skipped"
|
||||
* and "the middleware will bounce this user to /mfa/verify" the same statement:
|
||||
* the cookie survives untouched and `/mfa/verify` consumes it once the second
|
||||
* factor is in. A user whose MFA is not enforced (self-hosted, BankID-linked)
|
||||
* is deliberately never deferred, because nothing would bounce them and the
|
||||
* token would sit there unused.
|
||||
*
|
||||
* A failed read is not evidence of a pending step-up, so it falls through to
|
||||
* the attempt: the server is the authority, and a 403 keeps the token anyway.
|
||||
*/
|
||||
async function mfaStepUpOwed(deps: InviteHandoffDeps): Promise<boolean> {
|
||||
try {
|
||||
const user = await deps.getUser()
|
||||
if (!user || !shouldEnforceMfa(user)) return false
|
||||
|
||||
const aal = await deps.getAssuranceLevel()
|
||||
return aal?.nextLevel === 'aal2' && aal.currentLevel === 'aal1'
|
||||
} catch (err) {
|
||||
console.error('[reset-password] could not read the session MFA state', err)
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Loader2, KeyRound } from 'lucide-react'
|
||||
import { INVITE_PROBLEM_MESSAGE_KEYS } from '@/lib/auth/consume-invite-cookie'
|
||||
import { handoffPendingInvite } from './invite-handoff'
|
||||
|
||||
/**
|
||||
* Three entry modes:
|
||||
@@ -31,6 +33,7 @@ type Mode = 'loading' | 'set-password' | 'confirm-link' | 'enter-code'
|
||||
|
||||
function ResetPasswordInner() {
|
||||
const t = useTranslations('reset_password')
|
||||
const tInvite = useTranslations('invite')
|
||||
const searchParams = useSearchParams()
|
||||
const tokenHash = searchParams.get('token_hash')
|
||||
const [mode, setMode] = useState<Mode>('loading')
|
||||
@@ -156,6 +159,34 @@ function ResetPasswordInner() {
|
||||
description: t('saved_description'),
|
||||
})
|
||||
|
||||
// Only now, with the reset finished and the session proven by the 2xx
|
||||
// above (that route runs requireAuth()), pick up a pending invitation.
|
||||
// This is the recovery flow's copy of what login, register and
|
||||
// /mfa/verify already do, and it is the only chance an invitee who
|
||||
// already has a company of their own gets: the server-side retry on
|
||||
// /onboarding never sees them. See ./invite-handoff.ts.
|
||||
const inviteDestination = await handoffPendingInvite({
|
||||
getUser: async () => (await supabase.auth.getUser()).data.user,
|
||||
getAssuranceLevel: async () =>
|
||||
(await supabase.auth.mfa.getAuthenticatorAssuranceLevel()).data,
|
||||
reportProblem: (problem) => {
|
||||
const keys = INVITE_PROBLEM_MESSAGE_KEYS[problem]
|
||||
toast({
|
||||
title: tInvite(keys.title),
|
||||
description: tInvite(keys.body),
|
||||
variant: 'destructive',
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
if (inviteDestination) {
|
||||
// Hard navigation: either the membership and the active company just
|
||||
// changed server-side, or the destination re-runs acceptance on the
|
||||
// server. Both leave the client router's cached render stale.
|
||||
window.location.href = inviteDestination
|
||||
return
|
||||
}
|
||||
|
||||
router.push('/')
|
||||
router.refresh()
|
||||
} catch {
|
||||
|
||||
@@ -410,6 +410,7 @@ export default function ArticleDetailPage({
|
||||
<ArticleForm
|
||||
onSubmit={handleUpdate}
|
||||
isLoading={isUpdating}
|
||||
onCancel={() => setIsEditOpen(false)}
|
||||
initialData={{
|
||||
article_number: article.article_number || undefined,
|
||||
name: article.name,
|
||||
|
||||
@@ -279,6 +279,7 @@ function ArticlesPageInner() {
|
||||
<ArticleForm
|
||||
onSubmit={handleCreateArticle}
|
||||
isLoading={isCreating}
|
||||
onCancel={() => setIsDialogOpen(false)}
|
||||
/>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
+227
-108
@@ -23,6 +23,23 @@ import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-m
|
||||
|
||||
const supabase = createClient()
|
||||
|
||||
/**
|
||||
* The sentence the route meant to say, from a response it refused.
|
||||
*
|
||||
* The parsed body goes to the mapper as-is. Wrapping it in `new Error()` first,
|
||||
* which every handler here used to do, stringifies the canonical envelope
|
||||
* `{ error: { code, message } }` into "[object Object]": the mapper then has
|
||||
* nothing to match on and falls through to the generic "Något gick fel",
|
||||
* discarding the route's own Swedish reason and its Zod field list. Passing the
|
||||
* status as well means a body-less or non-JSON refusal still resolves to the
|
||||
* right sentence, so a 403 read-only refusal reads as one instead of as a
|
||||
* generic failure.
|
||||
*/
|
||||
async function describeFailure(response: Response): Promise<string> {
|
||||
const body: unknown = await response.json().catch(() => null)
|
||||
return getUserErrorMessage(body, { statusCode: response.status })
|
||||
}
|
||||
|
||||
export default function DeadlinesPage() {
|
||||
const { company } = useCompany()
|
||||
const companyId = company?.id
|
||||
@@ -37,8 +54,11 @@ export default function DeadlinesPage() {
|
||||
const [editingDeadline, setEditingDeadline] = useState<Deadline | null>(null)
|
||||
const { toast } = useToast()
|
||||
|
||||
const fetchData = useCallback(async () => {
|
||||
if (!companyId) return
|
||||
// Returns whether the list on screen was actually refreshed. Handlers that
|
||||
// confirm an outcome to the user need that: claiming a row moved while the
|
||||
// reload failed would describe a list the user is not looking at.
|
||||
const fetchData = useCallback(async (): Promise<boolean> => {
|
||||
if (!companyId) return false
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
@@ -73,7 +93,17 @@ export default function DeadlinesPage() {
|
||||
.from('invoices')
|
||||
.select('total_sek, total, currency')
|
||||
.eq('company_id', companyId)
|
||||
.in('status', ['sent', 'unpaid'])
|
||||
// The open statuses, and only those the CHECK actually allows
|
||||
// (draft, sent, paid, partially_paid, overdue, cancelled,
|
||||
// credited): draft is not owed yet, paid/cancelled/credited are
|
||||
// settled. There is no 'unpaid' status; this filter used to name
|
||||
// one, so every invoice the reminder run had already flipped to
|
||||
// 'overdue' fell out of the total silently. partially_paid is
|
||||
// deliberately absent: the sum below is the invoice total, not
|
||||
// remaining_amount, so counting one would report money already
|
||||
// received as still owed, and the action link lands on the
|
||||
// invoices tab that lists exactly sent + overdue.
|
||||
.in('status', ['sent', 'overdue'])
|
||||
.lt('due_date', today)
|
||||
.order('id', { ascending: true })
|
||||
.range(from, to),
|
||||
@@ -94,12 +124,14 @@ export default function DeadlinesPage() {
|
||||
setDeadlines(deadlineRows)
|
||||
setCustomers(customerRows)
|
||||
setOverdueInvoices({ count: overdueRows.length, total: overdueTotal, unconverted: unconvertedCount })
|
||||
return true
|
||||
} catch {
|
||||
toast({
|
||||
title: t('load_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return false
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
@@ -112,13 +144,33 @@ export default function DeadlinesPage() {
|
||||
const handleGenerateSystemDeadlines = async () => {
|
||||
setIsGenerating(true)
|
||||
try {
|
||||
const response = await fetch('/api/tax-deadlines/generate', { method: 'POST' })
|
||||
const result = await response.json()
|
||||
const response = await fetch('/api/tax-deadlines/generate', {
|
||||
method: 'POST',
|
||||
}).catch(() => null)
|
||||
|
||||
// The request never reached the route (offline, connection reset), so
|
||||
// point at the connection rather than the data.
|
||||
if (!response) {
|
||||
toast({
|
||||
title: t('generate_failed_title'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(result.error || t('generate_failed_description'))
|
||||
toast({
|
||||
title: t('generate_failed_title'),
|
||||
description: await describeFailure(response),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Only a malformed success body reaches the catch below now.
|
||||
const result = await response.json()
|
||||
|
||||
if ((result.created ?? 0) === 0) {
|
||||
// Nothing was generated: the tax settings are genuinely incomplete.
|
||||
// Point the user to fill them in (the banner's settings link stays visible).
|
||||
@@ -145,149 +197,216 @@ export default function DeadlinesPage() {
|
||||
}
|
||||
}
|
||||
|
||||
const handleDeadlineCreate = async (data: DeadlineFormValues) => {
|
||||
try {
|
||||
const response = await fetch('/api/deadlines', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
// Returns whether the create landed. False keeps the form open with the
|
||||
// user's input (handleFormSubmit only closes it on success); the toast above
|
||||
// each return is the user's copy of why. Not a throw: DeadlineForm's submit
|
||||
// wrapper has no catch, so a rejection here would escape as an unhandled
|
||||
// promise rejection rather than control flow.
|
||||
const handleDeadlineCreate = async (data: DeadlineFormValues): Promise<boolean> => {
|
||||
const response = await fetch('/api/deadlines', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
}).catch(() => null)
|
||||
|
||||
if (!response.ok) {
|
||||
const result = await response.json()
|
||||
throw new Error(result.error || 'Failed to create deadline')
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('created_title'),
|
||||
description: t('created_description'),
|
||||
})
|
||||
|
||||
fetchData()
|
||||
} catch (error) {
|
||||
if (!response) {
|
||||
// The request never reached the route (offline, connection reset), so
|
||||
// point at the connection rather than the data.
|
||||
toast({
|
||||
title: t('create_failed_title'),
|
||||
description: error instanceof Error ? getUserErrorMessage(error) : t('retry'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
throw error
|
||||
return false
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('create_failed_title'),
|
||||
description: await describeFailure(response),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('created_title'),
|
||||
description: t('created_description'),
|
||||
})
|
||||
|
||||
fetchData()
|
||||
return true
|
||||
}
|
||||
|
||||
// "Ångra" on the marked-done toast. It lives here rather than inline in the
|
||||
// toast so it gets the same treatment as every other mutation on this page:
|
||||
// gated on res.ok, refetched, and answered with exactly one sentence. A
|
||||
// Skatteverket deadline that is still marked done must never be reported as
|
||||
// back on the list, and a failed undo must not look like a successful one.
|
||||
const handleUndoComplete = useCallback(
|
||||
async (deadline: Deadline) => {
|
||||
const response = await fetch(`/api/deadlines/${deadline.id}/complete`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
// The target state, not a toggle: clicking undo twice, or undoing a row
|
||||
// something else already un-ticked, must not re-complete the deadline.
|
||||
body: JSON.stringify({ is_completed: false }),
|
||||
}).catch(() => null)
|
||||
|
||||
// null: the request never completed (offline, connection reset). Nothing
|
||||
// was undone, so point at the connection rather than the data.
|
||||
if (!response) {
|
||||
toast({
|
||||
title: t('undo_failed'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('undo_failed'),
|
||||
// The route knows why it refused (gone, read-only member); prefer its
|
||||
// own message over generic retry copy.
|
||||
description: await describeFailure(response),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Confirm only once the row is provably back. When the reload failed,
|
||||
// fetchData has already said so and TOAST_LIMIT is 1, so a success
|
||||
// sentence here would evict that warning and render alone.
|
||||
if (!(await fetchData())) return
|
||||
|
||||
toast({ title: t('marked_not_done', { title: deadline.title }) })
|
||||
},
|
||||
[fetchData, toast, t],
|
||||
)
|
||||
|
||||
const handleDeadlineToggle = async (deadline: Deadline) => {
|
||||
const wasCompleted = deadline.is_completed
|
||||
const newCompleted = !wasCompleted
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/deadlines/${deadline.id}/complete`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ is_completed: newCompleted }),
|
||||
})
|
||||
const response = await fetch(`/api/deadlines/${deadline.id}/complete`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ is_completed: newCompleted }),
|
||||
}).catch(() => null)
|
||||
|
||||
if (!response.ok) {
|
||||
const result = await response.json()
|
||||
throw new Error(result.error || 'Failed to toggle deadline')
|
||||
}
|
||||
|
||||
fetchData()
|
||||
|
||||
if (newCompleted) {
|
||||
toast({
|
||||
title: t('marked_done', { title: deadline.title }),
|
||||
action: (
|
||||
<ToastAction altText={t('undo')} onClick={async () => {
|
||||
try {
|
||||
await fetch(`/api/deadlines/${deadline.id}/complete`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ is_completed: false }),
|
||||
})
|
||||
} catch {
|
||||
toast({
|
||||
title: t('undo_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}}>
|
||||
{t('undo')}
|
||||
</ToastAction>
|
||||
),
|
||||
})
|
||||
} else {
|
||||
toast({ title: t('marked_not_done', { title: deadline.title }) })
|
||||
}
|
||||
} catch (error) {
|
||||
if (!response) {
|
||||
toast({
|
||||
title: t('toggle_failed_title'),
|
||||
description: error instanceof Error ? getUserErrorMessage(error) : t('retry'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('toggle_failed_title'),
|
||||
description: await describeFailure(response),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
fetchData()
|
||||
|
||||
if (newCompleted) {
|
||||
toast({
|
||||
title: t('marked_done', { title: deadline.title }),
|
||||
action: (
|
||||
<ToastAction
|
||||
altText={t('undo')}
|
||||
onClick={() => {
|
||||
void handleUndoComplete(deadline)
|
||||
}}
|
||||
>
|
||||
{t('undo')}
|
||||
</ToastAction>
|
||||
),
|
||||
})
|
||||
} else {
|
||||
toast({ title: t('marked_not_done', { title: deadline.title }) })
|
||||
}
|
||||
}
|
||||
|
||||
// Sends ONLY the form-managed fields: the PUT route whitelists to the same
|
||||
// set, and posting a whole Deadline row from here would fabricate system
|
||||
// fields (source, status, reminder_offsets) that only the whitelist drops.
|
||||
const handleDeadlineEdit = async (id: string, data: DeadlineFormValues) => {
|
||||
try {
|
||||
const response = await fetch(`/api/deadlines/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
// Returns whether the edit landed, same contract as create: false keeps the
|
||||
// form open with the user's input instead of silently discarding it.
|
||||
const handleDeadlineEdit = async (id: string, data: DeadlineFormValues): Promise<boolean> => {
|
||||
const response = await fetch(`/api/deadlines/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
}).catch(() => null)
|
||||
|
||||
if (!response.ok) {
|
||||
const result = await response.json()
|
||||
throw new Error(result.error || 'Failed to edit deadline')
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('updated_title'),
|
||||
description: t('updated_description'),
|
||||
})
|
||||
|
||||
fetchData()
|
||||
} catch (error) {
|
||||
if (!response) {
|
||||
toast({
|
||||
title: t('update_failed_title'),
|
||||
description: error instanceof Error ? getUserErrorMessage(error) : t('retry'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
// Rethrow (like create) so a failed edit keeps the form open with the
|
||||
// user's input instead of silently discarding it.
|
||||
throw error
|
||||
return false
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('update_failed_title'),
|
||||
description: await describeFailure(response),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('updated_title'),
|
||||
description: t('updated_description'),
|
||||
})
|
||||
|
||||
fetchData()
|
||||
return true
|
||||
}
|
||||
|
||||
const handleDeadlineDelete = async (deadline: Deadline) => {
|
||||
try {
|
||||
const response = await fetch(`/api/deadlines/${deadline.id}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
const response = await fetch(`/api/deadlines/${deadline.id}`, {
|
||||
method: 'DELETE',
|
||||
}).catch(() => null)
|
||||
|
||||
if (!response.ok) {
|
||||
const result = await response.json()
|
||||
throw new Error(result.error || 'Failed to delete deadline')
|
||||
}
|
||||
|
||||
toast({ title: t('deleted_title') })
|
||||
fetchData()
|
||||
} catch (error) {
|
||||
if (!response) {
|
||||
toast({
|
||||
title: t('delete_failed_title'),
|
||||
description: error instanceof Error ? getUserErrorMessage(error) : t('retry'),
|
||||
description: t('load_failed_description'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
toast({
|
||||
title: t('delete_failed_title'),
|
||||
description: await describeFailure(response),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
toast({ title: t('deleted_title') })
|
||||
fetchData()
|
||||
}
|
||||
|
||||
const handleFormSubmit = async (data: DeadlineFormValues) => {
|
||||
if (editingDeadline) {
|
||||
await handleDeadlineEdit(editingDeadline.id, data)
|
||||
} else {
|
||||
await handleDeadlineCreate(data)
|
||||
}
|
||||
const ok = editingDeadline
|
||||
? await handleDeadlineEdit(editingDeadline.id, data)
|
||||
: await handleDeadlineCreate(data)
|
||||
// On failure the handler has already toasted; leave the form open so the
|
||||
// user's input survives a retry.
|
||||
if (!ok) return
|
||||
setShowForm(false)
|
||||
setEditingDeadline(null)
|
||||
}
|
||||
|
||||
@@ -271,7 +271,10 @@ function BankFileImportWizard() {
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
setBankError(data.error || 'Importen misslyckades')
|
||||
// Map the parsed body plus the status: on the thrown-error path
|
||||
// `data.error` is the canonical envelope OBJECT (withRouteContext),
|
||||
// which must never be stored into a rendered string state.
|
||||
setBankError(getErrorMessage(data, { statusCode: res.status }))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -872,7 +875,9 @@ function OpeningBalanceFlow() {
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
setObError(data.error || 'Kunde inte läsa filen')
|
||||
// Map the parsed body plus the status, never render `data.error` raw:
|
||||
// the thrown-error path answers with the canonical envelope OBJECT.
|
||||
setObError(getErrorMessage(data, { statusCode: res.status }))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -927,7 +932,7 @@ function OpeningBalanceFlow() {
|
||||
const data = await res.json()
|
||||
|
||||
if (!res.ok) {
|
||||
setObError(data.error || 'Kunde inte läsa filen med de valda kolumnerna')
|
||||
setObError(getErrorMessage(data, { statusCode: res.status }))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -45,10 +45,6 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
const [createdCreditNote, setCreatedCreditNote] = useState<InvoiceWithRelations | null>(null)
|
||||
const [showSendPrompt, setShowSendPrompt] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
fetchInvoice()
|
||||
}, [id])
|
||||
|
||||
async function fetchInvoice() {
|
||||
setIsLoading(true)
|
||||
|
||||
@@ -103,6 +99,10 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchInvoice()
|
||||
}, [id])
|
||||
|
||||
async function handleSubmit() {
|
||||
if (!invoice) return
|
||||
|
||||
@@ -119,8 +119,19 @@ export default function CreateCreditNotePage({ params }: { params: Promise<{ id:
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json()
|
||||
throw new Error(data.error || t('create_failed_fallback'))
|
||||
// Map the parsed body plus the status, never `new Error(data.error)`:
|
||||
// the route answers thrown errors with the canonical envelope
|
||||
// `{ error: { code, message } }`, and the Error constructor would
|
||||
// stringify that object to "[object Object]", discarding the route's
|
||||
// own Swedish reason.
|
||||
const body = await response.json().catch(() => null)
|
||||
toast({
|
||||
title: t('create_failed_title'),
|
||||
description: getUserErrorMessage(body, { statusCode: response.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setIsSubmitting(false)
|
||||
return
|
||||
}
|
||||
|
||||
const { data: creditNote } = await response.json() as { data: InvoiceWithRelations }
|
||||
|
||||
@@ -18,6 +18,13 @@ import { isEditableInvoiceDraft } from '@/lib/invoices/is-editable-draft'
|
||||
import { creditNoteNeedsJournalEntry } from '@/lib/invoices/issue-credit-note'
|
||||
import { getCreditNoteSendMode } from '@/lib/invoices/credit-note-send-mode'
|
||||
import { canCopyInvoice } from '@/lib/invoices/copy-invoice'
|
||||
import {
|
||||
invoiceDocumentCaveat,
|
||||
invoiceRerenderUrl,
|
||||
resolveInvoicePdfSource,
|
||||
type InvoicePdfRerenderReason,
|
||||
type InvoicePdfSource,
|
||||
} from '@/lib/invoices/invoice-pdf-source'
|
||||
import { contentDispositionFilename } from '@/lib/api/content-disposition'
|
||||
import {
|
||||
Loader2,
|
||||
@@ -70,6 +77,18 @@ const statusVariantMap: Record<InvoiceStatus, 'default' | 'secondary' | 'success
|
||||
credited: 'secondary',
|
||||
}
|
||||
|
||||
// Why the downloaded file is not the invoice the customer received. One key
|
||||
// per reason: "no archived copy exists" and "the archive could not be reached"
|
||||
// are different facts and must not be told as the same story.
|
||||
const RERENDER_CAVEAT_KEYS: Record<
|
||||
Exclude<InvoicePdfRerenderReason, 'not_sent_yet'>,
|
||||
string
|
||||
> = {
|
||||
sent_outside_accounted: 'pdf_rerender_reason_sent_outside',
|
||||
no_archived_copy: 'pdf_rerender_reason_no_archive',
|
||||
archive_unreachable: 'pdf_rerender_reason_archive_unreachable',
|
||||
}
|
||||
|
||||
// A line is periodiserad when both period dates are set: the revenue was
|
||||
// parked on the 29xx interim account and dissolves monthly via accrual_schedules.
|
||||
const itemHasAccrual = (item: InvoiceItem): boolean =>
|
||||
@@ -99,6 +118,14 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
const [invoice, setInvoice] = useState<InvoiceWithRelations | null>(null)
|
||||
const [reminders, setReminders] = useState<InvoiceReminder[]>([])
|
||||
const [deliveries, setDeliveries] = useState<InvoiceDeliveryView[]>([])
|
||||
// An empty deliveries list means "nothing was ever sent through Accounted".
|
||||
// A failed read also produces an empty list, and the two must never be
|
||||
// conflated: the archived PDF the customer received is the räkenskapsunderlag
|
||||
// (BFL 7 kap), and a freshly re-rendered one is a different document.
|
||||
const [deliveriesUnreadable, setDeliveriesUnreadable] = useState(false)
|
||||
// Set when the archived copy could not be produced, so the user is asked
|
||||
// instead of being handed a substitute that looks like the original.
|
||||
const [pdfArchiveIssue, setPdfArchiveIssue] = useState<'history' | 'document' | null>(null)
|
||||
// Payment history backing the new Betalningsstatus card. Fetched alongside
|
||||
// the invoice itself so the card stays in sync with paid_amount /
|
||||
// remaining_amount on the invoice row.
|
||||
@@ -142,6 +169,34 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
fetchInvoice()
|
||||
}, [id])
|
||||
|
||||
/**
|
||||
* Read the delivery history, keeping "read failed" distinct from "nothing
|
||||
* has been sent". Both used to arrive as `[]`, which is what let a network
|
||||
* blip silently downgrade the invoice download from the archived PDF the
|
||||
* customer received to a freshly re-rendered one.
|
||||
*/
|
||||
async function loadDeliveries(): Promise<{
|
||||
ok: boolean
|
||||
deliveries: InvoiceDeliveryView[]
|
||||
}> {
|
||||
try {
|
||||
const response = await fetch(`/api/invoices/${encodeURIComponent(id)}/deliveries`)
|
||||
if (!response.ok) return { ok: false, deliveries: [] }
|
||||
const payload = (await response.json()) as { data?: InvoiceDeliveryView[] }
|
||||
if (!Array.isArray(payload.data)) return { ok: false, deliveries: [] }
|
||||
return { ok: true, deliveries: payload.data }
|
||||
} catch {
|
||||
return { ok: false, deliveries: [] }
|
||||
}
|
||||
}
|
||||
|
||||
async function retryLoadDeliveries() {
|
||||
const result = await loadDeliveries()
|
||||
setDeliveries(result.deliveries)
|
||||
setDeliveriesUnreadable(!result.ok)
|
||||
return result
|
||||
}
|
||||
|
||||
async function fetchInvoice() {
|
||||
setIsLoading(true)
|
||||
|
||||
@@ -155,13 +210,7 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
.maybeSingle()
|
||||
: Promise.resolve(null)
|
||||
|
||||
const deliveriesPromise = fetch(`/api/invoices/${encodeURIComponent(id)}/deliveries`)
|
||||
.then(async (response) => {
|
||||
if (!response.ok) return []
|
||||
const payload = (await response.json()) as { data?: InvoiceDeliveryView[] }
|
||||
return Array.isArray(payload.data) ? payload.data : []
|
||||
})
|
||||
.catch(() => [] as InvoiceDeliveryView[])
|
||||
const deliveriesPromise = loadDeliveries()
|
||||
|
||||
// Invoice, reminders, payments, and deliveries all key on the route id: one
|
||||
// parallel batch. Only the follow-ups below need the invoice row.
|
||||
@@ -211,7 +260,8 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
}
|
||||
|
||||
setInvoice(data as InvoiceWithRelations)
|
||||
setDeliveries(deliveryData)
|
||||
setDeliveries(deliveryData.deliveries)
|
||||
setDeliveriesUnreadable(!deliveryData.ok)
|
||||
|
||||
if (reminderData) {
|
||||
setReminders(reminderData as InvoiceReminder[])
|
||||
@@ -419,25 +469,36 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
setIsConverting(false)
|
||||
}
|
||||
|
||||
async function downloadPDF() {
|
||||
/**
|
||||
* Fetch and save one specific document, then say truthfully which one it was.
|
||||
*
|
||||
* The archived delivery is the invoice the customer actually received and is
|
||||
* the räkenskapsunderlag kept for 7 years (BFL 7 kap). A re-render comes off
|
||||
* today's invoice row, customer row, company settings and logo, so it is a
|
||||
* different document whenever any of those moved. It may be served when it
|
||||
* is the only thing that exists, but never under the plain "nedladdad" toast
|
||||
* that reads as "here is what you sent".
|
||||
*/
|
||||
async function runInvoiceDownload(source: InvoicePdfSource) {
|
||||
if (!invoice) return
|
||||
|
||||
if (source.kind === 'unavailable') {
|
||||
setPdfArchiveIssue('history')
|
||||
return
|
||||
}
|
||||
|
||||
setIsDownloading(true)
|
||||
|
||||
try {
|
||||
const mostRecentDelivery = deliveries.find(
|
||||
(delivery) => delivery.status === 'sent' || delivery.status === 'marked_sent',
|
||||
)
|
||||
const archivedDelivery = mostRecentDelivery?.status === 'sent'
|
||||
? mostRecentDelivery
|
||||
: undefined
|
||||
const response = await fetch(
|
||||
archivedDelivery?.document_attachment_id
|
||||
? `/api/documents/${archivedDelivery.document_attachment_id}/inline`
|
||||
: `/api/invoices/${invoice.id}/pdf`,
|
||||
)
|
||||
const response = await fetch(source.url)
|
||||
|
||||
if (!response.ok) {
|
||||
// A missing archive is not a generation failure and must not offer a
|
||||
// silent substitute: hand the choice back to the user.
|
||||
if (source.kind === 'archived') {
|
||||
setPdfArchiveIssue('document')
|
||||
return
|
||||
}
|
||||
throw new Error(t('pdf_generate_failed'))
|
||||
}
|
||||
|
||||
@@ -452,21 +513,73 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
window.URL.revokeObjectURL(url)
|
||||
document.body.removeChild(a)
|
||||
|
||||
toast({
|
||||
title: t('pdf_downloaded_title'),
|
||||
description: invoice.invoice_number
|
||||
? t('pdf_downloaded_with_number', { number: invoice.invoice_number })
|
||||
: t('pdf_downloaded_draft'),
|
||||
})
|
||||
const caveat = invoiceDocumentCaveat(source)
|
||||
if (caveat) {
|
||||
toast({
|
||||
title: t('pdf_rerender_downloaded_title'),
|
||||
description: t(RERENDER_CAVEAT_KEYS[caveat]),
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: t('pdf_downloaded_title'),
|
||||
description: invoice.invoice_number
|
||||
? t('pdf_downloaded_with_number', { number: invoice.invoice_number })
|
||||
: t('pdf_downloaded_draft'),
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: t('pdf_download_failed_title'),
|
||||
description: error instanceof Error ? getUserErrorMessage(error) : t('fallback_try_again'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
} finally {
|
||||
setIsDownloading(false)
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadPDF() {
|
||||
if (!invoice) return
|
||||
setPdfArchiveIssue(null)
|
||||
await runInvoiceDownload(
|
||||
resolveInvoicePdfSource({
|
||||
invoiceId: invoice.id,
|
||||
invoiceStatus: invoice.status,
|
||||
deliveriesLoaded: !deliveriesUnreadable,
|
||||
deliveries,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// "Försök igen" from the archive dialog. Re-reads the delivery history first
|
||||
// so a transient list failure resolves back to the archived copy instead of
|
||||
// getting stuck on the stale empty state.
|
||||
async function retryArchivedDownload() {
|
||||
if (!invoice) return
|
||||
setIsDownloading(true)
|
||||
const result = await retryLoadDeliveries()
|
||||
setIsDownloading(false)
|
||||
setPdfArchiveIssue(null)
|
||||
await runInvoiceDownload(
|
||||
resolveInvoicePdfSource({
|
||||
invoiceId: invoice.id,
|
||||
invoiceStatus: invoice.status,
|
||||
deliveriesLoaded: result.ok,
|
||||
deliveries: result.deliveries,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
// The user explicitly accepted a re-render after being told it is not the
|
||||
// document that was sent. The toast still says so.
|
||||
async function downloadRerenderAnyway() {
|
||||
if (!invoice) return
|
||||
setPdfArchiveIssue(null)
|
||||
await runInvoiceDownload({
|
||||
kind: 'rerender',
|
||||
url: invoiceRerenderUrl(invoice.id),
|
||||
reason: 'archive_unreachable',
|
||||
})
|
||||
}
|
||||
|
||||
// Open the finalize dialog and peek the next F-number so the user can see
|
||||
@@ -1002,7 +1115,32 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{isRealInvoice && !isSelfBilled && (
|
||||
{/* The legacy empty state asserts "sent before delivery history
|
||||
existed". A failed read produces the same empty list, so that
|
||||
claim would be a guess: say what actually happened instead. */}
|
||||
{isRealInvoice && !isSelfBilled && deliveriesUnreadable && (
|
||||
<Card className="lg:col-span-2">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Mail className="h-5 w-5" />
|
||||
{t('delivery_history_title')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
|
||||
<p className="font-medium text-foreground">
|
||||
{t('delivery_history_unreadable_title')}
|
||||
</p>
|
||||
<p className="mt-1">{t('delivery_history_unreadable_description')}</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={() => void retryLoadDeliveries()}>
|
||||
{t('delivery_history_unreadable_retry')}
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{isRealInvoice && !isSelfBilled && !deliveriesUnreadable && (
|
||||
<InvoiceDeliveryHistory
|
||||
deliveries={deliveries}
|
||||
showLegacyEmptyState={[
|
||||
@@ -1533,6 +1671,47 @@ export default function InvoiceDetailPage({ params }: { params: Promise<{ id: st
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* The archived PDF the customer received could not be produced. Nothing
|
||||
has been downloaded at this point: a re-render is a different
|
||||
document, so the user chooses it deliberately or not at all. */}
|
||||
<Dialog
|
||||
open={pdfArchiveIssue !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPdfArchiveIssue(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('pdf_archive_issue_title')}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{pdfArchiveIssue === 'document'
|
||||
? t('pdf_archive_issue_document_desc')
|
||||
: t('pdf_archive_issue_history_desc')}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setPdfArchiveIssue(null)}
|
||||
disabled={isDownloading}
|
||||
>
|
||||
{t('pdf_archive_issue_cancel')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={downloadRerenderAnyway}
|
||||
disabled={isDownloading}
|
||||
>
|
||||
{t('pdf_archive_issue_rerender')}
|
||||
</Button>
|
||||
<Button onClick={retryArchivedDownload} disabled={isDownloading}>
|
||||
{isDownloading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t('pdf_archive_issue_retry')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<PaymentBookingDialog
|
||||
open={showPaymentDialog}
|
||||
onOpenChange={setShowPaymentDialog}
|
||||
|
||||
+154
-49
@@ -1,14 +1,21 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useState, useEffect, useCallback, useId } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { Settings2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { HelpPopover } from '@/components/ui/help-popover'
|
||||
import { AttnLine } from '@/components/ui/attn-line'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { FyPicker } from '@/components/common/FyPicker'
|
||||
import { KPIPanes, KPIBreakdown } from '@/components/kpi/KPIStory'
|
||||
import { KPISettingsDialog } from '@/components/kpi/KPISettingsDialog'
|
||||
import { getDefaultPreferences } from '@/lib/reports/kpi-definitions'
|
||||
import { saveKPIPreferences } from '@/components/kpi/save-preferences'
|
||||
import { loadKPIPreferences } from '@/components/kpi/load-preferences'
|
||||
import { failureDescription, type ActionFailure } from '@/lib/browser/action-failure'
|
||||
import type { ErrorLocale } from '@/lib/errors/get-error-message'
|
||||
import type { KPIReport, KPIPreferences } from '@/types'
|
||||
|
||||
/**
|
||||
@@ -19,26 +26,50 @@ import type { KPIReport, KPIPreferences } from '@/types'
|
||||
*/
|
||||
export default function KpiPage() {
|
||||
const t = useTranslations('kpi')
|
||||
const locale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const [selectedPeriod, setSelectedPeriod] = useState<string>('')
|
||||
const [report, setReport] = useState<KPIReport | null>(null)
|
||||
const [preferences, setPreferences] = useState<KPIPreferences>(getDefaultPreferences())
|
||||
// null = the stored layout is not known: still loading, or the read failed
|
||||
// (prefsError). It never holds a fabricated value.
|
||||
const [preferences, setPreferences] = useState<KPIPreferences | null>(null)
|
||||
const [prefsError, setPrefsError] = useState<ActionFailure | null>(null)
|
||||
const [reloadKey, setReloadKey] = useState(0)
|
||||
const [isLoadingReport, setIsLoadingReport] = useState(false)
|
||||
const [isSavingPrefs, setIsSavingPrefs] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const prefsStatusId = useId()
|
||||
|
||||
// A page that could not read the stored layout must not render one, and above
|
||||
// all must not let the user save over it. The previous version fell back to
|
||||
// getDefaultPreferences() on any failed read, silently: the grid presented
|
||||
// the defaults as though they were the user's, the settings dialog seeded
|
||||
// its draft from them, and the next save PUT a complete defaults-based
|
||||
// object over the stored row (the route merges key by key, so a payload
|
||||
// carrying every key replaces the row outright). A transient read failure
|
||||
// became permanent loss of the user's layout.
|
||||
//
|
||||
// So the unknown stays unknown: preferences stays null, the preference-driven
|
||||
// panes do not render, "Anpassa" is disabled, and one AttnLine says the
|
||||
// layout could not be read. An expired session (401/403) is the only case
|
||||
// where the reason changes what the user must do, so there the status-map
|
||||
// sentence replaces the retry; everything else is transient and the retry is
|
||||
// the whole answer.
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
;(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/kpi/preferences')
|
||||
const { data } = await res.json()
|
||||
if (!cancelled && data) setPreferences(data)
|
||||
} catch {
|
||||
// Silently fall back to defaults
|
||||
setPrefsError(null)
|
||||
const result = await loadKPIPreferences({ locale })
|
||||
if (cancelled) return
|
||||
if (result.ok) {
|
||||
setPreferences(result.preferences)
|
||||
} else {
|
||||
setPreferences(null)
|
||||
setPrefsError(result)
|
||||
}
|
||||
})()
|
||||
return () => { cancelled = true }
|
||||
}, [])
|
||||
}, [reloadKey, locale])
|
||||
|
||||
const fetchReport = useCallback(async (periodId: string) => {
|
||||
setIsLoadingReport(true)
|
||||
@@ -64,60 +95,134 @@ export default function KpiPage() {
|
||||
return () => { cancelled = true }
|
||||
}, [selectedPeriod, fetchReport])
|
||||
|
||||
async function handleSavePreferences(prefs: KPIPreferences) {
|
||||
/**
|
||||
* Resolves true only when the row was written. The dialog keeps itself open on
|
||||
* false, so the draft the user assembled survives a failed save.
|
||||
*
|
||||
* The previous version swallowed both the `!res.ok` throw and every thrown
|
||||
* fetch behind "Silently fail: user can retry": the dialog closed, this grid
|
||||
* went on rendering the layout the user had just picked, and the next page
|
||||
* load read the untouched row back and reverted it. Exactly one toast per
|
||||
* outcome, since TOAST_LIMIT is 1.
|
||||
*/
|
||||
async function handleSavePreferences(prefs: KPIPreferences): Promise<boolean> {
|
||||
let result
|
||||
setIsSavingPrefs(true)
|
||||
try {
|
||||
const res = await fetch('/api/kpi/preferences', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(prefs),
|
||||
})
|
||||
if (!res.ok) throw new Error()
|
||||
const { data } = await res.json()
|
||||
setPreferences(data)
|
||||
if (selectedPeriod) await fetchReport(selectedPeriod)
|
||||
} catch {
|
||||
// Silently fail: user can retry
|
||||
result = await saveKPIPreferences({ preferences: prefs, locale })
|
||||
} finally {
|
||||
// The busy state covers the save and nothing else. The report refetch
|
||||
// below is unbounded and has its own skeleton, and holding `saving` open
|
||||
// across it would keep the dialog locked on a request that is not the save.
|
||||
setIsSavingPrefs(false)
|
||||
}
|
||||
|
||||
if (!result.ok) {
|
||||
toast({
|
||||
title: t('save_failed_title'),
|
||||
description: failureDescription(result, {
|
||||
// A timeout on a write is genuinely ambiguous: the row may have been
|
||||
// written. Say that instead of claiming the save failed.
|
||||
timeout: t('save_timeout'),
|
||||
network: t('save_network'),
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return false
|
||||
}
|
||||
|
||||
setPreferences(result.preferences)
|
||||
// Not awaited: the layout is stored, so the dialog closes now. A failing
|
||||
// refetch reports itself through the `error` surface below.
|
||||
if (selectedPeriod) void fetchReport(selectedPeriod)
|
||||
return true
|
||||
}
|
||||
|
||||
const isLoadingPrefs = preferences === null && prefsError === null
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<PageHeader
|
||||
title={t('title')}
|
||||
help={
|
||||
<HelpPopover>
|
||||
<p>{t('help_text')}</p>
|
||||
</HelpPopover>
|
||||
}
|
||||
action={
|
||||
<div className="flex items-center gap-2">
|
||||
<KPISettingsDialog
|
||||
preferences={preferences}
|
||||
onSave={handleSavePreferences}
|
||||
saving={isSavingPrefs}
|
||||
/>
|
||||
<FyPicker
|
||||
value={selectedPeriod || null}
|
||||
onChange={(id) => setSelectedPeriod(id || '')}
|
||||
includeAllOption={false}
|
||||
hideFuturePeriods
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
{/* Header and read-status share one flow child so the always-mounted
|
||||
live region adds no vertical rhythm while it is empty. */}
|
||||
<div>
|
||||
<PageHeader
|
||||
title={t('title')}
|
||||
help={
|
||||
<HelpPopover>
|
||||
<p>{t('help_text')}</p>
|
||||
</HelpPopover>
|
||||
}
|
||||
action={
|
||||
<div className="flex items-center gap-2">
|
||||
{preferences ? (
|
||||
<KPISettingsDialog
|
||||
preferences={preferences}
|
||||
onSave={handleSavePreferences}
|
||||
saving={isSavingPrefs}
|
||||
/>
|
||||
) : (
|
||||
// The dialog seeds its draft from `preferences` and saves the
|
||||
// complete draft, so while the stored layout is unknown the
|
||||
// control that opens it must not exist: a save from here would
|
||||
// overwrite the row with a layout the user never chose.
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-1.5"
|
||||
disabled
|
||||
aria-describedby={prefsError ? prefsStatusId : undefined}
|
||||
>
|
||||
<Settings2 className="h-3.5 w-3.5" />
|
||||
{t('customize')}
|
||||
</Button>
|
||||
)}
|
||||
<FyPicker
|
||||
value={selectedPeriod || null}
|
||||
onChange={(id) => setSelectedPeriod(id || '')}
|
||||
includeAllOption={false}
|
||||
hideFuturePeriods
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Live region always mounted so a failed read is announced when it
|
||||
appears, not merely inserted. Inline, never a toast: TOAST_LIMIT is
|
||||
1 and a toast here could evict a save failure's toast. */}
|
||||
<div id={prefsStatusId} role="status" aria-live="polite">
|
||||
{prefsError && (
|
||||
<AttnLine
|
||||
className="mt-3"
|
||||
action={
|
||||
prefsError.reason === 'server' &&
|
||||
(prefsError.status === 401 || prefsError.status === 403)
|
||||
? undefined
|
||||
: { label: t('load_retry'), onClick: () => setReloadKey((k) => k + 1) }
|
||||
}
|
||||
>
|
||||
{failureDescription(prefsError, {
|
||||
timeout: t('load_timeout'),
|
||||
network: t('load_network'),
|
||||
})}
|
||||
</AttnLine>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="py-8 text-center text-sm text-muted-foreground">{error}</p>
|
||||
)}
|
||||
|
||||
{isLoadingReport && <LoadingSkeleton />}
|
||||
{(isLoadingReport || (!error && report !== null && isLoadingPrefs)) && (
|
||||
<LoadingSkeleton />
|
||||
)}
|
||||
|
||||
{!isLoadingReport && !error && report && (
|
||||
{!isLoadingReport && !error && report && !isLoadingPrefs && (
|
||||
<div className="stagger-enter space-y-10">
|
||||
<KPIPanes report={report} preferences={preferences} />
|
||||
{/* The panes are the preference-driven surface: with the layout
|
||||
unknown they stay off rather than render defaults as if they
|
||||
were the user's. The cost story below reads only the report. */}
|
||||
{preferences && <KPIPanes report={report} preferences={preferences} />}
|
||||
<KPIBreakdown report={report} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -2,22 +2,36 @@
|
||||
|
||||
import Link from 'next/link'
|
||||
import { useEffect, useState, useCallback } from 'react'
|
||||
import { useLocale, useTranslations } from 'next-intl'
|
||||
import { PageHeader } from '@/components/ui/page-header'
|
||||
import { FyPicker } from '@/components/common/FyPicker'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Skeleton } from '@/components/ui/skeleton'
|
||||
import { EmptyState } from '@/components/ui/empty-state'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/info-tooltip'
|
||||
import { ArrowLeft, Download, FileSpreadsheet, AlertTriangle, CheckCircle2 } from 'lucide-react'
|
||||
import {
|
||||
ArrowLeft,
|
||||
Download,
|
||||
FileSpreadsheet,
|
||||
AlertTriangle,
|
||||
CheckCircle2,
|
||||
Loader2,
|
||||
} from 'lucide-react'
|
||||
import { formatDate } from '@/lib/utils'
|
||||
import { downloadFile } from '@/lib/browser/download-file'
|
||||
import { failureDescription } from '@/lib/browser/action-failure'
|
||||
import type { KassaflodesanalysReport } from '@/lib/reports/kassaflodesanalys'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import {
|
||||
getErrorMessage as getUserErrorMessage,
|
||||
type ErrorLocale,
|
||||
} from '@/lib/errors/get-error-message'
|
||||
|
||||
function formatAmount(n: number): string {
|
||||
return n.toLocaleString('sv-SE', {
|
||||
@@ -55,10 +69,14 @@ function SubtotalRow({ label, amount }: SubtotalRowProps) {
|
||||
}
|
||||
|
||||
export function KassaflodesanalysClient() {
|
||||
const t = useTranslations('reports')
|
||||
const locale = useLocale() as ErrorLocale
|
||||
const { toast } = useToast()
|
||||
const [selectedPeriod, setSelectedPeriod] = useState<string | null>(null)
|
||||
const [report, setReport] = useState<KassaflodesanalysReport | null>(null)
|
||||
const [isLoadingPeriods, setIsLoadingPeriods] = useState(true)
|
||||
const [isLoadingReport, setIsLoadingReport] = useState(false)
|
||||
const [isDownloadingPdf, setIsDownloadingPdf] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const loadReport = useCallback(async (periodId: string) => {
|
||||
@@ -88,10 +106,60 @@ export function KassaflodesanalysClient() {
|
||||
}
|
||||
}, [selectedPeriod, loadReport])
|
||||
|
||||
const handleDownloadPdf = useCallback(() => {
|
||||
if (!selectedPeriod) return
|
||||
window.location.href = `/api/reports/kassaflodesanalys/pdf?period_id=${selectedPeriod}`
|
||||
}, [selectedPeriod])
|
||||
/**
|
||||
* Fetch the statutory kassaflödesanalys PDF and save it only if the server
|
||||
* actually produced one.
|
||||
*
|
||||
* This used to be `window.location.href = <pdf route>`, which has no seam for
|
||||
* either half of the problem. On success the browser cancels the navigation
|
||||
* (the route answers Content-Disposition: attachment) and the click gives no
|
||||
* feedback at all, so nothing marks the render as in flight: a second click
|
||||
* starts a second full report query plus renderToBuffer. On failure the route
|
||||
* answers a JSON error envelope with no Content-Disposition, so the browser
|
||||
* navigates the whole app away and the user is left staring at raw JSON with
|
||||
* their report page gone. There is no `res` to check and no promise to catch
|
||||
* on a location assignment; the only fix is to make the download a bounded
|
||||
* fetch.
|
||||
*
|
||||
* The filename mirrors the route's Content-Disposition
|
||||
* (kassaflodesanalys-<period_start>.pdf): both sides derive it from the same
|
||||
* fiscal period, and the button is disabled until that report is loaded.
|
||||
*
|
||||
* No success toast: the saved file is the feedback. On failure nothing was
|
||||
* written to disk and exactly one toast says why. Never two, TOAST_LIMIT is 1
|
||||
* (components/ui/use-toast.tsx), so a second toast in the same tick evicts the
|
||||
* first and only the last is rendered.
|
||||
*/
|
||||
const handleDownloadPdf = useCallback(async () => {
|
||||
// The button is disabled while a render is in flight; this guard closes the
|
||||
// double-click / Enter-repeat race before React has re-rendered it.
|
||||
if (!selectedPeriod || !report || isDownloadingPdf) return
|
||||
setIsDownloadingPdf(true)
|
||||
try {
|
||||
// The shared 15s deadline applies: this is one fiscal year of aggregation
|
||||
// plus a single-page render with stock fonts, so the realistic worst case
|
||||
// is a cold start and one round trip. If a healthy render ever needs
|
||||
// longer, the answer is maxDuration on the route plus a matching
|
||||
// timeoutMs here, never an unbounded fetch that spins forever.
|
||||
const result = await downloadFile({
|
||||
url: `/api/reports/kassaflodesanalys/pdf?period_id=${selectedPeriod}`,
|
||||
filename: `kassaflodesanalys-${report.period_start}.pdf`,
|
||||
locale,
|
||||
})
|
||||
if (!result.ok) {
|
||||
toast({
|
||||
title: t('pdf_download_failed_title'),
|
||||
description: failureDescription(result, {
|
||||
timeout: t('pdf_download_timeout'),
|
||||
network: t('pdf_download_network'),
|
||||
}),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
} finally {
|
||||
setIsDownloadingPdf(false)
|
||||
}
|
||||
}, [selectedPeriod, report, isDownloadingPdf, locale, toast, t])
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
@@ -116,9 +184,13 @@ export function KassaflodesanalysClient() {
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleDownloadPdf}
|
||||
disabled={!report || isLoadingReport}
|
||||
disabled={!report || isLoadingReport || isDownloadingPdf}
|
||||
>
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
{isDownloadingPdf ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Ladda ner PDF
|
||||
</Button>
|
||||
<TooltipProvider delayDuration={300}>
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
lookupBankByClearing,
|
||||
checkEmployeeAccountChecksum,
|
||||
} from '@/lib/salary/payment/bank-account'
|
||||
import type { Employee } from '@/types'
|
||||
import type { EmployeeMasked } from '@/types'
|
||||
import { EmployeeBenefitsPanel } from '@/components/salary/EmployeeBenefitsPanel'
|
||||
import { OpeningBalancesPanel } from '@/components/salary/OpeningBalancesPanel'
|
||||
import EmployeeTaxCard, { type EmployeeTaxValue } from '@/components/salary/EmployeeTaxCard'
|
||||
@@ -49,7 +49,7 @@ export default function EmployeeDetailPage({ params }: { params: Promise<{ id: s
|
||||
const { toast } = useToast()
|
||||
const { canWrite } = useCanWrite()
|
||||
const { dialogProps, confirm: confirmAction } = useDestructiveConfirm()
|
||||
const [employee, setEmployee] = useState<Employee | null>(null)
|
||||
const [employee, setEmployee] = useState<EmployeeMasked | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [deactivating, setDeactivating] = useState(false)
|
||||
@@ -241,7 +241,7 @@ export default function EmployeeDetailPage({ params }: { params: Promise<{ id: s
|
||||
{employee.first_name} {employee.last_name}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{employee.personnummer} · {t(EMPLOYMENT_LABEL_KEYS[employee.employment_type])}
|
||||
{employee.personnummer_masked} · {t(EMPLOYMENT_LABEL_KEYS[employee.employment_type])}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -416,9 +416,10 @@ export default function EmployeeDetailPage({ params }: { params: Promise<{ id: s
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Tax */}
|
||||
{/* Tax. The masked personnummer is enough input here: EmployeeTaxCard
|
||||
only reads the leading birthdate digits to suggest a tax column. */}
|
||||
<EmployeeTaxCard
|
||||
personnummer={employee.personnummer || ''}
|
||||
personnummer={employee.personnummer_masked || ''}
|
||||
disabled={!canWrite}
|
||||
onChange={setTax}
|
||||
initial={{
|
||||
|
||||
@@ -13,7 +13,7 @@ import { Plus, UserCircle } from 'lucide-react'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { cn, formatCurrency } from '@/lib/utils'
|
||||
import { DialogLoadingSkeleton } from '@/components/ui/dialog-loading-skeleton'
|
||||
import type { Employee } from '@/types'
|
||||
import type { EmployeeMasked } from '@/types'
|
||||
|
||||
const NewEmployeeDialog = dynamic(
|
||||
() => import('@/components/salary/NewEmployeeDialog'),
|
||||
@@ -33,7 +33,7 @@ const EMPLOYMENT_LABEL_KEYS: Record<string, string> = {
|
||||
*/
|
||||
export default function EmployeesPage() {
|
||||
const t = useTranslations('employees')
|
||||
const [employees, setEmployees] = useState<Employee[]>([])
|
||||
const [employees, setEmployees] = useState<EmployeeMasked[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const { canWrite } = useCanWrite()
|
||||
const router = useRouter()
|
||||
@@ -120,7 +120,7 @@ export default function EmployeesPage() {
|
||||
</Link>
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'hidden whitespace-nowrap tabular-nums text-muted-foreground md:table-cell')}>
|
||||
{emp.personnummer}
|
||||
{emp.personnummer_masked}
|
||||
</td>
|
||||
<td className={cn(TD_CLASS, 'whitespace-nowrap text-muted-foreground')}>
|
||||
{EMPLOYMENT_LABEL_KEYS[emp.employment_type]
|
||||
|
||||
@@ -14,7 +14,7 @@ import { useToast } from '@/components/ui/use-toast'
|
||||
import { useCanWrite } from '@/lib/hooks/use-can-write'
|
||||
import { getErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { cn, formatCurrency, formatDate } from '@/lib/utils'
|
||||
import type { Employee, SalaryRun } from '@/types'
|
||||
import type { EmployeeMasked, SalaryRun } from '@/types'
|
||||
|
||||
const STATUS_LABEL_KEYS: Record<string, string> = {
|
||||
draft: 'status_draft',
|
||||
@@ -46,7 +46,7 @@ const STATUS_VARIANTS: Record<string, 'default' | 'secondary' | 'success' | 'war
|
||||
*/
|
||||
export default function SalaryPage() {
|
||||
const [runs, setRuns] = useState<SalaryRun[]>([])
|
||||
const [employees, setEmployees] = useState<Employee[]>([])
|
||||
const [employees, setEmployees] = useState<EmployeeMasked[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [starting, setStarting] = useState(false)
|
||||
const { canWrite } = useCanWrite()
|
||||
|
||||
@@ -9,7 +9,7 @@ import { Button } from '@/components/ui/button'
|
||||
import { SalaryCalendar } from '@/components/salary/SalaryCalendar'
|
||||
import { SalaryOverridePanel } from '@/components/salary/SalaryOverridePanel'
|
||||
import { formatCurrency } from '@/lib/utils'
|
||||
import type { SalaryRun, SalaryRunEmployee, SalaryLineItem, SalaryLineItemType, Employee } from '@/types'
|
||||
import type { SalaryRun, SalaryRunEmployee, SalaryLineItem, SalaryLineItemType, EmployeeMasked } from '@/types'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
/** Translation keys in the `salary_run_employee` namespace. */
|
||||
@@ -55,7 +55,7 @@ const LINE_ITEM_TYPE_KEYS: Record<SalaryLineItemType, string> = {
|
||||
|
||||
interface DetailResponse {
|
||||
run: SalaryRun
|
||||
runEmployee: SalaryRunEmployee & { employee: Employee; line_items: SalaryLineItem[] }
|
||||
runEmployee: SalaryRunEmployee & { employee: EmployeeMasked; line_items: SalaryLineItem[] }
|
||||
}
|
||||
|
||||
export default function SalaryRunEmployeeDetailPage({
|
||||
@@ -81,10 +81,21 @@ export default function SalaryRunEmployeeDetailPage({
|
||||
fetch(`/api/salary/runs/${runId}`),
|
||||
fetch(`/api/salary/runs/${runId}/employees/${employeeId}`),
|
||||
])
|
||||
const runJson = await runRes.json()
|
||||
const sreJson = await sreRes.json()
|
||||
if (!runRes.ok) throw new Error(runJson.error || t('error_load_run'))
|
||||
if (!sreRes.ok) throw new Error(sreJson.error || t('error_load_employee'))
|
||||
const runJson = await runRes.json().catch(() => null)
|
||||
const sreJson = await sreRes.json().catch(() => null)
|
||||
// Map the parsed body plus the status, never `new Error(json.error)`:
|
||||
// the routes answer thrown errors with the canonical envelope
|
||||
// `{ error: { code, message } }`, and the Error constructor stringifies
|
||||
// that object to "[object Object]", which falls through to the generic
|
||||
// "Något gick fel" and discards the route's own Swedish reason.
|
||||
if (!runRes.ok) {
|
||||
setError(getUserErrorMessage(runJson, { statusCode: runRes.status }))
|
||||
return
|
||||
}
|
||||
if (!sreRes.ok) {
|
||||
setError(getUserErrorMessage(sreJson, { statusCode: sreRes.status }))
|
||||
return
|
||||
}
|
||||
setData({ run: runJson.data, runEmployee: sreJson.data })
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? getUserErrorMessage(e) : t('unknown_error'))
|
||||
@@ -103,9 +114,12 @@ export default function SalaryRunEmployeeDetailPage({
|
||||
setError(null)
|
||||
try {
|
||||
const res = await fetch(`/api/salary/runs/${runId}/calculate`, { method: 'POST' })
|
||||
const json = await res.json().catch(() => ({}))
|
||||
const json = await res.json().catch(() => null)
|
||||
if (!res.ok) {
|
||||
throw new Error(json.error || t('error_calculate'))
|
||||
// Same reason as in load(): the calculate route builds its refusals
|
||||
// with errorResponse(), so `json.error` is the envelope object.
|
||||
setError(getUserErrorMessage(json, { statusCode: res.status }))
|
||||
return
|
||||
}
|
||||
await load()
|
||||
} catch (e) {
|
||||
@@ -176,7 +190,7 @@ export default function SalaryRunEmployeeDetailPage({
|
||||
{employee.first_name} {employee.last_name}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground tabular-nums">
|
||||
{employee.personnummer} · {t('payslip_period', { period: periodLabel })}
|
||||
{employee.personnummer_masked} · {t('payslip_period', { period: periodLabel })}
|
||||
</p>
|
||||
</div>
|
||||
{run.status === 'draft' && (
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -188,7 +188,15 @@ export default function SkattekontoPage() {
|
||||
}
|
||||
return
|
||||
}
|
||||
throw new Error(json.error || 'Synk misslyckades')
|
||||
// Map the parsed body plus the status, never `new Error(json.error)`:
|
||||
// the Error constructor stringifies a non-string body field, and the
|
||||
// mapper would discard the route's own Swedish reason.
|
||||
toast({
|
||||
title: 'Synk misslyckades',
|
||||
description: getUserErrorMessage(json, { statusCode: res.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
setReconnectMessage(null)
|
||||
toast({
|
||||
@@ -216,7 +224,12 @@ export default function SkattekontoPage() {
|
||||
)
|
||||
const json = await res.json()
|
||||
if (!res.ok) {
|
||||
throw new Error(json.error || 'Bokföring misslyckades')
|
||||
toast({
|
||||
title: 'Kunde inte bokföra',
|
||||
description: getUserErrorMessage(json, { statusCode: res.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: 'Utkast skapat',
|
||||
@@ -245,7 +258,13 @@ export default function SkattekontoPage() {
|
||||
)
|
||||
const json = await res.json()
|
||||
if (!res.ok) {
|
||||
throw new Error(json.error || 'Kunde inte söka kandidater')
|
||||
toast({
|
||||
title: 'Kunde inte hämta kandidater',
|
||||
description: getUserErrorMessage(json, { statusCode: res.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
setMatchOpenFor(null)
|
||||
return
|
||||
}
|
||||
setMatchCandidates(json.data.candidates as MatchCandidate[])
|
||||
} catch (err) {
|
||||
@@ -274,7 +293,12 @@ export default function SkattekontoPage() {
|
||||
)
|
||||
const json = await res.json()
|
||||
if (!res.ok) {
|
||||
throw new Error(json.error || 'Matchning misslyckades')
|
||||
toast({
|
||||
title: 'Kunde inte koppla transaktionen',
|
||||
description: getUserErrorMessage(json, { statusCode: res.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
toast({ title: 'Transaktion kopplad till verifikat' })
|
||||
setMatchOpenFor(null)
|
||||
|
||||
@@ -1824,7 +1824,15 @@ export default function TransactionsPage() {
|
||||
)
|
||||
const json = await res.json()
|
||||
if (!res.ok) {
|
||||
throw new Error(json.error || 'Bokföring misslyckades')
|
||||
// Map the parsed body plus the status, never `new Error(json.error)`:
|
||||
// the Error constructor stringifies a non-string body field, and the
|
||||
// mapper would discard the route's own Swedish reason.
|
||||
toast({
|
||||
title: 'Kunde inte bokföra',
|
||||
description: getErrorMessage(json, { statusCode: res.status }),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
toast({
|
||||
title: 'Utkast skapat',
|
||||
|
||||
@@ -5,6 +5,7 @@ import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { hasCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { ensureTicSnapshot } from '@/lib/agent/composer/tic-fetch'
|
||||
import { employeeFieldValue, loadActiveEmployeeCount } from '@/lib/agent/composer/employee-facts'
|
||||
import AgentOnboarding from '@/components/onboarding/agent/AgentOnboarding'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
@@ -41,12 +42,13 @@ export default async function AgentOnboardingPage() {
|
||||
{ data: profile },
|
||||
{ data: existingProfile },
|
||||
{ data: atomRows },
|
||||
activeEmployees,
|
||||
hdrs,
|
||||
] = await Promise.all([
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select(
|
||||
'is_sandbox, city, address_line1, postal_code, f_skatt, vat_registered, moms_period, fiscal_year_start_month, employee_count, has_employees',
|
||||
'is_sandbox, city, address_line1, postal_code, f_skatt, vat_registered, moms_period, fiscal_year_start_month, employer_registered, pays_salaries',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle(),
|
||||
@@ -61,6 +63,9 @@ export default async function AgentOnboardingPage() {
|
||||
.select('id, title')
|
||||
.eq('is_active', true)
|
||||
.is('parent_atom_id', null), // skill titles only; reference children never appear as profile chips
|
||||
// The only source that actually knows the headcount. Cheap: a head-only
|
||||
// count served by idx_employees_active, and it rides the same batch.
|
||||
loadActiveEmployeeCount(supabase, companyId).catch(() => null),
|
||||
headers(),
|
||||
])
|
||||
|
||||
@@ -101,7 +106,7 @@ export default async function AgentOnboardingPage() {
|
||||
const firstName = profile?.full_name?.split(' ')[0] ?? null
|
||||
// Pre-render-friendly snapshot of company info: used to seed Phase B fields
|
||||
// before the stream completes so the layout doesn't jump.
|
||||
const initialFields = buildInitialFields(company, settings)
|
||||
const initialFields = buildInitialFields(company, settings, activeEmployees)
|
||||
|
||||
const atomTitles: Record<string, string> = {}
|
||||
for (const row of (atomRows ?? []) as { id: string; title: string }[]) {
|
||||
@@ -143,8 +148,12 @@ interface CompanySettingsForPhaseB {
|
||||
vat_registered: boolean | null
|
||||
moms_period: string | null
|
||||
fiscal_year_start_month: number | null
|
||||
employee_count: number | null
|
||||
has_employees: boolean | null
|
||||
// The employer facts that exist on company_settings. This select used to name
|
||||
// `employee_count` and `has_employees`, neither of which is a column on this
|
||||
// table, so PostgREST rejected the select whole (42703) and every field above
|
||||
// arrived null as well.
|
||||
employer_registered: boolean | null
|
||||
pays_salaries: boolean | null
|
||||
}
|
||||
|
||||
function buildInitialFields(
|
||||
@@ -155,6 +164,7 @@ function buildInitialFields(
|
||||
tic_snapshot: Record<string, unknown> | null
|
||||
},
|
||||
settings: CompanySettingsForPhaseB | null,
|
||||
activeEmployees: number | null,
|
||||
): InitialFields {
|
||||
const tic = (company.tic_snapshot ?? null) as Record<string, unknown> | null
|
||||
const entityLabel =
|
||||
@@ -173,7 +183,7 @@ function buildInitialFields(
|
||||
let fSkatt: string | null = null
|
||||
let vatPeriod: string | null = null
|
||||
let fiscalPeriod: string | null = null
|
||||
let employees: string | null = null
|
||||
let ticEmployeeRange: string | null = null
|
||||
|
||||
if (tic) {
|
||||
const sni = (tic.sniCodes as { code: string; name: string }[] | undefined) ?? []
|
||||
@@ -184,7 +194,7 @@ function buildInitialFields(
|
||||
if (addr?.city) city = addr.city
|
||||
const reg = tic.registration as { fTax?: boolean } | undefined
|
||||
if (reg) fSkatt = reg.fTax ? 'Aktivt' : 'Saknas'
|
||||
if (tic.employeeRange) employees = tic.employeeRange as string
|
||||
if (tic.employeeRange) ticEmployeeRange = tic.employeeRange as string
|
||||
// v2 caches `fiscalYear` (current fiscal-year configuration) on the
|
||||
// snapshot. Prefer it over the user-entered value below so onboarding
|
||||
// can show the registered fiscal period from Bolagsverket without
|
||||
@@ -208,13 +218,19 @@ function buildInitialFields(
|
||||
if (!fiscalPeriod && settings.fiscal_year_start_month != null) {
|
||||
fiscalPeriod = fiscalYearLabel(settings.fiscal_year_start_month)
|
||||
}
|
||||
if (!employees && settings.employee_count != null) {
|
||||
employees = String(settings.employee_count)
|
||||
} else if (!employees && settings.has_employees != null) {
|
||||
employees = settings.has_employees ? 'Ja' : 'Nej'
|
||||
}
|
||||
}
|
||||
|
||||
// "Anställda": the live headcount if there is one, else Bolagsverket's
|
||||
// interval, else the attested employer facts, else null so the row shows its
|
||||
// placeholder instead of a number nobody entered. See employee-facts.ts for
|
||||
// why pays_salaries === false is not treated as "Nej".
|
||||
const employees = employeeFieldValue({
|
||||
activeEmployees,
|
||||
ticEmployeeRange,
|
||||
employerRegistered: settings?.employer_registered ?? null,
|
||||
paysSalaries: settings?.pays_salaries ?? null,
|
||||
})
|
||||
|
||||
return {
|
||||
entity_type_label: entityLabel,
|
||||
sni_codes: sniCodes,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user