Compare commits
No commits in common. "master" and "ui-mobile" have entirely different histories.
@ -68,8 +68,8 @@ Theme state lives in `ui/src/theme.jsx` — a React context (`ThemeContext`) wit
|
||||
`ThemeProvider` that wraps the app in `main.jsx`.
|
||||
|
||||
- **Storage key:** `df_dark` in `localStorage`; falls back to `window.matchMedia('(prefers-color-scheme: dark)')` on first visit
|
||||
- **Toggle:** button at the foot of the sidebar (`Sidebar.jsx`), and in `BottomNav.jsx` on mobile; the effect writes `localStorage` and toggles the `.dark` class on `<html>`
|
||||
- **CSS:** `ui/src/index.css` declares semantic tokens under `@theme` (`bg-surface`, `text-ink`, `text-muted`, `border-line`, `text-danger`, …) that resolve to CSS custom properties redefined by `.dark`. **Write components against the tokens, never against literal shades like `bg-white` or `text-gray-400`** — the old per-utility `.dark .bg-white { … }` overrides are gone and must not come back
|
||||
- **Toggle:** button in the sidebar header in `App.jsx`; effect writes `localStorage` and toggles the `.dark` class on `<html>`
|
||||
- **CSS:** `ui/src/index.css` defines CSS custom properties under `:root` (light) and `.dark`. All Tailwind color overrides are written as `.dark .bg-white { ... }` etc.
|
||||
- **Palette:** dark mode uses Perspective's "Pro Dark" colours (`--bg-primary: #242526`, panels `#2a2c2f`, gridlines `#3b3f46`, text `#c5c9d0`)
|
||||
- **Perspective viewer:** `Pivot.jsx` calls `viewer.setAttribute('theme', dark ? 'Pro Dark' : 'Pro Light')` on initial load and in a `useEffect([dark])` so the viewer stays in sync when the toggle fires
|
||||
- **Consuming the theme:** `import useTheme from '../theme.jsx'` then `const { dark, setDark } = useTheme()`
|
||||
|
||||
@ -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, 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 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]);
|
||||
} catch (err) {
|
||||
|
||||
@ -197,8 +197,8 @@ BEGIN
|
||||
v_view := 'dfv.' || quote_ident(p_source_name);
|
||||
EXECUTE format('DROP VIEW IF EXISTS %s CASCADE', v_view);
|
||||
v_sql := format(
|
||||
'CREATE VIEW %s AS SELECT df_id, df_overridden, %s FROM ('
|
||||
|| 'SELECT id AS df_id, overrides IS NOT NULL AS df_overridden, '
|
||||
'CREATE VIEW %s AS SELECT id, _overridden, %s FROM ('
|
||||
|| 'SELECT id, overrides IS NOT NULL AS _overridden, '
|
||||
|| 'data || COALESCE(transformed, ''{}''::jsonb) || COALESCE(overrides, ''{}''::jsonb) AS r '
|
||||
|| 'FROM dataflow.records WHERE source_name = %L AND transformed IS NOT NULL) rec',
|
||||
v_view, v_cols, p_source_name
|
||||
|
||||
@ -35,9 +35,6 @@ 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)
|
||||
);
|
||||
|
||||
@ -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 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
|
||||
@ -61,7 +56,6 @@ 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);
|
||||
|
||||
------------------------------------------------------
|
||||
@ -116,8 +110,6 @@ 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), '[]')
|
||||
@ -182,13 +174,11 @@ 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_from DATE DEFAULT NULL,
|
||||
p_date_to DATE DEFAULT NULL
|
||||
p_date_field TEXT 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, 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 (
|
||||
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)
|
||||
)
|
||||
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,
|
||||
balance_offset = EXCLUDED.balance_offset,
|
||||
amount_field = EXCLUDED.amount_field,
|
||||
date_field = EXCLUDED.date_field,
|
||||
date_from = EXCLUDED.date_from,
|
||||
date_to = EXCLUDED.date_to
|
||||
date_field = EXCLUDED.date_field
|
||||
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
|
||||
------------------------------------------------------
|
||||
@ -240,7 +214,6 @@ 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
|
||||
@ -254,17 +227,18 @@ 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
|
||||
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;
|
||||
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;
|
||||
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');
|
||||
@ -319,7 +293,7 @@ BEGIN
|
||||
FOR v_src IN
|
||||
SELECT * FROM dataflow.stack_sources WHERE stack_name = p_stack_name ORDER BY seq, id
|
||||
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)
|
||||
LOOP
|
||||
@ -356,9 +330,6 @@ 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);
|
||||
|
||||
51
docs/spec.md
51
docs/spec.md
@ -59,14 +59,10 @@ api/
|
||||
ui/
|
||||
src/
|
||||
api.js — fetch wrapper, credential management
|
||||
App.jsx — root: login gate, routing, stale/reprocess banners
|
||||
index.css — semantic colour tokens for light and dark
|
||||
App.jsx — root: login gate, sidebar, source selector, routing
|
||||
pages/
|
||||
Login.jsx — username/password form
|
||||
SourceList.jsx — source list and the create dialog
|
||||
SourceDetail.jsx — one source: connection, fields, view, maintenance
|
||||
Bridge.jsx — SimpleFIN accounts, balances, and subtotals
|
||||
ImportHub.jsx — all sources with sync / upload actions
|
||||
Sources.jsx — source CRUD, field config, view generation
|
||||
Import.jsx — CSV upload, SimpleFIN sync, and import log
|
||||
Rules.jsx — rule CRUD with live pattern preview
|
||||
Mappings.jsx — mapping table with TSV import/export
|
||||
@ -75,7 +71,7 @@ ui/
|
||||
Stacks.jsx — multi-source union views with running balance
|
||||
Remap.jsx — bulk remap of an output field value across mappings
|
||||
Log.jsx — global import log across all sources
|
||||
components/ — Sidebar, BottomNav, navItems, SourceTabs, Section, SampleTable
|
||||
components/ — Sidebar, StatusBar
|
||||
theme.jsx — light/dark context provider
|
||||
public/ — compiled UI (output of npm run build in ui/)
|
||||
docs/ — this file, tutorial, UI and Perspective references
|
||||
@ -288,7 +284,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 (`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 |
|
||||
| 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) |
|
||||
@ -331,43 +327,11 @@ Built with React + Vite + Tailwind CSS. Compiled output goes to `public/`. The s
|
||||
3. On 401 response, credentials are cleared and the login screen is shown.
|
||||
4. `localStorage` persists the selected source name across sessions.
|
||||
|
||||
**Navigation.** The selected source is a route parameter, not global state: `/sources`
|
||||
lists sources, `/sources/:name` owns one, and Import, Rules, Mappings, Records, and Pivot
|
||||
are tabs beneath it (`components/SourceTabs.jsx`). The sidebar holds only top-level
|
||||
destinations — Sources, Import, Bridge, Remap, Stacks, Log — defined once in
|
||||
`components/navItems.jsx` and rendered by `Sidebar.jsx` on desktop and `BottomNav.jsx`
|
||||
below the `md:` breakpoint. Out-of-sync and reprocess banners render above every page from
|
||||
`App.jsx`.
|
||||
|
||||
**Colour.** Components use semantic tokens (`bg-surface`, `text-ink`, `text-muted`,
|
||||
`border-line`, `text-danger`) declared in `index.css` under `@theme`, which resolve to CSS
|
||||
variables redefined by `.dark`. There are no per-utility `.dark` override rules; a new
|
||||
component gets both themes for free.
|
||||
|
||||
**Bundle.** `Pivot` is loaded with `React.lazy`, keeping Perspective (~4.7 MB gzipped) out
|
||||
of the initial download and in a chunk fetched only when a pivot is opened.
|
||||
|
||||
**Pages:**
|
||||
|
||||
- **Sources** (`SourceList.jsx`) — Lists every source with its constraint fields and a
|
||||
badge for bank feeds; clicking opens it. "New source" opens the create dialog, which can
|
||||
seed fields from a CSV sample or from a linked SimpleFIN account.
|
||||
- **Sources** — View and edit source configuration. Shows all known field names and their origins (raw data, schema, rules, mappings). Checkboxes control which fields are constraint fields and which appear in the output view. Supports CSV upload to auto-detect fields.
|
||||
|
||||
- **Source detail** (`SourceDetail.jsx`) — The Setup tab, grouped into titled panels:
|
||||
Connection (link/unlink a SimpleFIN account, warns when constraint fields aren't `id`),
|
||||
Fields and view (all known field names and their origins, with checkboxes for constraint
|
||||
fields and view columns), Sample rows, Maintenance (reprocess), and Delete source.
|
||||
|
||||
- **Bridge** (`Bridge.jsx`) — Every account behind the SimpleFIN credential with balances,
|
||||
the source each maps to, and subtotals split into banking versus retirement (recognised by
|
||||
keyword on the account and institution names). Queries SimpleFIN only when Refresh is
|
||||
pressed. Balances render in accounting style with negatives in parentheses.
|
||||
|
||||
- **Import** (`ImportHub.jsx`) — Top-level entry point for the frequent job. Lists every
|
||||
source with record counts and last import date, a Sync button for bank feeds, and an
|
||||
upload link for CSV sources.
|
||||
|
||||
- **Source › Import tab** — Upload a CSV to import records into the selected source. Transformations run automatically on new records. Shows import log with inserted/duplicate counts, expandable key detail, checkbox selection, and delete with confirmation. Sources with `config.simplefin.account_id` also get a Sync panel — a window selector (10/30/45 days or a full backfill) and a "Sync now" button that pulls from the bank API through the same import path.
|
||||
- **Import** — Upload a CSV to import records into the selected source. Transformations run automatically on new records. Shows import log with inserted/duplicate counts, expandable key detail, checkbox selection, and delete with confirmation. Sources with `config.simplefin.account_id` also get a Sync panel — a window selector (10/30/90 days or everything) and a "Sync now" button that pulls from the bank API through the same import path.
|
||||
|
||||
- **Rules** — Create and manage regex rules. Live preview fires automatically (debounced 500ms) as pattern/field/flags are edited, showing match results against real records. Rules can be enabled/disabled by toggle.
|
||||
|
||||
@ -394,8 +358,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. 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** — Named unions of multiple sources. 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.
|
||||
|
||||
|
||||
@ -141,7 +141,6 @@ export default function App() {
|
||||
setExpanded={setSidebarExpanded}
|
||||
loginUser={loginUser}
|
||||
onLogout={handleLogout}
|
||||
sources={sources}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@ -202,8 +201,7 @@ export default function App() {
|
||||
|
||||
<Route path="/sources" element={<SourceList sources={sources} setSources={setSources} setSource={setSource} />} />
|
||||
<Route path="/sources/:name" element={<SourceTabs sources={sources} />}>
|
||||
<Route index element={<Navigate to="records" replace />} />
|
||||
<Route path="setup" element={<SourceDetail sources={sources} setSources={setSources} />} />
|
||||
<Route index element={<SourceDetail sources={sources} setSources={setSources} />} />
|
||||
<Route path="import" element={<ScopedToSource component={Import} />} />
|
||||
<Route path="rules" element={<ScopedToSource component={Rules} onStale={markSourceStale} />} />
|
||||
<Route path="mappings" element={<ScopedToSource component={Mappings} onNeedsReprocess={markNeedsReprocess} />} />
|
||||
|
||||
@ -1,37 +1,10 @@
|
||||
import { Fragment, useMemo } from 'react'
|
||||
import { NavLink } from 'react-router-dom'
|
||||
import useTheme from '../theme.jsx'
|
||||
import { NAV } from './navItems.jsx'
|
||||
|
||||
// Same distinction the Import page makes: a source is either on a bank feed or
|
||||
// it gets CSVs uploaded to it.
|
||||
const feedIcon = (
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round">
|
||||
<path d="M4 10.5a4.5 4.5 0 0 1 4.5 4.5"/>
|
||||
<path d="M4 6a9 9 0 0 1 9 9"/>
|
||||
<circle cx="4.2" cy="14.8" r="1.2" fill="currentColor" stroke="none"/>
|
||||
</svg>
|
||||
)
|
||||
|
||||
const csvIcon = (
|
||||
<svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round">
|
||||
<path d="M4 1.5h5l3 3v10H4z"/>
|
||||
<polyline points="9,1.5 9,4.5 12,4.5"/>
|
||||
</svg>
|
||||
)
|
||||
|
||||
export default function Sidebar({ expanded, setExpanded, loginUser, onLogout, sources = [] }) {
|
||||
export default function Sidebar({ expanded, setExpanded, loginUser, onLogout }) {
|
||||
const { dark, setDark } = useTheme()
|
||||
|
||||
// Bank feeds first, then CSV sources, alphabetical within each group
|
||||
const navSources = useMemo(() => (
|
||||
sources
|
||||
.map(s => ({ ...s, isFeed: !!s.config?.simplefin?.account_id }))
|
||||
.sort((a, b) =>
|
||||
(b.isFeed - a.isFeed) || a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
|
||||
)
|
||||
), [sources])
|
||||
|
||||
return (
|
||||
<div
|
||||
className="bg-surface border-r border-line flex flex-col shrink-0 overflow-hidden transition-all duration-150"
|
||||
@ -59,52 +32,28 @@ export default function Sidebar({ expanded, setExpanded, loginUser, onLogout, so
|
||||
</div>
|
||||
|
||||
{/* Nav */}
|
||||
<nav className="flex flex-col gap-0.5 p-2 flex-1 overflow-y-auto">
|
||||
<nav className="flex flex-col gap-0.5 p-2 flex-1">
|
||||
{NAV.map(({ to, label, icon }) => (
|
||||
<Fragment key={to}>
|
||||
<NavLink
|
||||
to={to}
|
||||
end={to === '/sources'}
|
||||
title={!expanded ? label : undefined}
|
||||
className={({ isActive }) =>
|
||||
`flex items-center gap-3 px-2 py-2 rounded w-full transition-colors ${
|
||||
isActive
|
||||
? 'bg-accent-soft text-accent'
|
||||
: 'text-muted hover:bg-raised hover:text-ink'
|
||||
}`
|
||||
}
|
||||
<NavLink
|
||||
key={to}
|
||||
to={to}
|
||||
title={!expanded ? label : undefined}
|
||||
className={({ isActive }) =>
|
||||
`flex items-center gap-3 px-2 py-2 rounded w-full transition-colors ${
|
||||
isActive
|
||||
? 'bg-accent-soft text-accent'
|
||||
: 'text-muted hover:bg-raised hover:text-ink'
|
||||
}`
|
||||
}
|
||||
>
|
||||
<span className="shrink-0">{icon}</span>
|
||||
<span
|
||||
className="text-sm whitespace-nowrap transition-opacity duration-100"
|
||||
style={{ opacity: expanded ? 1 : 0, pointerEvents: expanded ? 'auto' : 'none', width: expanded ? 'auto' : 0, overflow: 'hidden' }}
|
||||
>
|
||||
<span className="shrink-0">{icon}</span>
|
||||
<span
|
||||
className="text-sm whitespace-nowrap transition-opacity duration-100"
|
||||
style={{ opacity: expanded ? 1 : 0, pointerEvents: expanded ? 'auto' : 'none', width: expanded ? 'auto' : 0, overflow: 'hidden' }}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</NavLink>
|
||||
|
||||
{/* Jump straight to a source. Collapsed there is no room for names,
|
||||
so the shortcut list only exists when the sidebar is open. */}
|
||||
{to === '/sources' && expanded && navSources.map(({ isFeed, ...s }) => {
|
||||
return (
|
||||
<NavLink
|
||||
key={s.name}
|
||||
to={`/sources/${encodeURIComponent(s.name)}`}
|
||||
title={`${s.name} — ${isFeed ? 'bank feed' : 'CSV'}`}
|
||||
className={({ isActive }) =>
|
||||
`flex items-center gap-2 ml-4 pl-2 pr-2 py-1 rounded border-l border-line-soft transition-colors ${
|
||||
isActive
|
||||
? 'bg-accent-soft text-accent'
|
||||
: 'text-muted hover:bg-raised hover:text-ink'
|
||||
}`
|
||||
}
|
||||
>
|
||||
<span className="shrink-0 opacity-70">{isFeed ? feedIcon : csvIcon}</span>
|
||||
<span className="text-xs truncate">{s.name}</span>
|
||||
</NavLink>
|
||||
)
|
||||
})}
|
||||
</Fragment>
|
||||
{label}
|
||||
</span>
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
|
||||
@ -2,15 +2,13 @@ import { NavLink, Outlet, useParams, Link } from 'react-router-dom'
|
||||
|
||||
// Everything scoped to one source lives under /sources/:name, so the source is
|
||||
// in the URL rather than in a global selector.
|
||||
// Records is the tab you want nine times out of ten, so it leads and is what
|
||||
// /sources/:name redirects to; Setup is the rare one and sits at the end.
|
||||
const TABS = [
|
||||
{ to: 'records', label: 'Records' },
|
||||
{ to: '', label: 'Setup', end: true },
|
||||
{ to: 'import', label: 'Import' },
|
||||
{ to: 'rules', label: 'Rules' },
|
||||
{ to: 'mappings', label: 'Mappings' },
|
||||
{ to: 'records', label: 'Records' },
|
||||
{ to: 'pivot', label: 'Pivot' },
|
||||
{ to: 'setup', label: 'Setup' },
|
||||
]
|
||||
|
||||
export default function SourceTabs({ sources }) {
|
||||
|
||||
@ -63,14 +63,14 @@ function AutocompleteInput({ value, onChange, onEnter, suggestions = [], classNa
|
||||
|
||||
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
|
||||
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
|
||||
const GRID_HIDDEN_COLS = new Set(['df_overridden'])
|
||||
const GRID_HIDDEN_COLS = new Set(['_overridden'])
|
||||
|
||||
// id first, then the rest in view order
|
||||
function gridCols(keys) {
|
||||
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) {
|
||||
@ -155,7 +155,7 @@ export default function Records({ source }) {
|
||||
}
|
||||
return false
|
||||
})
|
||||
setSelected(new Set(matches.map(r => r.df_id)))
|
||||
setSelected(new Set(matches.map(r => r.id)))
|
||||
}, [rowFilter, rows])
|
||||
|
||||
async function load(off, col, dir, filt) {
|
||||
@ -189,7 +189,7 @@ export default function Records({ source }) {
|
||||
|
||||
function addFilter() {
|
||||
// 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: '' }])
|
||||
}
|
||||
|
||||
@ -219,7 +219,7 @@ export default function Records({ source }) {
|
||||
setOverrideDraft({})
|
||||
setPanelMsg(null)
|
||||
|
||||
const id = row.df_id
|
||||
const id = row.id
|
||||
if (!id) {
|
||||
setPanelMsg({ text: 'No record ID — regenerate the view in Sources.', ok: false })
|
||||
return
|
||||
@ -427,9 +427,9 @@ export default function Records({ source }) {
|
||||
<input
|
||||
type="checkbox"
|
||||
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 => {
|
||||
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())
|
||||
}}
|
||||
/>
|
||||
@ -448,9 +448,9 @@ export default function Records({ source }) {
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row, i) => {
|
||||
const isOverridden = row.df_overridden
|
||||
const isRowSelected = selected.has(row.df_id)
|
||||
const isPanelSelected = selectedRow?.df_id != null && selectedRow.df_id === row.df_id
|
||||
const isOverridden = row._overridden
|
||||
const isRowSelected = selected.has(row.id)
|
||||
const isPanelSelected = selectedRow?.id != null && selectedRow.id === row.id
|
||||
return (
|
||||
<tr key={i} onClick={() => openPanel(row)}
|
||||
className={`border-t border-line-soft cursor-pointer transition-colors
|
||||
@ -462,7 +462,7 @@ export default function Records({ source }) {
|
||||
checked={isRowSelected}
|
||||
onChange={e => {
|
||||
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>
|
||||
|
||||
@ -19,21 +19,6 @@ 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('')
|
||||
@ -146,8 +131,6 @@ 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 || {}) },
|
||||
}]))
|
||||
)
|
||||
@ -190,7 +173,13 @@ 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, 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, {
|
||||
fields,
|
||||
@ -311,18 +300,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, 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
|
||||
await api.updateStack(stack.name, {
|
||||
@ -340,7 +329,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: '', 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
|
||||
try {
|
||||
const f = await api.getFields(addingSrc)
|
||||
@ -389,13 +378,25 @@ 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, 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)
|
||||
}
|
||||
|
||||
async function applyCalibration(srcName, offset) {
|
||||
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 } }))
|
||||
setCalibratingSource(null)
|
||||
onStale?.(stack.name)
|
||||
@ -514,20 +515,6 @@ function StackPanel({ stack, sources, onUpdated, onStale, onViewGenerated, onSql
|
||||
</button>
|
||||
</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>
|
||||
)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user