* fix: surface active TIC companies + block duplicate org numbers
Three fixes from live-prod testing:
1. Enrichment filter hid the user's directorships. Now accepts both
Completed and PartiallyCompleted status from TIC (tenants without
CompanyRoles enabled still get SPAR) and the /select-company role
filter no longer requires companyStatus === 'Aktivt' — real TIC
payloads have been observed with different values, and positionEnd
alone is the authoritative "currently a director" signal. Added
PII-free diagnostic logs so the next shape-mismatch is debuggable
from Vercel logs without a round trip.
2. Manual wizard silently allowed duplicate org numbers. Added:
- findExistingCompanyByOrgNumber helper in actions.ts (service role,
bypasses RLS to see cross-tenant rows)
- Server-side guard in createCompanyFromOnboarding — returns
'org_number_exists' before the create RPC so we don't leave ghost
companies
- New /api/company/check-org-number endpoint for debounced client
checks
- Warning + disabled submit in Step2CompanyDetails
- Friendly error toasts in WelcomeOnboarding + BankIdCompanyPicker
- Mirror cleaned org_number onto companies.org_number on creation so
future duplicate checks and lookups are reliable
3. /onboarding ignored ?org_number= when the picker routed there as a
fallback. Now reads searchParams and pre-fills settings; also fixed
a latent bug where Step1's entity-type change wiped the pre-fill on
*first* selection (it should only reset on a genuine change).
Tests: duplicate-org guard (with formatted-input normalization),
check-org-number route (auth + 400 + exists true/false +
normalization).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: address PR review feedback on duplicate-org guard
Greptile P1 findings + swedish-compliance feedback:
- findExistingCompanyByOrgNumber now throws on Supabase error instead
of silently returning null. Previously a DB outage or RLS
misconfiguration would bypass the entire duplicate guard and allow
duplicates through.
- createCompanyFromOnboarding catches the throw and returns a
user-facing error ("Kunde inte verifiera organisationsnummer"),
failing closed instead of open.
- companies.update({ org_number }) error is now checked and triggers a
rollback. Silent failure would leave the company without an
org_number, breaking all future duplicate checks for that entity.
- New normalizeOrgNumber helper validates 10- or 12-digit input,
strips the century prefix for 12-digit personnummer form, and
rejects anything else. Malformed input would have corrupted SIE4
(#ORGNR) and SRU (INFO.SRU) exports downstream.
- /select-company now uses loose `== null` for positionEnd — TIC has
been observed returning `undefined` for open-ended positions, which
strict `=== null` would silently filter out. Documented the two
downstream isCeased guards so future maintainers don't remove one
without the other.
- createCompanyFromTicRole refuses to provision when lookup.isCeased
(BFL 2 kap — bokföringsskyldighet ends at avregistrering).
BankIdCompanyPicker surfaces this client-side too.
- WelcomeOnboarding + BankIdCompanyPicker recognise new error codes:
org_number_invalid, company_ceased.
Tests: +4 cases covering malformed input rejection, fail-closed
behaviour on DB error, 12-digit personnummer normalization, and the
ceased-company refusal path. Full suite: 2306 passing.
Out of scope for this PR (follow-up):
- Partial unique index on companies(org_number) WHERE archived_at IS
NULL. Closes the race-condition window but needs a migration plus
any existing-duplicate cleanup — too risky for this hotfix.
- Rate limiting on /api/company/check-org-number. Endpoint is
auth-gated so not an immediate concern.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix: add Luhn validation and extract org-number normalization
Third round of PR review feedback (swedish-compliance):
- Add Luhn-10 check-digit validation to normalizeOrgNumber. Rejects
structurally invalid org_numbers (wrong check digit) at the boundary
instead of letting them propagate into SIE4 #ORGNR and SRU INFO.SRU,
where Skatteverket and receiving accounting systems would reject
them later anyway. Reuses the existing luhnValidate helper from
lib/bankgiro/luhn.ts (Bankgirot 10-modulen — same algorithm applies
to both Bolagsverket org numbers and Swedish personnummer).
- Extract normalizeOrgNumber into lib/company-lookup/normalize-org-number.ts
so the server action and /api/company/check-org-number use the same
rule. Previously the API route only stripped hyphens/spaces, so a
12-digit input would miss a stored 10-digit duplicate and mislead the
client debounce check ("not a duplicate" → submit → server rejects).
- /api/company/check-org-number now returns exists=false for
Luhn-invalid input rather than querying the DB. The submit-time
server action surfaces org_number_invalid, which is the right place
for the error.
Test coverage: dedicated normalize-org-number.test.ts (10 cases
covering both-lengths, Luhn, whitespace tolerance, garbage). Updated
existing tests to use Luhn-valid numbers (real Volvo 5560125790,
synthetic personnummer 8001011231). New failing-Luhn test in
actions.test.ts. New 12-digit-normalization and
luhn-invalid-returns-false tests in route.test.ts.
Full suite: 2315 passing.
Not fixed (out of scope for this hotfix):
- 10↔12 digit round-trip fragility for personnummer born 2000+. This
is a codebase-wide architectural choice (see lib/skatteverket/format.ts
which uses a two-digit-year heuristic to choose 19/20 at export).
Migrating to 12-digit storage is a separate refactor.
- Server-side re-fetch of TIC /lookup for isCeased. The trust boundary
here is user-to-their-own-onboarding, not adversarial; doubling TIC
API cost isn't proportionate.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
452 lines
18 KiB
TypeScript
452 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'
|
|
|
|
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 gnubok
|
|
</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 gnubok
|
|
</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>
|
|
)
|
|
}
|