Files
accounted/lib/bookkeeping/dimension-rules.ts
T
Jakob WennbergandClaude Fable 5 764348e99c feat(dimensions): PR10 advanced — custom dimensions, hierarchy, account rules, commit enforcement (#886)
* feat(dimensions): PR10 advanced — custom dimensions, hierarchy, account rules, commit enforcement

The final rung of the dimensions ladder
(dev_docs/dimensions_implementation_plan.md §7 row 10):

- custom dimensions: POST /api/dimensions creates registry dims (next free
  SIE number >= 20 when omitted; explicit numbers allowed — SIE import
  already mints reserved ones); register gets a 'Ny dimension' dialog with
  a quiet Avancerat disclosure for the #UNDERDIM parent; GET now carries
  parent_sie_dim_no (the column + SIE round-trip existed since PR1/PR5 —
  this exposes it)
- account_dimension_rules (migration 20260703120000): one rule per
  (account, dimension) — required / default / fixed, per-rule is_active,
  company-scoped RLS, composite FK to the registry, value-presence CHECK
- enforcement, opt-in BY CONSTRUCTION (zero rules = engine byte-identical;
  deliberately NO settings toggle — a rule that exists but is ignored is
  worse than either extreme): default/fixed apply onto line bags at draft
  creation (fixed overwrites, default fills); required asserts at
  commitEntry with a Swedish MANDATORY_DIMENSION_MISSING naming every
  account + dimension; the bulk-book route runs the same policy before its
  RPC; storno/correction paths never pass through commitEntry so history
  always reverses regardless of policy; rule fetches fail open incl.
  thrown exceptions
- chart of accounts: per-account Dimensionsregler section in
  EditAccountDialog (Krävs/Förval/Låst, value picker, pause switch),
  gated on the existing dimensions toggle, quiet when empty
- pickers: LineDimensionFields is registry-driven (one combobox per active
  dimension, cached fetch, hardcoded 1/6 fallback) — every existing mount
  lights up custom dims with zero changes
- agent briefing: per-dimension required_on_accounts/default_on_accounts
  so agents self-correct instead of bouncing off the policy error
- rules CRUD API with existence/active/company validation and qualified
  DTO ids; firm_id FK deferred until the firms table lands (per plan)

39 new tests (pure-fn rules, engine enforcement, both new API surfaces,
pg-real RLS/CHECK/cascade suite); full suite 6,791 green; migration
replayed on a fresh container.

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

* fix: renumber migration to 20260703200000 — version collision with prod

The concurrent session shipped pending_operations_add_link_document_to_voucher
as 20260703120000 today; the Supabase preview branch (cloned from prod)
rejected the duplicate version key.

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

* fix: review round — auto-pick retry on collision, fail-open warnings, query schema

- POST /api/dimensions retries once past a concurrent number claim when the
  number was auto-picked (explicit choices still 409)
- every fail-open skip of the dimension-rules policy now logs a structured
  warning (engine draft/commit paths + bulk-book) — deliberate fail-open,
  but observable
- GET /api/dimensions/rules validates its query through
  ListDimensionRulesQuerySchema instead of an inline regex

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 16:50:28 +02:00

177 lines
6.4 KiB
TypeScript

/**
* Account dimension rules (dimensions PR10) — the policy layer over the
* dimensions substrate. Rules live in account_dimension_rules
* (20260703200000), one per (account, dimension):
*
* 'required' the account cannot be POSTED without a value → enforced by
* assertMandatoryDimensions at commitEntry and the bulk-book
* route pre-check. Drafts may be incomplete by design; storno/
* correction paths never pass through commitEntry, so history
* always reverses regardless of policy.
* 'default' pre-applied to the line bag at draft creation when the key
* is absent (user-overridable).
* 'fixed' ALWAYS applied at draft creation (overwrites the caller's
* key) — the account is pinned to one value.
*
* Zero rules (every company by default) short-circuits everything — the
* engine behaves exactly as before PR10. Rule fetches FAIL OPEN like the
* soft registry validation: a transient DB error must not block bookkeeping,
* and the write hits the same database anyway.
*
* Pure of next/server so it stays importable from anywhere the resolver is.
*/
import type { SupabaseClient } from '@supabase/supabase-js'
import {
MandatoryDimensionMissingError,
type MandatoryDimensionViolation,
} from './dimension-errors'
import {
normalizeLineDimensions,
type DimensionAliasInput,
type LineDimensions,
} from './dimension-resolver'
export interface AccountDimensionRule {
account_number: string
rule_type: 'required' | 'default' | 'fixed'
/** Canonical SIE dimension number as a string key, e.g. '6'. */
sie_dim_no: string
dimension_name: string
/** Value code for default/fixed rules; null for required. */
value_code: string | null
}
interface RawRuleRow {
account_number: string
rule_type: 'required' | 'default' | 'fixed'
dimensions: { sie_dim_no: number; name: string }
dimension_values: { code: string } | null
}
/**
* All ACTIVE rules for the company. Returns null on query failure (callers
* fail open — same posture as validateEntryDimensions). The table is tiny
* and indexed on (company_id, account_number); one fetch per booking is the
* whole cost for rule-less companies.
*/
export async function fetchActiveDimensionRules(
supabase: SupabaseClient,
companyId: string
): Promise<AccountDimensionRule[] | null> {
// try/catch on top of the error-result check: fail-open must also cover
// thrown exceptions (broken client, network throw) — policy lookups are
// never allowed to take bookkeeping down with them.
try {
const { data, error } = await supabase
.from('account_dimension_rules')
.select(
'account_number, rule_type, dimensions!account_dimension_rules_dimension_id_company_id_fkey(sie_dim_no, name), dimension_values!account_dimension_rules_value_id_fkey(code)'
)
.eq('company_id', companyId)
.eq('is_active', true)
if (error) return null
return ((data ?? []) as unknown as RawRuleRow[]).map((row) => ({
account_number: row.account_number,
rule_type: row.rule_type,
sie_dim_no: String(row.dimensions.sie_dim_no),
dimension_name: row.dimensions.name,
value_code: row.dimension_values?.code ?? null,
}))
} catch {
return null
}
}
/**
* Apply default/fixed rules onto entry lines before validation + insert.
* Returns the same array when nothing applies (zero allocation on the
* common path); otherwise a copy where affected lines carry the augmented
* bag (aliases folded in first, so the returned lines are bag-authoritative).
*/
export function applyDimensionRules<
T extends DimensionAliasInput & { account_number: string },
>(lines: T[], rules: AccountDimensionRule[]): T[] {
const applicable = rules.filter(
(r) => (r.rule_type === 'default' || r.rule_type === 'fixed') && r.value_code
)
if (applicable.length === 0) return lines
const byAccount = new Map<string, AccountDimensionRule[]>()
for (const rule of applicable) {
const bucket = byAccount.get(rule.account_number) ?? []
bucket.push(rule)
byAccount.set(rule.account_number, bucket)
}
let anyChanged = false
const result = lines.map((line) => {
const forAccount = byAccount.get(line.account_number)
if (!forAccount) return line
const bag: LineDimensions = normalizeLineDimensions(line)
let changed = false
for (const rule of forAccount) {
if (rule.rule_type === 'fixed') {
if (bag[rule.sie_dim_no] !== rule.value_code) {
bag[rule.sie_dim_no] = rule.value_code as string
changed = true
}
} else if (!(rule.sie_dim_no in bag)) {
bag[rule.sie_dim_no] = rule.value_code as string
changed = true
}
}
if (!changed) return line
anyChanged = true
// The bag now carries everything (aliases folded by normalize) — clear
// the deprecated aliases so downstream normalization can't resurrect a
// value a fixed rule just overwrote.
return { ...line, dimensions: bag, cost_center: null, project: null }
})
return anyChanged ? result : lines
}
/**
* Throw MandatoryDimensionMissingError when any ACTIVE 'required' rule is
* unsatisfied. One violation per (account, dimension) regardless of how many
* lines miss it — the Swedish message stays readable for multi-line entries.
*/
export function assertMandatoryDimensions(
lines: Array<DimensionAliasInput & { account_number: string }>,
rules: AccountDimensionRule[]
): void {
const required = rules.filter((r) => r.rule_type === 'required')
if (required.length === 0) return
const byAccount = new Map<string, AccountDimensionRule[]>()
for (const rule of required) {
const bucket = byAccount.get(rule.account_number) ?? []
bucket.push(rule)
byAccount.set(rule.account_number, bucket)
}
const violations = new Map<string, MandatoryDimensionViolation>()
for (const line of lines) {
const forAccount = byAccount.get(line.account_number)
if (!forAccount) continue
const bag = normalizeLineDimensions(line)
for (const rule of forAccount) {
if (!bag[rule.sie_dim_no]) {
violations.set(`${line.account_number} ${rule.sie_dim_no}`, {
account_number: line.account_number,
sie_dim_no: rule.sie_dim_no,
dimension_name: rule.dimension_name,
})
}
}
}
if (violations.size > 0) {
throw new MandatoryDimensionMissingError([...violations.values()])
}
}