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:
co-authored by
Claude Fable 5
parent
70e893b8d4
commit
764348e99c
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user