diff --git a/api/routes/stacks.js b/api/routes/stacks.js index 57009a9..83bce5c 100644 --- a/api/routes/stacks.js +++ b/api/routes/stacks.js @@ -67,10 +67,10 @@ module.exports = (pool) => { // Add or update a source in a stack router.put('/:name/sources/:source', async (req, res, next) => { try { - const { field_map, amount_sign, balance_offset, amount_field, date_field } = req.body; + const { field_map, amount_sign, balance_offset, amount_field, date_field, date_from, date_to } = req.body; const n = v => v != null ? lit(v) : 'NULL'; const result = await pool.query( - `SELECT * FROM upsert_stack_source(${lit(req.params.name)}, ${lit(req.params.source)}, ${lit(JSON.stringify(field_map || {}))}, ${lit(amount_sign ?? 1)}, ${lit(balance_offset ?? 0)}, ${n(amount_field)}, ${n(date_field)})` + `SELECT * FROM upsert_stack_source(${lit(req.params.name)}, ${lit(req.params.source)}, ${lit(JSON.stringify(field_map || {}))}, ${lit(amount_sign ?? 1)}, ${lit(balance_offset ?? 0)}, ${n(amount_field)}, ${n(date_field)}, ${n(date_from || null)}, ${n(date_to || null)})` ); res.json(result.rows[0]); } catch (err) { diff --git a/database/stacks.sql b/database/stacks.sql index 47a8e7c..513f8ce 100644 --- a/database/stacks.sql +++ b/database/stacks.sql @@ -35,6 +35,9 @@ CREATE TABLE IF NOT EXISTS dataflow.stack_sources ( date_field TEXT, -- Calibration offset added to this source's running balance balance_offset NUMERIC NOT NULL DEFAULT 0, + -- Optional window on date_field: rows outside it are left out of the stack + date_from DATE, + date_to DATE, UNIQUE (stack_name, source_name) ); @@ -43,6 +46,8 @@ ALTER TABLE dataflow.stack_sources ADD COLUMN IF NOT EXISTS balance_offset NUMER ALTER TABLE dataflow.stack_sources ADD COLUMN IF NOT EXISTS amount_field TEXT; ALTER TABLE dataflow.stack_sources ADD COLUMN IF NOT EXISTS date_field TEXT; ALTER TABLE dataflow.stack_sources ADD COLUMN IF NOT EXISTS seq INTEGER NOT NULL DEFAULT 0; +ALTER TABLE dataflow.stack_sources ADD COLUMN IF NOT EXISTS date_from DATE; +ALTER TABLE dataflow.stack_sources ADD COLUMN IF NOT EXISTS date_to DATE; -- Seed seq from insertion order for existing rows UPDATE dataflow.stack_sources ss @@ -56,6 +61,7 @@ WHERE ss.id = sub.id AND ss.seq = 0; -- Drop old signatures before recreating DROP FUNCTION IF EXISTS calibrate_balance(TEXT, DATE, NUMERIC); DROP FUNCTION IF EXISTS upsert_stack_source(TEXT, TEXT, JSONB, INTEGER, NUMERIC); +DROP FUNCTION IF EXISTS upsert_stack_source(TEXT, TEXT, JSONB, INTEGER, NUMERIC, TEXT, TEXT); DROP FUNCTION IF EXISTS generate_stack_view(TEXT); ------------------------------------------------------ @@ -110,6 +116,8 @@ RETURNS TABLE ( 'amount_sign', ss.amount_sign, 'date_field', ss.date_field, 'balance_offset', ss.balance_offset, + 'date_from', ss.date_from, + 'date_to', ss.date_to, 'seq', ss.seq ) ORDER BY ss.seq, ss.id ) FILTER (WHERE ss.id IS NOT NULL), '[]') @@ -174,11 +182,13 @@ CREATE OR REPLACE FUNCTION upsert_stack_source( p_amount_sign INTEGER DEFAULT 1, p_balance_offset NUMERIC DEFAULT 0, p_amount_field TEXT DEFAULT NULL, - p_date_field TEXT DEFAULT NULL + p_date_field TEXT DEFAULT NULL, + p_date_from DATE DEFAULT NULL, + p_date_to DATE DEFAULT NULL ) RETURNS dataflow.stack_sources AS $$ - INSERT INTO dataflow.stack_sources (stack_name, source_name, field_map, amount_sign, balance_offset, amount_field, date_field, seq) + INSERT INTO dataflow.stack_sources (stack_name, source_name, field_map, amount_sign, balance_offset, amount_field, date_field, date_from, date_to, seq) VALUES ( - p_stack_name, p_source_name, p_field_map, p_amount_sign, p_balance_offset, p_amount_field, p_date_field, + p_stack_name, p_source_name, p_field_map, p_amount_sign, p_balance_offset, p_amount_field, p_date_field, p_date_from, p_date_to, (SELECT COALESCE(MAX(seq), 0) + 1 FROM dataflow.stack_sources WHERE stack_name = p_stack_name) ) ON CONFLICT (stack_name, source_name) DO UPDATE SET @@ -186,10 +196,26 @@ CREATE OR REPLACE FUNCTION upsert_stack_source( amount_sign = EXCLUDED.amount_sign, balance_offset = EXCLUDED.balance_offset, amount_field = EXCLUDED.amount_field, - date_field = EXCLUDED.date_field + date_field = EXCLUDED.date_field, + date_from = EXCLUDED.date_from, + date_to = EXCLUDED.date_to RETURNING *; $$ LANGUAGE sql; +------------------------------------------------------ +-- Function: stack_source_window +-- The date_from/date_to condition for one stack source, or '' when it has none. +-- Lets a stack cut over from one source to another (an old card export to its +-- replacement feed) without deleting the overlapping records. +------------------------------------------------------ +CREATE OR REPLACE FUNCTION stack_source_window(p_src dataflow.stack_sources) +RETURNS TEXT AS $$ + SELECT CASE WHEN p_src.date_field IS NULL THEN '' ELSE concat_ws(' AND ', + CASE WHEN p_src.date_from IS NOT NULL THEN format('%I::date >= %L::date', p_src.date_field, p_src.date_from) END, + CASE WHEN p_src.date_to IS NOT NULL THEN format('%I::date <= %L::date', p_src.date_field, p_src.date_to) END + ) END; +$$ LANGUAGE sql IMMUTABLE; + ------------------------------------------------------ -- Function: remove_stack_source ------------------------------------------------------ @@ -214,6 +240,7 @@ CREATE OR REPLACE FUNCTION calibrate_balance( DECLARE v_src dataflow.stack_sources%ROWTYPE; v_running NUMERIC; + v_where TEXT; v_sql TEXT; BEGIN SELECT * INTO v_src @@ -227,18 +254,17 @@ BEGIN RETURN json_build_object('success', false, 'error', 'Set amount and date fields on this source first'); END IF; + -- Only count rows the stack includes, so the offset matches the stack's balance + v_where := concat_ws(' AND ', + NULLIF(dataflow.stack_source_window(v_src), ''), + CASE WHEN p_as_of_date IS NOT NULL THEN format('%I <= %L::date', v_src.date_field, p_as_of_date) END + ); + BEGIN - IF p_as_of_date IS NULL THEN - v_sql := format( - 'SELECT COALESCE(SUM(%I * %s), 0) FROM dfv.%I', - v_src.amount_field, v_src.amount_sign, p_source_name - ); - ELSE - v_sql := format( - 'SELECT COALESCE(SUM(%I * %s), 0) FROM dfv.%I WHERE %I <= %L::date', - v_src.amount_field, v_src.amount_sign, p_source_name, v_src.date_field, p_as_of_date - ); - END IF; + v_sql := format( + 'SELECT COALESCE(SUM(%I * %s), 0) FROM dfv.%I', + v_src.amount_field, v_src.amount_sign, p_source_name + ) || CASE WHEN v_where <> '' THEN ' WHERE ' || v_where ELSE '' END; EXECUTE v_sql INTO v_running; EXCEPTION WHEN undefined_table THEN RETURN json_build_object('success', false, 'error', 'Source view not found — generate the source view first'); @@ -330,6 +356,9 @@ BEGIN END LOOP; v_select := v_select || format(' FROM dfv.%I', v_src.source_name); + IF dataflow.stack_source_window(v_src) <> '' THEN + v_select := v_select || ' WHERE ' || dataflow.stack_source_window(v_src); + END IF; v_ctes := v_ctes || format('%I AS (%s)', v_src.source_name, v_select); v_cte_names := v_cte_names || quote_ident(v_src.source_name); diff --git a/docs/spec.md b/docs/spec.md index 79f3e51..9c40a0a 100644 --- a/docs/spec.md +++ b/docs/spec.md @@ -288,7 +288,7 @@ All routes are under `/api`. Every route requires HTTP Basic Auth. The `GET /hea | POST | /api/stacks | Create stack | | PUT | /api/stacks/:name | Update stack | | DELETE | /api/stacks/:name | Delete stack | -| PUT | /api/stacks/:name/sources/:source | Add or update a source in the stack | +| PUT | /api/stacks/:name/sources/:source | Add or update a source in the stack (`field_map`, `amount_field`, `amount_sign`, `date_field`, `balance_offset`, optional `date_from`/`date_to`) | | DELETE | /api/stacks/:name/sources/:source | Remove a source from the stack | | PUT | /api/stacks/:name/sources/reorder | Reorder the stack's sources | | GET | /api/stacks/:name/view-sql | Preview the SQL that would build the view (dry run) | @@ -395,7 +395,7 @@ of the initial download and in a chunk fetched only when a pivot is opened. See `docs/perspective.md` for the full technical reference on controlling Perspective programmatically. - **Stacks** — Named unions of multiple sources, each chip linking to its pivot at - `/stacks/:name/pivot`. Each stack defines a field mapping (how source fields map to common output columns), an amount field, a date field, and an optional balance offset. The view-data endpoint unions the underlying source views and computes a running balance sorted by date. The Pivot page supports stacks as well as individual sources, with layouts stored in the same `pivot_layouts` table. + `/stacks/:name/pivot`. Each stack defines a field mapping (how source fields map to common output columns), an amount field, a date field, and an optional balance offset. Each source can also carry a `date_from`/`date_to` window on its date field; rows outside it are left out of the stack (and out of calibration), which is how a stack cuts over from a retired source to its replacement without deleting the overlap. The view-data endpoint unions the underlying source views and computes a running balance sorted by date. The Pivot page supports stacks as well as individual sources, with layouts stored in the same `pivot_layouts` table. - **Log** — Global import log across all sources. Same expandable key detail and delete capability as the Import page, plus a source name column. diff --git a/ui/src/pages/Stacks.jsx b/ui/src/pages/Stacks.jsx index 8bb60ba..ad99a4a 100644 --- a/ui/src/pages/Stacks.jsx +++ b/ui/src/pages/Stacks.jsx @@ -19,6 +19,21 @@ function fmt(n) { return Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) } +// Request body for upsertStackSource. Every save sends the whole config, so all +// call sites build it here — a field left out would be wiped on the next save. +function srcBody(cfg, extra = {}) { + return { + field_map: cfg.field_map || {}, + amount_sign: cfg.sign ?? 1, + balance_offset: cfg.offset ?? 0, + amount_field: cfg.amount_field || null, + date_field: cfg.date_field || null, + date_from: cfg.date_from || null, + date_to: cfg.date_to || null, + ...extra, + } +} + function CalibrateModal({ stack, sourceName, currentOffset, onClose, onApply }) { const [asOf, setAsOf] = useState('') const [known, setKnown] = useState('') @@ -131,6 +146,8 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql offset: m.balance_offset ?? 0, amount_field: m.amount_field || '', date_field: m.date_field || '', + date_from: m.date_from || '', + date_to: m.date_to || '', field_map: { ...(m.field_map || {}) }, }])) ) @@ -173,13 +190,7 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql try { for (const m of members) { const cfg = srcCfg[m.source_name] || {} - await api.upsertStackSource(stack.name, m.source_name, { - field_map: cfg.field_map || {}, - amount_sign: cfg.sign ?? 1, - balance_offset: cfg.offset ?? 0, - amount_field: cfg.amount_field || null, - date_field: cfg.date_field || null, - }) + await api.upsertStackSource(stack.name, m.source_name, srcBody(cfg)) } await api.updateStack(stack.name, { fields, @@ -300,18 +311,18 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql setMappingsDirty(true) } + // key is date_from or date_to + function setSrcDate(srcName, key, value) { + setSrcCfg(prev => ({ ...prev, [srcName]: { ...prev[srcName], [key]: value } })) + setMappingsDirty(true) + } + async function saveMappings() { setSaving(true); setError('') try { for (const m of members) { const cfg = srcCfg[m.source_name] || {} - await api.upsertStackSource(stack.name, m.source_name, { - field_map: cfg.field_map || {}, - amount_sign: cfg.sign ?? 1, - balance_offset: cfg.offset ?? 0, - amount_field: cfg.amount_field || null, - date_field: cfg.date_field || null, - }) + await api.upsertStackSource(stack.name, m.source_name, srcBody(cfg)) } // Persist the auto-detected canonical field names on the stack await api.updateStack(stack.name, { @@ -329,7 +340,7 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql async function addSource() { if (!addingSrc) return await api.upsertStackSource(stack.name, addingSrc, { field_map: {}, amount_sign: 1 }) - setSrcCfg(prev => ({ ...prev, [addingSrc]: { sign: 1, offset: 0, amount_field: '', date_field: '', field_map: {} } })) + setSrcCfg(prev => ({ ...prev, [addingSrc]: { sign: 1, offset: 0, amount_field: '', date_field: '', date_from: '', date_to: '', field_map: {} } })) // Load fields immediately so dropdowns are ready try { const f = await api.getFields(addingSrc) @@ -378,25 +389,13 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql async function handleCalibrate(srcName) { // Save this source's current config before opening modal const cfg = srcCfg[srcName] || {} - await api.upsertStackSource(stack.name, srcName, { - field_map: cfg.field_map || {}, - amount_sign: cfg.sign ?? 1, - balance_offset: cfg.offset ?? 0, - amount_field: cfg.amount_field || null, - date_field: cfg.date_field || null, - }) + await api.upsertStackSource(stack.name, srcName, srcBody(cfg)) setCalibratingSource(srcName) } async function applyCalibration(srcName, offset) { const cfg = srcCfg[srcName] || {} - await api.upsertStackSource(stack.name, srcName, { - field_map: cfg.field_map || {}, - amount_sign: cfg.sign ?? 1, - balance_offset: offset, - amount_field: cfg.amount_field || null, - date_field: cfg.date_field || null, - }) + await api.upsertStackSource(stack.name, srcName, srcBody(cfg, { balance_offset: offset })) setSrcCfg(prev => ({ ...prev, [srcName]: { ...prev[srcName], offset } })) setCalibratingSource(null) onStale?.(stack.name) @@ -515,6 +514,20 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql +