fix: surface active TIC companies + block duplicate org numbers (#344)

* 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>
This commit is contained in:
Jakob Wennberg
2026-04-22 14:47:58 +02:00
committed by GitHub
co-authored by Claude Opus 4.7
parent f3a3d07ed3
commit 8fd3f112f8
12 changed files with 801 additions and 32 deletions
+39 -5
View File
@@ -48,9 +48,17 @@ interface WelcomeOnboardingProps {
teamId: string
skipWelcome?: boolean
hasExistingCompanies?: boolean
/** Pre-fill Step 2 org_number when the picker routed here via ?org_number=. */
initialOrgNumber?: string
}
export default function WelcomeOnboarding({ firstName, teamId, skipWelcome, hasExistingCompanies }: WelcomeOnboardingProps) {
export default function WelcomeOnboarding({
firstName,
teamId,
skipWelcome,
hasExistingCompanies,
initialOrgNumber,
}: WelcomeOnboardingProps) {
const router = useRouter()
const { toast } = useToast()
const supabase = createClient()
@@ -59,7 +67,9 @@ export default function WelcomeOnboarding({ firstName, teamId, skipWelcome, hasE
const [isLoading, setIsLoading] = useState(true)
const [isSaving, setIsSaving] = useState(false)
const [currentStep, setCurrentStep] = useState(1)
const [settings, setSettings] = useState<Partial<CompanySettings>>({})
const [settings, setSettings] = useState<Partial<CompanySettings>>(
initialOrgNumber ? { org_number: initialOrgNumber } : {},
)
const ticEnabled = ENABLED_EXTENSION_IDS.has('tic')
const [ticLookup, setTicLookup] = useState<CompanyLookupResult | null>(null)
@@ -109,7 +119,15 @@ export default function WelcomeOnboarding({ firstName, teamId, skipWelcome, hasE
}, [supabase, router])
const handleNext = async (stepData: Partial<CompanySettings>) => {
if (currentStep === 1 && stepData.entity_type && stepData.entity_type !== settings.entity_type) {
// Reset org_number/company_name only on a genuine change (user going back
// and picking a different entity type). First-time selection must not
// wipe a pre-fill (e.g. ?org_number= deep-link from /select-company).
if (
currentStep === 1 &&
stepData.entity_type &&
settings.entity_type &&
stepData.entity_type !== settings.entity_type
) {
stepData = { ...stepData, org_number: '', company_name: '' }
setTicLookup(null)
}
@@ -163,11 +181,27 @@ export default function WelcomeOnboarding({ firstName, teamId, skipWelcome, hasE
if (result.error || !result.companyId) {
logError('create company action failed', { error: result.error })
let title = 'Fel'
let description: string = result.error || 'Kunde inte skapa företag. Försök igen.'
let backToStep2 = false
if (result.error === 'org_number_exists') {
title = 'Företaget finns redan'
description = 'Det här företaget finns redan i gnubok. Be en befintlig administratör att bjuda in dig.'
backToStep2 = true
} else if (result.error === 'org_number_invalid') {
title = 'Ogiltigt organisationsnummer'
description = 'Kontrollera att du angett ett giltigt 10- eller 12-siffrigt organisationsnummer.'
backToStep2 = true
}
toast({
title: 'Fel',
description: result.error || 'Kunde inte skapa företag. Försök igen.',
title,
description,
variant: 'destructive',
})
// Back user up to step 2 so they can correct the org number.
if (backToStep2) {
setCurrentStep(2)
}
return
}
@@ -132,6 +132,18 @@ export default function BankIdCompanyPicker({
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 () => {
@@ -151,6 +163,40 @@ export default function BankIdCompanyPicker({
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',
+46 -1
View File
@@ -68,10 +68,43 @@ export default function Step2CompanyDetails({
const [isLooking, setIsLooking] = useState(false)
const [lookupError, setLookupError] = useState<string | null>(null)
const [lookupDone, setLookupDone] = useState<CompanyLookupResult | null>(null)
const [orgNumberExists, setOrgNumberExists] = useState(false)
const abortRef = useRef<AbortController | null>(null)
const dupAbortRef = useRef<AbortController | null>(null)
const orgNumber = watch('org_number')
// Debounced duplicate check against gnubok's own companies table. Runs in
// parallel with the TIC lookup — they don't conflict. On match, the submit
// button is disabled; the server action would also reject ('org_number_exists')
// but blocking client-side avoids a wasted roundtrip.
useEffect(() => {
if (!orgNumber || !ORG_NUMBER_REGEX.test(orgNumber)) {
setOrgNumberExists(false)
return
}
const timer = setTimeout(() => {
dupAbortRef.current?.abort()
const controller = new AbortController()
dupAbortRef.current = controller
fetch(`/api/company/check-org-number?org_number=${encodeURIComponent(orgNumber)}`, {
signal: controller.signal,
})
.then(async (res) => {
if (controller.signal.aborted || !res.ok) return
const { data } = await res.json()
setOrgNumberExists(!!data?.exists)
})
.catch(() => {
// Network failure is non-fatal — the server action will re-check.
})
}, 500)
return () => {
clearTimeout(timer)
dupAbortRef.current?.abort()
}
}, [orgNumber])
useEffect(() => {
if (!ticEnabled || !orgNumber || !ORG_NUMBER_REGEX.test(orgNumber)) {
return
@@ -201,6 +234,14 @@ export default function Step2CompanyDetails({
{ticEnabled && lookupError && (
<p className="text-xs text-muted-foreground">{lookupError}</p>
)}
{orgNumberExists && (
<div className="flex items-start gap-2 text-sm text-destructive">
<AlertTriangle className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
<span>
Det här företaget finns redan i gnubok. Be en befintlig administratör att bjuda in dig.
</span>
</div>
)}
</div>
<div className="space-y-2">
@@ -262,7 +303,11 @@ export default function Step2CompanyDetails({
<ArrowLeft className="mr-2 h-4 w-4" />
Tillbaka
</Button>
<Button type="submit" disabled={isSaving} className="w-full sm:w-auto">
<Button
type="submit"
disabled={isSaving || orgNumberExists}
className="w-full sm:w-auto"
>
{isSaving ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />