feat(dimensions): PR2 registry — CRUD API, register UI, settings toggle, SIE export on the new registry (#858)

* feat(dimensions): PR2 registry — CRUD API, register UI, settings toggle, SIE export on the new registry

Phase 2 of dev_docs/dimensions_implementation_plan.md. Companies with
dimensions_enabled=false (default) see zero change.

API:
- Dashboard CRUD: GET /api/dimensions (lazy-seeds system dims 1/6 via the
  ensure_company_dimensions RPC), PATCH /api/dimensions/[id] (is_system
  rename blocked), POST/PATCH/DELETE values (code immutable after creation;
  strict Fortnox code format ^[A-Za-z0-9ÅÄÖåäö_+\-]{1,20}$ at the API layer;
  retention-trigger deletes surface the Swedish "arkivera istället" message
  as 409 DIMENSION_VALUE_REFERENCED).
- POST /api/dimensions/import-existing — scans journal_entry_lines.dimensions
  for unregistered codes and mints inactive placeholder registry rows.
- v1 public API: GET dimensions + POST values (Idempotency-Key, dry-run),
  registered in the OpenAPI spec (102→104 endpoints).
- dimensions_enabled boolean on company_settings (new migration,
  UI-visibility only, never correctness-bearing) exposed through the
  existing settings read/update path.

SIE export (lib/reports/sie-export.ts):
- Reads the new dimensions/dimension_values registry; legacy
  cost_centers/projects tables now have zero readers (drop migration next).
- Fixes the latent Visma-rejection bug: #OBJEKT now declared for INACTIVE
  values referenced by lines.
- Generic-N: #DIM/#UNDERDIM loop sorted by sie_dim_no; #TRANS object lists
  serialize from the line JSONB map (sorted, '01'→'1' collapse); orphan
  codes/dims synthesize declarations from the SIE reserved-number seed —
  every referenced (dim, code) pair is guaranteed declared.

UI:
- /dimensions register (Register-recipe): tabs per dimension, search,
  sortable table, value dialog (code immutable on edit, projekt dates on
  dim 6), archive-not-delete affordances.
- DimensionCombobox shipped (mounts in the tagging PR).
- Settings toggle "Aktivera kostnadsställen & projekt" — toggle-on runs the
  import-existing scan and links to the register.
- Nav row in redovisning, rendered only when dimensions_enabled (same
  mechanism as pays_salaries).
- dimensions.* i18n namespace (51 keys, sv/en parity).
- Sandbox seed: demo dims + values, revenue line tagged {"1":"BUTIK","6":"P001"}.

Verified: 6328/6328 unit tests, guard + coverage gate green, tsc parity with
main (210=210), production build passes.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(dimensions): PR2 review round — atomic archived-create, UNDERDIM ordering, import robustness, date semantics

- POST values accepts is_active so "create as archived" is atomic; the UI's
  fragile create-then-PATCH fallback is deleted (PR Agent finding 1).
- DimensionCombobox blur revert reads the committed value/values through refs
  so a selection landing inside the 150ms window always wins (finding 2).
- import-existing sanitizes candidate codes like the PR1 backfill and upserts
  with ignoreDuplicates — one bad/duplicate code can no longer abort the
  batch; created counted from returned rows (finding 3).
- SIE export emits all root #DIM before any #UNDERDIM so a parent always
  precedes a lower-numbered child (SIE4 declaration order — Swedish review);
  synthesized placeholder declarations now log one structured warning
  (BFNAR 2013:2 behandlingshistorik) + defence-in-depth comment.
- Value dates rejected (400 DIMENSION_VALUE_DATES_NOT_ALLOWED) when the
  parent dimension is flow-period (resets_annually=true); explicit null
  still clears (Swedish review).
- Sandbox seed logs seeded dimension codes; GET /api/dimensions documents
  the deliberate absence of dimensions_enabled gating (UI-visibility flag,
  not a security boundary — compliance-swarm V8.2.1 rejected by design).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-07-02 12:26:42 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 8cc2efb083
commit 8bb49c07a2
35 changed files with 3981 additions and 100 deletions
+52 -1
View File
@@ -7,6 +7,7 @@ import { createLogger } from '@/lib/logger'
import { checkRateLimit } from '@/lib/auth/rate-limit-http'
import { truncateIp } from '@/lib/api/v1/with-api-v1'
import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent'
import { lineDimensionColumns } from '@/lib/bookkeeping/dimension-resolver'
// Anonymous sign-in is enabled in all environments so visitors can try the
// product; a per-/24 cap on the seed endpoint keeps a single network from
@@ -146,6 +147,8 @@ export async function POST(request: Request) {
onboarding_step: 6,
onboarding_complete: true,
is_sandbox: true,
// Dimensions demo — the register/pickers render out of the box.
dimensions_enabled: true,
})
if (settingsError) throw settingsError
@@ -157,6 +160,39 @@ export async function POST(request: Request) {
})
if (coaError) throw coaError
// 3b. Seed demo dimensions (kostnadsställe/projekt). ensure_company_dimensions
// lazily creates the system dims 1/6; two values per dim give the register,
// pickers, and the dimension-tagged journal lines below something to show.
const { error: dimsRpcError } = await supabase.rpc('ensure_company_dimensions', {
p_company_id: companyId,
})
if (dimsRpcError) throw dimsRpcError
const { data: demoDims, error: demoDimsError } = await supabase
.from('dimensions')
.select('id, sie_dim_no')
.eq('company_id', companyId)
.in('sie_dim_no', [1, 6])
if (demoDimsError) throw demoDimsError
const dimIdByNo = Object.fromEntries(
(demoDims ?? []).map(d => [d.sie_dim_no as number, d.id as string])
) as Record<number, string>
if (dimIdByNo[1] && dimIdByNo[6]) {
const seededDimensionCodes = ['BUTIK', 'WEBB', 'P001', 'P002']
const { error: dimValuesError } = await supabase
.from('dimension_values')
.insert([
{ company_id: companyId, dimension_id: dimIdByNo[1], code: 'BUTIK', name: 'Butiken' },
{ company_id: companyId, dimension_id: dimIdByNo[1], code: 'WEBB', name: 'Webbshoppen' },
{ company_id: companyId, dimension_id: dimIdByNo[6], code: 'P001', name: 'Projekt Björk' },
{ company_id: companyId, dimension_id: dimIdByNo[6], code: 'P002', name: 'Projekt Alm' },
])
if (dimValuesError) throw dimValuesError
log.info('seeded sandbox dimension values', { companyId, codes: seededDimensionCodes })
}
// 4. Create fiscal period (current year)
const currentYear = new Date().getFullYear()
const { data: fiscalPeriod, error: fpError } = await supabase
@@ -424,11 +460,20 @@ export async function POST(request: Request) {
if (je2Error) throw je2Error
// 10. Create journal entry lines
// 10. Create journal entry lines. The P&L line carries demo dimensions
// ({"1":"BUTIK","6":"P001"}) so the register's "antal taggade rader",
// voucher-detail badges, and the dimension P&L report light up in the
// sandbox. Mirror columns derived via lineDimensionColumns — never set
// independently of the dimensions map.
const revenueDims = { '1': 'BUTIK', '6': 'P001' }
const { error: jelError } = await supabase
.from('journal_entry_lines')
.insert([
// JE1: Invoice creation — Debit AR, Credit Revenue + VAT
// NB: `dimensions` must be set explicitly on EVERY row — same PostgREST
// bulk-insert normalization as paid_amount below: omitting it on some
// rows while one row sets it sends null (violating NOT NULL) instead
// of falling through to the schema default '{}'.
{
journal_entry_id: je1.id,
account_number: '1510',
@@ -436,6 +481,7 @@ export async function POST(request: Request) {
debit_amount: 18750,
credit_amount: 0,
sort_order: 0,
dimensions: {},
},
{
journal_entry_id: je1.id,
@@ -444,6 +490,8 @@ export async function POST(request: Request) {
debit_amount: 0,
credit_amount: 15000,
sort_order: 1,
dimensions: revenueDims,
...lineDimensionColumns(revenueDims),
},
{
journal_entry_id: je1.id,
@@ -452,6 +500,7 @@ export async function POST(request: Request) {
debit_amount: 0,
credit_amount: 3750,
sort_order: 2,
dimensions: {},
},
// JE2: Invoice payment — Debit Bank, Credit AR
{
@@ -461,6 +510,7 @@ export async function POST(request: Request) {
debit_amount: 18750,
credit_amount: 0,
sort_order: 0,
dimensions: {},
},
{
journal_entry_id: je2.id,
@@ -469,6 +519,7 @@ export async function POST(request: Request) {
debit_amount: 0,
credit_amount: 18750,
sort_order: 1,
dimensions: {},
},
])