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>
This commit is contained in:
Jakob Wennberg
2026-07-03 16:50:28 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 70e893b8d4
commit 764348e99c
26 changed files with 2800 additions and 72 deletions
+56
View File
@@ -841,6 +841,62 @@ export const CreateDimensionValueSchema = z
* open period, lock date, active registry values); this schema only shapes
* the request. An empty bag {} untags the line.
*/
/**
* POST /api/dimensions — create a custom dimension (dimensions PR10).
* sie_dim_no omitted → server picks the next free number >= 20 (SIE leaves
* 20+ unreserved). parent_sie_dim_no declares an #UNDERDIM hierarchy.
*/
export const CreateDimensionSchema = z.object({
name: z.string().trim().min(1).max(60),
sie_dim_no: z.coerce.number().int().min(1).max(9999).optional(),
resets_annually: z.boolean().optional(),
parent_sie_dim_no: z.coerce.number().int().min(1).max(9999).nullable().optional(),
})
const AccountDimensionRuleTypeSchema = z.enum(['required', 'default', 'fixed'])
/** GET /api/dimensions/rules query — optional exact-account filter. */
export const ListDimensionRulesQuerySchema = z.object({
account_number: accountNumber.optional(),
})
/**
* POST /api/dimensions/rules — per-account dimension policy (dimensions
* PR10). 'required' carries no value; 'default'/'fixed' must carry the value
* to apply. One rule per (account, dimension) — enforced by the DB UNIQUE.
*/
export const CreateAccountDimensionRuleSchema = z
.object({
account_number: accountNumber,
dimension_id: uuid,
rule_type: AccountDimensionRuleTypeSchema,
value_id: uuid.optional(),
is_active: z.boolean().optional(),
})
.superRefine((rule, ctx) => {
if (rule.rule_type === 'required' && rule.value_id) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['value_id'],
message: 'En obligatorisk regel har inget värde — värden hör till Förval/Låst.',
})
}
if (rule.rule_type !== 'required' && !rule.value_id) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ['value_id'],
message: 'Välj vilket värde regeln ska använda.',
})
}
})
/** PATCH /api/dimensions/rules/[id] — the value-presence rule re-checks in the route (partial update). */
export const UpdateAccountDimensionRuleSchema = z.object({
rule_type: AccountDimensionRuleTypeSchema.optional(),
value_id: uuid.nullable().optional(),
is_active: z.boolean().optional(),
})
export const RetagLineDimensionsSchema = z.object({
// {} passes (no entries to validate) = UNTAG. Intentional divergence from
// the MCP staged path (RetagLineDimensionsParamsSchema), which rejects an
@@ -0,0 +1,255 @@
/**
* Pure-function tests for the account dimension rule layer (dimensions PR10).
*
* applyDimensionRules: 'default' fills only absent bag keys, 'fixed' always
* overwrites (including alias-sourced values, with the deprecated aliases
* cleared on changed lines), and the zero-effect paths preserve array/line
* identity so the common rule-less booking allocates nothing.
*
* assertMandatoryDimensions: throws MandatoryDimensionMissingError with one
* violation per (account, dimension) regardless of line count, treats
* alias-sourced values as satisfying (normalize folds them into the bag),
* and no-ops when no 'required' rule exists.
*/
import { describe, it, expect } from 'vitest'
import {
applyDimensionRules,
assertMandatoryDimensions,
type AccountDimensionRule,
} from '../dimension-rules'
import {
MANDATORY_DIMENSION_MISSING,
MandatoryDimensionMissingError,
} from '../dimension-errors'
interface TestLine {
account_number: string
dimensions?: Record<string, string> | null
cost_center?: string | null
project?: string | null
}
function makeRule(overrides: Partial<AccountDimensionRule> = {}): AccountDimensionRule {
return {
account_number: '4010',
rule_type: 'default',
sie_dim_no: '6',
dimension_name: 'Projekt',
value_code: 'P001',
...overrides,
}
}
describe('applyDimensionRules', () => {
it('default fills only absent keys — caller-set keys win', () => {
const lines: TestLine[] = [
{ account_number: '4010', dimensions: { '6': 'CALLER' } },
]
const rules = [
makeRule({ rule_type: 'default', sie_dim_no: '6', value_code: 'PDEF' }),
makeRule({
rule_type: 'default',
sie_dim_no: '1',
dimension_name: 'Kostnadsställe',
value_code: 'KS01',
}),
]
const out = applyDimensionRules(lines, rules)
// Absent key '1' filled; present key '6' untouched.
expect(out[0].dimensions).toEqual({ '6': 'CALLER', '1': 'KS01' })
// The input line object was not mutated.
expect(lines[0].dimensions).toEqual({ '6': 'CALLER' })
})
it('default does not override an alias-sourced value (line identity preserved)', () => {
const lines: TestLine[] = [{ account_number: '4010', cost_center: 'KS-ALIAS' }]
const rules = [
makeRule({
rule_type: 'default',
sie_dim_no: '1',
dimension_name: 'Kostnadsställe',
value_code: 'KS99',
}),
]
// normalize folds cost_center into key '1', so the default has nothing to
// fill — nothing applies and the SAME array comes back.
expect(applyDimensionRules(lines, rules)).toBe(lines)
expect(lines[0].cost_center).toBe('KS-ALIAS')
})
it('fixed overwrites an alias-sourced value and clears the aliases', () => {
const lines: TestLine[] = [{ account_number: '4010', cost_center: 'OLD' }]
const rules = [
makeRule({
rule_type: 'fixed',
sie_dim_no: '1',
dimension_name: 'Kostnadsställe',
value_code: 'KS99',
}),
]
const out = applyDimensionRules(lines, rules)
expect(out[0].dimensions).toEqual({ '1': 'KS99' })
// Aliases nulled so downstream normalization cannot resurrect 'OLD'.
expect(out[0].cost_center).toBeNull()
expect(out[0].project).toBeNull()
})
it('fixed overwrites a caller-supplied bag value', () => {
const lines: TestLine[] = [{ account_number: '4010', dimensions: { '6': 'CALLER' } }]
const rules = [makeRule({ rule_type: 'fixed', sie_dim_no: '6', value_code: 'PLOCK' })]
const out = applyDimensionRules(lines, rules)
expect(out[0].dimensions).toEqual({ '6': 'PLOCK' })
})
it('a fixed rule already satisfied is a no-op — same array identity', () => {
const lines: TestLine[] = [{ account_number: '4010', dimensions: { '6': 'P001' } }]
const rules = [makeRule({ rule_type: 'fixed', sie_dim_no: '6', value_code: 'P001' })]
expect(applyDimensionRules(lines, rules)).toBe(lines)
})
it('untouched lines keep identity while changed lines are copied', () => {
const lines: TestLine[] = [
{ account_number: '4010' },
{ account_number: '1930', dimensions: { '1': 'KS01' } },
]
const rules = [makeRule({ rule_type: 'fixed', sie_dim_no: '6', value_code: 'P001' })]
const out = applyDimensionRules(lines, rules)
expect(out).not.toBe(lines)
expect(out[0]).not.toBe(lines[0])
expect(out[0].dimensions).toEqual({ '6': 'P001' })
// The 1930 line has no rule — the exact same object rides through.
expect(out[1]).toBe(lines[1])
})
it('returns the same array for zero rules and for required-only rules', () => {
const lines: TestLine[] = [{ account_number: '4010' }]
expect(applyDimensionRules(lines, [])).toBe(lines)
// 'required' rules carry no value — they never apply at draft time.
expect(
applyDimensionRules(lines, [
makeRule({ rule_type: 'required', value_code: null }),
]),
).toBe(lines)
})
it('rules for other accounts do not leak onto unrelated lines', () => {
const lines: TestLine[] = [{ account_number: '4010' }]
const rules = [
makeRule({ account_number: '5010', rule_type: 'fixed', value_code: 'P001' }),
makeRule({ account_number: '5010', rule_type: 'default', value_code: 'P002' }),
]
expect(applyDimensionRules(lines, rules)).toBe(lines)
expect(lines[0].dimensions).toBeUndefined()
})
})
describe('assertMandatoryDimensions', () => {
const requiredProjekt = makeRule({ rule_type: 'required', value_code: null })
it('throws with one deduped violation across multiple missing lines', () => {
const lines: TestLine[] = [
{ account_number: '4010', dimensions: {} },
{ account_number: '4010' },
{ account_number: '1930' },
]
let caught: unknown
try {
assertMandatoryDimensions(lines, [requiredProjekt])
} catch (err) {
caught = err
}
expect(caught).toBeInstanceOf(MandatoryDimensionMissingError)
const error = caught as MandatoryDimensionMissingError
expect(error.code).toBe(MANDATORY_DIMENSION_MISSING)
// Two 4010 lines miss the same rule → ONE violation, not two.
expect(error.violations).toEqual([
{ account_number: '4010', sie_dim_no: '6', dimension_name: 'Projekt' },
])
})
it('reports one violation per (account, dimension) pair', () => {
const lines: TestLine[] = [
{ account_number: '4010' },
{ account_number: '5010' },
]
const rules = [
requiredProjekt,
makeRule({
account_number: '5010',
rule_type: 'required',
sie_dim_no: '1',
dimension_name: 'Kostnadsställe',
value_code: null,
}),
]
let caught: unknown
try {
assertMandatoryDimensions(lines, rules)
} catch (err) {
caught = err
}
const error = caught as MandatoryDimensionMissingError
expect(error.violations).toEqual([
{ account_number: '4010', sie_dim_no: '6', dimension_name: 'Projekt' },
{ account_number: '5010', sie_dim_no: '1', dimension_name: 'Kostnadsställe' },
])
})
it('uses the Swedish message format naming account and dimension', () => {
expect(() =>
assertMandatoryDimensions([{ account_number: '4010' }], [requiredProjekt]),
).toThrow('Konto 4010 kräver Projekt — välj ett värde innan bokföring.')
})
it('is satisfied via the deprecated cost_center alias through normalize', () => {
const requiredKostnadsstalle = makeRule({
rule_type: 'required',
sie_dim_no: '1',
dimension_name: 'Kostnadsställe',
value_code: null,
})
const lines: TestLine[] = [{ account_number: '4010', cost_center: 'KS01' }]
expect(() => assertMandatoryDimensions(lines, [requiredKostnadsstalle])).not.toThrow()
})
it('is satisfied by a bag value on the required key', () => {
const lines: TestLine[] = [{ account_number: '4010', dimensions: { '6': 'P001' } }]
expect(() => assertMandatoryDimensions(lines, [requiredProjekt])).not.toThrow()
})
it('never throws when no required rule exists (default/fixed only)', () => {
const lines: TestLine[] = [{ account_number: '4010' }]
const rules = [
makeRule({ rule_type: 'default' }),
makeRule({ rule_type: 'fixed', sie_dim_no: '1', value_code: 'KS01' }),
]
expect(() => assertMandatoryDimensions(lines, rules)).not.toThrow()
expect(() => assertMandatoryDimensions(lines, [])).not.toThrow()
})
it('required rules on other accounts do not fire', () => {
const lines: TestLine[] = [{ account_number: '4010' }]
const rules = [makeRule({ account_number: '5010', rule_type: 'required', value_code: null })]
expect(() => assertMandatoryDimensions(lines, rules)).not.toThrow()
})
})
@@ -1,14 +1,20 @@
/**
* Engine wiring of validateEntryDimensions (dimensions plan PR3).
* Engine wiring of validateEntryDimensions (dimensions plan PR3) and of the
* account dimension rules (dimensions PR10).
*
* createDraftEntry and updateDraftEntry must run the soft dimension
* validation AFTER balance validation and BEFORE any insert/update, so a
* rejection leaves no orphan rows. Untagged entries must not even fetch
* company_settings; companies without the toggle keep free-text passthrough.
*
* PR10: createDraftEntry applies default/fixed rules onto the line bags
* before validation + insert; commitEntry asserts 'required' rules against
* the entry's stored lines BEFORE the commit_journal_entry RPC, and skips
* the line fetch entirely when no required rule exists.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createDraftEntry, updateDraftEntry } from '../engine'
import { DimensionValidationError } from '../errors'
import { commitEntry, createDraftEntry, updateDraftEntry } from '../engine'
import { DimensionValidationError, MandatoryDimensionMissingError } from '../errors'
import type { CreateJournalEntryInput } from '@/types'
vi.mock('@/lib/events', () => ({
@@ -252,3 +258,136 @@ describe('updateDraftEntry — dimension validation wiring', () => {
expect(lineRows[0].dimensions).toEqual({ '6': 'P001' })
})
})
/**
* Raw account_dimension_rules row exactly as fetchActiveDimensionRules
* selects it: joined registry rows ride along nested (dimensions,
* dimension_values).
*/
function makeRuleRow(overrides: Record<string, unknown> = {}) {
return {
account_number: '4010',
rule_type: 'default',
dimensions: { sie_dim_no: 6, name: 'Projekt' },
dimension_values: { code: 'P001' },
...overrides,
}
}
describe('createDraftEntry — account dimension rules (PR10)', () => {
it('applies a default rule onto the inserted line bag when the key is absent', async () => {
const { supabase, inserts } = buildSupabase({
...BASE_TABLES,
account_dimension_rules: { data: [makeRuleRow()] },
})
const entry = await createDraftEntry(supabase as never, 'company-1', 'user-1', makeInput())
expect(entry.id).toBe('entry-1')
const lineRows = inserts.journal_entry_lines[0] as Array<Record<string, unknown>>
// The 4010 line got the default; the 1930 line has no rule and stays bare.
expect(lineRows[0].dimensions).toEqual({ '6': 'P001' })
expect(lineRows[1].dimensions).toEqual({})
// PR9 cutover: generated mirror columns must never appear in the payload.
expect('cost_center' in lineRows[0]).toBe(false)
expect('project' in lineRows[0]).toBe(false)
})
it('fixed rule overwrites the caller-supplied bag value', async () => {
const { supabase, inserts } = buildSupabase({
...BASE_TABLES,
account_dimension_rules: {
data: [makeRuleRow({ rule_type: 'fixed', dimension_values: { code: 'PLOCK' } })],
},
})
const entry = await createDraftEntry(
supabase as never,
'company-1',
'user-1',
makeInput({ '6': 'CALLER' })
)
expect(entry.id).toBe('entry-1')
const lineRows = inserts.journal_entry_lines[0] as Array<Record<string, unknown>>
// Rule pinned the 4010 line; the rule-less 1930 line keeps the caller tag.
expect(lineRows[0].dimensions).toEqual({ '6': 'PLOCK' })
expect(lineRows[1].dimensions).toEqual({ '6': 'CALLER' })
})
})
describe('commitEntry — mandatory dimension enforcement (PR10)', () => {
const requiredRule = makeRuleRow({ rule_type: 'required', dimension_values: null })
it('rejects an untagged line BEFORE the commit_journal_entry RPC fires', async () => {
const { supabase } = buildSupabase({
...BASE_TABLES,
account_dimension_rules: { data: [requiredRule] },
journal_entry_lines: {
data: [
{ account_number: '4010', dimensions: {} },
{ account_number: '1930', dimensions: {} },
],
},
})
await expect(
commitEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
).rejects.toBeInstanceOf(MandatoryDimensionMissingError)
await expect(
commitEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
).rejects.toThrow('Konto 4010 kräver Projekt — välj ett värde innan bokföring.')
// The verifikat must never have been posted.
expect(supabase.rpc).not.toHaveBeenCalled()
})
it('commits when every required dimension is satisfied on the stored lines', async () => {
const { supabase } = buildSupabase({
...BASE_TABLES,
account_dimension_rules: { data: [requiredRule] },
journal_entry_lines: {
data: [
{ account_number: '4010', dimensions: { '6': 'P001' } },
{ account_number: '1930', dimensions: {} },
],
},
})
const entry = await commitEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
expect(entry.id).toBe('entry-1')
expect(supabase.rpc).toHaveBeenCalledWith(
'commit_journal_entry',
expect.objectContaining({ p_company_id: 'company-1', p_entry_id: 'entry-1' })
)
})
it('skips the line fetch entirely when the company has zero rules', async () => {
const { supabase, queriedTables } = buildSupabase(BASE_TABLES)
const entry = await commitEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
expect(entry.id).toBe('entry-1')
// Rules were checked, but no required rule exists → no line fetch.
expect(queriedTables()).toContain('account_dimension_rules')
expect(queriedTables()).not.toContain('journal_entry_lines')
expect(supabase.rpc).toHaveBeenCalledWith(
'commit_journal_entry',
expect.objectContaining({ p_entry_id: 'entry-1' })
)
})
it('skips the line fetch when the only rules are default/fixed', async () => {
const { supabase, queriedTables } = buildSupabase({
...BASE_TABLES,
account_dimension_rules: {
data: [makeRuleRow(), makeRuleRow({ rule_type: 'fixed', account_number: '5010' })],
},
})
await commitEntry(supabase as never, 'company-1', 'user-1', 'entry-1')
expect(queriedTables()).not.toContain('journal_entry_lines')
})
})
@@ -83,8 +83,11 @@ describe('voucher number atomicity', () => {
p_actor_label: null,
})
// from() was never called — the RPC handles everything atomically
expect(supabase.from).not.toHaveBeenCalled()
// No line/entry fetch happened — the RPC handles everything atomically.
// (PR10: commitEntry now also probes account_dimension_rules first; the
// bare mock makes that probe fail open, which is exactly the posture.)
expect(supabase.from).not.toHaveBeenCalledWith('journal_entries')
expect(supabase.from).not.toHaveBeenCalledWith('journal_entry_lines')
})
it('commitEntry succeeds via atomic RPC and returns posted entry', async () => {
+41
View File
@@ -97,3 +97,44 @@ export class DimensionValidationError extends Error {
export function isDimensionValidationError(err: unknown): err is DimensionValidationError {
return err instanceof DimensionValidationError
}
// ============================================================================
// Mandatory dimension enforcement (dimensions PR10)
// ============================================================================
export const MANDATORY_DIMENSION_MISSING = 'MANDATORY_DIMENSION_MISSING' as const
export interface MandatoryDimensionViolation {
account_number: string
/** SIE dimension number the rule requires, e.g. '6'. */
sie_dim_no: string
/** Registry display name for the dimension, e.g. 'Projekt'. */
dimension_name: string
}
/** Swedish user-facing sentence for a single missing-dimension violation. */
export function formatMandatoryDimensionViolation(v: MandatoryDimensionViolation): string {
return `Konto ${v.account_number} kräver ${v.dimension_name} — välj ett värde innan bokföring.`
}
/**
* Raised at COMMIT time (commitEntry / the bulk-book pre-check) when an
* active 'required' rule in account_dimension_rules is unsatisfied by a
* line's dimensions bag. Drafts may be incomplete by design — the rule bites
* when the verifikat is about to become immutable. Companies without rules
* (every company by default) never reach this error.
*/
export class MandatoryDimensionMissingError extends Error {
readonly code = MANDATORY_DIMENSION_MISSING
constructor(public readonly violations: MandatoryDimensionViolation[]) {
super(violations.map(formatMandatoryDimensionViolation).join(' '))
this.name = 'MandatoryDimensionMissingError'
}
}
export function isMandatoryDimensionMissingError(
err: unknown,
): err is MandatoryDimensionMissingError {
return err instanceof MandatoryDimensionMissingError
}
+176
View File
@@ -0,0 +1,176 @@
/**
* 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()])
}
}
+58 -4
View File
@@ -18,6 +18,11 @@ import {
normalizeLineDimensions,
validateEntryDimensions,
} from '@/lib/bookkeeping/dimension-resolver'
import {
applyDimensionRules,
assertMandatoryDimensions,
fetchActiveDimensionRules,
} from '@/lib/bookkeeping/dimension-rules'
import { backfillStandardBASAccounts } from '@/lib/bookkeeping/account-backfill'
import { syncInvoiceStatusFromPaymentEntry, isPaymentSourceType } from '@/lib/bookkeeping/payment-sync'
import { getActor } from '@/lib/bookkeeping/actor-context'
@@ -227,12 +232,22 @@ export async function createDraftEntry(
throw new JournalEntryNotBalancedError(balance.totalDebit, balance.totalCredit, 'draft')
}
// Account dimension rules (dimensions PR10): apply 'default'/'fixed'
// values onto the line bags before validation + insert. Zero rules —
// every company by default — returns the input untouched; a failed rule
// fetch fails open like the soft validation below.
const rules = await fetchActiveDimensionRules(supabase, companyId)
if (rules === null) {
log.warn('dimension rule fetch failed — defaults/fixed skipped (fail-open)', { companyId })
}
const lines = rules ? applyDimensionRules(input.lines, rules) : input.lines
// Soft dimension validation (dimensions plan PR3): free for untagged
// entries; free-text passthrough unless company_settings.dimensions_enabled;
// enabled companies get registry validation with a typed Swedish rejection.
// Runs before any insert so a rejection leaves no orphan rows. Reversal/
// storno/correction paths bypass this — they copy posted data verbatim.
await validateEntryDimensions(supabase, companyId, input.lines)
await validateEntryDimensions(supabase, companyId, lines)
// Validate that entry_date falls within the selected fiscal period
const { data: period, error: periodError } = await supabase
@@ -319,7 +334,7 @@ export async function createDraftEntry(
}
// Insert journal entry lines with dimensions
const lineInserts = buildLineInserts(entry.id, input.lines, accountIdMap)
const lineInserts = buildLineInserts(entry.id, lines, accountIdMap)
const { error: linesError } = await supabase
.from('journal_entry_lines')
@@ -409,7 +424,13 @@ export async function updateDraftEntry(
// Same soft dimension validation as createDraftEntry — before any write, so
// a rejection leaves both the header and the existing lines untouched.
await validateEntryDimensions(supabase, companyId, input.lines)
// Account dimension rules (PR10) apply first — same as create.
const rules = await fetchActiveDimensionRules(supabase, companyId)
if (rules === null) {
log.warn('dimension rule fetch failed — defaults/fixed skipped (fail-open)', { companyId })
}
const lines = rules ? applyDimensionRules(input.lines, rules) : input.lines
await validateEntryDimensions(supabase, companyId, lines)
// Entry date must fall within the selected fiscal period.
const { data: period, error: periodError } = await supabase
@@ -479,7 +500,7 @@ export async function updateDraftEntry(
throw new BookkeepingDatabaseError('create_entry_lines', deleteError.message)
}
const lineInserts = buildLineInserts(entryId, input.lines, accountIdMap)
const lineInserts = buildLineInserts(entryId, lines, accountIdMap)
const { error: linesError } = await supabase
.from('journal_entry_lines')
.insert(lineInserts)
@@ -528,6 +549,39 @@ export async function commitEntry(
): Promise<JournalEntry> {
const actor = getActor()
// Mandatory dimension rules (dimensions PR10): 'required' rules bite when
// the verifikat is about to become immutable — drafts may be incomplete,
// posting may not. Zero active rules (the default) skips the line fetch
// entirely; a failed rule fetch fails open (transient DB errors must not
// block bookkeeping). Reversal/correction paths never pass through
// commitEntry, so history always reverses regardless of policy.
const rules = await fetchActiveDimensionRules(supabase, companyId)
if (rules === null) {
// Deliberate fail-open, but LOUD: a transient policy-table error must not
// block month-end bookings company-wide, yet a silently skipped control
// is invisible — the warning makes the degradation observable.
log.warn('dimension rule fetch failed — mandatory enforcement skipped (fail-open)', {
companyId,
entityId: entryId,
})
} else if (rules.some((r) => r.rule_type === 'required')) {
const { data: ruleLines, error: ruleLinesError } = await supabase
.from('journal_entry_lines')
.select('account_number, dimensions')
.eq('journal_entry_id', entryId)
if (ruleLinesError || !ruleLines) {
log.warn('line fetch for mandatory dimension check failed — enforcement skipped (fail-open)', {
companyId,
entityId: entryId,
})
} else {
assertMandatoryDimensions(
ruleLines as Array<{ account_number: string; dimensions: Record<string, string> }>,
rules
)
}
}
// Atomic: increment voucher sequence + update status in one transaction.
// Rolls back the sequence if the balance trigger or any constraint fails.
const { data: rpcResult, error: commitError } = await supabase.rpc('commit_journal_entry', {
+24 -2
View File
@@ -1,5 +1,5 @@
import { NextResponse } from 'next/server'
import { DimensionValidationError } from './dimension-errors'
import { DimensionValidationError, MandatoryDimensionMissingError } from './dimension-errors'
// ============================================================================
// Dimension validation error — class lives in ./dimension-errors.ts (pure
@@ -14,10 +14,15 @@ export {
formatDimensionValidationIssue,
formatDimensionValidationIssues,
isDimensionValidationError,
MANDATORY_DIMENSION_MISSING,
MandatoryDimensionMissingError,
formatMandatoryDimensionViolation,
isMandatoryDimensionMissingError,
} from './dimension-errors'
export type {
DimensionValidationIssue,
DimensionValidationReason,
MandatoryDimensionViolation,
} from './dimension-errors'
// ============================================================================
@@ -331,7 +336,8 @@ export function isBookkeepingError(err: unknown): boolean {
err instanceof NoOpenPeriodForDateError ||
err instanceof TargetPeriodClosedError ||
err instanceof TargetPeriodLockedError ||
err instanceof DimensionValidationError
err instanceof DimensionValidationError ||
err instanceof MandatoryDimensionMissingError
)
}
@@ -574,6 +580,22 @@ export function bookkeepingErrorResponse(err: unknown): NextResponse | null {
)
}
if (err instanceof MandatoryDimensionMissingError) {
// Policy rejection at commit (dimensions PR10): the message names every
// account + required dimension so a user or agent self-corrects in one
// pass; details.violations is the machine-readable list.
return NextResponse.json(
{
error: {
code: err.code,
message: err.message,
details: { violations: err.violations },
},
},
{ status: 400 }
)
}
if (err instanceof BookkeepingDatabaseError) {
return NextResponse.json(
{