fix(vat): drop personnummer century so enskild firma VAT number is SE+12 not SE+14 (#796)

* fix(vat): drop personnummer century so enskild firma VAT number is SE+12 not SE+14

Onboarding derived the VAT number as SE${orgNumber}01. For an enskild firma the
org number is a 12-digit personnummer, producing SE + 14 digits, which fails the
^SE\d{12}$ validation — the pre-filled value is re-submitted on save and the tax
settings page becomes unsavable.

New shared helper lib/vat/vat-number.ts (normalize/validate/derive, reusing
normalizeOrgNumber to drop the century + Luhn-validate). UpdateSettingsSchema,
the onboarding wizard, the onboarding upsert in lib/company/actions.ts, and the
arcim-migration provider import all route through it. Backfill migration repairs
existing SE+14 rows to SE+12 (idempotent, scoped to ^SE\d{14}$ only).

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

* chore(arcim): warn when a provider VAT number is dropped as malformed

The provider VAT guard silently discarded a value that doesn't normalise to a
valid SE+12 momsregistreringsnummer. Emit a structured warn (provider +
company, no raw value — it can embed a personnummer) so consistently-bad
provider data is observable rather than invisible. Addresses the OWASP V16
logging finding on the arcim VAT-normalisation change in this PR.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-06-26 15:29:58 +02:00
committed by GitHub
co-authored by Claude Opus 4.8
parent 9278221616
commit 5bacda4839
8 changed files with 207 additions and 7 deletions
@@ -0,0 +1,22 @@
-- Repair malformed company VAT numbers (momsregistreringsnummer).
--
-- The onboarding wizard (components/onboarding/Step4VatAccounting.tsx) derived
-- the VAT number as `SE` || org_number || `01`. For an enskild firma the
-- org_number is a 12-digit personnummer (YYYYMMDD-NNNN), so this produced
-- `SE` + 14 digits instead of the canonical `SE` + 10-digit identity + `01`
-- (= SE + 12 digits). Those companies could not save the tax settings page:
-- the pre-filled value is re-submitted on save and rejected by the
-- `^SE\d{12}$` validation in UpdateSettingsSchema.
--
-- Fix: drop the 2 leading junk digits (the personnummer century, or a
-- duplicated org-number prefix) so the value matches SE + 12 digits. The
-- remaining 12 digits already carry the correct 10-digit identity + `01`
-- suffix — verified that every affected row reconciles to the org-number-based
-- canonical value.
--
-- Idempotent and tightly scoped: only rows that are exactly `SE` followed by
-- 14 digits are touched. Already-valid SE+12 rows, NULLs and empty strings are
-- left untouched.
UPDATE public.company_settings
SET vat_number = 'SE' || substr(vat_number, 5)
WHERE vat_number ~ '^SE\d{14}$';