From da822724df3539d4e926c9628a25bbdc8bc7aefa Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Sat, 17 Oct 2026 12:06:58 -0400 Subject: [PATCH 1/2] feat(store): compute analytics on read instead of maintaining rollups project_rollup is one counter row per project, so every donation, report and roster change on a project wrote the same row and conflicted on Aurora DSQL. Drop the stored counters: the dashboard, project list, overview and pagination counts now SUM/COUNT the base tables (filtered deleted_at IS NULL), and the store's writes no longer touch either rollup table. The tables stay for now. createProject still seeds a zeroed project_rollup row, because lambdas still on the rollup code throw when a bump finds no row; a follow-up drops the tables, their functions and that insert. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- apps/backend/AGENTS.md | 8 +- apps/backend/db/testkit.ts | 94 ----- .../expenditures/services/expenditures.ts | 13 - .../lambdas/projects/controllers/dashboard.ts | 76 ++-- .../lambdas/projects/services/projects.ts | 12 +- ...lups.e2e.test.ts => analytics.e2e.test.ts} | 230 ++--------- .../test/approved-expenditures.e2e.test.ts | 3 +- .../projects/test/project-page.unit.test.ts | 4 - .../projects/test/projects.e2e.test.ts | 4 +- .../projects/test/rollup-store.e2e.test.ts | 372 ------------------ .../lambdas/reports/controllers/reports.ts | 9 +- .../lambdas/reports/test/reports.unit.test.ts | 2 - shared/store/package.json | 2 +- shared/store/src/donations.ts | 46 +-- shared/store/src/expenditures.ts | 21 +- shared/store/src/projects.ts | 53 ++- shared/store/src/reports.ts | 24 +- shared/store/src/rollups.ts | 61 --- shared/store/src/users.ts | 12 +- 20 files changed, 128 insertions(+), 920 deletions(-) rename apps/backend/lambdas/projects/test/{rollups.e2e.test.ts => analytics.e2e.test.ts} (50%) delete mode 100644 apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts delete mode 100644 shared/store/src/rollups.ts diff --git a/AGENTS.md b/AGENTS.md index 688547a4..38fd08a8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,7 +32,7 @@ BRANCH is a non-profit accounting platform (projects, donors, donations, expendi Five `file:`-linked packages dedupe code across the repo: -- **`@branch/store`** (`shared/store/`) — the lambdas' only database connection and only writer: a read-only `db` plus one named operation per write, each keeping the rollups in step. Connects to Aurora DSQL with IAM tokens when `DB_HOST` is a DSQL endpoint (production), and to plain Postgres otherwise (local dev, CI). +- **`@branch/store`** (`shared/store/`) — the lambdas' only database connection and only writer: a read-only `db` plus one named operation per write. Connects to Aurora DSQL with IAM tokens when `DB_HOST` is a DSQL endpoint (production), and to plain Postgres otherwise (local dev, CI). - **`@branch/types`** (`shared/types/`) — types only, no runtime. Exports DB row types (`DB`, `BranchUsers`, ...) + auth DTOs (`AuthContext`, `AuthenticatedUser`, `AccessLevel`, `AuthorizationCheck`). It is the **single declaration** of those DTOs: `@branch/lambda-auth` depends on this package and re-exports them, so never add a second copy anywhere. `db-types.d.ts` is **generated** from `apps/backend/db/migrations/**` by the `Schema Change Checks` workflow (or locally by `make types`) — never hand-edit it. - **`@branch/rbac`** (`shared/rbac/`) — the authorization policy, as one table of rules plus a pure `can`/`authorize`. **The lambdas and the frontend both evaluate this module**, so a disabled button and the 403 behind it cannot disagree. It is the only place a permission is defined; do not re-derive one from `isAdmin` in a component or a controller. Read `shared/rbac/README.md` — it carries the role matrix — before changing who may do what. diff --git a/apps/backend/AGENTS.md b/apps/backend/AGENTS.md index 66294c69..6ba8f1da 100644 --- a/apps/backend/AGENTS.md +++ b/apps/backend/AGENTS.md @@ -42,12 +42,12 @@ http://localhost:3000//health ## Database -- Schema built from `db/migrations/*.sql` (Postgres schema `branch`); dev/test rows in `db/seed.sql`. Tables: `users`, `projects`, `project_memberships` (roles: Director/Student), `donors`, `project_donations`, `expenditures` (status: approved/pending/denied/needs_more_info), `reports` (report_type: technical/narrative), plus the rollups `expenditure_rollup` and `project_rollup`. +- Schema built from `db/migrations/*.sql` (Postgres schema `branch`); dev/test rows in `db/seed.sql`. Tables: `users`, `projects`, `project_memberships` (roles: Director/Student), `donors`, `project_donations`, `expenditures` (status: approved/pending/denied/needs_more_info), `reports` (report_type: technical/narrative), plus the unused `expenditure_rollup` and `project_rollup` (see below). - **Production runs on Aurora DSQL** (local dev and CI run Postgres 16), so every migration must be DSQL-compatible: one DDL per file, `CREATE INDEX ${async}`, no SERIAL/triggers/PL/pgSQL/TRUNCATE, no bare `NUMERIC`. CI enforces it. See `db/README.md`. -- **Analytics reads go through the rollups, never the base tables.** `expenditure_rollup` (grain: project × month × category × status) and `project_rollup` (per project: member/donation/report counts and `total_donated`) are maintained by `@branch/store` in the same transaction as the write, so they are exact rather than eventually consistent. Spend lives **only** in `expenditure_rollup`. Increments upsert; decrements are a plain `UPDATE`, and emptied buckets stay at zero. Time-relative figures (the active-project count, "spend on active projects") cannot be rolled up and still read `projects` live. -- **`@branch/store` (`shared/store`) is the only connection and the only writer.** It exports `db` (a read-only `Kysely`) and one named operation per write, each of which maintains the rollups. Env `DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME`; a DSQL `DB_HOST` switches it to IAM-token auth with no password. Query with the `branch.` schema prefix: `db.selectFrom('branch.users')`. +- **Analytics are computed on read from the base tables** (`SUM`/`COUNT` over `expenditures`, `project_donations`, `reports`, `project_memberships`, filtered `deleted_at IS NULL`). There are no stored counters: a per-project counter row made every concurrent write to one project conflict on Aurora DSQL. `expenditure_rollup` and `project_rollup` are dead tables awaiting a drop migration; nothing reads them, and the store writes only a zeroed `project_rollup` row on `createProject`, because lambdas still on the old code fail a bump against a project with no row. +- **`@branch/store` (`shared/store`) is the only connection and the only writer.** It exports `db` (a read-only `Kysely`) and one named operation per write. Env `DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME`; a DSQL `DB_HOST` switches it to IAM-token auth with no password. Query with the `branch.` schema prefix: `db.selectFrom('branch.users')`. - **Changing the schema:** `make new-migration NAME=add_thing` → write SQL → `make migrate` (applies it and regenerates `shared/types/db-types.d.ts`). `make show-migrations` shows applied vs pending; the ledger is `branch.flyway_schema_history`. Forward-only — never edit a merged migration, and never hand-edit `db-types.d.ts`. Migrations apply to prod automatically on merge **before** the lambda deploy, so a single PR may only contain additive changes; see `db/README.md` for expand/contract. -- **Deletes are soft.** `users`, `projects`, `donors`, `project_donations`, `expenditures` and `reports` carry a nullable `deleted_at`; every `remove*` in `@branch/store` stamps it instead of deleting (a project stamps its donations, expenditures and reports with the same time; a donor its donations). `project_memberships` and both rollups are still hard-deleted, so the rollups only ever count live rows, and a user delete still clears `expenditures.entered_by` as `ON DELETE SET NULL` did. **Every read of those six tables filters `deleted_at IS NULL`** — on a `leftJoin`, in the `ON` clause, so the parent row survives with null joined fields — and `shared/store/test/soft-delete-guard.test.ts` fails a query that forgets; each lambda's `soft-delete-parity.e2e.test.ts` proves its GETs read a soft-deleted row exactly like an absent one. The store's Kysely strips `deleted_at` from every result row, so responses never carry it. Inserts under a soft-deleted parent throw a `23503`, as the FK did. That parent check is `FOR KEY SHARE`, never `FOR UPDATE`: the `*_live_key` unique index on `(id, deleted_at)` makes the stamp a key update, so a delete conflicts with in-flight inserts while inserts never conflict with each other (`projects/test/soft-delete-concurrency.e2e.test.ts`). S3 objects and the row stay; the Cognito user is still deleted. There is no restore endpoint — recover by SQL (clear `deleted_at` on the row and its same-timestamp children, then rebuild the rollups). +- **Deletes are soft.** `users`, `projects`, `donors`, `project_donations`, `expenditures` and `reports` carry a nullable `deleted_at`; every `remove*` in `@branch/store` stamps it instead of deleting (a project stamps its donations, expenditures and reports with the same time; a donor its donations). `project_memberships` is still hard-deleted, and a user delete still clears `expenditures.entered_by` as `ON DELETE SET NULL` did. **Every read of those six tables filters `deleted_at IS NULL`** — on a `leftJoin`, in the `ON` clause, so the parent row survives with null joined fields — and `shared/store/test/soft-delete-guard.test.ts` fails a query that forgets; each lambda's `soft-delete-parity.e2e.test.ts` proves its GETs read a soft-deleted row exactly like an absent one. The store's Kysely strips `deleted_at` from every result row, so responses never carry it. Inserts under a soft-deleted parent throw a `23503`, as the FK did. That parent check is `FOR KEY SHARE`, never `FOR UPDATE`: the `*_live_key` unique index on `(id, deleted_at)` makes the stamp a key update, so a delete conflicts with in-flight inserts while inserts never conflict with each other (`projects/test/soft-delete-concurrency.e2e.test.ts`). S3 objects and the row stay; the Cognito user is still deleted. There is no restore endpoint — recover by SQL (clear `deleted_at` on the row and its same-timestamp children, and re-add the memberships). - The migration runner is Flyway over plain `.sql` files, configured once in `db/flyway.sh`; `db/src/` holds seeding, the schema rebuild and type generation. Root `package.json` still carries NestJS/TypeORM **dependencies** from the original scaffold, but nothing uses them; its dead `migration:*` scripts have been removed. ## Shared packages diff --git a/apps/backend/db/testkit.ts b/apps/backend/db/testkit.ts index b142a47c..e7dfbbda 100644 --- a/apps/backend/db/testkit.ts +++ b/apps/backend/db/testkit.ts @@ -228,35 +228,8 @@ export async function resetData(client: Queryable): Promise { await client.query(await truncateAll(client)); await client.query(RESTART_SEQUENCES); await client.query(seedSql()); - await reconcileRollups(client); } -const EXPECTED_EXPENDITURE_ROLLUP = ` - SELECT project_id, - date_trunc('month', spent_on)::date AS month, - category, - status, - SUM(amount) AS total_amount, - COUNT(*)::int AS expenditure_count - FROM ${SCHEMA}.expenditures - WHERE deleted_at IS NULL - GROUP BY project_id, date_trunc('month', spent_on)::date, category, status`; - -const EXPECTED_PROJECT_ROLLUP = ` - SELECT p.project_id, - COALESCE(m.c, 0) AS member_count, - COALESCE(d.total, 0) AS total_donated, - COALESCE(d.c, 0) AS donation_count, - COALESCE(r.c, 0) AS report_count - FROM ${SCHEMA}.projects p - LEFT JOIN (SELECT project_id, COUNT(*) AS c FROM ${SCHEMA}.project_memberships GROUP BY project_id) m - ON m.project_id = p.project_id - LEFT JOIN (SELECT project_id, COUNT(*) AS c, SUM(amount) AS total FROM ${SCHEMA}.project_donations WHERE deleted_at IS NULL GROUP BY project_id) d - ON d.project_id = p.project_id - LEFT JOIN (SELECT project_id, COUNT(*) AS c FROM ${SCHEMA}.reports WHERE deleted_at IS NULL GROUP BY project_id) r - ON r.project_id = p.project_id - WHERE p.deleted_at IS NULL`; - export async function purgeSoftDeleted(client: Queryable): Promise { for (const table of ['expenditures', 'reports', 'project_donations', 'donors', 'projects', 'users']) { await client.query(`DELETE FROM ${SCHEMA}.${table} WHERE deleted_at IS NOT NULL`); @@ -272,73 +245,6 @@ export const PARITY_DELETES = { user: 5, } as const; -// A zero-count expenditure_rollup row equals a missing one: _remove decrements without deleting. -export async function findRollupDrift(client: Queryable): Promise { - const expenditures = await client.query(` - WITH expected AS (${EXPECTED_EXPENDITURE_ROLLUP}) - SELECT 'expenditure_rollup project=' || COALESCE(e.project_id, a.project_id) - || ' month=' || COALESCE(e.month, a.month) - || ' status=' || COALESCE(e.status, a.status) - || ' category=' || COALESCE(e.category, a.category, '') - || ' expected=' || COALESCE(e.total_amount, 0) || '/' || COALESCE(e.expenditure_count, 0) - || ' actual=' || COALESCE(a.total_amount, 0) || '/' || COALESCE(a.expenditure_count, 0) AS drift - FROM expected e - FULL OUTER JOIN ${SCHEMA}.expenditure_rollup a - ON a.project_id = e.project_id - AND a.month = e.month - AND a.status = e.status - AND (a.category IS NULL) = (e.category IS NULL) - AND COALESCE(a.category, '') = COALESCE(e.category, '') - WHERE COALESCE(a.expenditure_count, 0) <> COALESCE(e.expenditure_count, 0) - OR COALESCE(a.total_amount, 0) <> COALESCE(e.total_amount, 0)`); - - const projects = await client.query(` - WITH expected AS (${EXPECTED_PROJECT_ROLLUP}) - SELECT 'project_rollup project=' || e.project_id - || ' expected=' || e.member_count || '/' || e.total_donated || '/' || e.donation_count || '/' || e.report_count - || ' actual=' || COALESCE(a.member_count::text, 'ROW MISSING') - || '/' || COALESCE(a.total_donated::text, '-') - || '/' || COALESCE(a.donation_count::text, '-') - || '/' || COALESCE(a.report_count::text, '-') AS drift - FROM expected e - LEFT JOIN ${SCHEMA}.project_rollup a ON a.project_id = e.project_id - WHERE a.project_id IS NULL - OR a.member_count <> e.member_count - OR a.total_donated <> e.total_donated - OR a.donation_count <> e.donation_count - OR a.report_count <> e.report_count`); - - return [...(expenditures.rows ?? []), ...(projects.rows ?? [])].map( - (row) => row.drift as string, - ); -} - -export async function assertRollupsConsistent(client: Queryable): Promise { - const drift = await findRollupDrift(client); - if (drift.length > 0) { - throw new Error( - `rollups disagree with the base tables:\n ${drift.join('\n ')}`, - ); - } -} - -export async function reconcileRollups(client: Queryable): Promise { - await client.query(`DELETE FROM ${SCHEMA}.expenditure_rollup`); - await client.query( - `INSERT INTO ${SCHEMA}.expenditure_rollup - (project_id, month, category, status, total_amount, expenditure_count) - SELECT project_id, month, category, status, total_amount, expenditure_count - FROM (${EXPECTED_EXPENDITURE_ROLLUP}) AS expected`, - ); - await client.query(`DELETE FROM ${SCHEMA}.project_rollup`); - await client.query( - `INSERT INTO ${SCHEMA}.project_rollup - (project_id, member_count, total_donated, donation_count, report_count) - SELECT project_id, member_count, total_donated, donation_count, report_count - FROM (${EXPECTED_PROJECT_ROLLUP}) AS expected`, - ); -} - /** * Seeds only a database that has never been seeded, so `make up` does not wipe a * locally registered account (or a `make grant-admin` promotion) on restart. diff --git a/apps/backend/lambdas/expenditures/services/expenditures.ts b/apps/backend/lambdas/expenditures/services/expenditures.ts index 82df0ddf..97b9b5e4 100644 --- a/apps/backend/lambdas/expenditures/services/expenditures.ts +++ b/apps/backend/lambdas/expenditures/services/expenditures.ts @@ -32,19 +32,6 @@ export function receiptKeyForProject(objectUrl: string, projectId: number): stri } export async function countExpenditures(projectId: number | null, scope: ExpenditureScope): Promise { - // Only the unscoped count can come from the rollup. A scoped one is - // `project_id IN (...) OR entered_by = me`, and entered_by is not in the - // grain, so summing buckets would double-count rows matching both arms. - if (scope.projectIds === null) { - let rollup = db - .selectFrom('branch.expenditure_rollup') - .select(db.fn.sum('expenditure_count').as('count')); - if (projectId !== null) rollup = rollup.where('project_id', '=', projectId); - const rolledUp = await rollup.executeTakeFirst(); - - return Number(rolledUp?.count || 0); - } - let query = db .selectFrom('branch.expenditures') .where('deleted_at', 'is', null) diff --git a/apps/backend/lambdas/projects/controllers/dashboard.ts b/apps/backend/lambdas/projects/controllers/dashboard.ts index e2f60d62..4b21a3e2 100644 --- a/apps/backend/lambdas/projects/controllers/dashboard.ts +++ b/apps/backend/lambdas/projects/controllers/dashboard.ts @@ -19,7 +19,6 @@ export const getDashboard: RouteHandler = async () => { const now = new Date(); const year = now.getUTCFullYear(); const yearStart = `${year}-01-01`; - // Half-open: the rollup's month column is the first of the month. const nextYearStart = `${year + 1}-01-01`; const today = now.toISOString().slice(0, 10); @@ -29,8 +28,7 @@ export const getDashboard: RouteHandler = async () => { const isActive = (column: any) => (eb: any) => eb.or([eb(column, 'is', null), eb(column, '>=', today as any)]); - // The rollup stores the month; this only formats it. - const monthExpr = sql`to_char(month, 'YYYY-MM')`; + const monthExpr = sql`to_char(spent_on, 'YYYY-MM')`; const [ totalSpentRow, @@ -40,71 +38,81 @@ export const getDashboard: RouteHandler = async () => { projectRows, monthRows, ] = await Promise.all([ - db.selectFrom('branch.expenditure_rollup') - .select(db.fn.sum('total_amount').as('total')) + db.selectFrom('branch.expenditures') + .select(db.fn.sum('amount').as('total')) + .where('deleted_at', 'is', null) .where('status', '=', APPROVED_EXPENDITURE_STATUS) - .where('month', '>=', yearStart as any) - .where('month', '<', nextYearStart as any) + .where('spent_on', '>=', yearStart as any) + .where('spent_on', '<', nextYearStart as any) .executeTakeFirst(), - // Not a rollup: "active" changes with the clock, not with a write. db.selectFrom('branch.projects') .select(db.fn.count('project_id').as('count')) .where('deleted_at', 'is', null) .where(isActive('end_date')) .executeTakeFirst(), - db.selectFrom('branch.expenditure_rollup') - .select(['category', db.fn.sum('total_amount').as('total')]) + db.selectFrom('branch.expenditures') + .select(['category', db.fn.sum('amount').as('total')]) + .where('deleted_at', 'is', null) .where('status', '=', APPROVED_EXPENDITURE_STATUS) .where('category', 'is not', null) - .where('month', '>=', yearStart as any) - .where('month', '<', nextYearStart as any) + .where('spent_on', '>=', yearStart as any) + .where('spent_on', '<', nextYearStart as any) .groupBy('category') - .orderBy(db.fn.sum('total_amount'), 'desc') + .orderBy(db.fn.sum('amount'), 'desc') .limit(1) .executeTakeFirst(), // Numerator for the average: this year's spend on the very projects the // denominator counts. - db.selectFrom('branch.expenditure_rollup as er') - .innerJoin('branch.projects as p', 'p.project_id', 'er.project_id') - .select((eb) => eb.fn.sum('er.total_amount').as('total')) - .where('er.status', '=', APPROVED_EXPENDITURE_STATUS) - .where('er.month', '>=', yearStart as any) - .where('er.month', '<', nextYearStart as any) + db.selectFrom('branch.expenditures as e') + .innerJoin('branch.projects as p', 'p.project_id', 'e.project_id') + .select((eb) => eb.fn.sum('e.amount').as('total')) + .where('e.deleted_at', 'is', null) + .where('e.status', '=', APPROVED_EXPENDITURE_STATUS) + .where('e.spent_on', '>=', yearStart as any) + .where('e.spent_on', '<', nextYearStart as any) .where('p.deleted_at', 'is', null) .where(isActive('p.end_date')) .executeTakeFirst(), - // Spend stays a pre-aggregated subquery: the rollup is per - // (month, category) and must collapse to one row per project before it - // joins, or each project row multiplies by its bucket count. + // Both aggregate before joining, or each project row multiplies by the other's row count. db.selectFrom('branch.projects as p') .leftJoin( (eb) => - eb.selectFrom('branch.expenditure_rollup') + eb.selectFrom('branch.expenditures') .select('project_id') - .select((sub) => sub.fn.sum('total_amount').as('total')) + .select((sub) => sub.fn.sum('amount').as('total')) + .where('deleted_at', 'is', null) .where('status', '=', APPROVED_EXPENDITURE_STATUS) .groupBy('project_id') .as('spend'), (join) => join.onRef('spend.project_id', '=', 'p.project_id'), ) - .leftJoin('branch.project_rollup as pr', 'pr.project_id', 'p.project_id') + .leftJoin( + (eb) => + eb.selectFrom('branch.project_memberships') + .select('project_id') + .select((sub) => sub.fn.countAll().as('count')) + .groupBy('project_id') + .as('staff'), + (join) => join.onRef('staff.project_id', '=', 'p.project_id'), + ) .select([ 'p.project_id', 'p.name', 'p.total_budget', 'p.currency', 'spend.total as spent', - 'pr.member_count as staff_count', + 'staff.count as staff_count', ]) .where('p.deleted_at', 'is', null) .orderBy('p.project_id', 'asc') .execute(), - db.selectFrom('branch.expenditure_rollup') - .select([monthExpr.as('month'), 'category', db.fn.sum('total_amount').as('total')]) + db.selectFrom('branch.expenditures') + .select([monthExpr.as('month'), 'category', db.fn.sum('amount').as('total')]) + .where('deleted_at', 'is', null) .where('status', '=', APPROVED_EXPENDITURE_STATUS) .where('category', 'is not', null) - .where('month', '>=', yearStart as any) - .where('month', '<', nextYearStart as any) + .where('spent_on', '>=', yearStart as any) + .where('spent_on', '<', nextYearStart as any) .groupBy([monthExpr, 'category']) .orderBy(monthExpr) .orderBy('category') @@ -202,16 +210,16 @@ export const getOverview: RouteHandler = async (ctx) => { .orderBy('spent_on', 'desc') .execute(), db - .selectFrom('branch.project_rollup') - .select('total_donated') + .selectFrom('branch.project_donations') + .select(db.fn.sum('amount').as('total_donated')) .where('project_id', '=', id) + .where('deleted_at', 'is', null) .executeTakeFirst(), ]); if (!project) return json(404, { message: `Project not found for id: ${id}` }); const totalBudget = project.total_budget !== null ? Number(project.total_budget) : 0; - // Summed in JS, not from the rollup: the table renders every row anyway, so - // the reduce is free and the total cannot disagree with the list. + // Summed in JS: the table renders every row anyway, so the total cannot disagree with the list. // The list includes rows still in review; the stats count only approved ones. const approved = expenditures.filter((e) => e.status === APPROVED_EXPENDITURE_STATUS); const totalSpent = approved.reduce((sum, e) => sum + Number(e.amount), 0); diff --git a/apps/backend/lambdas/projects/services/projects.ts b/apps/backend/lambdas/projects/services/projects.ts index 1d9d5f27..a80b159d 100644 --- a/apps/backend/lambdas/projects/services/projects.ts +++ b/apps/backend/lambdas/projects/services/projects.ts @@ -33,7 +33,7 @@ export function indexByProject( return new Map(rows.map((row) => [row.project_id, pick(row)])); } -/** Per-project spend and headcount, read from the trigger-maintained rollups. */ +/** Per-project approved spend and headcount. */ export async function loadProjectAggregates(projectIds: number[]): Promise<{ spent: Map; members: Map; @@ -42,16 +42,18 @@ export async function loadProjectAggregates(projectIds: number[]): Promise<{ const [spentRows, memberRows] = await Promise.all([ db - .selectFrom('branch.expenditure_rollup') - .select(['project_id', db.fn.sum('total_amount').as('total')]) + .selectFrom('branch.expenditures') + .select(['project_id', db.fn.sum('amount').as('total')]) + .where('deleted_at', 'is', null) .where('status', '=', APPROVED_EXPENDITURE_STATUS) .where('project_id', 'in', projectIds) .groupBy('project_id') .execute(), db - .selectFrom('branch.project_rollup') - .select(['project_id', 'member_count']) + .selectFrom('branch.project_memberships') + .select(['project_id', db.fn.countAll().as('member_count')]) .where('project_id', 'in', projectIds) + .groupBy('project_id') .execute(), ]); diff --git a/apps/backend/lambdas/projects/test/rollups.e2e.test.ts b/apps/backend/lambdas/projects/test/analytics.e2e.test.ts similarity index 50% rename from apps/backend/lambdas/projects/test/rollups.e2e.test.ts rename to apps/backend/lambdas/projects/test/analytics.e2e.test.ts index aab86e1b..953f6b93 100644 --- a/apps/backend/lambdas/projects/test/rollups.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/analytics.e2e.test.ts @@ -1,11 +1,6 @@ -/** - * The rollups must be exact, not eventually correct. `auditRollups` re-derives - * every rollup figure from the base tables; each test mutates in one shape and - * audits, so a regression names the trigger path that broke. - */ import { describe, test, expect, beforeAll, beforeEach, afterEach, afterAll, jest } from '@jest/globals'; import { Pool, PoolClient } from 'pg'; -import { ensureSchema, resetData, reconcileRollups } from '../../../db/testkit'; +import { ensureSchema, resetData } from '../../../db/testkit'; jest.mock('../auth', () => { const { createAuthResolver } = jest.requireActual( @@ -30,16 +25,13 @@ import { handler } from '../handler'; import { closeConnection, createProject, - db, editExpenditure, recordDonation, recordExpenditure, - recordReport, removeDonation, removeDonor, removeExpenditure, removeProject, - removeReport, updateProject, } from '@branch/store'; import { authenticateRequest } from '../auth'; @@ -60,59 +52,6 @@ const pool = new Pool({ ssl: false, }); -/** - * Every rollup figure, re-derived from the base tables. category is COALESCE'd - * into the join key because a FULL JOIN cannot use IS NOT DISTINCT FROM and - * USING(category) would never match NULL to NULL. - */ -async function auditRollups(client: PoolClient): Promise { - const expenditures = await client.query(` - SELECT er.project_id, er.month, er.cat_key, er.status, - er.total_amount AS rollup_amount, live.total_amount AS live_amount, - er.expenditure_count AS rollup_count, live.expenditure_count AS live_count - FROM ( - SELECT project_id, month, COALESCE(category, '') AS cat_key, status, - total_amount, expenditure_count - FROM branch.expenditure_rollup - WHERE expenditure_count <> 0 - ) er - FULL OUTER JOIN ( - SELECT project_id, date_trunc('month', spent_on)::date AS month, - COALESCE(category, '') AS cat_key, status, - SUM(amount) AS total_amount, COUNT(*)::int AS expenditure_count - FROM branch.expenditures - WHERE deleted_at IS NULL - GROUP BY 1, 2, 3, 4 - ) live USING (project_id, month, cat_key, status) - WHERE er.total_amount IS DISTINCT FROM live.total_amount - OR er.expenditure_count IS DISTINCT FROM live.expenditure_count - `); - expect(expenditures.rows).toEqual([]); - - const projects = await client.query(` - SELECT pr.project_id, - pr.member_count, live.member_count AS live_member_count, - pr.total_donated, live.total_donated AS live_total_donated, - pr.donation_count, live.donation_count AS live_donation_count, - pr.report_count, live.report_count AS live_report_count - FROM branch.project_rollup pr - FULL OUTER JOIN ( - SELECT p.project_id, - (SELECT count(*) FROM branch.project_memberships m WHERE m.project_id = p.project_id) AS member_count, - (SELECT COALESCE(SUM(amount), 0) FROM branch.project_donations d WHERE d.project_id = p.project_id AND d.deleted_at IS NULL) AS total_donated, - (SELECT count(*) FROM branch.project_donations d WHERE d.project_id = p.project_id AND d.deleted_at IS NULL) AS donation_count, - (SELECT count(*) FROM branch.reports r WHERE r.project_id = p.project_id AND r.deleted_at IS NULL) AS report_count - FROM branch.projects p - WHERE p.deleted_at IS NULL - ) live USING (project_id) - WHERE pr.member_count IS DISTINCT FROM live.member_count - OR pr.total_donated IS DISTINCT FROM live.total_donated - OR pr.donation_count IS DISTINCT FROM live.donation_count - OR pr.report_count IS DISTINCT FROM live.report_count - `); - expect(projects.rows).toEqual([]); -} - let client: PoolClient; beforeAll(async () => { @@ -138,7 +77,6 @@ beforeEach(async () => { await client.query('DELETE FROM branch.expenditures'); await client.query('DELETE FROM branch.project_donations'); await client.query('DELETE FROM branch.reports'); - await reconcileRollups(client); }); afterEach(() => { @@ -161,24 +99,8 @@ async function get(rawPath: string) { return JSON.parse(res.body); } -/** Live buckets for one project. Emptied buckets stay at zero, so exclude them. */ -async function bucketsFor(projectId: number): Promise { - const { rows } = await client.query( - `SELECT count(*)::int AS n FROM branch.expenditure_rollup - WHERE project_id = $1 AND expenditure_count <> 0`, - [projectId], - ); - return rows[0].n; -} - const today = new Date().toISOString().slice(0, 10); -function monthsAgo(n: number): string { - const d = new Date(); - d.setMonth(d.getMonth() - n); - return d.toISOString().slice(0, 10); -} - const travel = { project_id: 1, entered_by: 1, @@ -188,178 +110,97 @@ const travel = { spent_on: today, }; -describe('reset', () => { - test('resetData leaves both rollups in step with the base tables', async () => { - await resetData(client); - await auditRollups(client); - }); -}); - describe('expenditure spend reaches the dashboard', () => { - test('recordExpenditure lands in a bucket and reaches the dashboard', async () => { + test('a recorded expenditure counts', async () => { await recordExpenditure(travel); - await auditRollups(client); - - const body = await get('/dashboard'); - expect(body.summary.totalSpent).toBe(250); + expect((await get('/dashboard')).summary.totalSpent).toBe(250); }); - test('unapproved rows are rolled up but stay out of every spend figure', async () => { + test('unapproved rows stay out of every spend figure', async () => { await recordExpenditure(travel); await recordExpenditure({ ...travel, amount: 900, status: 'pending' }); - await auditRollups(client); - - expect(await bucketsFor(1)).toBe(2); - const body = await get('/dashboard'); - expect(body.summary.totalSpent).toBe(250); - }); - - test('two NULL-category rows share one bucket', async () => { - await recordExpenditure({ ...travel, amount: 50, category: null, spent_on: '2026-03-11' }); - await recordExpenditure({ ...travel, amount: 25, category: null, spent_on: '2026-03-12' }); - await auditRollups(client); - - const { rows } = await client.query(` - SELECT total_amount, expenditure_count FROM branch.expenditure_rollup - WHERE project_id = 1 AND category IS NULL AND month = DATE '2026-03-01' - `); - expect(rows).toHaveLength(1); - expect(Number(rows[0].total_amount)).toBe(75); - expect(rows[0].expenditure_count).toBe(2); + expect((await get('/dashboard')).summary.totalSpent).toBe(250); }); - test('editing the amount alone stays in the same bucket', async () => { + test('an edited amount replaces the old one', async () => { const row = await recordExpenditure(travel); await editExpenditure(row.expenditure_id, { amount: 400 }); - await auditRollups(client); - - expect(await bucketsFor(1)).toBe(1); - const body = await get('/dashboard'); - expect(body.summary.totalSpent).toBe(400); - }); - - test.each([ - ['category', { category: 'Equipment' }], - ['month', { spent_on: monthsAgo(2) }], - ['status', { status: 'denied' }], - ])('an edit crossing %s decrements the old bucket and increments the new', async (_label, patch) => { - const row = await recordExpenditure(travel); - await editExpenditure(row.expenditure_id, patch as Record); - await auditRollups(client); + expect((await get('/dashboard')).summary.totalSpent).toBe(400); }); test('a status change moves spend off the dashboard', async () => { const row = await recordExpenditure(travel); await editExpenditure(row.expenditure_id, { status: 'denied' }); - await auditRollups(client); - - const body = await get('/dashboard'); - expect(body.summary.totalSpent).toBe(0); + expect((await get('/dashboard')).summary.totalSpent).toBe(0); }); - test('removeExpenditure decrements the bucket', async () => { + test('a removed expenditure stops counting', async () => { await recordExpenditure(travel); const second = await recordExpenditure({ ...travel, amount: 100 }); await removeExpenditure(second.expenditure_id); - await auditRollups(client); - - const body = await get('/dashboard'); - expect(body.summary.totalSpent).toBe(250); + expect((await get('/dashboard')).summary.totalSpent).toBe(250); }); - test('deleting a project cascades without orphaning or resurrecting a bucket', async () => { + test("a deleted project's spend leaves the dashboard", async () => { await recordExpenditure({ ...travel, project_id: 4 }); - await recordReport({ project_id: 4, title: 'r', object_url: 's3://r', report_type: 'technical' }); await removeProject(4); - await auditRollups(client); - - const orphans = await client.query(` - SELECT (SELECT count(*)::int FROM branch.expenditure_rollup er - LEFT JOIN branch.projects p ON p.project_id = er.project_id AND p.deleted_at IS NULL - WHERE p.project_id IS NULL) AS exp_orphans, - (SELECT count(*)::int FROM branch.project_rollup pr - LEFT JOIN branch.projects p ON p.project_id = pr.project_id AND p.deleted_at IS NULL - WHERE p.project_id IS NULL) AS proj_orphans - `); - expect(orphans.rows[0]).toEqual({ exp_orphans: 0, proj_orphans: 0 }); - const kept = await client.query(` - SELECT (SELECT count(*)::int FROM branch.expenditures - WHERE project_id = 4 AND deleted_at IS NOT NULL) AS expenditures, - (SELECT count(*)::int FROM branch.reports - WHERE project_id = 4 AND deleted_at IS NOT NULL) AS reports - `); - expect(kept.rows[0]).toEqual({ expenditures: 1, reports: 1 }); + const body = await get('/dashboard'); + expect(body.summary.totalSpent).toBe(0); + expect(body.projects.some((p: any) => p.project_id === 4)).toBe(false); }); }); describe('project overview figures', () => { - test('createProject seeds a zeroed rollup row', async () => { + test('a new project reads zero everywhere', async () => { const created = await createProject( { name: 'fresh', description: 'x', total_budget: 500, currency: 'USD' }, [], 'Student', ); - await auditRollups(client); - - const rollup = await client.query( - 'SELECT * FROM branch.project_rollup WHERE project_id = $1', - [created.project_id], - ); - expect(rollup.rows).toHaveLength(1); - expect(rollup.rows[0].member_count).toBe(0); - expect(Number(rollup.rows[0].total_donated)).toBe(0); + const body = await get(`/${created.project_id}/overview`); + expect(body.stats.totalDonated).toBe(0); + expect(body.stats.totalSpent).toBe(0); }); test('donations move totalDonated on the project overview', async () => { const donation = await recordDonation({ donor_id: 1, project_id: 1, amount: 500 }); - await auditRollups(client); expect((await get('/1/overview')).stats.totalDonated).toBe(500); await removeDonation(donation.donation_id); - await auditRollups(client); expect((await get('/1/overview')).stats.totalDonated).toBe(0); }); test('deleting a donor takes its donations off the overview', async () => { await recordDonation({ donor_id: 1, project_id: 1, amount: 500 }); - await auditRollups(client); await removeDonor(1); - await auditRollups(client); expect((await get('/1/overview')).stats.totalDonated).toBe(0); }); - test('roster replacement keeps member_count exact through delete-then-insert', async () => { - await updateProject(1, {}, [{ user_id: 1 }, { user_id: 2 }], 'Student'); - await auditRollups(client); + test('adding a non-admin member raises dashboard staff_count by one', async () => { + const staffCount = async () => + (await get('/dashboard')).projects.find((p: any) => p.project_id === 1).staff_count; + const before = await staffCount(); - const { rows } = await client.query( - 'SELECT member_count FROM branch.project_rollup WHERE project_id = 1', + const { rows: added } = await client.query( + `INSERT INTO branch.users (email, name, is_admin) VALUES ('newmember@branch.org', 'New Member', false) + RETURNING user_id`, ); - expect(rows[0].member_count).toBe(2); - }); - - test('reports move report_count', async () => { - await recordReport({ project_id: 1, title: 'a', object_url: 's3://a', report_type: 'technical' }); - const b = await recordReport({ - project_id: 1, - title: 'b', - object_url: 's3://b', - report_type: 'narrative', - }); - await auditRollups(client); - - const { rows } = await client.query( - 'SELECT report_count FROM branch.project_rollup WHERE project_id = 1', + const { rows: current } = await client.query( + 'SELECT user_id FROM branch.project_memberships WHERE project_id = 1', + ); + await updateProject( + 1, + {}, + [...current.map((r) => ({ user_id: r.user_id })), { user_id: added[0].user_id }], + 'Student', ); - expect(rows[0].report_count).toBe(2); - await removeReport(b.report_id); - await auditRollups(client); + expect(await staffCount()).toBe(before + 1); }); }); -describe('rollup-backed read paths agree with the base tables', () => { +describe('read paths agree with the base tables', () => { beforeEach(async () => { // Spread across months, categories, statuses and projects. await client.query(` @@ -371,7 +212,6 @@ describe('rollup-backed read paths agree with the base tables', () => { (2, 1, 500, 'Travel', 'approved', date_trunc('year', CURRENT_DATE)), (2, 1, 50, NULL, 'approved', date_trunc('year', CURRENT_DATE)) `); - await reconcileRollups(client); }); test('dashboard totalSpent equals the approved sum for the year', async () => { diff --git a/apps/backend/lambdas/projects/test/approved-expenditures.e2e.test.ts b/apps/backend/lambdas/projects/test/approved-expenditures.e2e.test.ts index f56688fe..1fa5cf32 100644 --- a/apps/backend/lambdas/projects/test/approved-expenditures.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/approved-expenditures.e2e.test.ts @@ -9,7 +9,7 @@ */ import { describe, test, expect, beforeAll, beforeEach, afterAll, jest } from '@jest/globals'; import { Pool } from 'pg'; -import { ensureSchema, resetData, reconcileRollups } from '../../../db/testkit'; +import { ensureSchema, resetData } from '../../../db/testkit'; jest.mock('../auth', () => { // dispatch() resolves the caller through resolveAuth, so an auto-mock would @@ -83,7 +83,6 @@ beforeEach(async () => { (1, 1, 1000, 'Travel', 'needs info', 'needs_more_info', CURRENT_DATE) `); await client.query(`UPDATE branch.projects SET end_date = '2099-12-31' WHERE end_date IS NOT NULL`); - await reconcileRollups(client); } finally { client.release(); } diff --git a/apps/backend/lambdas/projects/test/project-page.unit.test.ts b/apps/backend/lambdas/projects/test/project-page.unit.test.ts index 2855339f..adf29942 100644 --- a/apps/backend/lambdas/projects/test/project-page.unit.test.ts +++ b/apps/backend/lambdas/projects/test/project-page.unit.test.ts @@ -256,10 +256,6 @@ test('PUT keeps hours and start dates of members who stay on the roster', async ); expect(after.rows.map((r) => r.user_id)).toEqual([4, 6]); expect(after.rows[0]).toEqual(before.rows[0]); - const rollup = await pool.query( - `SELECT member_count FROM branch.project_rollup WHERE project_id = 1`, - ); - expect(rollup.rows[0].member_count).toBe(2); }); test('PUT without a members key leaves the roster alone', async () => { diff --git a/apps/backend/lambdas/projects/test/projects.e2e.test.ts b/apps/backend/lambdas/projects/test/projects.e2e.test.ts index ea6ce51f..0600ef58 100644 --- a/apps/backend/lambdas/projects/test/projects.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/projects.e2e.test.ts @@ -1,6 +1,6 @@ import { describe, test, expect, beforeAll, beforeEach, afterAll, jest } from '@jest/globals'; import { Pool } from 'pg'; -import { ensureSchema, resetData, reconcileRollups } from '../../../db/testkit'; +import { ensureSchema, resetData } from '../../../db/testkit'; jest.mock('../auth', () => { // dispatch() resolves the caller through resolveAuth, so an auto-mock would @@ -147,7 +147,6 @@ describe('Authorization', () => { `INSERT INTO branch.project_memberships (project_id, user_id, role, start_date, hours) SELECT 1, user_id, 'Director', '2025-01-01', 10 FROM branch.users WHERE email = 'directormember@branch.org'`, ); - await reconcileRollups(client); } finally { client.release(); } @@ -428,7 +427,6 @@ describe('GET /dashboard (e2e)', () => { EXTRACT(DAY FROM spent_on)::int ) `); - await reconcileRollups(client); } finally { client.release(); } diff --git a/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts b/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts deleted file mode 100644 index fec414ac..00000000 --- a/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts +++ /dev/null @@ -1,372 +0,0 @@ -import { describe, test, expect, beforeAll, beforeEach, afterEach, afterAll } from '@jest/globals'; -import { Pool, PoolClient } from 'pg'; -import { ensureSchema, resetData, reconcileRollups } from '../../../db/testkit'; -import { - closeConnection, - createProject, - editExpenditure, - recordDonation, - recordExpenditure, - recordReport, - removeDonation, - removeDonor, - removeExpenditure, - removeProject, - removeReport, - removeUser, - updateProject, -} from '@branch/store'; - -const pool = new Pool({ - host: 'localhost', - port: Number(process.env.DB_PORT ?? 5432), - user: 'branch_dev', - password: 'password', - database: 'branch_db', - ssl: false, -}); - -/** - * category is COALESCE'd into the join key because a FULL JOIN cannot use - * IS NOT DISTINCT FROM and USING(category) would never match NULL to NULL. - */ -async function auditRollups(client: PoolClient): Promise { - const expenditures = await client.query(` - SELECT er.project_id, er.month, er.cat_key, er.status, - er.total_amount AS rollup_amount, live.total_amount AS live_amount, - er.expenditure_count AS rollup_count, live.expenditure_count AS live_count - FROM ( - SELECT project_id, month, COALESCE(category, '') AS cat_key, status, - total_amount, expenditure_count - FROM branch.expenditure_rollup - WHERE expenditure_count <> 0 - ) er - FULL OUTER JOIN ( - SELECT project_id, date_trunc('month', spent_on)::date AS month, - COALESCE(category, '') AS cat_key, status, - SUM(amount) AS total_amount, COUNT(*)::int AS expenditure_count - FROM branch.expenditures - WHERE deleted_at IS NULL - GROUP BY 1, 2, 3, 4 - ) live USING (project_id, month, cat_key, status) - WHERE er.total_amount IS DISTINCT FROM live.total_amount - OR er.expenditure_count IS DISTINCT FROM live.expenditure_count - `); - expect(expenditures.rows).toEqual([]); - - const projects = await client.query(` - SELECT pr.project_id, - pr.member_count, live.member_count AS live_member_count, - pr.total_donated, live.total_donated AS live_total_donated, - pr.donation_count, live.donation_count AS live_donation_count, - pr.report_count, live.report_count AS live_report_count - FROM branch.project_rollup pr - FULL OUTER JOIN ( - SELECT p.project_id, - (SELECT count(*) FROM branch.project_memberships m WHERE m.project_id = p.project_id) AS member_count, - (SELECT COALESCE(SUM(amount), 0) FROM branch.project_donations d WHERE d.project_id = p.project_id AND d.deleted_at IS NULL) AS total_donated, - (SELECT count(*) FROM branch.project_donations d WHERE d.project_id = p.project_id AND d.deleted_at IS NULL) AS donation_count, - (SELECT count(*) FROM branch.reports r WHERE r.project_id = p.project_id AND r.deleted_at IS NULL) AS report_count - FROM branch.projects p - WHERE p.deleted_at IS NULL - ) live USING (project_id) - WHERE pr.member_count IS DISTINCT FROM live.member_count - OR pr.total_donated IS DISTINCT FROM live.total_donated - OR pr.donation_count IS DISTINCT FROM live.donation_count - OR pr.report_count IS DISTINCT FROM live.report_count - `); - expect(projects.rows).toEqual([]); -} - -let client: PoolClient; - -beforeAll(async () => { - const setup = await pool.connect(); - try { - await ensureSchema(setup); - } finally { - setup.release(); - } -}); - -beforeEach(async () => { - client = await pool.connect(); - await resetData(client); - await client.query('DELETE FROM branch.expenditures'); - await client.query('DELETE FROM branch.project_donations'); - await client.query('DELETE FROM branch.reports'); - await reconcileRollups(client); - await auditRollups(client); -}); - -afterEach(() => { - client.release(); -}); - -afterAll(async () => { - await pool.end(); - await closeConnection(); -}); - -/** Live buckets for one project. Emptied buckets stay at zero, so exclude them. */ -async function bucketsFor(projectId: number): Promise { - const { rows } = await client.query( - `SELECT count(*)::int AS n FROM branch.expenditure_rollup - WHERE project_id = $1 AND expenditure_count <> 0`, - [projectId], - ); - return rows[0].n; -} - -async function approvedTotal(): Promise { - const { rows } = await client.query( - `SELECT COALESCE(SUM(total_amount), 0) AS t FROM branch.expenditure_rollup - WHERE status = 'approved'`, - ); - return Number(rows[0].t); -} - -const travel = { - project_id: 1, - entered_by: 1, - amount: 250, - category: 'Travel', - status: 'approved', - spent_on: '2026-03-11', -}; - -describe('reconcile', () => { - test('resetData leaves both rollups in step with the base tables', async () => { - await resetData(client); - await auditRollups(client); - }); -}); - -describe('expenditure_rollup', () => { - test('recordExpenditure lands in a bucket', async () => { - await recordExpenditure(travel); - await auditRollups(client); - expect(await bucketsFor(1)).toBe(1); - expect(await approvedTotal()).toBe(250); - }); - - test('status is part of the grain, so an unapproved row is stored separately', async () => { - await recordExpenditure(travel); - await recordExpenditure({ ...travel, amount: 900, status: 'pending' }); - await auditRollups(client); - expect(await bucketsFor(1)).toBe(2); - expect(await approvedTotal()).toBe(250); - }); - - test('two NULL-category rows share one bucket', async () => { - await recordExpenditure({ ...travel, amount: 50, category: null }); - await recordExpenditure({ ...travel, amount: 25, category: null, spent_on: '2026-03-12' }); - await auditRollups(client); - - const { rows } = await client.query(` - SELECT total_amount, expenditure_count FROM branch.expenditure_rollup - WHERE project_id = 1 AND category IS NULL AND month = DATE '2026-03-01' - `); - expect(rows).toHaveLength(1); - expect(Number(rows[0].total_amount)).toBe(75); - expect(rows[0].expenditure_count).toBe(2); - }); - - test("a category of '' does not share NULL's bucket", async () => { - await recordExpenditure({ ...travel, amount: 50, category: null }); - await recordExpenditure({ ...travel, amount: 25, category: '' }); - await auditRollups(client); - expect(await bucketsFor(1)).toBe(2); - }); - - test('editing the amount alone stays in the same bucket', async () => { - const row = await recordExpenditure(travel); - await editExpenditure(row.expenditure_id, { amount: 400 }); - await auditRollups(client); - expect(await bucketsFor(1)).toBe(1); - expect(await approvedTotal()).toBe(400); - }); - - test.each([ - ['category', { category: 'Equipment' }], - ['month', { spent_on: '2026-01-11' }], - ['status', { status: 'denied' }], - ['category to NULL', { category: null }], - ])('an edit crossing %s debits the old bucket and credits the new', async (_label, patch) => { - const row = await recordExpenditure(travel); - await editExpenditure(row.expenditure_id, patch as Record); - await auditRollups(client); - }); - - test('a status change takes the row out of approved spend', async () => { - const row = await recordExpenditure(travel); - await editExpenditure(row.expenditure_id, { status: 'denied' }); - await auditRollups(client); - expect(await approvedTotal()).toBe(0); - }); - - test('removeExpenditure decrements the bucket', async () => { - await recordExpenditure(travel); - const second = await recordExpenditure({ ...travel, amount: 100 }); - await removeExpenditure(second.expenditure_id); - await auditRollups(client); - expect(await approvedTotal()).toBe(250); - }); - - test('removeExpenditure on an unknown id is a no-op', async () => { - await recordExpenditure(travel); - expect(await removeExpenditure(999_999)).toBe(0n); - await auditRollups(client); - expect(await approvedTotal()).toBe(250); - }); - - // Sequential on purpose: the store pool is max: 1, so a concurrent version of - // this passes even against the unfixed code. - test('removing the same row twice decrements once', async () => { - const row = await recordExpenditure(travel); - await recordExpenditure({ ...travel, amount: 100 }); - - expect(await removeExpenditure(row.expenditure_id)).toBe(1n); - expect(await removeExpenditure(row.expenditure_id)).toBe(0n); - - await auditRollups(client); - expect(await approvedTotal()).toBe(100); - }); - - test('deleting a project cascades without orphaning or resurrecting a bucket', async () => { - await recordExpenditure({ ...travel, project_id: 4 }); - await recordReport({ project_id: 4, title: 'r', object_url: 's3://r', report_type: 'technical' }); - await removeProject(4); - await auditRollups(client); - - const orphans = await client.query(` - SELECT (SELECT count(*)::int FROM branch.expenditure_rollup er - LEFT JOIN branch.projects p ON p.project_id = er.project_id AND p.deleted_at IS NULL - WHERE p.project_id IS NULL) AS exp_orphans, - (SELECT count(*)::int FROM branch.project_rollup pr - LEFT JOIN branch.projects p ON p.project_id = pr.project_id AND p.deleted_at IS NULL - WHERE p.project_id IS NULL) AS proj_orphans - `); - expect(orphans.rows[0]).toEqual({ exp_orphans: 0, proj_orphans: 0 }); - - const kept = await client.query(` - SELECT (SELECT count(*)::int FROM branch.expenditures - WHERE project_id = 4 AND deleted_at IS NOT NULL) AS expenditures, - (SELECT count(*)::int FROM branch.reports - WHERE project_id = 4 AND deleted_at IS NOT NULL) AS reports - `); - expect(kept.rows[0]).toEqual({ expenditures: 1, reports: 1 }); - }); -}); - -describe('project_rollup', () => { - test('createProject seeds a zeroed rollup row', async () => { - const created = await createProject( - { name: 'fresh', description: 'x', total_budget: 500, currency: 'USD' }, - [], - 'Student', - ); - await auditRollups(client); - - const rollup = await client.query( - 'SELECT * FROM branch.project_rollup WHERE project_id = $1', - [created.project_id], - ); - expect(rollup.rows).toHaveLength(1); - expect(rollup.rows[0].member_count).toBe(0); - expect(Number(rollup.rows[0].total_donated)).toBe(0); - }); - - test('donations add and remove', async () => { - const donation = await recordDonation({ donor_id: 1, project_id: 1, amount: 500 }); - await auditRollups(client); - await removeDonation(donation.donation_id); - await auditRollups(client); - }); - - test('deleting a donor takes its donations off the rollup', async () => { - await recordDonation({ donor_id: 1, project_id: 1, amount: 500 }); - await recordDonation({ donor_id: 1, project_id: 2, amount: 250 }); - await auditRollups(client); - - await removeDonor(1); - await auditRollups(client); - - const { rows } = await client.query( - 'SELECT total_donated, donation_count FROM branch.project_rollup WHERE project_id IN (1, 2) ORDER BY project_id', - ); - expect(rows.every((r) => Number(r.total_donated) === 0 && r.donation_count === 0)).toBe(true); - }); - - test('roster replacement keeps member_count in step', async () => { - await updateProject(1, {}, [{ user_id: 1 }, { user_id: 2 }], 'Student'); - await auditRollups(client); - await updateProject(1, {}, [{ user_id: 3 }], 'Student'); - await auditRollups(client); - await updateProject(1, {}, [], 'Student'); - await auditRollups(client); - }); - - test('deleting a user takes its memberships off the rollup', async () => { - await updateProject(1, {}, [{ user_id: 4 }], 'Student'); - await updateProject(2, {}, [{ user_id: 4 }], 'Student'); - await auditRollups(client); - - const before = await client.query( - 'SELECT project_id, member_count FROM branch.project_rollup WHERE project_id IN (1, 2) ORDER BY project_id', - ); - expect(before.rows.map((r) => r.member_count)).toEqual([1, 1]); - - expect(await removeUser(4)).toBe(1n); - await auditRollups(client); - - const gone = await client.query( - 'SELECT 1 FROM branch.users WHERE user_id = 4 AND deleted_at IS NOT NULL', - ); - expect(gone.rows).toHaveLength(1); - const orphaned = await client.query( - 'SELECT 1 FROM branch.project_memberships WHERE user_id = 4', - ); - expect(orphaned.rows).toHaveLength(0); - - const after = await client.query( - 'SELECT project_id, member_count FROM branch.project_rollup WHERE project_id IN (1, 2) ORDER BY project_id', - ); - expect(after.rows.map((r) => r.member_count)).toEqual([0, 0]); - }); - - test('removing a user that does not exist is a no-op', async () => { - expect(await removeUser(999_999)).toBe(0n); - await auditRollups(client); - }); - - test('a write against a project with no rollup row fails loudly', async () => { - await client.query('DELETE FROM branch.project_rollup WHERE project_id = 1'); - - await expect( - recordReport({ project_id: 1, title: 'a', object_url: 's3://a', report_type: 'technical' }), - ).rejects.toThrow(/no row for project 1/); - - const reports = await client.query('SELECT 1 FROM branch.reports WHERE project_id = 1'); - expect(reports.rows).toHaveLength(0); - }); - - test('reports add and remove', async () => { - await recordReport({ project_id: 1, title: 'a', object_url: 's3://a', report_type: 'technical' }); - const b = await recordReport({ - project_id: 1, - title: 'b', - object_url: 's3://b', - report_type: 'narrative', - }); - await auditRollups(client); - - const { rows } = await client.query( - 'SELECT report_count FROM branch.project_rollup WHERE project_id = 1', - ); - expect(rows[0].report_count).toBe(2); - - await removeReport(b.report_id); - await auditRollups(client); - }); -}); diff --git a/apps/backend/lambdas/reports/controllers/reports.ts b/apps/backend/lambdas/reports/controllers/reports.ts index 28ecd902..6dcb836a 100644 --- a/apps/backend/lambdas/reports/controllers/reports.ts +++ b/apps/backend/lambdas/reports/controllers/reports.ts @@ -129,17 +129,14 @@ export const listReports: RouteHandler = async ({ event }) => { if (page && limit) { const offset = (page - 1) * limit; - // Count from the rollup, not a scan of `reports`. No reports reads 0, and an - // unknown project has no row — both yield 0, as COUNT(*) did. - const countPromise = projectId !== null - ? db.selectFrom('branch.project_rollup').where('project_id', '=', projectId).select('report_count as count').executeTakeFirst() - : db.selectFrom('branch.project_rollup').select(db.fn.sum('report_count').as('count')).executeTakeFirst(); + let countQuery = db.selectFrom('branch.reports').where('deleted_at', 'is', null).select(db.fn.count('report_id').as('count')); + if (projectId !== null) countQuery = countQuery.where('project_id', '=', projectId); let pageQuery = db.selectFrom('branch.reports').where('deleted_at', 'is', null).selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc'); if (projectId !== null) pageQuery = pageQuery.where('project_id', '=', projectId); const [totalCount, reports] = await Promise.all([ - countPromise, + countQuery.executeTakeFirst(), pageQuery.limit(limit).offset(offset).execute(), ]); diff --git a/apps/backend/lambdas/reports/test/reports.unit.test.ts b/apps/backend/lambdas/reports/test/reports.unit.test.ts index 2d902fca..d470b07c 100644 --- a/apps/backend/lambdas/reports/test/reports.unit.test.ts +++ b/apps/backend/lambdas/reports/test/reports.unit.test.ts @@ -264,10 +264,8 @@ describe('GET /reports unit tests', () => { beforeEach(() => { jest.clearAllMocks(); mockAuthenticateRequest.mockResolvedValue(adminAuthContext); - // db.fn is used by pagination count queries; sum() reads project_rollup. mockDb.fn = { count: jest.fn().mockReturnValue({ as: jest.fn().mockReturnValue('count') }), - sum: jest.fn().mockReturnValue({ as: jest.fn().mockReturnValue('count') }), }; }); diff --git a/shared/store/package.json b/shared/store/package.json index e33a6257..171dcbfa 100644 --- a/shared/store/package.json +++ b/shared/store/package.json @@ -2,7 +2,7 @@ "name": "@branch/store", "version": "1.0.0", "private": true, - "description": "The only writer of rollup-affecting tables. Shared verbatim by the lambdas.", + "description": "The lambdas' only database connection and only writer. Shared verbatim by the lambdas.", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ diff --git a/shared/store/src/donations.ts b/shared/store/src/donations.ts index 4b935237..52375bf5 100644 --- a/shared/store/src/donations.ts +++ b/shared/store/src/donations.ts @@ -1,53 +1,27 @@ import type { Selectable } from 'kysely' import type { DB, NewDonation, NewDonor } from '@branch/types' import { tx } from './tx' -import { projectRollupBump } from './rollups' import { now, requireLiveDonor, requireLiveProject } from './live' type Donation = Selectable -// amount is NUMERIC (a string); negate textually so the exact decimal survives. -const negate = (amount: string) => (amount.startsWith('-') ? amount.slice(1) : `-${amount}`) - export async function recordDonation(values: NewDonation): Promise { return tx(async (trx) => { await requireLiveDonor(trx, values.donor_id) await requireLiveProject(trx, values.project_id) - const row = await trx - .insertInto('branch.project_donations') - .values(values) - .returningAll() - .executeTakeFirstOrThrow() - await projectRollupBump(trx, row.project_id, { donated: row.amount, donations: 1 }) - return row + return trx.insertInto('branch.project_donations').values(values).returningAll().executeTakeFirstOrThrow() }) } export async function removeDonation(id: number): Promise { return tx(async (trx) => { - const before = await trx - .selectFrom('branch.project_donations') - .where('donation_id', '=', id) - .where('deleted_at', 'is', null) - .selectAll() - .forUpdate() - .executeTakeFirst() - if (!before) return 0n - const deleted = await trx .updateTable('branch.project_donations') .set({ deleted_at: now() }) .where('donation_id', '=', id) .where('deleted_at', 'is', null) .executeTakeFirst() - const removed = deleted.numUpdatedRows - if (removed === 0n) return 0n - - await projectRollupBump(trx, before.project_id, { - donated: negate(before.amount), - donations: -1, - }) - return removed + return deleted.numUpdatedRows }) } @@ -66,25 +40,15 @@ export async function removeDonor(donorId: number): Promise { .set({ deleted_at: now() }) .where('donor_id', '=', donorId) .where('deleted_at', 'is', null) - .returning('donor_id') .executeTakeFirst() - if (!deleted) return 0n + if (deleted.numUpdatedRows === 0n) return 0n - // RETURNING, not a prior SELECT: a donation added in between would be missed. - const removed = await trx + await trx .updateTable('branch.project_donations') .set({ deleted_at: now() }) .where('donor_id', '=', donorId) .where('deleted_at', 'is', null) - .returning(['project_id', 'amount']) .execute() - - for (const donation of removed) { - await projectRollupBump(trx, donation.project_id, { - donated: negate(donation.amount), - donations: -1, - }) - } - return 1n + return deleted.numUpdatedRows }) } diff --git a/shared/store/src/expenditures.ts b/shared/store/src/expenditures.ts index 479f3572..a49da907 100644 --- a/shared/store/src/expenditures.ts +++ b/shared/store/src/expenditures.ts @@ -1,7 +1,6 @@ import type { Selectable } from 'kysely' import type { DB, ExpenditureEdit, NewExpenditure } from '@branch/types' import { tx } from './tx' -import { expenditureRollupAdd, expenditureRollupRemove } from './rollups' import { now, requireLiveProject } from './live' type Expenditure = Selectable @@ -9,13 +8,7 @@ type Expenditure = Selectable export async function recordExpenditure(values: NewExpenditure): Promise { return tx(async (trx) => { await requireLiveProject(trx, values.project_id) - const row = await trx - .insertInto('branch.expenditures') - .values(values) - .returningAll() - .executeTakeFirstOrThrow() - await expenditureRollupAdd(trx, row) - return row + return trx.insertInto('branch.expenditures').values(values).returningAll().executeTakeFirstOrThrow() }) } @@ -44,16 +37,12 @@ export async function editExpenditure( throw new ExpenditureStatusChangedError(before.status) } - const after = await trx + return trx .updateTable('branch.expenditures') .set(values) .where('expenditure_id', '=', id) .returningAll() .executeTakeFirstOrThrow() - - await expenditureRollupRemove(trx, before) - await expenditureRollupAdd(trx, after) - return after }) } @@ -77,10 +66,6 @@ export async function removeExpenditure(id: number, expectedStatus?: string): Pr .where('expenditure_id', '=', id) .where('deleted_at', 'is', null) .executeTakeFirst() - const removed = deleted.numUpdatedRows - if (removed === 0n) return 0n - - await expenditureRollupRemove(trx, before) - return removed + return deleted.numUpdatedRows }) } diff --git a/shared/store/src/projects.ts b/shared/store/src/projects.ts index 6ecfa713..8296523b 100644 --- a/shared/store/src/projects.ts +++ b/shared/store/src/projects.ts @@ -1,7 +1,6 @@ import type { Selectable, Transaction } from 'kysely' import type { DB, NewProject, ProjectEdit, ProjectMemberInput } from '@branch/types' import { tx } from './tx' -import { projectRollupBump, seedProjectRollup } from './rollups' import { now, requireLiveUsers } from './live' type Project = Selectable @@ -24,14 +23,13 @@ async function syncMemberships( // Diffed rather than replaced, so kept members keep their hours and start_date. const removed = existing.map((row) => row.user_id).filter((id) => !wanted.has(id)) - const cleared = - removed.length > 0 - ? await trx - .deleteFrom('branch.project_memberships') - .where('project_id', '=', projectId) - .where('user_id', 'in', removed) - .executeTakeFirst() - : undefined + if (removed.length > 0) { + await trx + .deleteFrom('branch.project_memberships') + .where('project_id', '=', projectId) + .where('user_id', 'in', removed) + .execute() + } const roleChanges = new Map() for (const [userId, role] of wanted) { @@ -49,25 +47,19 @@ async function syncMemberships( } const added = [...wanted].filter(([userId]) => !heldRole.has(userId)) - const inserted = - added.length > 0 - ? await trx - .insertInto('branch.project_memberships') - .values( - added.map(([userId, role]) => ({ - project_id: projectId, - user_id: userId, - role: role ?? defaultRole, - })), - ) - .onConflict((oc) => oc.columns(['project_id', 'user_id']).doNothing()) - .returning('membership_id') - .execute() - : [] - - // Counted from what the statements touched: a concurrent roster edit makes `existing` stale. - const delta = inserted.length - Number(cleared?.numDeletedRows ?? 0n) - if (delta !== 0) await projectRollupBump(trx, projectId, { members: delta }) + if (added.length > 0) { + await trx + .insertInto('branch.project_memberships') + .values( + added.map(([userId, role]) => ({ + project_id: projectId, + user_id: userId, + role: role ?? defaultRole, + })), + ) + .onConflict((oc) => oc.columns(['project_id', 'user_id']).doNothing()) + .execute() + } } export async function createProject( @@ -81,7 +73,8 @@ export async function createProject( .values(values) .returningAll() .executeTakeFirstOrThrow() - await seedProjectRollup(trx, row.project_id) + // Lambdas still on the rollup code fail a write to a project with no row; drop with the tables. + await trx.insertInto('branch.project_rollup').values({ project_id: row.project_id }).execute() if (members.length > 0) await syncMemberships(trx, row.project_id, members, defaultRole) return row }) @@ -136,8 +129,6 @@ export async function removeProject(id: number): Promise { .execute() } await trx.deleteFrom('branch.project_memberships').where('project_id', '=', id).execute() - await trx.deleteFrom('branch.expenditure_rollup').where('project_id', '=', id).execute() - await trx.deleteFrom('branch.project_rollup').where('project_id', '=', id).execute() return deleted.numUpdatedRows }) } diff --git a/shared/store/src/reports.ts b/shared/store/src/reports.ts index c3938fdf..1a43c67a 100644 --- a/shared/store/src/reports.ts +++ b/shared/store/src/reports.ts @@ -1,7 +1,6 @@ import type { Selectable } from 'kysely' import type { DB, NewReport } from '@branch/types' import { tx } from './tx' -import { projectRollupBump } from './rollups' import { now, requireLiveProject } from './live' type Report = Selectable @@ -9,37 +8,18 @@ type Report = Selectable export async function recordReport(values: NewReport): Promise { return tx(async (trx) => { await requireLiveProject(trx, values.project_id) - const row = await trx - .insertInto('branch.reports') - .values(values) - .returningAll() - .executeTakeFirstOrThrow() - await projectRollupBump(trx, row.project_id, { reports: 1 }) - return row + return trx.insertInto('branch.reports').values(values).returningAll().executeTakeFirstOrThrow() }) } export async function removeReport(id: number): Promise { return tx(async (trx) => { - const before = await trx - .selectFrom('branch.reports') - .where('report_id', '=', id) - .where('deleted_at', 'is', null) - .select('project_id') - .forUpdate() - .executeTakeFirst() - if (!before) return 0n - const deleted = await trx .updateTable('branch.reports') .set({ deleted_at: now() }) .where('report_id', '=', id) .where('deleted_at', 'is', null) .executeTakeFirst() - const removed = deleted.numUpdatedRows - if (removed === 0n) return 0n - - await projectRollupBump(trx, before.project_id, { reports: -1 }) - return removed + return deleted.numUpdatedRows }) } diff --git a/shared/store/src/rollups.ts b/shared/store/src/rollups.ts deleted file mode 100644 index 60f26585..00000000 --- a/shared/store/src/rollups.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { sql, type Selectable, type Transaction } from 'kysely' -import type { DB } from '@branch/types' - -export type ExpenditureGrain = Pick< - Selectable, - 'project_id' | 'spent_on' | 'category' | 'status' | 'amount' -> - -export async function expenditureRollupAdd( - trx: Transaction, - row: ExpenditureGrain, -): Promise { - await sql`select branch.expenditure_rollup_add( - ${row.project_id}, ${row.spent_on}, ${row.category}, ${row.status}, ${row.amount} - )`.execute(trx) -} - -export async function expenditureRollupRemove( - trx: Transaction, - row: ExpenditureGrain, -): Promise { - await sql`select branch.expenditure_rollup_remove( - ${row.project_id}, ${row.spent_on}, ${row.category}, ${row.status}, ${row.amount} - )`.execute(trx) -} - -export type RollupDelta = { - members?: number - donated?: number | string - donations?: number - reports?: number -} - -export async function projectRollupBump( - trx: Transaction, - projectId: number, - delta: RollupDelta, -): Promise { - const result = await sql<{ hit: number | null }>`select branch.project_rollup_bump( - ${projectId}, - ${delta.members ?? 0}, - ${delta.donated ?? 0}, - ${delta.donations ?? 0}, - ${delta.reports ?? 0} - ) AS hit`.execute(trx) - - if (result.rows[0]?.hit !== 1) { - throw new Error(`project_rollup has no row for project ${projectId}`) - } -} - -export async function seedProjectRollup( - trx: Transaction, - projectId: number, -): Promise { - await trx - .insertInto('branch.project_rollup') - .values({ project_id: projectId }) - .onConflict((oc) => oc.column('project_id').doNothing()) - .execute() -} diff --git a/shared/store/src/users.ts b/shared/store/src/users.ts index 3f7ea1ca..1ecc7905 100644 --- a/shared/store/src/users.ts +++ b/shared/store/src/users.ts @@ -1,7 +1,6 @@ import type { Selectable } from 'kysely' import type { DB, NewUser, UserEdit } from '@branch/types' import { tx } from './tx' -import { projectRollupBump } from './rollups' import { now } from './live' type User = Selectable @@ -58,16 +57,7 @@ export async function removeUser(userId: number): Promise { .where('entered_by', '=', userId) .execute() - // RETURNING, not a prior SELECT: a membership added in between would be missed. - const removed = await trx - .deleteFrom('branch.project_memberships') - .where('user_id', '=', userId) - .returning('project_id') - .execute() - - for (const membership of removed) { - await projectRollupBump(trx, membership.project_id, { members: -1 }) - } + await trx.deleteFrom('branch.project_memberships').where('user_id', '=', userId).execute() return deleted.numUpdatedRows }) } From acb8a35ea7da7991f2846abc6af2d83292705912 Mon Sep 17 00:00:00 2001 From: nourshoreibah Date: Sat, 17 Oct 2026 12:07:45 -0400 Subject: [PATCH 2/2] chore: trim comments Co-Authored-By: Claude Opus 5.5 --- apps/backend/lambdas/projects/controllers/dashboard.ts | 2 -- apps/backend/lambdas/projects/services/projects.ts | 1 - 2 files changed, 3 deletions(-) diff --git a/apps/backend/lambdas/projects/controllers/dashboard.ts b/apps/backend/lambdas/projects/controllers/dashboard.ts index 4b21a3e2..025d4e2d 100644 --- a/apps/backend/lambdas/projects/controllers/dashboard.ts +++ b/apps/backend/lambdas/projects/controllers/dashboard.ts @@ -73,7 +73,6 @@ export const getDashboard: RouteHandler = async () => { .where('p.deleted_at', 'is', null) .where(isActive('p.end_date')) .executeTakeFirst(), - // Both aggregate before joining, or each project row multiplies by the other's row count. db.selectFrom('branch.projects as p') .leftJoin( (eb) => @@ -219,7 +218,6 @@ export const getOverview: RouteHandler = async (ctx) => { if (!project) return json(404, { message: `Project not found for id: ${id}` }); const totalBudget = project.total_budget !== null ? Number(project.total_budget) : 0; - // Summed in JS: the table renders every row anyway, so the total cannot disagree with the list. // The list includes rows still in review; the stats count only approved ones. const approved = expenditures.filter((e) => e.status === APPROVED_EXPENDITURE_STATUS); const totalSpent = approved.reduce((sum, e) => sum + Number(e.amount), 0); diff --git a/apps/backend/lambdas/projects/services/projects.ts b/apps/backend/lambdas/projects/services/projects.ts index a80b159d..db169189 100644 --- a/apps/backend/lambdas/projects/services/projects.ts +++ b/apps/backend/lambdas/projects/services/projects.ts @@ -33,7 +33,6 @@ export function indexByProject( return new Map(rows.map((row) => [row.project_id, pick(row)])); } -/** Per-project approved spend and headcount. */ export async function loadProjectAggregates(projectIds: number[]): Promise<{ spent: Map; members: Map;