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
+64
View File
@@ -713,6 +713,67 @@ export const CorrectJournalEntrySchema = z.object({
lines: z.array(CreateJournalEntryLineSchema).min(2, 'At least two lines are required for double-entry'),
})
// ============================================================
// Dimension registry schemas (kostnadsställe/projekt)
// ============================================================
// dev_docs/dimensions_implementation_plan.md §6. The registry tables
// (dimensions/dimension_values) shipped in 20260702084500_dimensions_substrate.
/**
* Object code for USER-CREATED dimension values: strict Fortnox format.
* Deliberately tighter than both the DB CHECK (1..40 chars, no `"{}`') and
* DimensionsBagSchema (line-level values) — legacy free-text codes from the
* backfill/SIE import must survive on lines, but new registry codes minted
* through the API stay portable to Fortnox/Visma.
*/
const dimensionValueCode = z
.string()
.regex(
/^[A-Za-z0-9ÅÄÖåäö_+\-]{1,20}$/,
'Koden får bara innehålla bokstäver (A–Ö), siffror, _, + och - (max 20 tecken)',
)
const dimensionValueDates = {
start_date: isoDate.nullable().optional(),
end_date: isoDate.nullable().optional(),
}
/** PATCH /api/dimensions/[id] — name is rejected route-side for is_system dims. */
export const UpdateDimensionSchema = z
.object({
name: z.string().min(1).max(80).optional(),
is_active: z.boolean().optional(),
sort_order: z.number().int().min(0).optional(),
})
.refine((body) => Object.values(body).some((v) => v !== undefined), {
message: 'Minst ett fält måste anges',
})
/** POST /api/dimensions/[id]/values — code is immutable after creation (v1: no rename). */
export const CreateDimensionValueSchema = z
.object({
code: dimensionValueCode,
name: z.string().min(1).max(120),
/** Omitted → true. Lets "create as archived" be a single atomic POST. */
is_active: z.boolean().optional(),
...dimensionValueDates,
})
.refine(
(body) => !body.start_date || !body.end_date || body.end_date >= body.start_date,
{ message: 'Slutdatum får inte vara före startdatum', path: ['end_date'] },
)
/** PATCH /api/dimensions/[id]/values/[valueId] — no `code` field by design. */
export const UpdateDimensionValueSchema = z
.object({
name: z.string().min(1).max(120).optional(),
is_active: z.boolean().optional(),
...dimensionValueDates,
})
.refine((body) => Object.values(body).some((v) => v !== undefined), {
message: 'Minst ett fält måste anges',
})
/**
* Move a posted verifikation to a different date (and thereby fiscal period)
* without changing its lines — fixes a booking entered with the wrong
@@ -1172,6 +1233,9 @@ export const UpdateSettingsSchema = z.object({
.optional(),
// AI agent flow
ai_flow_enabled: z.boolean().optional(),
// Dimensions (kostnadsställe/projekt) — UI-visibility toggle only, never
// load-bearing for correctness (dev_docs/dimensions_implementation_plan.md §2).
dimensions_enabled: z.boolean().optional(),
// Salary payment file
preferred_payment_format: z.enum(['bg_lb', 'pain001']).optional(),
}).refine(
@@ -1,6 +1,6 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `102`;
exports[`v1 spec snapshot > matches the recorded endpoint count > endpoint-count 1`] = `104`;
exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-keys 1`] = `
[
@@ -14,6 +14,7 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
"GET /api/v1/companies/:companyId/compliance/check",
"GET /api/v1/companies/:companyId/customers",
"GET /api/v1/companies/:companyId/customers/:id",
"GET /api/v1/companies/:companyId/dimensions",
"GET /api/v1/companies/:companyId/documents/:id/download",
"GET /api/v1/companies/:companyId/employees",
"GET /api/v1/companies/:companyId/employees/:id",
@@ -60,6 +61,7 @@ exports[`v1 spec snapshot > matches the recorded endpoint key set > endpoint-key
"PATCH /api/v1/companies/:companyId/webhooks/:id",
"POST /api/v1/companies/:companyId/customers",
"POST /api/v1/companies/:companyId/customers/bulk-create",
"POST /api/v1/companies/:companyId/dimensions/:id/values",
"POST /api/v1/companies/:companyId/documents",
"POST /api/v1/companies/:companyId/documents/:id/link",
"POST /api/v1/companies/:companyId/employees",
+4
View File
@@ -132,4 +132,8 @@ import '@/app/api/v1/companies/[companyId]/webhooks/[id]/rotate-secret/route'
// Inbox item stamp.
import '@/app/api/v1/companies/[companyId]/inbox-items/[id]/stamp/route'
// Dimensions PR2 — registry list + value creation (kostnadsställe/projekt).
import '@/app/api/v1/companies/[companyId]/dimensions/route'
import '@/app/api/v1/companies/[companyId]/dimensions/[id]/values/route'
export {}