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
@@ -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', {
|
||||
|
||||
Reference in New Issue
Block a user