Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 4 additions & 4 deletions apps/backend/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ http://localhost:3000/<service>/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<DB>`) 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<DB>`) 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
Expand Down
94 changes: 0 additions & 94 deletions apps/backend/db/testkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,35 +228,8 @@ export async function resetData(client: Queryable): Promise<void> {
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<void> {
for (const table of ['expenditures', 'reports', 'project_donations', 'donors', 'projects', 'users']) {
await client.query(`DELETE FROM ${SCHEMA}.${table} WHERE deleted_at IS NOT NULL`);
Expand All @@ -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<string[]> {
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, '<null>')
|| ' 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<void> {
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<void> {
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.
Expand Down
13 changes: 0 additions & 13 deletions apps/backend/lambdas/expenditures/services/expenditures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,6 @@ export function receiptKeyForProject(objectUrl: string, projectId: number): stri
}

export async function countExpenditures(projectId: number | null, scope: ExpenditureScope): Promise<number> {
// 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)
Expand Down
Loading
Loading