Skip to content
Merged
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
3 changes: 2 additions & 1 deletion apps/backend/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ http://localhost:3000/<service>/health
- **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')`.
- **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. 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).
- 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 All @@ -67,7 +68,7 @@ Automatic on push to `main` touching `apps/backend/lambdas/**` or `shared/types/

## Env vars (lambdas)

`DB_HOST DB_PORT DB_USER DB_PASSWORD DB_NAME`, `COGNITO_USER_POOL_ID`, `COGNITO_CLIENT_ID` (or `COGNITO_APP_CLIENT_ID`), `REPORTS_BUCKET_NAME` (reports, expenditures and projects — one bucket holds both the `reports/` and `receipts/` prefixes, and all three delete out of it), `AWS_REGION` (default `us-east-2`, Lambda-reserved — never set it in Terraform).
`DB_HOST DB_PORT DB_USER DB_PASSWORD DB_NAME`, `COGNITO_USER_POOL_ID`, `COGNITO_CLIENT_ID` (or `COGNITO_APP_CLIENT_ID`), `REPORTS_BUCKET_NAME` (reports, expenditures and projects — one bucket holds both the `reports/` and `receipts/` prefixes; deletes leave the objects in place, see soft deletes below), `AWS_REGION` (default `us-east-2`, Lambda-reserved — never set it in Terraform).

**Anything a lambda reads from `process.env` must be declared in the `environment` block of `infrastructure/aws/lambda.tf`.** That block is authoritative and is deliberately not in `lifecycle.ignore_changes`, so a value set by hand in the console is deleted on the next apply. Locally the Cognito values must be the real shared dev-pool IDs (`apps/backend/.env`) — auth talks to the real pool for JWKS and `InitiateAuth` — but no AWS credentials are needed, because every Cognito API on the sign-in path is unsigned.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- V20261016230432__add_users_deleted_at
--
-- Flyway runs this file inside a SINGLE transaction, with search_path =
-- branch, public -- so table names can be unqualified.
--
-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its
-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE,
-- and at most 3,000 rows changed. CI lints this file with dsql-lint.
--
-- This migration is applied to PRODUCTION automatically when the PR merges,
-- BEFORE the new lambda code is deployed. It must be safe for the code that is
-- live right now: additive changes only. See apps/backend/db/README.md for the
-- expand/contract rules that destructive changes need.
--
-- Forward-only: there is no rollback. Fix a mistake with a new migration, and
-- never edit a migration that has been merged -- Flyway checksums it, and
-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not
-- silent drift.


ALTER TABLE users ADD COLUMN deleted_at TIMESTAMP;
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- V20261016230433__add_projects_deleted_at
--
-- Flyway runs this file inside a SINGLE transaction, with search_path =
-- branch, public -- so table names can be unqualified.
--
-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its
-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE,
-- and at most 3,000 rows changed. CI lints this file with dsql-lint.
--
-- This migration is applied to PRODUCTION automatically when the PR merges,
-- BEFORE the new lambda code is deployed. It must be safe for the code that is
-- live right now: additive changes only. See apps/backend/db/README.md for the
-- expand/contract rules that destructive changes need.
--
-- Forward-only: there is no rollback. Fix a mistake with a new migration, and
-- never edit a migration that has been merged -- Flyway checksums it, and
-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not
-- silent drift.


ALTER TABLE projects ADD COLUMN deleted_at TIMESTAMP;
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- V20261016230434__add_donors_deleted_at
--
-- Flyway runs this file inside a SINGLE transaction, with search_path =
-- branch, public -- so table names can be unqualified.
--
-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its
-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE,
-- and at most 3,000 rows changed. CI lints this file with dsql-lint.
--
-- This migration is applied to PRODUCTION automatically when the PR merges,
-- BEFORE the new lambda code is deployed. It must be safe for the code that is
-- live right now: additive changes only. See apps/backend/db/README.md for the
-- expand/contract rules that destructive changes need.
--
-- Forward-only: there is no rollback. Fix a mistake with a new migration, and
-- never edit a migration that has been merged -- Flyway checksums it, and
-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not
-- silent drift.


ALTER TABLE donors ADD COLUMN deleted_at TIMESTAMP;
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- V20261016230435__add_project_donations_deleted_at
--
-- Flyway runs this file inside a SINGLE transaction, with search_path =
-- branch, public -- so table names can be unqualified.
--
-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its
-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE,
-- and at most 3,000 rows changed. CI lints this file with dsql-lint.
--
-- This migration is applied to PRODUCTION automatically when the PR merges,
-- BEFORE the new lambda code is deployed. It must be safe for the code that is
-- live right now: additive changes only. See apps/backend/db/README.md for the
-- expand/contract rules that destructive changes need.
--
-- Forward-only: there is no rollback. Fix a mistake with a new migration, and
-- never edit a migration that has been merged -- Flyway checksums it, and
-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not
-- silent drift.


ALTER TABLE project_donations ADD COLUMN deleted_at TIMESTAMP;
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- V20261016230436__add_expenditures_deleted_at
--
-- Flyway runs this file inside a SINGLE transaction, with search_path =
-- branch, public -- so table names can be unqualified.
--
-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its
-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE,
-- and at most 3,000 rows changed. CI lints this file with dsql-lint.
--
-- This migration is applied to PRODUCTION automatically when the PR merges,
-- BEFORE the new lambda code is deployed. It must be safe for the code that is
-- live right now: additive changes only. See apps/backend/db/README.md for the
-- expand/contract rules that destructive changes need.
--
-- Forward-only: there is no rollback. Fix a mistake with a new migration, and
-- never edit a migration that has been merged -- Flyway checksums it, and
-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not
-- silent drift.


ALTER TABLE expenditures ADD COLUMN deleted_at TIMESTAMP;
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
-- V20261016230437__add_reports_deleted_at
--
-- Flyway runs this file inside a SINGLE transaction, with search_path =
-- branch, public -- so table names can be unqualified.
--
-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its
-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE,
-- and at most 3,000 rows changed. CI lints this file with dsql-lint.
--
-- This migration is applied to PRODUCTION automatically when the PR merges,
-- BEFORE the new lambda code is deployed. It must be safe for the code that is
-- live right now: additive changes only. See apps/backend/db/README.md for the
-- expand/contract rules that destructive changes need.
--
-- Forward-only: there is no rollback. Fix a mistake with a new migration, and
-- never edit a migration that has been merged -- Flyway checksums it, and
-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not
-- silent drift.


ALTER TABLE reports ADD COLUMN deleted_at TIMESTAMP;
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
-- V20261016230438__drop_users_email_unique
--
-- Flyway runs this file inside a SINGLE transaction, with search_path =
-- branch, public -- so table names can be unqualified.
--
-- Aurora DSQL: exactly ONE DDL statement per file (DML goes in a file of its
-- own), CREATE INDEX ${async} ..., no SERIAL, triggers, PL/pgSQL or TRUNCATE,
-- and at most 3,000 rows changed. CI lints this file with dsql-lint.
--
-- This migration is applied to PRODUCTION automatically when the PR merges,
-- BEFORE the new lambda code is deployed. It must be safe for the code that is
-- live right now: additive changes only. See apps/backend/db/README.md for the
-- expand/contract rules that destructive changes need.
--
-- Forward-only: there is no rollback. Fix a mistake with a new migration, and
-- never edit a migration that has been merged -- Flyway checksums it, and
-- someone has already run it. Do not use IF NOT EXISTS: you want a failure, not
-- silent drift.


-- Soft-deleted users keep their email; Cognito enforces uniqueness among live accounts.
ALTER TABLE users DROP CONSTRAINT users_email_key;
23 changes: 20 additions & 3 deletions apps/backend/db/testkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ const EXPECTED_EXPENDITURE_ROLLUP = `
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 = `
Expand All @@ -250,10 +251,26 @@ const EXPECTED_PROJECT_ROLLUP = `
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 GROUP BY project_id) d
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 GROUP BY project_id) r
ON r.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`);
}
}

export const PARITY_DELETES = {
expenditure: 1,
donation: 2,
donor: 3,
report: 4,
project: 3,
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[]> {
Expand Down
2 changes: 2 additions & 0 deletions apps/backend/lambdas/auth/controllers/impersonation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const handleListTargets: RouteHandler = async ({ event }) => {
let query = db
.selectFrom('branch.users')
.where('is_staff', 'is not', true)
.where('deleted_at', 'is', null)
.select(['user_id', 'name', 'email', 'is_admin', 'cognito_sub'])
.orderBy('name')
.limit(TARGET_LIMIT);
Expand Down Expand Up @@ -69,6 +70,7 @@ export const handleStartImpersonation: RouteHandler = async ({ event, auth }) =>
.selectFrom('branch.users')
.where('user_id', '=', targetUserId)
.where('is_staff', 'is not', true)
.where('deleted_at', 'is', null)
.select(['user_id', 'name', 'email'])
.executeTakeFirst();
// 404 for a staff target too: the console must not confirm one exists.
Expand Down
1 change: 1 addition & 0 deletions apps/backend/lambdas/auth/controllers/mfa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ export const handleMfaSetup: RouteHandler = async ({ event, auth }) => {
const me = await db
.selectFrom('branch.users')
.where('cognito_sub', '=', user.cognitoSub)
.where('deleted_at', 'is', null)
.select(['email'])
.executeTakeFirst();

Expand Down
1 change: 1 addition & 0 deletions apps/backend/lambdas/auth/controllers/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export async function handleRegister(event: any): Promise<APIGatewayProxyResult>
const existingUser = await db
.selectFrom('branch.users')
.where('email', '=', email.toLowerCase())
.where('deleted_at', 'is', null)
.selectAll()
.executeTakeFirst();

Expand Down
13 changes: 11 additions & 2 deletions apps/backend/lambdas/donors/controllers/donations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,13 @@ export async function getDonations({ event, auth }: RouteCtx) {

let countQuery = db
.selectFrom('branch.project_donations')
.where('deleted_at', 'is', null)
.select(db.fn.count('donation_id').as('count'));
if (inScope) countQuery = countQuery.where(inScope);

let pageQuery = db
.selectFrom('branch.project_donations')
.where('deleted_at', 'is', null)
.selectAll()
.orderBy('donation_id', 'asc');
if (inScope) pageQuery = pageQuery.where(inScope);
Expand All @@ -66,7 +68,7 @@ export async function getDonations({ event, auth }: RouteCtx) {
});
}

let query = db.selectFrom('branch.project_donations').selectAll();
let query = db.selectFrom('branch.project_donations').where('deleted_at', 'is', null).selectAll();
if (inScope) query = query.where(inScope);
const donations = await query.execute();
return json(200, { data: donations });
Expand Down Expand Up @@ -115,11 +117,17 @@ export async function createDonation({ event }: RouteCtx) {
// 404, but only with the combined "Donor or project not found" message, and
// these two tell the caller which id was wrong.
const [donor, project] = await Promise.all([
db.selectFrom('branch.donors').select('donor_id').where('donor_id', '=', donorId).executeTakeFirst(),
db
.selectFrom('branch.donors')
.select('donor_id')
.where('donor_id', '=', donorId)
.where('deleted_at', 'is', null)
.executeTakeFirst(),
db
.selectFrom('branch.projects')
.select('project_id')
.where('project_id', '=', projectId)
.where('deleted_at', 'is', null)
.executeTakeFirst(),
]);

Expand Down Expand Up @@ -158,6 +166,7 @@ export async function deleteDonation({ params, auth }: RouteCtx) {
const donation = await db
.selectFrom('branch.project_donations')
.where('donation_id', '=', Number(id))
.where('deleted_at', 'is', null)
.selectAll()
.executeTakeFirst();

Expand Down
9 changes: 7 additions & 2 deletions apps/backend/lambdas/donors/controllers/donors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,14 @@ export async function getDonors({ event }: RouteCtx) {

// The count does not depend on the page, so both go out at once.
const [totalCount, donors] = await Promise.all([
db.selectFrom('branch.donors').select(db.fn.count('donor_id').as('count')).executeTakeFirst(),
db
.selectFrom('branch.donors')
.where('deleted_at', 'is', null)
.select(db.fn.count('donor_id').as('count'))
.executeTakeFirst(),
db
.selectFrom('branch.donors')
.where('deleted_at', 'is', null)
.selectAll()
.orderBy('donor_id', 'asc')
.limit(limit)
Expand All @@ -51,7 +56,7 @@ export async function getDonors({ event }: RouteCtx) {
});
}

const donors = await db.selectFrom('branch.donors').selectAll().execute();
const donors = await db.selectFrom('branch.donors').where('deleted_at', 'is', null).selectAll().execute();
return json(200, { data: donors });
}

Expand Down
2 changes: 2 additions & 0 deletions apps/backend/lambdas/donors/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@ module.exports = {
testEnvironment: 'node',
roots: ['<rootDir>/test'],
testMatch: ['**/*.test.ts'],
// Suites share one database; parallel workers truncate each other's fixtures.
maxWorkers: 1,
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
};
10 changes: 5 additions & 5 deletions apps/backend/lambdas/donors/test/donors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ describe("Donor API with data", () => {

test("DELETE /donors/{id} returns 200 for admin and removes the donor", async () => {
mockAuthenticateRequest.mockResolvedValueOnce(adminUser);
// Donor 2 (Harvard Medical) — note this cascades and also removes donation_id 2
// Donor 2 (Harvard Medical) — note this also soft-deletes donation_id 2
const res = await handler(createEvent('DELETE', '/donors/2'));
const body = JSON.parse(res.body);

Expand All @@ -508,8 +508,8 @@ describe("Donor API with data", () => {

const client = await pool.connect();
try {
const result = await client.query('SELECT * FROM branch.donors WHERE donor_id = 2');
expect(result.rows.length).toBe(0);
const result = await client.query('SELECT * FROM branch.donors WHERE donor_id = 2 AND deleted_at IS NOT NULL');
expect(result.rows.length).toBe(1);
} finally {
client.release();
}
Expand Down Expand Up @@ -552,8 +552,8 @@ describe("Donor API with data", () => {

const client = await pool.connect();
try {
const result = await client.query('SELECT * FROM branch.project_donations WHERE donation_id = 3');
expect(result.rows.length).toBe(0);
const result = await client.query('SELECT * FROM branch.project_donations WHERE donation_id = 3 AND deleted_at IS NOT NULL');
expect(result.rows.length).toBe(1);
} finally {
client.release();
}
Expand Down
Loading
Loading