Compare commits

..

1 Commits

Author SHA1 Message Date
8f94296ad2 Pin Perspective at 5.2.0 exact; drop non-functional viewer-d3fc
docs/perspective.md claimed the 4.5.1-core + 4.4.1-d3fc pair was "deliberate
and necessary — the only combination that keeps both" inline WASM bundling and
d3fc charts, and said do NOT fix it to 4.4.1. That was wrong: it does not keep
charts.

Loading viewer-d3fc@4.4.1 against a 4.5.x viewer throws
`get_static_config is not a function`, once per chart plugin — the newer viewer
calls a registration method the older plugins don't implement. Confirmed in the
running deployment: no chart type except Datagrid works. So the choice was never
"both"; it is inline bundling XOR charts, and dataflow was carrying mixed-version
complexity to buy charts it did not have.

- pin client/viewer/viewer-datagrid/server exact at 5.2.0 (was ^4.5.1 carets).
  The explicit `server` pin is required: client declares it as "" (an empty
  range) which npm resolves to latest, and a mismatched server WASM fails to
  link with `psp_opfs_load ... requires a callable`. That took pf_app down on
  2026-08-10. Five packages to pin, not four.
- drop the viewer-d3fc import. Restoring charts would require a coherent 4.4.1
  suite, which has no /inline export — trading bundled WASM for runtime fetching,
  to regain a feature no code path selects by name.

Verified: build succeeds; the entry chunk and the Pivot chunk it lazy-imports
contain zero CDN URLs and zero runtime `new URL(...perspective-server...)`
constructions; the app loads with every non-localhost request aborted, with no
console errors. dataflow's exact API surface — plugin.save/restore/draw,
view.set_depth, viewer.restore with plugin_config — behaves identically on
4.5.2 and 5.2.0.

NOT verified: the pivot rendering end-to-end, which is behind authentication.
Worth a manual click-through before merging.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SBt3EtKaP9D2mmWJ6Q4bov
2026-08-17 21:37:44 -04:00
11 changed files with 140 additions and 1035 deletions

5
.gitignore vendored
View File

@ -2,8 +2,9 @@
.env .env
# Dependencies # Dependencies
# Lockfiles ARE tracked — they pin the Perspective 4.5.1/4.4.1 pairing that the # Lockfiles ARE tracked. Perspective is now pinned exact (5.2.0, all four packages
# caret ranges in ui/package.json would otherwise let drift. See docs/perspective.md. # including @perspective-dev/server) in ui/package.json, but keep the lockfile committed
# so transitive resolution can't drift either. See docs/perspective.md.
node_modules/ node_modules/
ui/node_modules/ ui/node_modules/

View File

