Files
accounted/lib/bookkeeping/dimension-resolver.ts
T
Jakob WennbergandClaude Fable 5 11126d6d56 feat(dimensions): PR3 tagging — voucher-form pickers, MCP dimension tools with resolve-don't-select, engine soft validation (#859)
Phase 3 of dev_docs/dimensions_implementation_plan.md. Companies with
dimensions_enabled=false see zero change; existing free-text API writers keep
working (validation is toggle-governed).

Engine (soft validation):
- validateEntryDimensions() in dimension-resolver: zero queries for untagged
  entries; toggle off → passthrough; toggle on → one settings fetch + two
  registry queries, rejects unknown dims/codes and archived values with
  Swedish per-code messages (DimensionValidationError, 400, details.issues).
  Wired into createDraftEntry + updateDraftEntry before any insert; reversal/
  storno paths untouched (verbatim copies). Fails open on transient registry
  errors — soft validation must never block bookkeeping.

MCP (agent write path):
- New tools: gnubok_list_dimensions, gnubok_list_dimension_values (fuse.js
  fuzzy), gnubok_create_dimension_value (STAGED via pending_operations —
  agents never silently mint reporting values; new op type + CHECK migration
  + executor with duplicate-idempotency).
- create_voucher/correct_entry: per-line dimensions bag + default_dimensions,
  resolve-don't-select server-side (code OR natural-language name; exact →
  fuzzy ≤0.30 with ≥0.15 runner-up margin; non-exact resolutions echoed with
  confidence; ambiguous → ranked candidates, no auto-create).
- gnubok_get_agent_briefing gains a dimensions block (enabled, dims, top
  values) — omitted when registry empty.
- TOOL_SCOPE_MAP entries; risk tier low for staged value creation.

UI:
- JournalEntryForm (manual voucher + TransactionBookingDialog embed): header
  "+ Kostnadsställe/Projekt" progressive disclosure (gäller alla rader with
  documented inheritance rule) + per-row tag popover + compact KS·PR badges;
  gated on dimensions_enabled.
- Voucher detail: display-only dimension badges with registry-name resolution.
- EditDraftEntryDialog carries line dimensions so editing a draft no longer
  strips tags.

categorize/bulk_book dims deferred to PR7 (needs the bulk_book RPC migration).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 13:36:45 +02:00

236 lines
9.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'
import type { SupabaseClient } from '@supabase/supabase-js'
import {
DimensionValidationError,
type DimensionValidationIssue,
} from '@/lib/bookkeeping/dimension-errors'
/** 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 }')
)
export 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,
}
}
/**
* Soft registry validation of the dimensions referenced by a set of entry
* lines (dev_docs/dimensions_implementation_plan.md, PR3). Called from
* createDraftEntry/updateDraftEntry after balance validation and before any
* insert, so a rejection leaves no orphan rows.
*
* Semantics:
* 1. Untagged entries are free: if no line carries a dimension, the function
* returns without touching the database at all.
* 2. Companies without company_settings.dimensions_enabled keep the historic
* free-text passthrough — existing API/MCP writers are unaffected. This is
* the ONE place the toggle is load-bearing beyond UI visibility.
* 3. Enabled companies get referential validation against the registry: a
* dimension number with no `dimensions` row, a code with no
* `dimension_values` row, or an archived (is_active = false) value rejects
* the whole entry with a DimensionValidationError whose Swedish message
* names every offending code.
*
* Cost: at most three queries per entry (settings, dimensions,
* dimension_values) regardless of line count — never per-line lookups.
*
* Failure posture: query errors fail OPEN (validation is skipped). This is
* soft validation — a transient DB error must not block bookkeeping, and the
* write that follows hits the same database anyway. Reversal/storno/correction
* paths intentionally bypass this function: they copy posted data verbatim
* (BFL 5 kap 5§ requires the storno to mirror the original even if a value
* has since been archived).
*/
export async function validateEntryDimensions(
supabase: SupabaseClient,
companyId: string,
lines: DimensionAliasInput[]
): Promise<void> {
// 1. Union of normalized dimension maps across all lines.
const union = new Map<string, Set<string>>()
for (const line of lines) {
for (const [dimNo, code] of Object.entries(normalizeLineDimensions(line))) {
const codes = union.get(dimNo) ?? new Set<string>()
codes.add(code)
union.set(dimNo, codes)
}
}
if (union.size === 0) return
// 2. Toggle gate — fetched once. Missing row/column or a query error means
// passthrough (fail-open, same posture as resolveSeriesFromSettings).
const { data: settings, error: settingsError } = await supabase
.from('company_settings')
.select('dimensions_enabled')
.eq('company_id', companyId)
.maybeSingle()
const enabled = (settings as { dimensions_enabled?: boolean } | null)?.dimensions_enabled
if (settingsError || !enabled) return
// 3a. Registry rows for every referenced dimension number — one query.
const { data: dimRows, error: dimError } = await supabase
.from('dimensions')
.select('id, sie_dim_no')
.eq('company_id', companyId)
.in('sie_dim_no', [...union.keys()].map(Number))
if (dimError) return
const dimIdByNo = new Map<string, string>()
for (const row of (dimRows ?? []) as { id: string; sie_dim_no: number }[]) {
dimIdByNo.set(String(row.sie_dim_no), row.id)
}
const issues: DimensionValidationIssue[] = []
const knownDimIds: string[] = []
for (const dimNo of union.keys()) {
const dimId = dimIdByNo.get(dimNo)
if (dimId) knownDimIds.push(dimId)
else issues.push({ sie_dim_no: dimNo, code: null, reason: 'unknown_dimension' })
}
// 3b. Value rows for every referenced (dimension, code) pair — one query.
// Filtering by the code union may return a same-named code under another
// referenced dimension; lookups below key on (dimension_id, code) so
// that cannot cause a false pass.
if (knownDimIds.length > 0) {
const allCodes = [...new Set([...union.values()].flatMap((codes) => [...codes]))]
const { data: valueRows, error: valueError } = await supabase
.from('dimension_values')
.select('dimension_id, code, is_active')
.eq('company_id', companyId)
.in('dimension_id', knownDimIds)
.in('code', allCodes)
if (valueError) return
// NUL-escape-separated composite key: a NUL can never occur in a Postgres
// text value, so (dimension_id, code) pairs stay unambiguous for any code.
const activeByKey = new Map<string, boolean>()
for (const row of (valueRows ?? []) as {
dimension_id: string
code: string
is_active: boolean
}[]) {
activeByKey.set(`${row.dimension_id}\u0000${row.code}`, row.is_active)
}
for (const [dimNo, codes] of union) {
const dimId = dimIdByNo.get(dimNo)
if (!dimId) continue
for (const code of codes) {
const isActive = activeByKey.get(`${dimId}\u0000${code}`)
if (isActive === undefined) {
issues.push({ sie_dim_no: dimNo, code, reason: 'unknown_value' })
} else if (!isActive) {
issues.push({ sie_dim_no: dimNo, code, reason: 'archived_value' })
}
}
}
}
if (issues.length > 0) {
throw new DimensionValidationError(issues)
}
}