764348e99c
* 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>
179 lines
6.3 KiB
TypeScript
179 lines
6.3 KiB
TypeScript
import { describe, it, expect } from 'vitest'
|
|
import { randomUUID } from 'node:crypto'
|
|
import { getPool, withUserContext } from './setup'
|
|
import { seedCompany } from './fixtures'
|
|
|
|
// PR10 account_dimension_rules (20260703200000_account_dimension_rules.sql):
|
|
// RLS via user_company_ids() on all four operations, the adr_value_presence
|
|
// CHECK (required ⇔ no value), UNIQUE (company_id, account_number,
|
|
// dimension_id), value_id ON DELETE CASCADE, and the composite
|
|
// (dimension_id, company_id) FK that pins a rule's dimension to the same
|
|
// company.
|
|
|
|
async function seedWithDimensions() {
|
|
const seeded = await seedCompany()
|
|
await getPool().query(`SELECT public.ensure_company_dimensions($1)`, [seeded.companyId])
|
|
return seeded
|
|
}
|
|
|
|
async function getDimensionId(companyId: string, sieDimNo: number): Promise<string> {
|
|
const { rows } = await getPool().query(
|
|
`SELECT id FROM public.dimensions WHERE company_id = $1 AND sie_dim_no = $2`,
|
|
[companyId, sieDimNo],
|
|
)
|
|
return rows[0].id
|
|
}
|
|
|
|
async function insertValue(params: {
|
|
companyId: string
|
|
dimensionId: string
|
|
code: string
|
|
name?: string
|
|
}): Promise<string> {
|
|
const id = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.dimension_values (id, company_id, dimension_id, code, name)
|
|
VALUES ($1, $2, $3, $4, $5)`,
|
|
[id, params.companyId, params.dimensionId, params.code, params.name ?? params.code],
|
|
)
|
|
return id
|
|
}
|
|
|
|
async function insertRule(params: {
|
|
companyId: string
|
|
dimensionId: string
|
|
ruleType: 'required' | 'default' | 'fixed'
|
|
accountNumber?: string
|
|
valueId?: string | null
|
|
}): Promise<string> {
|
|
const id = randomUUID()
|
|
await getPool().query(
|
|
`INSERT INTO public.account_dimension_rules
|
|
(id, company_id, account_number, dimension_id, rule_type, value_id)
|
|
VALUES ($1, $2, $3, $4, $5, $6)`,
|
|
[
|
|
id,
|
|
params.companyId,
|
|
params.accountNumber ?? '4010',
|
|
params.dimensionId,
|
|
params.ruleType,
|
|
params.valueId ?? null,
|
|
],
|
|
)
|
|
return id
|
|
}
|
|
|
|
describe('account_dimension_rules RLS', () => {
|
|
it('lets a member insert and read an own-company rule', async () => {
|
|
const { userId, companyId } = await seedWithDimensions()
|
|
const dimId = await getDimensionId(companyId, 6)
|
|
|
|
await withUserContext(userId, async (client) => {
|
|
await client.query(
|
|
`INSERT INTO public.account_dimension_rules
|
|
(company_id, account_number, dimension_id, rule_type)
|
|
VALUES ($1, '4010', $2, 'required')`,
|
|
[companyId, dimId],
|
|
)
|
|
const { rows } = await client.query(
|
|
`SELECT account_number, rule_type, value_id, is_active
|
|
FROM public.account_dimension_rules WHERE company_id = $1`,
|
|
[companyId],
|
|
)
|
|
expect(rows).toEqual([
|
|
{ account_number: '4010', rule_type: 'required', value_id: null, is_active: true },
|
|
])
|
|
})
|
|
})
|
|
|
|
it('hides other companies rules and blocks cross-company inserts', async () => {
|
|
const a = await seedWithDimensions()
|
|
const b = await seedWithDimensions()
|
|
const aDimId = await getDimensionId(a.companyId, 6)
|
|
await insertRule({ companyId: a.companyId, dimensionId: aDimId, ruleType: 'required' })
|
|
|
|
await withUserContext(b.userId, async (client) => {
|
|
// The outsider sees none of A's rules (and has none of their own).
|
|
const { rows } = await client.query(
|
|
`SELECT id FROM public.account_dimension_rules`,
|
|
)
|
|
expect(rows).toEqual([])
|
|
|
|
await expect(
|
|
client.query(
|
|
`INSERT INTO public.account_dimension_rules
|
|
(company_id, account_number, dimension_id, rule_type)
|
|
VALUES ($1, '5010', $2, 'required')`,
|
|
[a.companyId, aDimId],
|
|
),
|
|
).rejects.toThrow(/row-level security/)
|
|
})
|
|
})
|
|
})
|
|
|
|
describe('adr_value_presence CHECK', () => {
|
|
it('rejects a required rule that carries a value', async () => {
|
|
const { companyId } = await seedWithDimensions()
|
|
const dimId = await getDimensionId(companyId, 6)
|
|
const valueId = await insertValue({ companyId, dimensionId: dimId, code: 'P001' })
|
|
|
|
await expect(
|
|
insertRule({ companyId, dimensionId: dimId, ruleType: 'required', valueId }),
|
|
).rejects.toThrow(/adr_value_presence/)
|
|
})
|
|
|
|
it('rejects a default rule without a value', async () => {
|
|
const { companyId } = await seedWithDimensions()
|
|
const dimId = await getDimensionId(companyId, 6)
|
|
|
|
await expect(
|
|
insertRule({ companyId, dimensionId: dimId, ruleType: 'default', valueId: null }),
|
|
).rejects.toThrow(/adr_value_presence/)
|
|
})
|
|
})
|
|
|
|
describe('UNIQUE (company_id, account_number, dimension_id)', () => {
|
|
it('rejects a second rule for the same account and dimension', async () => {
|
|
const { companyId } = await seedWithDimensions()
|
|
const dimId = await getDimensionId(companyId, 6)
|
|
const valueId = await insertValue({ companyId, dimensionId: dimId, code: 'P001' })
|
|
await insertRule({ companyId, dimensionId: dimId, ruleType: 'default', valueId })
|
|
|
|
// Different rule_type, same (company, account, dimension) — still one slot.
|
|
await expect(
|
|
insertRule({ companyId, dimensionId: dimId, ruleType: 'required' }),
|
|
).rejects.toThrow(/duplicate|unique/)
|
|
})
|
|
})
|
|
|
|
describe('cascade behavior', () => {
|
|
it('deleting the dimension_value removes rules pinned to it (ON DELETE CASCADE)', async () => {
|
|
const { companyId } = await seedWithDimensions()
|
|
const dimId = await getDimensionId(companyId, 6)
|
|
const valueId = await insertValue({ companyId, dimensionId: dimId, code: 'P001' })
|
|
const ruleId = await insertRule({ companyId, dimensionId: dimId, ruleType: 'fixed', valueId })
|
|
|
|
// The value is unreferenced by posted lines, so the retention trigger
|
|
// allows the delete — and the rule must ride the cascade.
|
|
await getPool().query(`DELETE FROM public.dimension_values WHERE id = $1`, [valueId])
|
|
|
|
const { rows } = await getPool().query(
|
|
`SELECT id FROM public.account_dimension_rules WHERE id = $1`,
|
|
[ruleId],
|
|
)
|
|
expect(rows).toEqual([])
|
|
})
|
|
})
|
|
|
|
describe('composite (dimension_id, company_id) FK', () => {
|
|
it('rejects a rule whose dimension belongs to another company', async () => {
|
|
const a = await seedWithDimensions()
|
|
const b = await seedWithDimensions()
|
|
const aDimId = await getDimensionId(a.companyId, 6)
|
|
|
|
await expect(
|
|
insertRule({ companyId: b.companyId, dimensionId: aDimId, ruleType: 'required' }),
|
|
).rejects.toThrow(/foreign key/)
|
|
})
|
|
})
|