feat(dimensions): PR9 cutover — cost_center/project become GENERATED columns, dual-write removed (#870)

The dual-write window ends (dev_docs/dimensions_implementation_plan.md PR9):
journal_entry_lines.cost_center/project are now GENERATED ALWAYS AS
(NULLIF(dimensions->>'1'/'6','')) STORED — divergence from the bag is
impossible by construction instead of by convention.

- migration 20260702230000: drift pre-flight (refuses cutover on
  inconsistent data; prod verified 0 drift across 593k rows), column swap
  (DROP metadata-only + one-rewrite ADD pair), and atomic redefinition of
  the two SQL writers — retag_line_dimensions (SET dimensions only) and
  bulk_book_transactions (INSERT names the bag only)
- TS writers stripped of the mirror spread: engine buildLineInserts
  (covers create/update/reversal), storno-service (reversal + correction),
  SIE import bulk insert, sandbox seed
- lineDimensionColumns() removed from dimension-resolver — nothing derives
  mirrors in TypeScript anymore; normalizeLineDimensions + the deprecated
  cost_center/project INPUT aliases stay (API contract, they normalize
  into the bag); JournalEntryLine ROW type keeps the fields (generated
  columns still SELECT)
- immutability carve-out unchanged BY DESIGN: its whole-row diff already
  subtracts dimensions/cost_center/project on both sides, which is exactly
  what makes it correct with generated columns (BEFORE-trigger NEW carries
  not-yet-recomputed mirror values)
- audited every reader (v1 journal-entries, MCP query_journal filters +
  group_by, rc-basis-gaps) — reads are untouched; no index, view, or
  constraint referenced the TEXT columns, so DROP COLUMN cascades nothing
- new pg suite: generated derivation, explicit-mirror-write rejection,
  draft-update recompute; existing retag/substrate/bulk-book suites
  updated to bag-only writes (their mirror assertions now exercise the
  generation expression)

Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
Jakob Wennberg
2026-07-02 23:28:42 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 163fbd8222
commit fb3f0a9cee
12 changed files with 713 additions and 78 deletions
+2 -4
View File
@@ -7,7 +7,6 @@ import { createLogger } from '@/lib/logger'
import { checkRateLimit } from '@/lib/auth/rate-limit-http'
import { truncateIp } from '@/lib/api/v1/with-api-v1'
import { ensureSandboxAgentProfile } from '@/lib/sandbox/ensure-agent'
import { lineDimensionColumns } from '@/lib/bookkeeping/dimension-resolver'
// Anonymous sign-in is enabled in all environments so visitors can try the
// product; a per-/24 cap on the seed endpoint keeps a single network from
@@ -463,8 +462,8 @@ export async function POST(request: Request) {
// 10. Create journal entry lines. The P&L line carries demo dimensions
// ({"1":"BUTIK","6":"P001"}) so the register's "antal taggade rader",
// voucher-detail badges, and the dimension P&L report light up in the
// sandbox. Mirror columns derived via lineDimensionColumns — never set
// independently of the dimensions map.
// sandbox. cost_center/project are GENERATED from the bag since the PR9
// cutover — writing them explicitly would error.
const revenueDims = { '1': 'BUTIK', '6': 'P001' }
const { error: jelError } = await supabase
.from('journal_entry_lines')
@@ -491,7 +490,6 @@ export async function POST(request: Request) {
credit_amount: 15000,
sort_order: 1,
dimensions: revenueDims,
...lineDimensionColumns(revenueDims),
},
{
journal_entry_id: je1.id,
@@ -1,11 +1,8 @@
import { describe, it, expect } from 'vitest'
import {
normalizeLineDimensions,
lineDimensionColumns,
coerceDimensionsBag,
validateEntryDimensions,
DIM_COST_CENTER,
DIM_PROJECT,
} from '@/lib/bookkeeping/dimension-resolver'
// Imported from errors.ts on purpose: proves the re-export surface every
// server consumer uses (the class itself lives in dimension-errors.ts).
@@ -63,10 +60,11 @@ describe('normalizeLineDimensions', () => {
).toEqual({ '6': 'P001' })
})
it("canonicalizes leading-zero keys ('01' -> '1') so mirrors are derived", () => {
it("canonicalizes leading-zero keys ('01' -> '1') so the generated mirrors derive", () => {
// The DB generates cost_center/project from keys '1'/'6' (PR9 cutover) —
// '01' must land on '1' or the generated mirror misses the value.
const dims = normalizeLineDimensions({ dimensions: { '01': 'KS01', '06': 'P001' } })
expect(dims).toEqual({ '1': 'KS01', '6': 'P001' })
expect(lineDimensionColumns(dims)).toEqual({ cost_center: 'KS01', project: 'P001' })
})
it("clearing via a leading-zero key ('01': '') also clears the alias-filled '1'", () => {
@@ -120,24 +118,9 @@ describe('coerceDimensionsBag (boundary validator for staged payloads)', () => {
})
})
describe('lineDimensionColumns', () => {
it('derives both mirrors from the map', () => {
expect(lineDimensionColumns({ [DIM_COST_CENTER]: 'KS01', [DIM_PROJECT]: 'P001' })).toEqual({
cost_center: 'KS01',
project: 'P001',
})
})
it('returns nulls for missing keys', () => {
expect(lineDimensionColumns({})).toEqual({ cost_center: null, project: null })
expect(lineDimensionColumns({ '7': 'ANST-4' })).toEqual({ cost_center: null, project: null })
})
it('round-trips with normalizeLineDimensions (mirror consistency)', () => {
const dims = normalizeLineDimensions({ cost_center: 'KS01', dimensions: { '6': 'P001' } })
expect(lineDimensionColumns(dims)).toEqual({ cost_center: 'KS01', project: 'P001' })
})
})
// lineDimensionColumns() tests were removed with the function in the PR9
// cutover — mirror derivation now lives in the database as GENERATED columns
// and is covered by tests/pg/dimensions-generated-cutover.pg.test.ts.
describe('validateEntryDimensions (soft registry validation, PR3)', () => {
const enabledSettings = { data: { dimensions_enabled: true } }
@@ -145,10 +145,11 @@ describe('createDraftEntry — dimension validation wiring', () => {
// Toggle checked once, registry never consulted (free-text passthrough).
expect(queriedTables().filter((t) => t === 'company_settings')).toHaveLength(1)
expect(queriedTables()).not.toContain('dimensions')
// The free-text tag still lands on the inserted lines (bag + mirror).
// The free-text tag still lands on the inserted lines (bag only — the
// project mirror is GENERATED at the database since the PR9 cutover).
const lineRows = inserts.journal_entry_lines[0] as Array<Record<string, unknown>>
expect(lineRows[0].dimensions).toEqual({ '6': 'FRITEXT-PROJEKT' })
expect(lineRows[0].project).toBe('FRITEXT-PROJEKT')
expect('project' in lineRows[0]).toBe(false)
})
it('rejects an unknown code before ANY row is inserted (toggle on)', async () => {
@@ -194,8 +195,10 @@ describe('createDraftEntry — dimension validation wiring', () => {
expect(entry.id).toBe('entry-1')
const lineRows = inserts.journal_entry_lines[0] as Array<Record<string, unknown>>
expect(lineRows[0].dimensions).toEqual({ '1': 'KS01', '6': 'P001' })
expect(lineRows[0].cost_center).toBe('KS01')
expect(lineRows[0].project).toBe('P001')
// PR9 cutover: the payload must NOT name the generated mirror columns —
// an explicit value would make Postgres reject the insert.
expect('cost_center' in lineRows[0]).toBe(false)
expect('project' in lineRows[0]).toBe(false)
})
})
+8 -20
View File
@@ -1,13 +1,12 @@
/**
* Dimension resolver — the single place line dimensions are normalized and
* mirrored (dev_docs/dimensions_implementation_plan.md).
* Dimension resolver — the single place line dimensions are normalized
* (dev_docs/dimensions_implementation_plan.md).
*
* Storage model: journal_entry_lines.dimensions is a JSONB map keyed by SIE
* dimension number ({"1":"KS01","6":"P001"}) and is the single source of
* truth. The legacy cost_center/project TEXT columns are deterministic mirrors
* of keys '1'/'6' during the dual-write window (they become GENERATED columns
* in a later migration). Every journal_entry_lines writer MUST derive the
* mirror columns via lineDimensionColumns() — never set them independently.
* truth. Since the PR9 cutover (20260702230000) the cost_center/project
* columns are GENERATED ALWAYS from keys '1'/'6' — writers set only the
* bag; writing the mirror columns explicitly errors at the database.
*/
import { z } from 'zod'
@@ -134,20 +133,9 @@ export function dimensionsBagKey(dimensions?: LineDimensions): string {
)
}
/**
* Derive the legacy mirror columns from the canonical map. Pure function —
* divergence between `dimensions` and cost_center/project is impossible as
* long as every writer goes through this.
*/
export function lineDimensionColumns(dimensions: LineDimensions): {
cost_center: string | null
project: string | null
} {
return {
cost_center: dimensions[DIM_COST_CENTER] ?? null,
project: dimensions[DIM_PROJECT] ?? null,
}
}
// lineDimensionColumns() was removed in the PR9 cutover: the mirror columns
// are GENERATED ALWAYS from the bag at the database, so there is nothing for
// TypeScript writers to derive — they set only `dimensions`.
/**
* Soft registry validation of the dimensions referenced by a set of entry
+4 -5
View File
@@ -16,7 +16,6 @@ import {
import { resolveDefaultSeriesForSource } from '@/lib/bookkeeping/voucher-series-resolver'
import {
normalizeLineDimensions,
lineDimensionColumns,
validateEntryDimensions,
} from '@/lib/bookkeeping/dimension-resolver'
import { backfillStandardBASAccounts } from '@/lib/bookkeeping/account-backfill'
@@ -183,7 +182,7 @@ export async function findFiscalPeriod(
/**
* Build line insert objects from input lines, resolving account IDs and
* including tax_code, cost_center, project dimensions
* including tax_code and the dimensions bag
*/
function buildLineInserts(
entryId: string,
@@ -191,8 +190,9 @@ function buildLineInserts(
accountIdMap: Map<string, string>
) {
return lines.map((line, index) => {
// dimensions JSONB is the source of truth; cost_center/project are
// derived mirrors (dual-write window — see lib/bookkeeping/dimension-resolver.ts)
// dimensions JSONB is the single source of truth; cost_center/project
// are GENERATED columns derived from keys '1'/'6' since the PR9 cutover
// (20260702230000) — writing them explicitly would error.
const dimensions = normalizeLineDimensions(line)
return {
journal_entry_id: entryId,
@@ -206,7 +206,6 @@ function buildLineInserts(
line_description: line.line_description || null,
tax_code: line.tax_code || null,
dimensions,
...lineDimensionColumns(dimensions),
sort_order: index,
}
})
+1 -3
View File
@@ -6,7 +6,7 @@ import type {
JournalEntryLine,
} from '@/types'
import { validateBalance, getNextVoucherNumber } from '@/lib/bookkeeping/engine'
import { normalizeLineDimensions, lineDimensionColumns } from '@/lib/bookkeeping/dimension-resolver'
import { normalizeLineDimensions } from '@/lib/bookkeeping/dimension-resolver'
import { backfillStandardBASAccounts } from '@/lib/bookkeeping/account-backfill'
import { resolvePeriodStatusForDate } from '@/lib/core/bookkeeping/period-service'
import {
@@ -287,7 +287,6 @@ export async function correctEntry(
line_description: `Storno: ${line.line_description || ''}`,
tax_code: line.tax_code || null,
dimensions,
...lineDimensionColumns(dimensions),
sort_order: index,
}
})
@@ -372,7 +371,6 @@ export async function correctEntry(
line_description: line.line_description || null,
tax_code: line.tax_code || null,
dimensions,
...lineDimensionColumns(dimensions),
sort_order: index,
}
})
+1 -4
View File
@@ -7,7 +7,7 @@
*/
import type { SupabaseClient } from '@supabase/supabase-js'
import { normalizeLineDimensions, lineDimensionColumns } from '@/lib/bookkeeping/dimension-resolver'
import { normalizeLineDimensions } from '@/lib/bookkeeping/dimension-resolver'
import { importDimensionRegistry } from './sie-dimensions'
import { createJournalEntry, reverseEntry } from '@/lib/bookkeeping/engine'
import type {
@@ -1345,8 +1345,6 @@ export async function importVouchers(
line_description: string | null
sort_order: number
dimensions: Record<string, string>
cost_center: string | null
project: string | null
}[] = []
for (let i = 0; i < batch.length; i++) {
@@ -1372,7 +1370,6 @@ export async function importVouchers(
line_description: line.line_description,
sort_order: lineIndex,
dimensions: dims,
...lineDimensionColumns(dims),
})
})
File diff suppressed because it is too large Load Diff
+3 -3
View File
@@ -12,9 +12,9 @@ import { getPool, withUserContext } from '@/tests/pg/setup'
* Covers 20260702201000_bulk_book_transactions_dimensions (dimensions PR7):
*
* - p_new_entry lines may carry a dimensions bag {sie_dim_no: code}. The
* RPC stores it on journal_entry_lines.dimensions AND derives the
* dual-write mirror columns cost_center/project from keys '1'/'6'
* (lineDimensionColumns contract — mirrors never set independently).
* RPC stores it on journal_entry_lines.dimensions; cost_center/project
* derive from keys '1'/'6' (GENERATED columns since the PR9 cutover —
* the mirror assertions below now exercise the generation expression).
* - Bag normalization mirrors DimensionsBagSchema: non-canonical keys
* (leading zeros, non-numeric) and blank values are dropped; values are
* trimmed.
+6 -5
View File
@@ -41,10 +41,10 @@ async function insertPostedTaggedEntry(params: {
const dims = params.dimensions ?? {}
const { rows } = await getPool().query<{ id: string }>(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, dimensions, cost_center, project)
VALUES ($1, '5010', 1000, 0, $2::jsonb, $3, $4)
(journal_entry_id, account_number, debit_amount, credit_amount, dimensions)
VALUES ($1, '5010', 1000, 0, $2::jsonb)
RETURNING id`,
[entryId, JSON.stringify(dims), dims['1'] ?? null, dims['6'] ?? null],
[entryId, JSON.stringify(dims)],
)
await getPool().query(
`INSERT INTO public.journal_entry_lines
@@ -207,12 +207,13 @@ describe('dimension retag carve-out (PR6)', () => {
).rejects.toThrow(/Cannot UPDATE lines of a posted journal entry/)
await client.query('ROLLBACK')
// A pure dimension diff IS admitted under the GUC (the RPC's write shape).
// A pure dimension diff IS admitted under the GUC (the RPC's write
// shape). PR9: the bag alone — the generated mirrors recompute.
await client.query('BEGIN')
await client.query(`SELECT set_config('gnubok.allow_dimension_retag', 'true', true)`)
await client.query(
`UPDATE public.journal_entry_lines
SET dimensions = '{"6":"P001"}'::jsonb, project = 'P001'
SET dimensions = '{"6":"P001"}'::jsonb
WHERE id = $1`,
[lineId],
)
@@ -0,0 +1,99 @@
import { describe, expect, it } from 'vitest'
import {
insertAuthUser,
insertCompany,
insertCompanyMember,
insertFiscalPeriod,
insertDraftJournalEntry,
} from '@/tests/pg/fixtures'
import { getPool } from '@/tests/pg/setup'
/**
* Covers 20260702230000_dimensions_generated_column_cutover (dimensions PR9):
*
* - cost_center/project are GENERATED ALWAYS AS (NULLIF(dimensions->>'1'/'6',''))
* STORED — inserting only the bag produces the same mirror values the
* dual-write produced.
* - An INSERT that names either mirror column errors (the reason every
* writer was stripped in this PR).
* - The retag RPC (redefined here to SET only the bag) still updates a
* posted line under its carve-out, and the mirrors recompute.
*/
async function seedTenant() {
const userId = await insertAuthUser()
const companyId = await insertCompany({ createdBy: userId })
await insertCompanyMember({ companyId, userId, role: 'owner' })
const fiscalPeriodId = await insertFiscalPeriod({
userId,
companyId,
periodStart: '2026-01-01',
periodEnd: '2026-12-31',
})
return { userId, companyId, fiscalPeriodId }
}
describe('journal_entry_lines generated mirrors (PR9 cutover)', () => {
it('derives cost_center/project from the bag on insert; empty bag yields NULLs', async () => {
const { userId, companyId, fiscalPeriodId } = await seedTenant()
const entryId = await insertDraftJournalEntry({ userId, companyId, fiscalPeriodId })
const { rows } = await getPool().query<{
dimensions: Record<string, string>
cost_center: string | null
project: string | null
}>(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, dimensions)
VALUES ($1, '4010', 1000, 0, '{"1":"KS01","6":"P001"}'::jsonb),
($1, '1930', 0, 1000, '{}'::jsonb)
RETURNING dimensions, cost_center, project`,
[entryId],
)
const tagged = rows.find((r) => r.dimensions['1'])!
expect(tagged.cost_center).toBe('KS01')
expect(tagged.project).toBe('P001')
const untagged = rows.find((r) => !r.dimensions['1'])!
expect(untagged.cost_center).toBeNull()
expect(untagged.project).toBeNull()
})
it('rejects an INSERT that names a mirror column explicitly', async () => {
const { userId, companyId, fiscalPeriodId } = await seedTenant()
const entryId = await insertDraftJournalEntry({ userId, companyId, fiscalPeriodId })
await expect(
getPool().query(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, dimensions, cost_center)
VALUES ($1, '4010', 1000, 0, '{"1":"KS01"}'::jsonb, 'KS01')`,
[entryId],
),
).rejects.toThrow(/non-DEFAULT value into column/i)
})
it('mirrors recompute when a draft bag is updated (bag-only write)', async () => {
const { userId, companyId, fiscalPeriodId } = await seedTenant()
const entryId = await insertDraftJournalEntry({ userId, companyId, fiscalPeriodId })
const { rows } = await getPool().query<{ id: string }>(
`INSERT INTO public.journal_entry_lines
(journal_entry_id, account_number, debit_amount, credit_amount, dimensions)
VALUES ($1, '4010', 500, 0, '{"6":"P001"}'::jsonb)
RETURNING id`,
[entryId],
)
await getPool().query(
`UPDATE public.journal_entry_lines SET dimensions = '{"1":"KS02"}'::jsonb WHERE id = $1`,
[rows[0].id],
)
const after = await getPool().query<{ cost_center: string | null; project: string | null }>(
`SELECT cost_center, project FROM public.journal_entry_lines WHERE id = $1`,
[rows[0].id],
)
expect(after.rows[0].cost_center).toBe('KS02')
expect(after.rows[0].project).toBeNull()
})
})
+5 -7
View File
@@ -47,16 +47,14 @@ async function insertDimensionedLines(
const lineId = randomUUID()
await getPool().query(
`INSERT INTO public.journal_entry_lines
(id, journal_entry_id, account_number, debit_amount, credit_amount, dimensions, cost_center, project)
VALUES ($1, $2, '4010', $3, 0, $4, $5, $6),
(gen_random_uuid(), $2, '1930', 0, $3, '{}', NULL, NULL)`,
(id, journal_entry_id, account_number, debit_amount, credit_amount, dimensions)
VALUES ($1, $2, '4010', $3, 0, $4),
(gen_random_uuid(), $2, '1930', 0, $3, '{}')`,
[
lineId,
journalEntryId,
amount,
JSON.stringify(dimensions),
dimensions['1'] ?? null,
dimensions['6'] ?? null,
],
)
return lineId
@@ -267,9 +265,9 @@ describe('journal_entry_lines.dimensions', () => {
const entryId = await insertDraftJournalEntry({ userId, companyId, fiscalPeriodId })
const lineId = await insertDimensionedLines(entryId, { '6': 'P001' })
// Draft: retagging is allowed
// Draft: retagging is allowed (PR9: the bag alone — mirrors generate)
await getPool().query(
`UPDATE public.journal_entry_lines SET dimensions = '{"6":"P002"}', project = 'P002' WHERE id = $1`,
`UPDATE public.journal_entry_lines SET dimensions = '{"6":"P002"}' WHERE id = $1`,
[lineId],
)