Files
accounted/components/onboarding/BankIdCompanyPicker.tsx
T
MattssonandClaude Opus 4.7 064fb7f7a9 Add/white label (#381)
* feat(branding): add BrandingService with default-preserving env layer

Introduce lib/branding/service.ts mirroring lib/email/service.ts. Defaults
match current gnubok values exactly, so production behaviour is unchanged
unless an env var (NEXT_PUBLIC_BRANDING_*, BRANDING_*) or extension override
(via registerBrandingService) is set.

Resolution order: defaults < env vars < extension override.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(branding): route root layout, manifest, and PWA assets through branding service

- app/layout.tsx now reads title, description, themeColor, and apple-touch-icon
  from getBranding() instead of hardcoded values.
- public/manifest.json replaced by dynamic app/manifest.ts so PWA name,
  short_name, description, theme_color, background_color, and icon paths
  are resolved at request time.

The manifest now serves at /manifest.webmanifest (Next.js convention for
the metadata file route). The previous /manifest.json URL is no longer
populated; nothing in core references it after this commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(branding): route email service and templates through branding service

- resend-service.ts: From line uses getBranding().appName instead of
  hardcoded "Gnubok" in both the with-fromName and bare cases.
- invite-templates.ts: subject, HTML header, body, plain text, and the
  team-invite variants all read from branding (sentence case in prose,
  uppercased for the styled <p> header).
- consent-notification-templates.ts: signature fallback (companyName ||
  branding) for both HTML and plain text variants.

Defaults preserve the exact current strings ("Gnubok", "GNUBOK", "gnubok"
in their respective contexts) so no email content changes for production.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(branding): route OAuth consent page through branding service

The MCP OAuth consent page rendered for Claude Desktop / Claude.ai
connector flows now reads the app name from getBranding() for both the
HTML <title> and the body copy. Default still produces "gnubok" in
lowercase prose, matching current behaviour.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(branding): route auth, dashboard, and onboarding text through branding service

Replace user-visible "gnubok" / "Gnubok" references with calls to
getBranding(). Touches:

- Auth pages (login, register, mfa/enroll): logo src/alt, MFA TOTP
  friendlyName.
- Onboarding (companies/new, invite, sandbox, WelcomeOnboarding,
  Step2CompanyDetails, NewUserChecklist, BankIdCompanyPicker,
  ArcimMigrationWorkspace): logo, headings, error/help text.
- Dashboard fallback (companyName="gnubok") and settings (backup copy,
  ApiKeysPanel MCP connector name + login note, CompanyDangerZone,
  retention-notice).
- API routes (support contact subject prefix, enable-banking consent
  email companyName fallback, AI inbox receipt-request appUrl,
  pain001 messageId prefix).
- MCP server "open the gnubok web app" review message.
- Salary/reports filings (AGI Programnamn, KU10 Programnamn,
  payslip footer, full-archive system metadata, SRU #PROGRAM line).

Internal identifiers (cookie names gnubok-company-id /
gnubok-invite-token, API key prefix gnubok_sk_, invite token prefix
gnubok_inv_, MCP tool names, npm package gnubok-mcp, GNUBOK_API_KEY
env name) are deliberately left unchanged — they're stable contracts
that whitelabels must not break.

Defaults match current behaviour exactly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(branding): support legal page field-level swaps for entity and contact

Privacy and DPA pages now interpolate appName, legalEntity, and
privacyEmail from the branding service instead of hardcoding "Gnubok",
"Arcim", and "privacy@gnubok.se". Page metadata uses generateMetadata()
so titles also reflect the brand.

lib/support.ts now falls back to getBranding().supportEmail when
SUPPORT_RECIPIENT_EMAIL is unset, so a single BRANDING_SUPPORT_EMAIL
env var configures both the support form recipient and the displayed
support address.

Whitelabels with a different legal jurisdiction or entirely different
DPA text should override the page route from an extension. Phase 1
intentionally only supports field-level swaps.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(branding): add WHITELABEL.md and example branding extension

WHITELABEL.md: fork checklist, env var reference, the "do not change"
list (cookies, API key prefixes, invite token prefixes, MCP tool names,
gnubok-mcp npm package, GNUBOK_API_KEY env name), out-of-scope items,
the upstream sync workflow YAML to copy into a fork, conflict avoidance
guidance, and a verification checklist.

extensions/general/_example-branding/: copy-paste starter extension with
index.ts (commented placeholder values for registerBrandingService),
manifest.json, and README.md. Disabled by default (not added to
extensions.config.json); whitelabels cp the folder, edit, and enable.

sectors.test.ts: bumped expected extension count 12 -> 13 to account
for the new starter extension on disk. The generated registry is
unchanged because the example is disabled.

The sync workflow YAML is documented inline in WHITELABEL.md rather
than checked in as a workflow file. It's only meaningful in a fork --
gnubok itself has nothing to sync from.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(branding): address PR review — lazy support email + escape brand in HTML/XML

Three issues from code review:

P1 — lib/support.ts: SUPPORT_RECIPIENT_EMAIL was a module-level const,
evaluated at import time before extensions register branding overrides
via ensureInitialized(). Convert to getSupportRecipientEmail() lazy
accessor; update the only caller in app/api/support/contact/route.ts.
Extension-supplied supportEmail values now route correctly.

P2 — app/api/mcp-oauth/authorize/route.ts: appName was interpolated
into the consent page HTML without escapeHtml(), inconsistent with
the existing escaping of companyName. Wrap appName.toLowerCase() in
escapeHtml() at use sites in <title> and the body paragraph.

P2 — lib/salary/agi/xml-generator.ts and lib/salary/ku/ku10-generator.ts:
appName placed inside <gem:Programnamn> / <Programnamn> XML elements
without escapeXml(), the helper already used for other admin-controlled
fields in the same files. Wrap accordingly to prevent malformed XML if
a brand name contains XML reserved characters.

All admin-controlled inputs only — no user-exploitable path. Defense in
depth, not a known incident.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(branding): security follow-up — lazy metadata, SRU/email header sanitization

Self-audit after the PR review surfaced four more concerns. Fixes them
with the same defense-in-depth posture as the prior review fixes.

1. app/layout.tsx — same eager-evaluation class as P1 support.ts. The
   module-level `const branding = getBranding()` froze branding before
   extensions registered, so extension-based overrides for title,
   description, themeColor, and apple-touch-icon silently never applied.
   - Convert to generateMetadata() / generateViewport() (lazy, run per
     request, see extension-registered overrides).
   - Inline getBranding() inside RootLayout for the apple-touch-icon
     href so it picks up overrides too.
   - Add ensureInitialized() at module level so extensions are loaded
     before the first metadata call. Mirrors the API route pattern.

2. app/manifest.ts — same class. The dynamic manifest function reads
   getBranding() per request, but if the manifest is requested before
   any other module has triggered ensureInitialized(), extensions are
   still unloaded. Add ensureInitialized() at module level.

3. lib/reports/ink2/sru-generator.ts — appName interpolated into the
   SRU `#PROGRAM` directive without sanitization. SRU's reserved char
   is `#` (directive marker) and CRLF injects new directives. Wrap in
   the existing sanitizeString() helper to match the pattern used for
   other admin-controlled fields in this file (#NAMN, #ADRESS, etc.).

4. extensions/general/email/lib/resend-service.ts — appName and the
   user-controlled fromName both flow into the From header. Resend's
   API does its own validation, but defense in depth: strip CRLF and
   angle brackets via a small sanitizeHeaderPart() helper before
   building the header string. fromName was a pre-existing surface;
   appName is new with this whitelabel work.

All four are admin-controlled inputs (env vars or extension code),
not user-exploitable. No known incidents — defense in depth, and
correctness for extension-based whitelabels.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-29 16:32:26 +02:00

455 lines
18 KiB
TypeScript

'use client'
import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
import { Building2, ArrowRight, Loader2, Plus, Check, AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import { useToast } from '@/components/ui/use-toast'
import { switchCompany, createCompanyFromTicRole } from '@/lib/company/actions'
import { mapEntityType } from '@/lib/company-lookup/entity-type-map'
import type { CompanyLookupResult, EnrichmentCompanyRole } from '@/lib/company-lookup/types'
import { getBranding } from '@/lib/branding/service'
const branding = getBranding()
export interface MemberCompany {
id: string
name: string
orgNumber: string | null
entityType: string | null
role: string
}
export interface TicPickerCompany {
role: EnrichmentCompanyRole
/** 'new' = not in gnubok, can set up. 'exists' = in gnubok but user is not a member. */
status: 'new' | 'exists'
}
interface BankIdCompanyPickerProps {
firstName: string | null
teamId: string
memberCompanies: MemberCompany[]
ticCompanies: TicPickerCompany[]
enrichmentStale: boolean
}
type SetupState =
| { kind: 'idle' }
| { kind: 'opening'; companyId: string }
| { kind: 'creating'; orgNumber: string; step: 'lookup' | 'provision' }
function humanEntityType(t: string | null | undefined): string {
if (!t) return ''
if (t === 'aktiebolag') return 'Aktiebolag'
if (t === 'enskild_firma') return 'Enskild firma'
// TIC legalEntityType strings ('AB', 'HB', etc.) fall through to this
return t
}
function humanTicEntityType(t: string): string {
const mapped = mapEntityType(t)
if (mapped === 'aktiebolag') return 'Aktiebolag'
if (mapped === 'enskild_firma') return 'Enskild firma'
if (t.toLowerCase().includes('handelsbolag') || t.toLowerCase() === 'hb') return 'Handelsbolag'
if (t.toLowerCase().includes('kommanditbolag') || t.toLowerCase() === 'kb') return 'Kommanditbolag'
return t
}
function positionLabel(role: EnrichmentCompanyRole): string {
const descs = role.positionDescriptions?.filter(Boolean)
if (descs && descs.length > 0) return descs.join(' · ')
const types = role.positionTypes?.filter(Boolean)
if (types && types.length > 0) return types.join(' · ')
return ''
}
export default function BankIdCompanyPicker({
firstName,
teamId,
memberCompanies,
ticCompanies,
enrichmentStale,
}: BankIdCompanyPickerProps) {
const router = useRouter()
const { toast } = useToast()
const [setup, setSetup] = useState<SetupState>({ kind: 'idle' })
const [isPending, startTransition] = useTransition()
const hour = new Date().getHours()
const greeting = hour < 5 ? 'God natt' : hour < 10 ? 'Godmorgon' : hour < 14 ? 'Hej' : hour < 18 ? 'God eftermiddag' : 'God kväll'
const busy = setup.kind !== 'idle' || isPending
async function handleOpenMember(companyId: string) {
if (busy) return
setSetup({ kind: 'opening', companyId })
const result = await switchCompany(companyId)
if (result.error) {
toast({ title: 'Fel', description: result.error, variant: 'destructive' })
setSetup({ kind: 'idle' })
return
}
window.location.assign('/')
}
async function handleCreateFromTic(role: EnrichmentCompanyRole) {
if (busy) return
const orgNumber = role.companyRegistrationNumber.replace(/[\s-]/g, '')
const mapped = mapEntityType(role.legalEntityType)
if (!mapped) {
// Entity type isn't supported end-to-end — route to manual wizard with
// the org number pre-filled.
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
return
}
setSetup({ kind: 'creating', orgNumber, step: 'lookup' })
let lookup: CompanyLookupResult | null = null
try {
const res = await fetch(
`/api/extensions/ext/tic/lookup?org_number=${encodeURIComponent(orgNumber)}`,
{ method: 'GET' },
)
if (res.ok) {
const json = await res.json()
lookup = (json?.data as CompanyLookupResult | undefined) ?? null
}
} catch {
// Network/parse failure — fall through to the lookup-missing branch below.
}
// Without a lookup we don't know the company's VAT/F-skatt status.
// Defaulting those to false for a momsregistrerat bolag would silently
// create a company that issues invoices without moms — ML 17 kap violation.
// Route to the manual wizard with the known fields pre-filled instead.
if (!lookup) {
toast({
title: 'Kunde inte hämta företagsuppgifter',
description: 'Fyll i resterande uppgifter manuellt.',
})
setSetup({ kind: 'idle' })
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
return
}
// Block provisioning for companies that are avregistrerade/likviderade.
// Under BFL 2 kap, bokföringsskyldighet ends when a company is struck off.
if (lookup.isCeased) {
toast({
title: 'Företaget är avregistrerat',
description: 'Det går inte att sätta upp bokföring för ett avregistrerat företag.',
variant: 'destructive',
})
setSetup({ kind: 'idle' })
return
}
setSetup({ kind: 'creating', orgNumber, step: 'provision' })
startTransition(async () => {
const result = await createCompanyFromTicRole({
teamId,
orgNumber,
legalName: role.legalName,
legalEntityType: role.legalEntityType,
lookup,
})
if (result.error === 'lookup_missing') {
// Extremely unlikely (we just verified lookup above) but if it happens,
// the same fallback applies.
setSetup({ kind: 'idle' })
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
return
}
if (result.error === 'org_number_exists') {
toast({
title: 'Företaget finns redan',
description: 'Be en befintlig administratör att bjuda in dig.',
variant: 'destructive',
})
setSetup({ kind: 'idle' })
return
}
if (result.error === 'company_ceased') {
// Belt-and-suspenders: we already check lookup.isCeased client-side
// above, but the server-side guard catches any race where TIC's
// cached result differs between the two calls.
toast({
title: 'Företaget är avregistrerat',
description: 'Det går inte att sätta upp bokföring för ett avregistrerat företag.',
variant: 'destructive',
})
setSetup({ kind: 'idle' })
return
}
if (result.error === 'org_number_invalid') {
toast({
title: 'Ogiltigt organisationsnummer',
description: 'Fortsätt med manuell uppsättning.',
variant: 'destructive',
})
setSetup({ kind: 'idle' })
router.push(`/onboarding?org_number=${encodeURIComponent(orgNumber)}`)
return
}
if (result.error || !result.companyId) {
toast({
title: 'Kunde inte skapa företag',
description: result.error ?? 'Försök igen eller lägg till manuellt.',
variant: 'destructive',
})
setSetup({ kind: 'idle' })
return
}
toast({ title: 'Välkommen!', description: 'Ditt företag är nu redo.' })
window.location.assign('/')
})
}
// Progress card while creating
if (setup.kind === 'creating') {
const lookupDone = setup.step === 'provision'
return (
<div className="stagger-enter">
<header className="mb-10">
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">
{greeting}{firstName ? `, ${firstName}` : ''}
</h1>
<p className="text-muted-foreground text-sm mt-1.5">Sätter upp ditt företag…</p>
</header>
<div className="max-w-lg rounded-xl border bg-card p-6" style={{ boxShadow: 'var(--shadow-md)' }}>
<div className="flex items-start gap-3">
<Building2 className="h-5 w-5 text-muted-foreground mt-0.5" />
<div className="flex-1">
<p className="font-medium text-sm">Org.nr {setup.orgNumber}</p>
<ul className="mt-3 space-y-2 text-sm">
<li className="flex items-center gap-2">
{lookupDone
? <Check className="h-4 w-4 text-sage" />
: <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />}
<span className={cn(!lookupDone && 'text-muted-foreground')}>
Hämtar uppgifter från Bolagsverket
</span>
</li>
<li className="flex items-center gap-2">
{lookupDone
? <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
: <span className="h-4 w-4 inline-block rounded-full border border-border" />}
<span className={cn(!lookupDone && 'text-muted-foreground/50')}>
Skapar företag och kontoplan
</span>
</li>
</ul>
</div>
</div>
</div>
</div>
)
}
return (
<div className="stagger-enter">
<header className="mb-10">
<h1 className="font-display text-2xl md:text-3xl font-medium tracking-tight">
{greeting}{firstName ? `, ${firstName}` : ''}
</h1>
<p className="text-muted-foreground text-sm mt-1.5">
Välj ett företag att öppna eller lägg till ett nytt.
</p>
</header>
<div className="max-w-lg space-y-8">
{enrichmentStale && (
<div className="rounded-lg border border-amber-200 bg-amber-50 p-3 dark:border-amber-900/60 dark:bg-amber-950/30">
<div className="flex items-start gap-2.5">
<AlertTriangle className="h-4 w-4 text-amber-600 dark:text-amber-400 mt-0.5 flex-shrink-0" />
<p className="text-sm text-amber-800 dark:text-amber-200">
Uppgifterna från BankID är äldre än en vecka. Logga in med BankID igen för att uppdatera listan.
</p>
</div>
</div>
)}
{memberCompanies.length > 0 && (
<section>
<h2 className="text-xs uppercase tracking-[0.08em] text-muted-foreground mb-3">
Dina företag i {branding.appName.toLowerCase()}
</h2>
<ul className="space-y-2">
{memberCompanies.map((c) => {
const isOpening = setup.kind === 'opening' && setup.companyId === c.id
return (
<li key={c.id}>
<button
type="button"
onClick={() => handleOpenMember(c.id)}
disabled={busy}
className={cn(
'w-full rounded-lg border bg-card p-4 text-left transition-colors',
!busy && 'hover:border-foreground/30 hover:bg-muted/30',
busy && 'opacity-60 cursor-not-allowed',
)}
>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<p className="font-medium text-sm truncate">{c.name}</p>
<p className="text-xs text-muted-foreground mt-0.5 truncate">
{c.orgNumber ? `${c.orgNumber} · ` : ''}
{humanEntityType(c.entityType)}
</p>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{c.role !== 'owner' && (
<span className="text-[10px] uppercase tracking-wide text-muted-foreground/80">
{c.role}
</span>
)}
{isOpening
? <Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
: <ArrowRight className="h-4 w-4 text-muted-foreground" />}
</div>
</div>
</button>
</li>
)
})}
</ul>
</section>
)}
{ticCompanies.length > 0 && (
<section>
<h2 className="text-xs uppercase tracking-[0.08em] text-muted-foreground mb-3">
Företag kopplade till ditt BankID
</h2>
<ul className="space-y-2">
{ticCompanies.map(({ role, status }) => {
const cleaned = role.companyRegistrationNumber.replace(/[\s-]/g, '')
const position = positionLabel(role)
const entityLabel = humanTicEntityType(role.legalEntityType)
const mappable = mapEntityType(role.legalEntityType) !== null
if (status === 'exists') {
return (
<li key={cleaned}>
<div className="w-full rounded-lg border bg-muted/20 p-4 text-left opacity-70">
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<p className="font-medium text-sm truncate">{role.legalName}</p>
<p className="text-xs text-muted-foreground mt-0.5 truncate">
{cleaned} · {entityLabel}
</p>
</div>
<span className="text-[10px] uppercase tracking-wide text-muted-foreground flex-shrink-0">
Finns redan i {branding.appName.toLowerCase()}
</span>
</div>
<p className="text-xs text-muted-foreground/70 mt-2">
Be en befintlig administratör att bjuda in dig.
</p>
</div>
</li>
)
}
if (!mappable) {
return (
<li key={cleaned}>
<Link
href={`/onboarding?org_number=${encodeURIComponent(cleaned)}`}
className={cn(
'block w-full rounded-lg border bg-card p-4 text-left transition-colors',
!busy && 'hover:border-foreground/30 hover:bg-muted/30',
busy && 'pointer-events-none opacity-60',
)}
>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<p className="font-medium text-sm truncate">{role.legalName}</p>
<p className="text-xs text-muted-foreground mt-0.5 truncate">
{cleaned} · {entityLabel}
{position ? ` · ${position}` : ''}
</p>
</div>
<span className="text-[10px] uppercase tracking-wide text-muted-foreground flex-shrink-0">
Sätts upp manuellt
</span>
</div>
</Link>
</li>
)
}
return (
<li key={cleaned}>
<button
type="button"
onClick={() => handleCreateFromTic(role)}
disabled={busy}
className={cn(
'w-full rounded-lg border bg-card p-4 text-left transition-colors',
!busy && 'hover:border-foreground/30 hover:bg-muted/30',
busy && 'opacity-60 cursor-not-allowed',
)}
>
<div className="flex items-center justify-between gap-3">
<div className="min-w-0">
<p className="font-medium text-sm truncate">{role.legalName}</p>
<p className="text-xs text-muted-foreground mt-0.5 truncate">
{cleaned} · {entityLabel}
{position ? ` · ${position}` : ''}
</p>
</div>
<ArrowRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
</div>
</button>
</li>
)
})}
</ul>
</section>
)}
{memberCompanies.length === 0 && ticCompanies.length === 0 && (
<p className="text-sm text-muted-foreground">
Inga företag hittades. Lägg till ditt första företag nedan.
</p>
)}
<div className="relative">
<div className="absolute inset-0 flex items-center" aria-hidden>
<div className="w-full border-t border-border/60" />
</div>
<div className="relative flex justify-center">
<span className="bg-background px-3 text-xs uppercase tracking-[0.08em] text-muted-foreground">
eller
</span>
</div>
</div>
<Link
href="/onboarding"
className={cn(
'flex items-center justify-center gap-2 w-full rounded-lg border border-dashed p-4 text-sm font-medium transition-colors',
!busy && 'hover:border-foreground/30 hover:bg-muted/30',
busy && 'pointer-events-none opacity-60',
)}
>
<Plus className="h-4 w-4" />
Lägg till företag manuellt
</Link>
</div>
</div>
)
}