* feat(dimensions): substrate — SIE-native registry + dimensions JSONB on journal lines (PR1)
Implements phase 1 of dev_docs/dimensions_implementation_plan.md:
- New company-native registry tables: dimensions (= SIE #DIM/#UNDERDIM,
seeded is_system 1=Kostnadsställe / 6=Projekt via ensure_company_dimensions,
nullable bare firm_id) and dimension_values (= #OBJEKT), full RLS incl.
DELETE, audit + updated_at triggers, guard triggers (system dims undeletable,
sie_dim_no immutable, values referenced by posted lines archive-not-delete).
- journal_entry_lines.dimensions jsonb NOT NULL DEFAULT '{}' as the single
source of truth ({sie_dim_no: object_code}), CHECK object-typed, GIN
(jsonb_path_ops) + partial expression indexes on dims 1/6. Inherits posted-
line immutability from the existing trigger with zero new triggers.
- Backfill: representation copy of legacy cost_center/project text into the
JSONB map (trigger-disabled, schema_sync precedent); legacy cost_centers/
projects registry rows copied into dimension_values; inactive placeholder
values for orphaned free-text codes.
- Dual-write: engine buildLineInserts + storno/correction/date-move now derive
cost_center/project mirrors from the map via lib/bookkeeping/dimension-resolver.ts
(normalizeLineDimensions / lineDimensionColumns); reversal copies dims.
- CreateJournalEntryLineInput + shared Zod line schema gain a dimensions bag
(cost_center/project stay as deprecated aliases); pending-ops voucher lines
coerce it.
- CI ratchet: direct-jel-insert check in no-new-antipatterns.mjs — inserts into
journal_entry_lines outside sanctioned writers fail CI.
- pg-real suite: registry RLS/guards/retention, ensure_company_dimensions
tenant guard, dims frozen on posted lines, CHECK enforcement (13 tests).
Non-breaking: companies without dimensions see zero change; no UI yet.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(dimensions): address review findings — canonical keys, boundary-validated staged bags, migration guidance
- normalizeLineDimensions canonicalizes numeric keys ('01' -> '1') so
leading-zero keys can't split values or miss the cost_center/project mirrors
(PR Agent finding).
- New coerceDimensionsBag() in dimension-resolver is the single boundary
validator for untyped staged payloads, enforcing the same constraints as the
Zod line schema (string-only values, 1-40 chars, no SIE-framing chars,
canonical keys). pending-operations normalizeVoucherLines now uses it —
staged payloads can no longer bypass API-layer validation via numeric
coercion (compliance-swarm V2.2/V1.2.5/PI1.1, Swedish review finding 4).
- Migration backfill comment now spells out the exact conditions under which
the trigger-disable pattern is defensible (BFL 5:5 / BFNAR 2013:2) and what
a future reviewer must verify before reusing it (Swedish review finding 2).
- 10 new resolver tests incl. reversal-parity (empty bag + aliases ==
alias-only) proving the reverseEntry and storno paths normalize identically
(PR Agent finding 1).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(dimensions): round-2 review — shared Zod schema, transactional backfill, empty-string guard
- DimensionsBagSchema now lives in dimension-resolver as the single source of
truth; CreateJournalEntryLineSchema and coerceDimensionsBag both delegate to
it, so the API layer and the staged pending-operations path provably cannot
drift (compliance-swarm V2.2). coerceDimensionsBag switches to whole-bag
semantics: any invalid entry rejects the bag, exactly like the API schema.
- Migration backfill now runs DISABLE TRIGGER / UPDATE / ENABLE TRIGGER inside
one transaction — the ACCESS EXCLUSIVE lock from ALTER TABLE holds until
COMMIT, so no concurrent writer can slip an unguarded line write into the
window during a live apply (compliance-swarm V1.2, Swedish review finding 1).
- NULLIF guard: empty-string legacy mirrors can no longer mint {"n":""}
entries the resolver would interpret as "cleared" (PR Agent round-2 edge).
- COMMENT ON dimensions.resets_annually documenting the SIE4 #IB/#OIB
semantics the PR2+ export path must honour (Swedish review finding 2).
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
109 lines
4.4 KiB
TypeScript
109 lines
4.4 KiB
TypeScript
/**
|
|
* Dimension resolver — the single place line dimensions are normalized and
|
|
* mirrored (dev_docs/dimensions_implementation_plan.md).
|
|
*
|
|
* Storage model: journal_entry_lines.dimensions is a JSONB map keyed by SIE
|
|
* dimension number ({"1":"KS01","6":"P001"}) and is the single source of
|
|
* truth. The legacy cost_center/project TEXT columns are deterministic mirrors
|
|
* of keys '1'/'6' during the dual-write window (they become GENERATED columns
|
|
* in a later migration). Every journal_entry_lines writer MUST derive the
|
|
* mirror columns via lineDimensionColumns() — never set them independently.
|
|
*/
|
|
|
|
import { z } from 'zod'
|
|
|
|
/** SIE dimension numbers with first-class mirror columns. */
|
|
export const DIM_COST_CENTER = '1'
|
|
export const DIM_PROJECT = '6'
|
|
|
|
export type LineDimensions = Record<string, string>
|
|
|
|
/**
|
|
* THE schema for a dimensions bag ({sie_dim_no: object_code}) — the single
|
|
* source of truth for its constraints. The API layer
|
|
* (CreateJournalEntryLineSchema) and the staged pending-operations path
|
|
* (coerceDimensionsBag) both use this exact schema, so the two validation
|
|
* layers cannot drift. Keys are canonical SIE dimension numbers (no leading
|
|
* zeros); values must not contain characters that break SIE field framing.
|
|
*/
|
|
export const DimensionsBagSchema = z.record(
|
|
z.string().regex(/^[1-9]\d*$/, 'Dimensionsnyckel måste vara ett SIE-dimensionsnummer'),
|
|
z.string().min(1).max(40).regex(/^[^"{}]+$/, 'Dimensionskod får inte innehålla ", { eller }')
|
|
)
|
|
|
|
interface DimensionAliasInput {
|
|
dimensions?: LineDimensions | null
|
|
cost_center?: string | null
|
|
project?: string | null
|
|
}
|
|
|
|
/**
|
|
* Merge the explicit `dimensions` bag with the deprecated cost_center/project
|
|
* aliases into one canonical map. The explicit bag wins per key; aliases only
|
|
* fill keys the bag does not set. Empty/blank values and non-numeric keys are
|
|
* dropped so the stored map never carries junk entries.
|
|
*/
|
|
export function normalizeLineDimensions(line: DimensionAliasInput): LineDimensions {
|
|
const out: LineDimensions = {}
|
|
|
|
const costCenter = line.cost_center?.trim()
|
|
if (costCenter) out[DIM_COST_CENTER] = costCenter
|
|
const project = line.project?.trim()
|
|
if (project) out[DIM_PROJECT] = project
|
|
|
|
if (line.dimensions) {
|
|
for (const [key, value] of Object.entries(line.dimensions)) {
|
|
if (!/^\d+$/.test(key) || Number(key) < 1) continue
|
|
// Canonical numeric form: '01' and '1' must land on the same key, or
|
|
// lineDimensionColumns misses the mirror and reports split the value.
|
|
const dimNo = String(Number(key))
|
|
const trimmed = typeof value === 'string' ? value.trim() : ''
|
|
if (!trimmed) {
|
|
// Explicit empty string in the bag means "clear this dimension" — it
|
|
// must also override a non-empty alias, so remove any alias-filled key.
|
|
delete out[dimNo]
|
|
continue
|
|
}
|
|
out[dimNo] = trimmed
|
|
}
|
|
}
|
|
|
|
return out
|
|
}
|
|
|
|
/**
|
|
* Boundary validator for an untyped dimensions bag (staged pending-operation
|
|
* params, tool payloads). Delegates to DimensionsBagSchema — the exact schema
|
|
* the API layer uses — so the staged path cannot drift from API validation.
|
|
* Whole-bag semantics: a bag containing ANY invalid entry is rejected
|
|
* (returns undefined) rather than partially salvaged; staged payloads were
|
|
* already schema-validated at staging time, so an invalid entry here means
|
|
* drift or tampering — booking then proceeds without dimensions, which are
|
|
* never load-bearing for validity. Interior normalization
|
|
* (normalizeLineDimensions) stays permissive on charset by design — it must
|
|
* preserve legacy DB values verbatim on reversal/correction; this function is
|
|
* the input gate.
|
|
*/
|
|
export function coerceDimensionsBag(raw: unknown): LineDimensions | undefined {
|
|
if (raw === undefined || raw === null) return undefined
|
|
const parsed = DimensionsBagSchema.safeParse(raw)
|
|
if (!parsed.success) return undefined
|
|
const dims = normalizeLineDimensions({ dimensions: parsed.data })
|
|
return Object.keys(dims).length > 0 ? dims : undefined
|
|
}
|
|
|
|
/**
|
|
* Derive the legacy mirror columns from the canonical map. Pure function —
|
|
* divergence between `dimensions` and cost_center/project is impossible as
|
|
* long as every writer goes through this.
|
|
*/
|
|
export function lineDimensionColumns(dimensions: LineDimensions): {
|
|
cost_center: string | null
|
|
project: string | null
|
|
} {
|
|
return {
|
|
cost_center: dimensions[DIM_COST_CENTER] ?? null,
|
|
project: dimensions[DIM_PROJECT] ?? null,
|
|
}
|
|
}
|