@ -67,10 +67,10 @@ module.exports = (pool) => {
// Add or update a source in a stack // Add or update a source in a stack
router.put('/:name/sources/:source', async (req, res, next) => { router.put('/:name/sources/:source', async (req, res, next) => {
try { try {
const { field_map, amount_sign, balance_offset, amount_field, date_field, date_from, date_to } = req.body; const { field_map, amount_sign, balance_offset, amount_field, date_field } = req.body;
const n = v => v != null ? lit(v) : 'NULL'; const n = v => v != null ? lit(v) : 'NULL';
const result = await pool.query( 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)}, ${n(date_from || null)}, ${n(date_to || null)})` `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)})`
); );
res.json(result.rows[0]); res.json(result.rows[0]);
} catch (err) { } catch (err) {

View File

@ -197,8 +197,8 @@ BEGIN
v_view := 'dfv.' || quote_ident(p_source_name); v_view := 'dfv.' || quote_ident(p_source_name);
EXECUTE format('DROP VIEW IF EXISTS %s CASCADE', v_view); EXECUTE format('DROP VIEW IF EXISTS %s CASCADE', v_view);
v_sql := format( v_sql := format(
'CREATE VIEW %s AS SELECT df_id, df_overridden, %s FROM (' 'CREATE VIEW %s AS SELECT id, _overridden, %s FROM ('
|| 'SELECT id AS df_id, overrides IS NOT NULL AS df_overridden, ' || 'SELECT id, overrides IS NOT NULL AS _overridden, '
|| 'data || COALESCE(transformed, ''{}''::jsonb) || COALESCE(overrides, ''{}''::jsonb) AS r ' || 'data || COALESCE(transformed, ''{}''::jsonb) || COALESCE(overrides, ''{}''::jsonb) AS r '
|| 'FROM dataflow.records WHERE source_name = %L AND transformed IS NOT NULL) rec', || 'FROM dataflow.records WHERE source_name = %L AND transformed IS NOT NULL) rec',
v_view, v_cols, p_source_name v_view, v_cols, p_source_name

View File

@ -35,9 +35,6 @@ CREATE TABLE IF NOT EXISTS dataflow.stack_sources (
date_field TEXT, date_field TEXT,
-- Calibration offset added to this source's running balance -- Calibration offset added to this source's running balance
balance_offset NUMERIC NOT NULL DEFAULT 0, 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) UNIQUE (stack_name, source_name)
); );
@ -46,8 +43,6 @@ 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 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 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 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 -- Seed seq from insertion order for existing rows
UPDATE dataflow.stack_sources ss UPDATE dataflow.stack_sources ss
@ -61,7 +56,6 @@ WHERE ss.id = sub.id AND ss.seq = 0;
-- Drop old signatures before recreating -- Drop old signatures before recreating
DROP FUNCTION IF EXISTS calibrate_balance(TEXT, DATE, NUMERIC); 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);
DROP FUNCTION IF EXISTS upsert_stack_source(TEXT, TEXT, JSONB, INTEGER, NUMERIC, TEXT, TEXT);
DROP FUNCTION IF EXISTS generate_stack_view(TEXT); DROP FUNCTION IF EXISTS generate_stack_view(TEXT);
------------------------------------------------------ ------------------------------------------------------
@ -116,8 +110,6 @@ RETURNS TABLE (
'amount_sign', ss.amount_sign, 'amount_sign', ss.amount_sign,
'date_field', ss.date_field, 'date_field', ss.date_field,
'balance_offset', ss.balance_offset, 'balance_offset', ss.balance_offset,
'date_from', ss.date_from,
'date_to', ss.date_to,
'seq', ss.seq 'seq', ss.seq
) ORDER BY ss.seq, ss.id ) ORDER BY ss.seq, ss.id
) FILTER (WHERE ss.id IS NOT NULL), '[]') ) FILTER (WHERE ss.id IS NOT NULL), '[]')
@ -182,13 +174,11 @@ CREATE OR REPLACE FUNCTION upsert_stack_source(
p_amount_sign INTEGER DEFAULT 1, p_amount_sign INTEGER DEFAULT 1,
p_balance_offset NUMERIC DEFAULT 0, p_balance_offset NUMERIC DEFAULT 0,
p_amount_field TEXT DEFAULT NULL, 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 $$ ) RETURNS dataflow.stack_sources AS $$
INSERT INTO dataflow.stack_sources (stack_name, source_name, field_map, amount_sign, balance_offset, amount_field, date_field, date_from, date_to, seq) INSERT INTO dataflow.stack_sources (stack_name, source_name, field_map, amount_sign, balance_offset, amount_field, date_field, seq)
VALUES ( VALUES (
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, p_stack_name, p_source_name, p_field_map, p_amount_sign, p_balance_offset, p_amount_field, p_date_field,
(SELECT COALESCE(MAX(seq), 0) + 1 FROM dataflow.stack_sources WHERE stack_name = p_stack_name) (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 ON CONFLICT (stack_name, source_name) DO UPDATE SET
@ -196,26 +186,10 @@ CREATE OR REPLACE FUNCTION upsert_stack_source(
amount_sign = EXCLUDED.amount_sign, amount_sign = EXCLUDED.amount_sign,
balance_offset = EXCLUDED.balance_offset, balance_offset = EXCLUDED.balance_offset,
amount_field = EXCLUDED.amount_field, 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 *; RETURNING *;
$$ LANGUAGE sql; $$ 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 -- Function: remove_stack_source
------------------------------------------------------ ------------------------------------------------------
@ -240,7 +214,6 @@ CREATE OR REPLACE FUNCTION calibrate_balance(
DECLARE DECLARE
v_src dataflow.stack_sources%ROWTYPE; v_src dataflow.stack_sources%ROWTYPE;
v_running NUMERIC; v_running NUMERIC;
v_where TEXT;
v_sql TEXT; v_sql TEXT;
BEGIN BEGIN
SELECT * INTO v_src SELECT * INTO v_src
@ -254,17 +227,18 @@ BEGIN
RETURN json_build_object('success', false, 'error', 'Set amount and date fields on this source first'); RETURN json_build_object('success', false, 'error', 'Set amount and date fields on this source first');
END IF; 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 BEGIN
v_sql := format( IF p_as_of_date IS NULL THEN
'SELECT COALESCE(SUM(%I * %s), 0) FROM dfv.%I', v_sql := format(
v_src.amount_field, v_src.amount_sign, p_source_name 'SELECT COALESCE(SUM(%I * %s), 0) FROM dfv.%I',
) || CASE WHEN v_where <> '' THEN ' WHERE ' || v_where ELSE '' END; 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;
EXECUTE v_sql INTO v_running; EXECUTE v_sql INTO v_running;
EXCEPTION WHEN undefined_table THEN EXCEPTION WHEN undefined_table THEN
RETURN json_build_object('success', false, 'error', 'Source view not found — generate the source view first'); RETURN json_build_object('success', false, 'error', 'Source view not found — generate the source view first');
@ -319,7 +293,7 @@ BEGIN
FOR v_src IN FOR v_src IN
SELECT * FROM dataflow.stack_sources WHERE stack_name = p_stack_name ORDER BY seq, id SELECT * FROM dataflow.stack_sources WHERE stack_name = p_stack_name ORDER BY seq, id
LOOP LOOP
v_select := format('SELECT %L AS _source, df_id AS _id', v_src.source_name); v_select := format('SELECT %L AS _source, id AS _id', v_src.source_name);
FOR v_field IN SELECT * FROM jsonb_array_elements(v_stack.fields) FOR v_field IN SELECT * FROM jsonb_array_elements(v_stack.fields)
LOOP LOOP
@ -356,9 +330,6 @@ BEGIN
END LOOP; END LOOP;
v_select := v_select || format(' FROM dfv.%I', v_src.source_name); 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_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); v_cte_names := v_cte_names || quote_ident(v_src.source_name);

View File

@ -25,34 +25,48 @@ pattern, upgrade smoke test). This file records what's specific to dataflow.
unless view sizes grow well past 100k. unless view sizes grow well past 100k.
- **Deploy:** `manage.py` + `dataflow.service` (systemd) + nginx. ✅ Reference pattern - **Deploy:** `manage.py` + `dataflow.service` (systemd) + nginx. ✅ Reference pattern
for the org; pf_app should copy it. for the org; pf_app should copy it.
- **Charts:** `viewer-d3fc` is imported, so the chart plugins are available in the UI. - **Charts:** **none — `viewer-d3fc` was removed on 2026-08-17.** It had been imported,
Default plugin config is datagrid-only (`{ edit_mode: 'SELECT_REGION' }`). but the chart plugins did *not* work: confirmed in the running deployment, where every
plugin other than Datagrid failed. Default plugin config is datagrid-only
(`{ edit_mode: 'SELECT_REGION' }`) and no chart is ever selected by name in the source.
- **Layout safety:** `cleanLayout()` filters saved configs against valid columns before - **Layout safety:** `cleanLayout()` filters saved configs against valid columns before
restore — the reference implementation; keep it. restore — the reference implementation; keep it.
## The version pair is correct — do NOT "fix" it to 4.4.1 ## Version policy — pinned to 5.2.0 exact (corrected 2026-08-17)
`ui/package.json` pins **viewer/client/datagrid at `^4.5.1`** and **`viewer-d3fc` at `ui/package.json` pins **client / viewer / viewer-datagrid / server** all at exactly
`^4.4.1`**. This looks like a skew but is **deliberate and necessary** — it's the only **`5.2.0`**, and `viewer-d3fc` is gone.
combination that keeps both of dataflow's hard requirements:
- **Inline WASM bundling.** `Pivot.jsx` imports `@perspective-dev/client/inline`, > ### ⚠️ This section previously said the 4.5.1 / 4.4.1 pair was "deliberate and
`@perspective-dev/viewer/inline`, and `@perspective-dev/viewer/themes`. Those export > necessary — do NOT fix it to 4.4.1". **That was wrong.**
paths **exist only in 4.5.x** — they are absent from 4.4.1's `exports` map. >
- **d3fc chart plugins.** `viewer-d3fc` is published only up to **4.4.1**. > The pair was justified as the only combination keeping *both* inline WASM bundling and
> d3fc charts. It does not keep charts. Loading `viewer-d3fc@4.4.1` against a 4.5.x
> viewer throws `get_static_config is not a function` — once per chart plugin — because
> the newer viewer calls a registration method the older plugins don't implement. The
> app owner confirmed independently that no chart type except Datagrid works.
>
> So the choice was never "both": it is **inline bundling XOR charts**. dataflow was
> carrying mixed-version complexity to buy charts it did not have.
Verified the hard way: pinning all four to 4.4.1 and rebuilding fails with **What changed and why 5.2.0:**
`"./inline" is not exported … from @perspective-dev/client`. So the 4.5.1/4.4.1 pair
stays. Don't touch it.
**What to actually do:** - **`@perspective-dev/server` must be pinned explicitly.** `client` declares it as
- Keep the versions as-is; **commit `package-lock.json`** so the resolved set can't drift `"@perspective-dev/server": ""` — an *empty* range, which npm resolves to `latest`.
on `npm install`. (Optionally tighten the carets to exact `4.5.1`/`4.4.1` to make that Left implicit, a fresh `npm install` pulls a mismatched server and the WASM fails to
explicit.) link with `Import #8 "env" "psp_opfs_load": function import requires a callable`.
- Treat any Perspective bump as gated by the canonical smoke test (§7): a d3fc **chart** That exact failure took pf_app down on 2026-08-10. Five packages to pin, not four.
renders, dark/light re-themes, and save→reload→drop-column layout restore. - **Exact versions, no carets.** Carets are what let the pinning drift in the first
- Revisit only when `viewer-d3fc` ships a 4.5.x — then a fully-coherent inline-capable place; the lockfile alone is not the whole guard.
4.5.x suite becomes possible and the pair can collapse to one version. - **d3fc dropped rather than downgraded.** Restoring charts would mean a coherent 4.4.1
suite, which has no `/inline` export — i.e. giving up bundled WASM and going back to
runtime fetching. Not worth it for a feature nothing in the source selects.
**Before choosing differently:** nobody has verified that d3fc charts render in *any*
configuration here, including a coherent 4.4.1 suite. Establish that first — don't
assume 4.4.1 works just because it's coherent.
Revisit when `viewer-d3fc` ships a 5.x; only then does "both" come back on the table.
--- ---

View File

@ -288,7 +288,7 @@ All routes are under `/api`. Every route requires HTTP Basic Auth. The `GET /hea
| POST | /api/stacks | Create stack | | POST | /api/stacks | Create stack |
| PUT | /api/stacks/:name | Update stack | | PUT | /api/stacks/:name | Update stack |
| DELETE | /api/stacks/:name | Delete stack | | DELETE | /api/stacks/:name | Delete 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`) | | PUT | /api/stacks/:name/sources/:source | Add or update a source in the stack |
| DELETE | /api/stacks/:name/sources/:source | Remove a source from the stack | | DELETE | /api/stacks/:name/sources/:source | Remove a source from the stack |
| PUT | /api/stacks/:name/sources/reorder | Reorder the stack's sources | | 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) | | 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. 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** — 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. 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. `/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.
- **Log** — Global import log across all sources. Same expandable key detail and delete capability as the Import page, plus a source name column. - **Log** — Global import log across all sources. Same expandable key detail and delete capability as the Import page, plus a source name column.

933
ui/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -10,10 +10,10 @@
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
"@perspective-dev/client": "^4.5.1", "@perspective-dev/client": "5.2.0",
"@perspective-dev/viewer": "^4.5.1", "@perspective-dev/server": "5.2.0",
"@perspective-dev/viewer-d3fc": "^4.4.1", "@perspective-dev/viewer": "5.2.0",
"@perspective-dev/viewer-datagrid": "^4.5.1", "@perspective-dev/viewer-datagrid": "5.2.0",
"react": "^19.2.7", "react": "^19.2.7",
"react-dom": "^19.2.7", "react-dom": "^19.2.7",
"react-router-dom": "^7.17.0", "react-router-dom": "^7.17.0",

View File

@ -1,10 +1,13 @@
import { useEffect, useRef, useState, useCallback } from 'react' import { useEffect, useRef, useState, useCallback } from 'react'
import { api } from '../api' import { api } from '../api'
import useTheme from '../theme.jsx' import useTheme from '../theme.jsx'
// Perspective, bundled (no runtime CDN fetch). All four packages are pinned exact in
// package.json and the lockfile is tracked — see docs/perspective.md.
// viewer-d3fc is deliberately absent: it publishes no 5.x, and loading 4.4.1 against a
// 5.x viewer only throws `get_static_config is not a function` per chart plugin.
import perspective from '@perspective-dev/client/inline' import perspective from '@perspective-dev/client/inline'
import '@perspective-dev/viewer/inline' import '@perspective-dev/viewer/inline'
import '@perspective-dev/viewer-datagrid' import '@perspective-dev/viewer-datagrid'
import '@perspective-dev/viewer-d3fc'
import '@perspective-dev/viewer/themes' import '@perspective-dev/viewer/themes'
async function fetchAllRows(source) { async function fetchAllRows(source) {

View File

@ -63,14 +63,14 @@ function AutocompleteInput({ value, onChange, onEnter, suggestions = [], classNa
const DATE_RE = /^\d{4}-\d{2}-\d{2}(T[\d:.Z+-]+)?$/ const DATE_RE = /^\d{4}-\d{2}-\d{2}(T[\d:.Z+-]+)?$/
// Hidden everywhere a field can be edited as an override — you can't override an id // Hidden everywhere a field can be edited as an override — you can't override an id
const HIDDEN_COLS = new Set(['df_id', 'df_overridden']) const HIDDEN_COLS = new Set(['id', '_overridden'])
// The grid and its filters keep id: it's the only handle on a specific row // The grid and its filters keep id: it's the only handle on a specific row
const GRID_HIDDEN_COLS = new Set(['df_overridden']) const GRID_HIDDEN_COLS = new Set(['_overridden'])
// id first, then the rest in view order // id first, then the rest in view order
function gridCols(keys) { function gridCols(keys) {
const visible = keys.filter(c => !GRID_HIDDEN_COLS.has(c)) const visible = keys.filter(c => !GRID_HIDDEN_COLS.has(c))
return visible.includes('df_id') ? ['df_id', ...visible.filter(c => c !== 'df_id')] : visible return visible.includes('id') ? ['id', ...visible.filter(c => c !== 'id')] : visible
} }
function formatVal(val) { function formatVal(val) {
@ -155,7 +155,7 @@ export default function Records({ source }) {
} }
return false return false
}) })
setSelected(new Set(matches.map(r => r.df_id))) setSelected(new Set(matches.map(r => r.id)))
}, [rowFilter, rows]) }, [rowFilter, rows])
async function load(off, col, dir, filt) { async function load(off, col, dir, filt) {
@ -189,7 +189,7 @@ export default function Records({ source }) {
function addFilter() { function addFilter() {
// id is filterable but a poor default — start on the first data column // id is filterable but a poor default — start on the first data column
const visCols = gridCols(cols).filter(c => c !== 'df_id') const visCols = gridCols(cols).filter(c => c !== 'id')
setFilters(f => [...f, { col: visCols[0] || '', pattern: '' }]) setFilters(f => [...f, { col: visCols[0] || '', pattern: '' }])
} }
@ -219,7 +219,7 @@ export default function Records({ source }) {
setOverrideDraft({}) setOverrideDraft({})
setPanelMsg(null) setPanelMsg(null)
const id = row.df_id const id = row.id
if (!id) { if (!id) {
setPanelMsg({ text: 'No record ID — regenerate the view in Sources.', ok: false }) setPanelMsg({ text: 'No record ID — regenerate the view in Sources.', ok: false })
return return
@ -427,9 +427,9 @@ export default function Records({ source }) {
<input <input
type="checkbox" type="checkbox"
className="cursor-pointer" className="cursor-pointer"
checked={rows.length > 0 && rows.every(r => selected.has(r.df_id))} checked={rows.length > 0 && rows.every(r => selected.has(r.id))}
onChange={e => { onChange={e => {
if (e.target.checked) setSelected(new Set(rows.map(r => r.df_id))) if (e.target.checked) setSelected(new Set(rows.map(r => r.id)))
else setSelected(new Set()) else setSelected(new Set())
}} }}
/> />
@ -448,9 +448,9 @@ export default function Records({ source }) {
</thead> </thead>
<tbody> <tbody>
{rows.map((row, i) => { {rows.map((row, i) => {
const isOverridden = row.df_overridden const isOverridden = row._overridden
const isRowSelected = selected.has(row.df_id) const isRowSelected = selected.has(row.id)
const isPanelSelected = selectedRow?.df_id != null && selectedRow.df_id === row.df_id const isPanelSelected = selectedRow?.id != null && selectedRow.id === row.id
return ( return (
<tr key={i} onClick={() => openPanel(row)} <tr key={i} onClick={() => openPanel(row)}
className={`border-t border-line-soft cursor-pointer transition-colors className={`border-t border-line-soft cursor-pointer transition-colors
@ -462,7 +462,7 @@ export default function Records({ source }) {
checked={isRowSelected} checked={isRowSelected}
onChange={e => { onChange={e => {
e.stopPropagation() e.stopPropagation()
setSelected(s => { const n = new Set(s); n.has(row.df_id) ? n.delete(row.df_id) : n.add(row.df_id); return n }) setSelected(s => { const n = new Set(s); n.has(row.id) ? n.delete(row.id) : n.add(row.id); return n })
}} }}
/> />
</td> </td>

View File

@ -19,21 +19,6 @@ function fmt(n) {
return Number(n).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) 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 }) { function CalibrateModal({ stack, sourceName, currentOffset, onClose, onApply }) {
const [asOf, setAsOf] = useState('') const [asOf, setAsOf] = useState('')
const [known, setKnown] = useState('') const [known, setKnown] = useState('')
@ -146,8 +131,6 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql
offset: m.balance_offset ?? 0, offset: m.balance_offset ?? 0,
amount_field: m.amount_field || '', amount_field: m.amount_field || '',
date_field: m.date_field || '', date_field: m.date_field || '',
date_from: m.date_from || '',
date_to: m.date_to || '',
field_map: { ...(m.field_map || {}) }, field_map: { ...(m.field_map || {}) },
}])) }]))
) )
@ -190,7 +173,13 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql
try { try {
for (const m of members) { for (const m of members) {
const cfg = srcCfg[m.source_name] || {} const cfg = srcCfg[m.source_name] || {}
await api.upsertStackSource(stack.name, m.source_name, srcBody(cfg)) 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.updateStack(stack.name, { await api.updateStack(stack.name, {
fields, fields,
@ -311,18 +300,18 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql
setMappingsDirty(true) 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() { async function saveMappings() {
setSaving(true); setError('') setSaving(true); setError('')
try { try {
for (const m of members) { for (const m of members) {
const cfg = srcCfg[m.source_name] || {} const cfg = srcCfg[m.source_name] || {}
await api.upsertStackSource(stack.name, m.source_name, srcBody(cfg)) 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,
})
} }
// Persist the auto-detected canonical field names on the stack // Persist the auto-detected canonical field names on the stack
await api.updateStack(stack.name, { await api.updateStack(stack.name, {
@ -340,7 +329,7 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql
async function addSource() { async function addSource() {
if (!addingSrc) return if (!addingSrc) return
await api.upsertStackSource(stack.name, addingSrc, { field_map: {}, amount_sign: 1 }) await api.upsertStackSource(stack.name, addingSrc, { field_map: {}, amount_sign: 1 })
setSrcCfg(prev => ({ ...prev, [addingSrc]: { sign: 1, offset: 0, amount_field: '', date_field: '', date_from: '', date_to: '', field_map: {} } })) setSrcCfg(prev => ({ ...prev, [addingSrc]: { sign: 1, offset: 0, amount_field: '', date_field: '', field_map: {} } }))
// Load fields immediately so dropdowns are ready // Load fields immediately so dropdowns are ready
try { try {
const f = await api.getFields(addingSrc) const f = await api.getFields(addingSrc)
@ -389,13 +378,25 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql
async function handleCalibrate(srcName) { async function handleCalibrate(srcName) {
// Save this source's current config before opening modal // Save this source's current config before opening modal
const cfg = srcCfg[srcName] || {} const cfg = srcCfg[srcName] || {}
await api.upsertStackSource(stack.name, srcName, srcBody(cfg)) 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,
})
setCalibratingSource(srcName) setCalibratingSource(srcName)
} }
async function applyCalibration(srcName, offset) { async function applyCalibration(srcName, offset) {
const cfg = srcCfg[srcName] || {} const cfg = srcCfg[srcName] || {}
await api.upsertStackSource(stack.name, srcName, srcBody(cfg, { balance_offset: offset })) 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,
})
setSrcCfg(prev => ({ ...prev, [srcName]: { ...prev[srcName], offset } })) setSrcCfg(prev => ({ ...prev, [srcName]: { ...prev[srcName], offset } }))
setCalibratingSource(null) setCalibratingSource(null)
onStale?.(stack.name) onStale?.(stack.name)
@ -514,20 +515,6 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql
</button> </button>
</div> </div>
</div> </div>
<div>
<label className="text-muted block mb-0.5">From date</label>
<input type="date" value={cfg.date_from || ''}
onChange={e => setSrcDate(m.source_name, 'date_from', e.target.value)}
title="Leave out rows before this date (on the date field)"
className="w-full border border-line rounded px-1.5 py-0.5 focus:outline-none focus:border-accent" />
</div>
<div>
<label className="text-muted block mb-0.5">To date</label>
<input type="date" value={cfg.date_to || ''}
onChange={e => setSrcDate(m.source_name, 'date_to', e.target.value)}
title="Leave out rows after this date (on the date field)"
className="w-full border border-line rounded px-1.5 py-0.5 focus:outline-none focus:border-accent" />
</div>
</div> </div>
</div> </div>
) )