diff --git a/apps/backend/AGENTS.md b/apps/backend/AGENTS.md index 6069907e..9fcf6387 100644 --- a/apps/backend/AGENTS.md +++ b/apps/backend/AGENTS.md @@ -47,6 +47,7 @@ http://localhost:3000//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`) 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 @@ -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. diff --git a/apps/backend/db/migrations/V20261016230432__add_users_deleted_at.sql b/apps/backend/db/migrations/V20261016230432__add_users_deleted_at.sql new file mode 100644 index 00000000..2a60e601 --- /dev/null +++ b/apps/backend/db/migrations/V20261016230432__add_users_deleted_at.sql @@ -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; diff --git a/apps/backend/db/migrations/V20261016230433__add_projects_deleted_at.sql b/apps/backend/db/migrations/V20261016230433__add_projects_deleted_at.sql new file mode 100644 index 00000000..1a845ead --- /dev/null +++ b/apps/backend/db/migrations/V20261016230433__add_projects_deleted_at.sql @@ -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; diff --git a/apps/backend/db/migrations/V20261016230434__add_donors_deleted_at.sql b/apps/backend/db/migrations/V20261016230434__add_donors_deleted_at.sql new file mode 100644 index 00000000..07856889 --- /dev/null +++ b/apps/backend/db/migrations/V20261016230434__add_donors_deleted_at.sql @@ -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; diff --git a/apps/backend/db/migrations/V20261016230435__add_project_donations_deleted_at.sql b/apps/backend/db/migrations/V20261016230435__add_project_donations_deleted_at.sql new file mode 100644 index 00000000..bcf10223 --- /dev/null +++ b/apps/backend/db/migrations/V20261016230435__add_project_donations_deleted_at.sql @@ -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; diff --git a/apps/backend/db/migrations/V20261016230436__add_expenditures_deleted_at.sql b/apps/backend/db/migrations/V20261016230436__add_expenditures_deleted_at.sql new file mode 100644 index 00000000..84db9ceb --- /dev/null +++ b/apps/backend/db/migrations/V20261016230436__add_expenditures_deleted_at.sql @@ -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; diff --git a/apps/backend/db/migrations/V20261016230437__add_reports_deleted_at.sql b/apps/backend/db/migrations/V20261016230437__add_reports_deleted_at.sql new file mode 100644 index 00000000..ab2483cc --- /dev/null +++ b/apps/backend/db/migrations/V20261016230437__add_reports_deleted_at.sql @@ -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; diff --git a/apps/backend/db/migrations/V20261016230438__drop_users_email_unique.sql b/apps/backend/db/migrations/V20261016230438__drop_users_email_unique.sql new file mode 100644 index 00000000..2df14724 --- /dev/null +++ b/apps/backend/db/migrations/V20261016230438__drop_users_email_unique.sql @@ -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; diff --git a/apps/backend/db/testkit.ts b/apps/backend/db/testkit.ts index c9eeba87..b142a47c 100644 --- a/apps/backend/db/testkit.ts +++ b/apps/backend/db/testkit.ts @@ -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 = ` @@ -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 { + 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 { diff --git a/apps/backend/lambdas/auth/controllers/impersonation.ts b/apps/backend/lambdas/auth/controllers/impersonation.ts index 0978c10f..9bf6dedd 100644 --- a/apps/backend/lambdas/auth/controllers/impersonation.ts +++ b/apps/backend/lambdas/auth/controllers/impersonation.ts @@ -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); @@ -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. diff --git a/apps/backend/lambdas/auth/controllers/mfa.ts b/apps/backend/lambdas/auth/controllers/mfa.ts index 6763312d..d3d5e2d5 100644 --- a/apps/backend/lambdas/auth/controllers/mfa.ts +++ b/apps/backend/lambdas/auth/controllers/mfa.ts @@ -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(); diff --git a/apps/backend/lambdas/auth/controllers/register.ts b/apps/backend/lambdas/auth/controllers/register.ts index c39818e6..f4be24f8 100644 --- a/apps/backend/lambdas/auth/controllers/register.ts +++ b/apps/backend/lambdas/auth/controllers/register.ts @@ -51,6 +51,7 @@ export async function handleRegister(event: any): Promise const existingUser = await db .selectFrom('branch.users') .where('email', '=', email.toLowerCase()) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); diff --git a/apps/backend/lambdas/donors/controllers/donations.ts b/apps/backend/lambdas/donors/controllers/donations.ts index 5bacfc27..a3641aa2 100644 --- a/apps/backend/lambdas/donors/controllers/donations.ts +++ b/apps/backend/lambdas/donors/controllers/donations.ts @@ -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); @@ -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 }); @@ -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(), ]); @@ -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(); diff --git a/apps/backend/lambdas/donors/controllers/donors.ts b/apps/backend/lambdas/donors/controllers/donors.ts index 9753fa96..00999f24 100644 --- a/apps/backend/lambdas/donors/controllers/donors.ts +++ b/apps/backend/lambdas/donors/controllers/donors.ts @@ -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) @@ -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 }); } diff --git a/apps/backend/lambdas/donors/jest.config.js b/apps/backend/lambdas/donors/jest.config.js index 7fc0bb23..008e78c1 100644 --- a/apps/backend/lambdas/donors/jest.config.js +++ b/apps/backend/lambdas/donors/jest.config.js @@ -3,5 +3,7 @@ module.exports = { testEnvironment: 'node', roots: ['/test'], testMatch: ['**/*.test.ts'], + // Suites share one database; parallel workers truncate each other's fixtures. + maxWorkers: 1, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], }; \ No newline at end of file diff --git a/apps/backend/lambdas/donors/test/donors.test.ts b/apps/backend/lambdas/donors/test/donors.test.ts index 7717068e..ac709a3b 100644 --- a/apps/backend/lambdas/donors/test/donors.test.ts +++ b/apps/backend/lambdas/donors/test/donors.test.ts @@ -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); @@ -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(); } @@ -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(); } diff --git a/apps/backend/lambdas/donors/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/donors/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..00d845ec --- /dev/null +++ b/apps/backend/lambdas/donors/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,108 @@ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const PAGES: Record[] = [ + {}, + { page: '1', limit: '2' }, + { page: '2', limit: '2' }, + { page: '1', limit: '100' }, +]; + +const REQUESTS: [string, Record][] = ['/donors', '/donors/donations'].flatMap((path) => + PAGES.map((query): [string, Record] => [path, query]), +); + +async function snapshot(): Promise> { + const out: Record = {}; + for (const [rawPath, queryStringParameters] of REQUESTS) { + const res = await handler({ + rawPath, + requestContext: { http: { method: 'GET' } }, + body: undefined, + queryStringParameters, + } as any); + out[`${rawPath}?${new URLSearchParams(queryStringParameters)}`] = { status: res.statusCode, body: res.body }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every donors GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + const donors = JSON.parse(soft['/donors?'].body).data as { donor_id: number }[]; + expect(donors.map((d) => d.donor_id)).not.toContain(PARITY_DELETES.donor); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/expenditures/controllers/expenditures.ts b/apps/backend/lambdas/expenditures/controllers/expenditures.ts index caac291e..45922e55 100644 --- a/apps/backend/lambdas/expenditures/controllers/expenditures.ts +++ b/apps/backend/lambdas/expenditures/controllers/expenditures.ts @@ -350,14 +350,8 @@ export const deleteExpenditure: RouteHandler = async ({ params, auth }) => { return json(404, { message: 'Expenditure not found' }); } - // After the row, never before: if the object went first and the delete - // below failed, the receipt would be gone with a row still pointing at it. - const receiptDeleted = await expendituresService.deleteReceiptObject( - expenditure.receipt_url, - expenditure.project_id, - ); - - return json(200, { ok: true, route: 'DELETE /expenditures/{id}', pathParams: { id }, receiptDeleted }); + // The receipt object stays in S3 so a soft delete can be restored. + return json(200, { ok: true, route: 'DELETE /expenditures/{id}', pathParams: { id } }); }; // PATCH /expenditures/{id}/status — approve/decline. `expense:review` on the diff --git a/apps/backend/lambdas/expenditures/jest.config.js b/apps/backend/lambdas/expenditures/jest.config.js index 3ed2e70d..acd0faa1 100644 --- a/apps/backend/lambdas/expenditures/jest.config.js +++ b/apps/backend/lambdas/expenditures/jest.config.js @@ -2,6 +2,8 @@ module.exports = { preset: 'ts-jest', testEnvironment: 'node', testMatch: ['**/*.test.ts'], + // Suites share one database; parallel workers truncate each other's fixtures. + maxWorkers: 1, extensionsToTreatAsEsm: ['.ts'], moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1', diff --git a/apps/backend/lambdas/expenditures/services/expenditures.ts b/apps/backend/lambdas/expenditures/services/expenditures.ts index 1a147f3d..82df0ddf 100644 --- a/apps/backend/lambdas/expenditures/services/expenditures.ts +++ b/apps/backend/lambdas/expenditures/services/expenditures.ts @@ -1,7 +1,6 @@ import { Insertable, Updateable } from 'kysely'; -import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'; +import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; -import { reportError } from '@branch/lambda-http'; import type { DB } from '@branch/types'; import { db, recordExpenditure, editExpenditure, removeExpenditure } from '@branch/store'; import type { ExpenditureStatus } from '../validation-utils'; @@ -32,36 +31,6 @@ export function receiptKeyForProject(objectUrl: string, projectId: number): stri return key && key.startsWith(`receipts/${projectId}/`) && !key.includes('..') ? key : null; } -/** - * Best-effort removal of the receipt behind a deleted expenditure. - * - * Deliberately never throws: the row is already gone by the time this runs, and - * the caller must not turn a successful delete into a 500 because S3 was - * unreachable or the role is missing `s3:DeleteObject`. A leftover object is - * recoverable; a row that cannot be deleted is not. - */ -export async function deleteReceiptObject(receiptUrl: string | null, projectId: number): Promise { - if (!receiptUrl) return true; - const key = receiptKeyForProject(receiptUrl, projectId); - if (!key) return false; - // Read at call time rather than using the module-level BUCKET: the value is - // then observable to callers that set it after import, which is what the - // unit tests do. - const bucket = process.env.REPORTS_BUCKET_NAME ?? ''; - if (!bucket) { - console.error('REPORTS_BUCKET_NAME is not set; leaving receipt object', key); - return false; - } - try { - await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: key })); - return true; - } catch (err) { - console.error('Failed to delete receipt object', key, err); - reportError(err, { key }); - return false; - } -} - 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 @@ -76,7 +45,10 @@ export async function countExpenditures(projectId: number | null, scope: Expendi return Number(rolledUp?.count || 0); } - let query = db.selectFrom('branch.expenditures').select(db.fn.count('expenditure_id').as('count')); + let query = db + .selectFrom('branch.expenditures') + .where('deleted_at', 'is', null) + .select(db.fn.count('expenditure_id').as('count')); if (projectId !== null) query = query.where('project_id', '=', projectId); const totalCount = await applyExpenditureScope(query, scope).executeTakeFirst(); @@ -88,7 +60,7 @@ export async function queryExpenditures( scope: ExpenditureScope, page?: { limit: number; offset: number }, ) { - let query = db.selectFrom('branch.expenditures').selectAll(); + let query = db.selectFrom('branch.expenditures').where('deleted_at', 'is', null).selectAll(); if (projectId !== null) query = query.where('project_id', '=', projectId); const scoped = applyExpenditureScope(query, scope) .orderBy('spent_on', 'desc') @@ -107,7 +79,12 @@ export async function findMembership(projectId: number, userId: number) { } export async function findProjectById(projectId: number) { - return db.selectFrom('branch.projects').where('project_id', '=', projectId).selectAll().executeTakeFirst(); + return db + .selectFrom('branch.projects') + .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) + .selectAll() + .executeTakeFirst(); } /** @@ -121,8 +98,12 @@ export async function findExpenditureWithNames(id: number) { return db .selectFrom('branch.expenditures as e') .innerJoin('branch.projects as p', 'p.project_id', 'e.project_id') - .leftJoin('branch.users as u', 'u.user_id', 'e.entered_by') + .leftJoin('branch.users as u', (join) => + join.onRef('u.user_id', '=', 'e.entered_by').on('u.deleted_at', 'is', null), + ) .where('e.expenditure_id', '=', id) + .where('e.deleted_at', 'is', null) + .where('p.deleted_at', 'is', null) .selectAll('e') .select(['p.name as project_name', 'u.name as submitted_by_name']) .executeTakeFirst(); @@ -133,7 +114,12 @@ export async function insertExpenditure(values: Insertable { @@ -158,12 +158,12 @@ async function firstExpenditureId(projectId: number): Promise { } } -// Directly queries the DB to confirm whether a row still exists +// Directly queries the DB to confirm whether a row is still live async function expenditureExists(id: number): Promise { const client = await pool.connect(); try { const result = await client.query( - 'SELECT 1 FROM branch.expenditures WHERE expenditure_id = $1', + 'SELECT 1 FROM branch.expenditures WHERE expenditure_id = $1 AND deleted_at IS NULL', [id] ); return (result.rowCount ?? 0) > 0; @@ -172,6 +172,14 @@ async function expenditureExists(id: number): Promise { } } +async function expenditureSoftDeleted(id: number): Promise { + const result = await pool.query( + 'SELECT 1 FROM branch.expenditures WHERE expenditure_id = $1 AND deleted_at IS NOT NULL', + [id] + ); + return (result.rowCount ?? 0) > 0; +} + describe('Expenditures integration tests', () => { beforeEach(async () => { jest.clearAllMocks(); @@ -546,6 +554,29 @@ describe('Expenditures integration tests', () => { const res = await handler(idRequestEvent('GET', id)); expect(res.statusCode).toBe(200); }); + + test('200: a soft-deleted author reads as null', async () => { + const id = await firstExpenditureId(1); // entered_by 4 + await removeUser(4); + + const res = await handler(idRequestEvent('GET', id)); + expect(res.statusCode).toBe(200); + const body = JSON.parse(res.body).body; + expect(body.enteredBy).toBeNull(); + expect(body.submittedByName).toBeNull(); + + const list = JSON.parse((await handler(getEvent('/'))).body).data; + expect(list.find((e: { expenditure_id: number }) => e.expenditure_id === id).entered_by).toBeNull(); + expect(list[0]).not.toHaveProperty('deleted_at'); + }); + + test('404: a soft-deleted expenditure is not found', async () => { + const id = await firstExpenditureId(1); + await pool.query('UPDATE branch.expenditures SET deleted_at = now() WHERE expenditure_id = $1', [id]); + + const res = await handler(idRequestEvent('GET', id)); + expect(res.statusCode).toBe(404); + }); }); describe('DELETE /expenditures/{id}', () => { @@ -619,7 +650,7 @@ describe('Expenditures integration tests', () => { const res = await handler(idRequestEvent('DELETE', id)); expect(res.statusCode).toBe(200); - expect(await expenditureExists(id)).toBe(false); + expect(await expenditureSoftDeleted(id)).toBe(true); }); test('200: admin can delete an expenditure on any project', async () => { @@ -627,7 +658,7 @@ describe('Expenditures integration tests', () => { const res = await handler(idRequestEvent('DELETE', id)); expect(res.statusCode).toBe(200); - expect(await expenditureExists(id)).toBe(false); + expect(await expenditureSoftDeleted(id)).toBe(true); }); test('404: deleting the same expenditure twice returns 404 the second time', async () => { @@ -644,7 +675,7 @@ describe('Expenditures integration tests', () => { const client = await pool.connect(); let totalBefore: number; try { - const result = await client.query('SELECT COUNT(*)::int AS count FROM branch.expenditures'); + const result = await client.query('SELECT COUNT(*)::int AS count FROM branch.expenditures WHERE deleted_at IS NULL'); totalBefore = result.rows[0].count; } finally { client.release(); @@ -656,7 +687,7 @@ describe('Expenditures integration tests', () => { const client2 = await pool.connect(); try { - const result = await client2.query('SELECT COUNT(*)::int AS count FROM branch.expenditures'); + const result = await client2.query('SELECT COUNT(*)::int AS count FROM branch.expenditures WHERE deleted_at IS NULL'); expect(result.rows[0].count).toBe(totalBefore - 1); } finally { client2.release(); diff --git a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts index f1fb1ca0..1788e9fb 100644 --- a/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts +++ b/apps/backend/lambdas/expenditures/test/expenditures.unit.test.ts @@ -32,8 +32,8 @@ jest.mock('@aws-sdk/s3-request-presigner', () => ({ getSignedUrl: jest.fn(async () => 'https://signed.example/url'), })); -// Nor must the receipt delete on DELETE /expenditures/{id}. Shared across -// instances so the assertions below can see the call. +// Nor must any S3 call. Shared across instances so the assertions below can +// see that DELETE /expenditures/{id} sends no DeleteObject. const mockS3Send = jest.fn<(command: unknown) => Promise>(); jest.mock('@aws-sdk/client-s3', () => ({ S3Client: jest.fn().mockImplementation(() => ({ send: mockS3Send })), @@ -131,59 +131,45 @@ const fakeExpenditure = { created_at: new Date('2025-06-01'), }; +function mockQuery(result: unknown | ((calls: string[]) => unknown)) { + const calls: string[] = []; + const settle = async () => (typeof result === 'function' ? (result as (c: string[]) => unknown)(calls) : result); + const methods: Record = {}; + const builder: any = new Proxy(methods, { + get(target, prop) { + if (typeof prop !== 'string' || prop === 'then') return undefined; + if (!(prop in target)) { + target[prop] = prop === 'execute' || prop === 'executeTakeFirst' + ? jest.fn(settle) + : jest.fn(() => { + calls.push(prop); + return builder; + }); + } + return target[prop]; + }, + }); + return builder; +} + +function mockQueryError(err: Error) { + return mockQuery(() => { + throw err; + }); +} + // Mocks the query chain used by the handler to fetch a single expenditure function mockSelectExpenditure(result: any, name?: string) { - return { - // GET /expenditures/{id} reads the row and the submitter and project names - // in one joined statement, so those names arrive as columns on the row. - innerJoin: jest.fn().mockReturnValue({ - leftJoin: jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest - .fn() - .mockReturnValue( - result && name - ? { ...result, project_name: name, submitted_by_name: name } - : result, - ), - }), - }), - }), - }), - }), - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(result), - }), - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(name ? { name } : undefined), - }), - }), - }; + return mockQuery((calls: string[]) => + calls.includes('innerJoin') && result && name + ? { ...result, project_name: name, submitted_by_name: name } + : result, + ); } // Mocks the query chain used by the handler to check project membership function mockMembership(result: any) { - return { - where: jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(result), - }), - }), - }), - }; -} - -// Mocks the query chain used by the handler to delete an expenditure -function mockDelete(numDeletedRows: bigint) { - return { - where: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue([{ numDeletedRows }]), - }), - }; + return mockQuery(result); } // Default authenticated admin user @@ -427,17 +413,11 @@ describe('POST /expenditures unit tests', () => { test('response has correct HTTP headers', async () => { // Setup mocks for successful expenditure creation - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 1, - name: 'Test Project', - total_budget: 50000, - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 1, + name: 'Test Project', + total_budget: 50000, + })); mockDb.insertInto.mockReturnValue({ values: jest.fn().mockReturnValue({ @@ -462,16 +442,10 @@ describe('POST /expenditures unit tests', () => { describe('Success Cases', () => { test('201: successful POST returns 201 status and correct response shape', async () => { // Mock: project exists - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 1, - name: 'Test Project', - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 1, + name: 'Test Project', + })); // Mock: insert succeeds mockDb.insertInto.mockReturnValue({ @@ -502,16 +476,10 @@ describe('POST /expenditures unit tests', () => { }); test('201: accepts explicit status and receipt_url', async () => { - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 1, - name: 'Test Project', - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 1, + name: 'Test Project', + })); mockDb.insertInto.mockReturnValue({ values: jest.fn().mockReturnValue({ @@ -549,13 +517,7 @@ describe('POST /expenditures unit tests', () => { test('404: returns 404 when project not found', async () => { // Mock: project doesn't exist - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(null as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(null)); const res = await handler( postEvent({ @@ -571,16 +533,10 @@ describe('POST /expenditures unit tests', () => { test('201: handles optional fields correctly', async () => { // Mock: project exists - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 2, - name: 'Another Project', - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 2, + name: 'Another Project', + })); // Mock: insert succeeds mockDb.insertInto.mockReturnValue({ @@ -607,16 +563,10 @@ describe('POST /expenditures unit tests', () => { describe('Error Handling', () => { test('500: returns 500 when database insert fails', async () => { // Mock: project exists - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - project_id: 1, - name: 'Test Project', - } as any), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery({ + project_id: 1, + name: 'Test Project', + })); mockRecordExpenditure.mockRejectedValue(new Error('Database connection failed')); @@ -634,13 +584,7 @@ describe('POST /expenditures unit tests', () => { test('500: returns 500 when project lookup fails', async () => { // Mock: project lookup throws error - mockDb.selectFrom.mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: (jest.fn() as any).mockRejectedValue(new Error('Database error')), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQueryError(new Error('Database error'))); const res = await handler( postEvent({ @@ -663,15 +607,7 @@ describe('POST /expenditures unit tests', () => { }); test('200: returns data array without pagination when no params', async () => { - mockDb.selectFrom.mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue(fakeExpenditures as any), - }), - }), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(fakeExpenditures)); const res = await handler(getEvent()); expect(res.statusCode).toBe(200); @@ -682,25 +618,9 @@ describe('POST /expenditures unit tests', () => { test('200: returns paginated response with page and limit', async () => { // count query - mockDb.selectFrom.mockReturnValueOnce({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ count: '3' } as any), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery({ count: '3' })); // data query - mockDb.selectFrom.mockReturnValueOnce({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue({ - limit: jest.fn().mockReturnValue({ - offset: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue([fakeExpenditures[0]] as any), - }), - }), - }), - }), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery([fakeExpenditures[0]])); const res = await handler(getEvent({ page: '1', limit: '1' })); expect(res.statusCode).toBe(200); @@ -941,63 +861,12 @@ describe('DELETE /expenditures/{id} unit tests', () => { }); }); - describe('the receipt goes with the row', () => { - const withReceipt = { - ...fakeExpenditure, - receipt_url: 'https://bucket.s3.us-east-2.amazonaws.com/receipts/1/flight.pdf', - }; - - beforeEach(() => { - mockMemberships.length = 0; - process.env.REPORTS_BUCKET_NAME = 'bucket'; - mockDb.selectFrom.mockReturnValueOnce(mockSelectExpenditure(withReceipt)); - mockRemoveExpenditure.mockResolvedValue(1n); - mockS3Send.mockResolvedValue({}); - }); - - test('deletes the receipt object', async () => { - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).receiptDeleted).toBe(true); - expect(mockS3Send).toHaveBeenCalledWith( - expect.objectContaining({ - __type: 'DeleteObject', - Bucket: 'bucket', - Key: 'receipts/1/flight.pdf', - }), - ); - }); - - test('a failing S3 delete still deletes the row', async () => { - // An orphaned object is recoverable; a row that cannot be deleted is not. - mockS3Send.mockRejectedValue(new Error('AccessDenied')); - - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).receiptDeleted).toBe(false); - }); - }); - - test('an expenditure with no receipt makes no S3 call', async () => { - process.env.REPORTS_BUCKET_NAME = 'bucket'; - mockDb.selectFrom.mockReturnValueOnce(mockSelectExpenditure(fakeExpenditure)); - mockRemoveExpenditure.mockResolvedValue(1n); - - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).receiptDeleted).toBe(true); - expect(mockS3Send).not.toHaveBeenCalled(); - }); - - test("never deletes a receipt stored under another project's prefix", async () => { + test('the receipt object is left in S3', async () => { process.env.REPORTS_BUCKET_NAME = 'bucket'; mockDb.selectFrom.mockReturnValueOnce( mockSelectExpenditure({ ...fakeExpenditure, - receipt_url: 'https://bucket.s3.us-east-2.amazonaws.com/receipts/2/theirs.pdf', + receipt_url: 'https://bucket.s3.us-east-2.amazonaws.com/receipts/1/flight.pdf', }), ); mockRemoveExpenditure.mockResolvedValue(1n); @@ -1005,8 +874,7 @@ describe('DELETE /expenditures/{id} unit tests', () => { const res = await handler(idEvent('DELETE', '5')); expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).receiptDeleted).toBe(false); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockS3Send).not.toHaveBeenCalledWith(expect.objectContaining({ __type: 'DeleteObject' })); }); test('409 when the expense was reviewed between the check and the delete', async () => { @@ -1089,15 +957,7 @@ describe('PATCH /expenditures/{id}/status unit tests', () => { ); mockDb.selectFrom.mockImplementation((table: string) => { - if (table === 'branch.users') { - return { - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: (jest.fn() as any).mockResolvedValue(submitter ?? undefined), - }), - }), - }; - } + if (table === 'branch.users') return mockQuery(submitter ?? undefined); throw new Error(`mockExpenditureForPatch: unexpected table "${table}"`); }); } diff --git a/apps/backend/lambdas/expenditures/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/expenditures/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..a3d3c9e7 --- /dev/null +++ b/apps/backend/lambdas/expenditures/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,116 @@ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); +jest.mock('../mailer'); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const LIST_QUERIES: Record[] = [ + {}, + { page: '1', limit: '3' }, + { page: '2', limit: '3' }, + { page: '1', limit: '100' }, + ...[1, 2, 3, 4].flatMap((projectId): Record[] => [ + { projectId: String(projectId) }, + { projectId: String(projectId), page: '1', limit: '100' }, + ]), +]; + +const REQUESTS: [string, Record][] = [ + ...LIST_QUERIES.map((query): [string, Record] => ['/expenditures', query]), + ...[1, 2, 3, 4, 5, 6].flatMap((id): [string, Record][] => [ + [`/expenditures/${id}`, {}], + [`/expenditures/${id}/receipt`, {}], + ]), +]; + +async function snapshot(): Promise> { + const out: Record = {}; + for (const [rawPath, queryStringParameters] of REQUESTS) { + const res = await handler({ + rawPath, + requestContext: { http: { method: 'GET' } }, + headers: { Authorization: 'Bearer fake-token' }, + queryStringParameters, + } as any); + out[`${rawPath}?${new URLSearchParams(queryStringParameters)}`] = { status: res.statusCode, body: res.body }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every expenditures GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + expect(soft[`/expenditures/${PARITY_DELETES.expenditure}?`].status).toBe(404); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/projects/controllers/dashboard.ts b/apps/backend/lambdas/projects/controllers/dashboard.ts index 758a9e7f..e2f60d62 100644 --- a/apps/backend/lambdas/projects/controllers/dashboard.ts +++ b/apps/backend/lambdas/projects/controllers/dashboard.ts @@ -49,6 +49,7 @@ export const getDashboard: RouteHandler = async () => { // 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') @@ -69,6 +70,7 @@ export const getDashboard: RouteHandler = async () => { .where('er.status', '=', APPROVED_EXPENDITURE_STATUS) .where('er.month', '>=', yearStart as any) .where('er.month', '<', 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 @@ -94,6 +96,7 @@ export const getDashboard: RouteHandler = async () => { 'spend.total as spent', 'pr.member_count as staff_count', ]) + .where('p.deleted_at', 'is', null) .orderBy('p.project_id', 'asc') .execute(), db.selectFrom('branch.expenditure_rollup') @@ -184,11 +187,17 @@ export const getOverview: RouteHandler = async (ctx) => { // None of the three below depend on the project row, so all four go out at // once and the 404 is settled from the result rather than ahead of them. const [project, members, expenditures, donationRow] = await Promise.all([ - db.selectFrom('branch.projects').where('project_id', '=', id).selectAll().executeTakeFirst(), + db + .selectFrom('branch.projects') + .where('project_id', '=', id) + .where('deleted_at', 'is', null) + .selectAll() + .executeTakeFirst(), listRoster(id), db .selectFrom('branch.expenditures') .where('project_id', '=', id) + .where('deleted_at', 'is', null) .selectAll() .orderBy('spent_on', 'desc') .execute(), diff --git a/apps/backend/lambdas/projects/controllers/donors.ts b/apps/backend/lambdas/projects/controllers/donors.ts index d8fe6270..2444404f 100644 --- a/apps/backend/lambdas/projects/controllers/donors.ts +++ b/apps/backend/lambdas/projects/controllers/donors.ts @@ -18,6 +18,7 @@ export const getProjectDonors: RouteHandler = async (ctx) => { const project = await db .selectFrom('branch.projects as p') .where('p.project_id', '=', projectId) + .where('p.deleted_at', 'is', null) .selectAll() .executeTakeFirst(); @@ -36,6 +37,9 @@ export const getProjectDonors: RouteHandler = async (ctx) => { .where('p.project_id', '=', projectId) .innerJoin('branch.project_donations as bpd', 'bpd.project_id', 'p.project_id') .innerJoin('branch.donors as bd', 'bd.donor_id', 'bpd.donor_id') + .where('p.deleted_at', 'is', null) + .where('bpd.deleted_at', 'is', null) + .where('bd.deleted_at', 'is', null) .select([ 'bd.donor_id', 'bd.organization', diff --git a/apps/backend/lambdas/projects/controllers/expenditures.ts b/apps/backend/lambdas/projects/controllers/expenditures.ts index 0ddeee94..a5c873e5 100644 --- a/apps/backend/lambdas/projects/controllers/expenditures.ts +++ b/apps/backend/lambdas/projects/controllers/expenditures.ts @@ -12,6 +12,7 @@ export const getProjectExpenditures: RouteHandler = async (ctx) => { const project = await db .selectFrom('branch.projects') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); @@ -22,6 +23,7 @@ export const getProjectExpenditures: RouteHandler = async (ctx) => { const expenditures = await db .selectFrom('branch.expenditures') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .selectAll() .orderBy('spent_on', 'desc') .execute(); diff --git a/apps/backend/lambdas/projects/controllers/members.ts b/apps/backend/lambdas/projects/controllers/members.ts index b803aba3..f010ddfc 100644 --- a/apps/backend/lambdas/projects/controllers/members.ts +++ b/apps/backend/lambdas/projects/controllers/members.ts @@ -30,6 +30,7 @@ export const getAssignableStaff: RouteHandler = async () => { .selectFrom('branch.users') .select(['user_id', 'name', 'email', 'profile_image']) .where('is_admin', 'is not', true) + .where('deleted_at', 'is', null) .where('is_staff', 'is not', true) .orderBy('name', 'asc') .execute(); diff --git a/apps/backend/lambdas/projects/controllers/projects.ts b/apps/backend/lambdas/projects/controllers/projects.ts index 15776c9c..eb7c143c 100644 --- a/apps/backend/lambdas/projects/controllers/projects.ts +++ b/apps/backend/lambdas/projects/controllers/projects.ts @@ -6,7 +6,6 @@ import { DEFAULT_PROJECT_ROLE, ProjectValidationUtils } from '../validation-util import { requireVisibleProject } from './project-guard'; import { ADMIN_ASSIGNMENT_MESSAGE, - deleteProjectObjects, findAdminUserIds, findUnknownUserIds, isProjectActive, @@ -28,7 +27,11 @@ export const listProjects: RouteHandler = async ({ auth }) => { // plan cache whatever the caller's project count. const scope = projectScopeIds(auth.subject); - let query = db.selectFrom('branch.projects').selectAll().orderBy('project_id', 'asc'); + let query = db + .selectFrom('branch.projects') + .where('deleted_at', 'is', null) + .selectAll() + .orderBy('project_id', 'asc'); if (scope) query = query.where(sql`project_id = ANY(${scope})`); const projects = await query.execute(); @@ -61,6 +64,7 @@ export const getProject: RouteHandler = async (ctx) => { const project = await db .selectFrom('branch.projects') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); if (!project) return json(404, { message: `Project not found for id: ${projectId}` }); @@ -100,6 +104,7 @@ export const updateProject: RouteHandler = async ({ event, params, auth }) => { const existing = await db .selectFrom('branch.projects') .where('project_id', '=', Number(id)) + .where('deleted_at', 'is', null) .select(['start_date', 'end_date']) .executeTakeFirst(); if (!existing) return json(404, { message: `Project not found for id: ${id}` }); @@ -155,14 +160,8 @@ export const deleteProject: RouteHandler = async ({ params }) => { return json(404, { message: 'Project not found' }); } - // The expenditure and report rows went with the project via ON DELETE - // CASCADE, so nothing is left to tell us which files they owned. Both - // services key their objects by project id, so clear those prefixes — - // otherwise every receipt and report for the project is orphaned at once, - // which is the single largest source of unreferenced objects. - const filesDeleted = await deleteProjectObjects(Number(id)); - - return json(200, { ok: true, route: 'DELETE /projects/{projectId}', pathParams: { id }, filesDeleted }); + // Files are kept so a soft-deleted project can be restored. + return json(200, { ok: true, route: 'DELETE /projects/{projectId}', pathParams: { id } }); }; // POST /projects — admin-only via `project:create` on the route. diff --git a/apps/backend/lambdas/projects/services/projects.ts b/apps/backend/lambdas/projects/services/projects.ts index 54d08d6c..1d9d5f27 100644 --- a/apps/backend/lambdas/projects/services/projects.ts +++ b/apps/backend/lambdas/projects/services/projects.ts @@ -1,77 +1,8 @@ -import { - S3Client, - ListObjectsV2Command, - DeleteObjectsCommand, -} from '@aws-sdk/client-s3'; -import { reportError } from '@branch/lambda-http'; import type { DB } from '@branch/types'; import { db } from '@branch/store'; import { ADMIN_MEMBER_ROLE, type MemberDisplayRole } from '@branch/rbac'; import { APPROVED_EXPENDITURE_STATUS, MemberAssignment } from '../validation-utils'; -const s3 = new S3Client({ region: process.env.AWS_REGION ?? 'us-east-2' }); - -/** Deletes every object under one prefix, following pagination. */ -async function deletePrefix(bucket: string, prefix: string): Promise { - let removed = 0; - let ContinuationToken: string | undefined; - - do { - const listed = await s3.send( - new ListObjectsV2Command({ Bucket: bucket, Prefix: prefix, ContinuationToken }), - ); - const keys = (listed.Contents ?? []) - .map((o) => o.Key) - .filter((k): k is string => Boolean(k)); - - if (keys.length > 0) { - // DeleteObjects caps at 1000 keys, which is also ListObjectsV2's page - // size, so one page maps to one delete call. - await s3.send( - new DeleteObjectsCommand({ - Bucket: bucket, - Delete: { Objects: keys.map((Key) => ({ Key })), Quiet: true }, - }), - ); - removed += keys.length; - } - - // Only follow the cursor while truncated; IsTruncated false ends the loop. - ContinuationToken = listed.IsTruncated ? listed.NextContinuationToken : undefined; - } while (ContinuationToken); - - return removed; -} - -/** - * Best-effort cleanup of the files a deleted project owned. - * - * Deliberately never throws: the project is already gone by the time this runs, - * and a delete that succeeded must not be reported as a 500 because S3 was - * unreachable or the role is missing `s3:DeleteObject`. Leftover objects are - * recoverable; a project that cannot be deleted is not. - */ -export async function deleteProjectObjects(projectId: number): Promise { - // Read at call time rather than at module load: the value is then observable - // to callers that set it after import, which is what the unit tests do. - const bucket = process.env.REPORTS_BUCKET_NAME ?? ''; - if (!bucket) { - console.error('REPORTS_BUCKET_NAME is not set; leaving files for project', projectId); - return null; - } - try { - const counts = await Promise.all([ - deletePrefix(bucket, `receipts/${projectId}/`), - deletePrefix(bucket, `reports/${projectId}/`), - ]); - return counts[0] + counts[1]; - } catch (err) { - console.error('Failed to delete objects for project', projectId, err); - reportError(err, { projectId }); - return null; - } -} - /** * Path segments carrying a project id are matched with this rather than a bare * "is there a segment here" check. Without it `/projects/assignable-staff` @@ -155,6 +86,7 @@ export async function listRoster(projectId: number): Promise { .selectFrom('branch.users') .select(['user_id', 'name', 'email', 'profile_image']) .where('is_admin', 'is', true) + .where('deleted_at', 'is', null) .where('is_staff', 'is not', true) .orderBy('name', 'asc') .execute(), @@ -163,6 +95,7 @@ export async function listRoster(projectId: number): Promise { .innerJoin('branch.users as u', 'u.user_id', 'pm.user_id') .select(['u.user_id', 'u.name', 'u.email', 'u.profile_image', 'pm.role']) .where('pm.project_id', '=', projectId) + .where('u.deleted_at', 'is', null) .orderBy('u.name', 'asc') .execute(), ]); @@ -186,6 +119,7 @@ export async function loadAdminHeadcount(projectIds: number[]): Promise<{ .selectFrom('branch.users') .select((eb) => eb.fn.countAll().as('count')) .where('is_admin', 'is', true) + .where('deleted_at', 'is', null) .where('is_staff', 'is not', true) .executeTakeFirst(), projectIds.length === 0 @@ -195,6 +129,7 @@ export async function loadAdminHeadcount(projectIds: number[]): Promise<{ .innerJoin('branch.users as u', 'u.user_id', 'pm.user_id') .select(['pm.project_id', (eb) => eb.fn.countAll().as('count')]) .where('u.is_admin', 'is', true) + .where('u.deleted_at', 'is', null) .where('pm.project_id', 'in', projectIds) .groupBy('pm.project_id') .execute(), @@ -215,6 +150,7 @@ export async function findAdminUserIds(members: MemberAssignment[]): Promise r.user_id)); diff --git a/apps/backend/lambdas/projects/test/delete-objects.unit.test.ts b/apps/backend/lambdas/projects/test/delete-objects.unit.test.ts index bbd10019..000637ae 100644 --- a/apps/backend/lambdas/projects/test/delete-objects.unit.test.ts +++ b/apps/backend/lambdas/projects/test/delete-objects.unit.test.ts @@ -1,11 +1,6 @@ /** - * DELETE /projects/{id} clears the project's files out of the bucket. - * - * The expenditure and report rows go with the project via ON DELETE CASCADE, so - * by the time the handler could look, nothing names the files any more. Both - * services key their objects by project id, so the prefixes are the only record - * left — which makes a project delete the single largest source of orphans if - * this does not run. + * DELETE /projects/{id} keeps the project's files: the delete is soft, so a + * restore must find its receipts and reports still in the bucket. */ import { describe, test, expect, beforeEach, jest } from '@jest/globals'; @@ -38,12 +33,8 @@ jest.mock('@branch/store', () => ({ const mockS3Send = jest.fn<(command: any) => Promise>(); jest.mock('@aws-sdk/client-s3', () => ({ S3Client: jest.fn().mockImplementation(() => ({ send: mockS3Send })), - ListObjectsV2Command: jest - .fn() - .mockImplementation((p: unknown) => ({ __type: 'List', ...(p as object) })), - DeleteObjectsCommand: jest - .fn() - .mockImplementation((p: unknown) => ({ __type: 'DeleteObjects', ...(p as object) })), + ListObjectsV2Command: jest.fn(), + DeleteObjectsCommand: jest.fn(), })); import { handler } from '../handler'; @@ -61,107 +52,29 @@ const adminContext = { user: { cognitoSub: 'admin-sub', userId: 1, email: 'admin@branch.org', isAdmin: true }, }; -/** Answers a List for `prefix` with `keys`, and every other List as empty. */ -function listReturns(map: Record) { - mockS3Send.mockImplementation(async (command: any) => { - if (command.__type === 'List') { - const keys = map[command.Prefix] ?? []; - return { Contents: keys.map((Key) => ({ Key })), IsTruncated: false }; - } - return {}; - }); -} - -describe('DELETE /projects/{id} object cleanup', () => { +describe('DELETE /projects/{id} keeps files', () => { beforeEach(() => { jest.clearAllMocks(); process.env.REPORTS_BUCKET_NAME = 'bucket'; mockSubject.isAdmin = true; - mockAuthenticateRequest.mockResolvedValue(adminContext as never); + mockAuthenticateRequest.mockResolvedValue(adminContext as never); mockDeleteExecute.mockResolvedValue(1n as never); }); - test('clears both the receipts and reports prefixes for that project', async () => { - listReturns({ - 'receipts/7/': ['receipts/7/a.pdf', 'receipts/7/b.pdf'], - 'reports/7/': ['reports/7/q1.docx'], - }); - + test('deletes the project without touching S3', async () => { const res = await handler(deleteEvent(7)); expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).filesDeleted).toBe(3); - - const deleted = mockS3Send.mock.calls - .map(([c]) => c) - .filter((c: any) => c.__type === 'DeleteObjects') - .flatMap((c: any) => c.Delete.Objects.map((o: any) => o.Key)); - - expect(deleted.sort()).toEqual([ - 'receipts/7/a.pdf', - 'receipts/7/b.pdf', - 'reports/7/q1.docx', - ]); - }); - - test('scopes the listing to that project, not the whole bucket', async () => { - listReturns({}); - - await handler(deleteEvent(7)); - - const prefixes = mockS3Send.mock.calls - .map(([c]) => c) - .filter((c: any) => c.__type === 'List') - .map((c: any) => c.Prefix); - - expect(prefixes.sort()).toEqual(['receipts/7/', 'reports/7/']); - }); - - test('issues no delete when the project owns no files', async () => { - listReturns({}); - - const res = await handler(deleteEvent(7)); - - expect(JSON.parse(res.body).filesDeleted).toBe(0); - expect( - mockS3Send.mock.calls.map(([c]) => c).some((c: any) => c.__type === 'DeleteObjects'), - ).toBe(false); - }); - - test('follows pagination past the 1000-key page limit', async () => { - let call = 0; - mockS3Send.mockImplementation(async (command: any) => { - if (command.__type !== 'List') return {}; - if (command.Prefix !== 'receipts/7/') return { Contents: [], IsTruncated: false }; - call += 1; - // First page is truncated, so the loop must come back with the cursor. - return call === 1 - ? { Contents: [{ Key: 'receipts/7/1.pdf' }], IsTruncated: true, NextContinuationToken: 'tok' } - : { Contents: [{ Key: 'receipts/7/2.pdf' }], IsTruncated: false }; + expect(JSON.parse(res.body)).toEqual({ + ok: true, + route: 'DELETE /projects/{projectId}', + pathParams: { id: '7' }, }); - - const res = await handler(deleteEvent(7)); - - expect(JSON.parse(res.body).filesDeleted).toBe(2); - const second = mockS3Send.mock.calls - .map(([c]) => c) - .find((c: any) => c.__type === 'List' && c.ContinuationToken === 'tok'); - expect(second).toBeDefined(); - }); - - test('a failing S3 cleanup still deletes the project', async () => { - // Leftover objects are recoverable; a project that cannot be deleted is not. - mockS3Send.mockRejectedValue(new Error('AccessDenied') as never); - - const res = await handler(deleteEvent(7)); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).filesDeleted).toBeNull(); + expect(mockS3Send).not.toHaveBeenCalled(); }); - test('touches nothing when the row was already gone', async () => { + test('404s when the row was already gone', async () => { mockDeleteExecute.mockResolvedValue(0n as never); - listReturns({ 'receipts/7/': ['receipts/7/a.pdf'] }); const res = await handler(deleteEvent(7)); @@ -175,6 +88,6 @@ describe('DELETE /projects/{id} object cleanup', () => { const res = await handler(deleteEvent(7)); expect(res.statusCode).toBe(403); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockDeleteExecute).not.toHaveBeenCalled(); }); }); diff --git a/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts b/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts index 0646f9a4..fec414ac 100644 --- a/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/rollup-store.e2e.test.ts @@ -46,6 +46,7 @@ async function auditRollups(client: PoolClient): Promise { 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 @@ -63,10 +64,11 @@ async function auditRollups(client: PoolClient): Promise { 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) AS total_donated, - (SELECT count(*) FROM branch.project_donations d WHERE d.project_id = p.project_id) AS donation_count, - (SELECT count(*) FROM branch.reports r WHERE r.project_id = p.project_id) AS report_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 @@ -239,11 +241,21 @@ describe('expenditure_rollup', () => { const orphans = await client.query(` SELECT (SELECT count(*)::int FROM branch.expenditure_rollup er - LEFT JOIN branch.projects p USING (project_id) WHERE p.project_id IS NULL) AS exp_orphans, + 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 USING (project_id) WHERE p.project_id IS NULL) AS proj_orphans + 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 }); }); }); @@ -308,8 +320,10 @@ describe('project_rollup', () => { expect(await removeUser(4)).toBe(1n); await auditRollups(client); - const gone = await client.query('SELECT 1 FROM branch.users WHERE user_id = 4'); - expect(gone.rows).toHaveLength(0); + 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', ); diff --git a/apps/backend/lambdas/projects/test/rollups.e2e.test.ts b/apps/backend/lambdas/projects/test/rollups.e2e.test.ts index ea86056c..aab86e1b 100644 --- a/apps/backend/lambdas/projects/test/rollups.e2e.test.ts +++ b/apps/backend/lambdas/projects/test/rollups.e2e.test.ts @@ -81,6 +81,7 @@ async function auditRollups(client: PoolClient): Promise { 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 @@ -98,10 +99,11 @@ async function auditRollups(client: PoolClient): Promise { 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) AS total_donated, - (SELECT count(*) FROM branch.project_donations d WHERE d.project_id = p.project_id) AS donation_count, - (SELECT count(*) FROM branch.reports r WHERE r.project_id = p.project_id) AS report_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 @@ -273,11 +275,21 @@ describe('expenditure spend reaches the dashboard', () => { const orphans = await client.query(` SELECT (SELECT count(*)::int FROM branch.expenditure_rollup er - LEFT JOIN branch.projects p USING (project_id) WHERE p.project_id IS NULL) AS exp_orphans, + 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 USING (project_id) WHERE p.project_id IS NULL) AS proj_orphans + 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 }); }); }); @@ -365,7 +377,7 @@ describe('rollup-backed read paths agree with the base tables', () => { test('dashboard totalSpent equals the approved sum for the year', async () => { const { rows } = await client.query(` SELECT COALESCE(SUM(amount), 0) AS total FROM branch.expenditures - WHERE status = 'approved' + WHERE status = 'approved' AND deleted_at IS NULL AND spent_on >= date_trunc('year', CURRENT_DATE) AND spent_on < date_trunc('year', CURRENT_DATE) + INTERVAL '1 year' `); @@ -376,7 +388,7 @@ describe('rollup-backed read paths agree with the base tables', () => { test('dashboard per-project spend equals the approved sum per project', async () => { const { rows } = await client.query(` SELECT project_id, SUM(amount) AS total FROM branch.expenditures - WHERE status = 'approved' GROUP BY project_id + WHERE status = 'approved' AND deleted_at IS NULL GROUP BY project_id `); const expected = new Map(rows.map((r) => [r.project_id, Number(r.total)])); @@ -391,7 +403,7 @@ describe('rollup-backed read paths agree with the base tables', () => { SELECT to_char(date_trunc('month', spent_on), 'YYYY-MM') AS month, category, SUM(amount) AS total FROM branch.expenditures - WHERE status = 'approved' AND category IS NOT NULL + WHERE status = 'approved' AND category IS NOT NULL AND deleted_at IS NULL AND spent_on >= date_trunc('year', CURRENT_DATE) AND spent_on < date_trunc('year', CURRENT_DATE) + INTERVAL '1 year' GROUP BY 1, 2 ORDER BY 1, 2 diff --git a/apps/backend/lambdas/projects/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/projects/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..f2fbc62c --- /dev/null +++ b/apps/backend/lambdas/projects/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,109 @@ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const PATHS = [ + '/projects', + '/projects/dashboard', + '/projects/assignable-staff', + ...[1, 2, 3, 4].flatMap((id) => [ + `/projects/${id}`, + `/projects/${id}/members`, + `/projects/${id}/overview`, + `/projects/${id}/donors`, + `/projects/${id}/expenditures`, + ]), +]; + +async function snapshot(): Promise> { + const out: Record = {}; + for (const rawPath of PATHS) { + const res = await handler({ + rawPath, + requestContext: { http: { method: 'GET' } }, + headers: { Authorization: 'Bearer fake-token' }, + queryStringParameters: {}, + } as any); + out[rawPath] = { status: res.statusCode, body: res.body }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every projects GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + expect(soft[`/projects/${PARITY_DELETES.project}`].status).toBe(404); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/reports/controllers/reports.ts b/apps/backend/lambdas/reports/controllers/reports.ts index 04882b84..3b063b95 100644 --- a/apps/backend/lambdas/reports/controllers/reports.ts +++ b/apps/backend/lambdas/reports/controllers/reports.ts @@ -1,6 +1,6 @@ -import { S3Client, PutObjectCommand, GetObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'; +import { S3Client, PutObjectCommand, GetObjectCommand } from '@aws-sdk/client-s3'; import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; -import { json, parseBody, reportError, serverError } from '@branch/lambda-http'; +import { json, parseBody, serverError } from '@branch/lambda-http'; import type { RouteHandler } from '@branch/lambda-http'; import { db, recordReport, removeReport } from '@branch/store'; import { @@ -37,36 +37,6 @@ type ReportType = typeof REPORT_TYPES[number]; // Numeric-only id, mirroring the old REPORT_ID_ROUTE/REPORT_DOWNLOAD_ROUTE regexes // so a non-numeric :id falls through to the same 404 as an unmatched route. -/** - * Best-effort removal of the generated file behind a deleted report. - * - * Deliberately never throws: the row is already gone by the time this runs, and - * the caller must not turn a successful delete into a 500 because S3 was - * unreachable or the role is missing `s3:DeleteObject`. A leftover object is - * recoverable; a row that cannot be deleted is not. - */ -async function deleteReportObject(objectUrl: string | null): Promise { - if (!objectUrl) return true; - const key = keyFromObjectUrl(objectUrl); - if (!key) return false; - // Read at call time rather than using the module-level BUCKET: the value is - // then observable to callers that set it after import, which is what the - // unit tests do. - const bucket = process.env.REPORTS_BUCKET_NAME ?? ''; - if (!bucket) { - console.error('REPORTS_BUCKET_NAME is not set; leaving report object', key); - return false; - } - try { - await s3.send(new DeleteObjectCommand({ Bucket: bucket, Key: key })); - return true; - } catch (err) { - console.error('Failed to delete report object', key, err); - reportError(err, { key }); - return false; - } -} - function notFoundUnlessNumericId(id: string, path: string, method: string) { return /^\d+$/.test(id) ? undefined : json(404, { message: 'Not Found', path, method }); } @@ -165,7 +135,7 @@ export const listReports: RouteHandler = async ({ event }) => { ? 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 pageQuery = db.selectFrom('branch.reports').selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc'); + 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([ @@ -183,8 +153,8 @@ export const listReports: RouteHandler = async ({ event }) => { } const reports = projectId !== null - ? await db.selectFrom('branch.reports').where('project_id', '=', projectId).selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc').execute() - : await db.selectFrom('branch.reports').selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc').execute(); + ? await db.selectFrom('branch.reports').where('project_id', '=', projectId).where('deleted_at', 'is', null).selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc').execute() + : await db.selectFrom('branch.reports').where('deleted_at', 'is', null).selectAll().orderBy('date_created', 'desc').orderBy('report_id', 'desc').execute(); return json(200, { data: reports }); }; @@ -211,6 +181,7 @@ export const getUploadUrl: RouteHandler = async ({ event }) => { const projectExists = await db.selectFrom('branch.projects') .where('project_id', '=', projectId) + .where('deleted_at', 'is', null) .select('project_id') .executeTakeFirst(); if (!projectExists) return json(404, { message: 'Project not found' }); @@ -250,6 +221,7 @@ export const createReport: RouteHandler = async ({ event }) => { const projectExists = await db.selectFrom('branch.projects') .where('project_id', '=', projectId as number) + .where('deleted_at', 'is', null) .select('project_id') .executeTakeFirst(); if (!projectExists) return json(404, { message: 'Project not found' }); @@ -264,6 +236,7 @@ export const createReport: RouteHandler = async ({ event }) => { // Two rows on one object would let deleting either break the other's download. const alreadyRegistered = await db.selectFrom('branch.reports') .where('object_url', '=', objectUrl) + .where('deleted_at', 'is', null) .select('report_id') .executeTakeFirst(); if (alreadyRegistered) { @@ -285,7 +258,7 @@ export const downloadReport: RouteHandler = async ({ params, path, method }) => if (notFound) return notFound; const id = params.id; - const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).selectAll().executeTakeFirst(); + const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).where('deleted_at', 'is', null).selectAll().executeTakeFirst(); if (!report) return json(404, { message: 'Report not found' }); const key = keyFromObjectUrl(report.object_url); @@ -306,7 +279,7 @@ export const getReport: RouteHandler = async ({ params, path, method }) => { if (notFound) return notFound; const id = params.id; - const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).selectAll().executeTakeFirst(); + const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).where('deleted_at', 'is', null).selectAll().executeTakeFirst(); if (!report) return json(404, { message: 'Report not found' }); return json(200, { ok: true, route: 'GET /reports/{id}', pathParams: { id }, body: report }); @@ -317,7 +290,7 @@ export const deleteReport: RouteHandler = async ({ params, path, method }) => { if (notFound) return notFound; const id = params.id; - const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).selectAll().executeTakeFirst(); + const report = await db.selectFrom('branch.reports').where('report_id', '=', Number(id)).where('deleted_at', 'is', null).select('report_id').executeTakeFirst(); if (!report) return json(404, { message: 'Report not found' }); const deleted = await removeReport(Number(id)); @@ -325,16 +298,8 @@ export const deleteReport: RouteHandler = async ({ params, path, method }) => { return json(404, { message: 'Report not found' }); } - // After the row, never before: if the file went first and this delete - // failed, the report would be gone with a row still pointing at it. - // Rows registered before the duplicate check may still share the object. - const stillReferenced = await db.selectFrom('branch.reports') - .where('object_url', '=', report.object_url) - .select('report_id') - .executeTakeFirst(); - const fileDeleted = stillReferenced ? false : await deleteReportObject(report.object_url); - - return json(200, { ok: true, route: 'DELETE /reports/{id}', pathParams: { id }, fileDeleted }); + // The file stays in S3 so a soft delete can be restored. + return json(200, { ok: true, route: 'DELETE /reports/{id}', pathParams: { id } }); }; async function withSizes(rows: T[]) { diff --git a/apps/backend/lambdas/reports/report-service.ts b/apps/backend/lambdas/reports/report-service.ts index 2522e5c9..03826f23 100644 --- a/apps/backend/lambdas/reports/report-service.ts +++ b/apps/backend/lambdas/reports/report-service.ts @@ -127,6 +127,7 @@ export async function fetchReportData(projectId: number): Promise + join + .onRef('branch.users.user_id', '=', 'branch.expenditures.entered_by') + .on('branch.users.deleted_at', 'is', null), + ) .where('branch.expenditures.project_id', '=', projectId) + .where('branch.expenditures.deleted_at', 'is', null) .where('branch.expenditures.status', '=', APPROVED_EXPENDITURE_STATUS) .select([ 'branch.expenditures.category', diff --git a/apps/backend/lambdas/reports/test/reports.e2e.test.ts b/apps/backend/lambdas/reports/test/reports.e2e.test.ts index b96dd95d..747aa027 100644 --- a/apps/backend/lambdas/reports/test/reports.e2e.test.ts +++ b/apps/backend/lambdas/reports/test/reports.e2e.test.ts @@ -465,19 +465,34 @@ describe('Reports e2e tests', () => { }; } - test('200: admin can delete a report, removed from db', async () => { + test('200: admin can delete a report, soft-deleted in db', async () => { const res = await handler(idEvent('DELETE', 4)); expect(res.statusCode).toBe(200); const client = await pool.connect(); try { - const result = await client.query('SELECT * FROM branch.reports WHERE report_id = 4'); - expect(result.rows.length).toBe(0); + const result = await client.query('SELECT deleted_at FROM branch.reports WHERE report_id = 4'); + expect(result.rows.length).toBe(1); + expect(result.rows[0].deleted_at).not.toBeNull(); } finally { client.release(); } }); + test('a deleted report is gone from reads', async () => { + expect((await handler(idEvent('DELETE', 4))).statusCode).toBe(200); + + expect((await handler(idEvent('GET', 4))).statusCode).toBe(404); + const list = await handler({ + rawPath: '/reports', + requestContext: { http: { method: 'GET' } }, + headers: { Authorization: 'Bearer fake-token' }, + queryStringParameters: {}, + }); + const ids = JSON.parse(list.body).data.map((r: { report_id: number }) => r.report_id); + expect(ids).not.toContain(4); + }); + test('404: non-numeric id falls through to catch-all', async () => { const res = await handler(idEvent('DELETE', 'abc')); expect(res.statusCode).toBe(404); @@ -506,7 +521,7 @@ describe('Reports e2e tests', () => { const client = await pool.connect(); let totalBefore: number; try { - const result = await client.query('SELECT COUNT(*)::int AS count FROM branch.reports'); + const result = await client.query('SELECT COUNT(*)::int AS count FROM branch.reports WHERE deleted_at IS NULL'); totalBefore = result.rows[0].count; } finally { client.release(); @@ -517,25 +532,23 @@ describe('Reports e2e tests', () => { const client2 = await pool.connect(); try { - const result = await client2.query('SELECT COUNT(*)::int AS count FROM branch.reports'); + const result = await client2.query('SELECT COUNT(*)::int AS count FROM branch.reports WHERE deleted_at IS NULL'); expect(result.rows[0].count).toBe(totalBefore - 1); } finally { client2.release(); } }); - test('200: deleting a report whose object_url is not under the reports bucket still deletes the row, fileDeleted false', async () => { - // Seed report 5's object_url ('https://s3.amazonaws.com/reports/b.pdf' or - // similar legacy-style URL) may not resolve via keyFromObjectUrl against + test('200: deleting a report whose object_url is not under the reports bucket still deletes the row', async () => { + // Seed report 2's object_url may not resolve via keyFromObjectUrl against // the current REPORTS_BUCKET_NAME; either way the row must go. const res = await handler(idEvent('DELETE', 2)); expect(res.statusCode).toBe(200); - expect(typeof JSON.parse(res.body).fileDeleted).toBe('boolean'); const client = await pool.connect(); try { - const result = await client.query('SELECT * FROM branch.reports WHERE report_id = 2'); - expect(result.rows.length).toBe(0); + const result = await client.query('SELECT 1 FROM branch.reports WHERE report_id = 2 AND deleted_at IS NOT NULL'); + expect(result.rows.length).toBe(1); } finally { client.release(); } diff --git a/apps/backend/lambdas/reports/test/reports.unit.test.ts b/apps/backend/lambdas/reports/test/reports.unit.test.ts index a96fb20a..88244dd3 100644 --- a/apps/backend/lambdas/reports/test/reports.unit.test.ts +++ b/apps/backend/lambdas/reports/test/reports.unit.test.ts @@ -23,7 +23,6 @@ jest.mock('../auth', () => { ), }; }); -// Shared across instances so the delete assertions below can see the call. const mockS3Send = jest.fn<(command: unknown) => Promise>(); jest.mock('@aws-sdk/client-s3', () => ({ S3Client: jest.fn().mockImplementation(() => ({ send: mockS3Send })), @@ -63,6 +62,22 @@ const mockRecordReport = recordReport as jest.MockedFunction; const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; const mockReportService = reportService as jest.Mocked; + +function mockQuery(result: unknown) { + const methods: Record = {}; + const builder: any = new Proxy(methods, { + get(target, prop) { + if (typeof prop !== 'string' || prop === 'then') return undefined; + if (!(prop in target)) { + target[prop] = prop === 'execute' || prop === 'executeTakeFirst' + ? jest.fn(async () => result) + : jest.fn(() => builder); + } + return target[prop]; + }, + }); + return builder; +} function getEvent(queryStringParameters?: Record) { return { rawPath: '/', @@ -114,13 +129,6 @@ function postEvent(body: Record) { }; } -// Every list query orders by date then id; this lets one mock answer both calls. -function orderable(next: T): T { - const node: any = { ...next }; - node.orderBy = jest.fn().mockReturnValue(node); - return node; -} - describe('POST /reports unit tests', () => { beforeEach(() => { jest.clearAllMocks(); @@ -287,13 +295,7 @@ describe('GET /reports unit tests', () => { describe('Response format', () => { test('200: returns data array without pagination when no params', async () => { - mockDb.selectFrom.mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue(orderable({ - execute: jest.fn().mockReturnValue(fakeReports as any), - })), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(fakeReports)); const res = await handler(getEvent()); expect(res.statusCode).toBe(200); @@ -321,22 +323,8 @@ describe('GET /reports unit tests', () => { // file_size at all, so these live under Pagination rather than Response format. describe('File sizes (paginated results only)', () => { function mockPaginatedQuery(rows: typeof fakeReports) { - mockDb.selectFrom.mockReturnValueOnce({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ count: String(rows.length) } as any), - }), - }); - mockDb.selectFrom.mockReturnValueOnce({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue(orderable({ - limit: jest.fn().mockReturnValue({ - offset: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue(rows as any), - }), - }), - })), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery({ count: String(rows.length) })); + mockDb.selectFrom.mockReturnValueOnce(mockQuery(rows)); } test('200: each report includes file_size sourced from getObjectSize', async () => { @@ -363,23 +351,9 @@ describe('GET /reports unit tests', () => { describe('Pagination', () => { test('200: returns paginated response with page and limit', async () => { // count query - mockDb.selectFrom.mockReturnValueOnce({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ count: '3' } as any), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery({ count: '3' })); // data query - mockDb.selectFrom.mockReturnValueOnce({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue(orderable({ - limit: jest.fn().mockReturnValue({ - offset: jest.fn().mockReturnValue({ - execute: jest.fn().mockReturnValue([fakeReports[0]] as any), - }), - }), - })), - }), - }); + mockDb.selectFrom.mockReturnValueOnce(mockQuery([fakeReports[0]])); const res = await handler(getEvent({ page: '1', limit: '1' })); expect(res.statusCode).toBe(200); @@ -392,13 +366,7 @@ describe('GET /reports unit tests', () => { }); test('200: only page provided returns all without pagination', async () => { - mockDb.selectFrom.mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue(orderable({ - execute: jest.fn().mockReturnValue(fakeReports as any), - })), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(fakeReports)); const res = await handler(getEvent({ page: '1' })); const json = JSON.parse(res.body); @@ -407,13 +375,7 @@ describe('GET /reports unit tests', () => { }); test('200: only limit provided returns all without pagination', async () => { - mockDb.selectFrom.mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - orderBy: jest.fn().mockReturnValue(orderable({ - execute: jest.fn().mockReturnValue(fakeReports as any), - })), - }), - }); + mockDb.selectFrom.mockReturnValue(mockQuery(fakeReports)); const res = await handler(getEvent({ limit: '2' })); const json = JSON.parse(res.body); @@ -473,14 +435,8 @@ describe('GET /reports/upload-url unit tests', () => { } function setupProjectMock(project: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - // First the project lookup; POST /reports then checks for a duplicate objectUrl. - executeTakeFirst: jest.fn().mockReturnValueOnce(project as any).mockReturnValue(undefined), - }), - }), - }); + // The project lookup, then POST /reports' duplicate-objectUrl check. + mockDb.selectFrom = jest.fn().mockReturnValueOnce(mockQuery(project)).mockReturnValue(mockQuery(undefined)); } beforeEach(() => { @@ -622,17 +578,11 @@ describe('Route precedence', () => { // the three-segment download route must be matched before the two-segment // getReport route swallows it as an id lookup with a trailing extra segment. test('GET /reports/{id}/download reaches downloadReport, not the /reports/{id} controller', async () => { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ - report_id: 5, - project_id: 1, - object_url: 'https://bucket.s3.us-east-2.amazonaws.com/reports/1/gen.pdf', - } as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery({ + report_id: 5, + project_id: 1, + object_url: 'https://bucket.s3.us-east-2.amazonaws.com/reports/1/gen.pdf', + })); const res = await handler({ rawPath: '/reports/5/download', requestContext: { http: { method: 'GET' } }, @@ -666,14 +616,8 @@ describe('POST /reports unit tests', () => { } function setupProjectMock(project: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - // First the project lookup; POST /reports then checks for a duplicate objectUrl. - executeTakeFirst: jest.fn().mockReturnValueOnce(project as any).mockReturnValue(undefined), - }), - }), - }); + // The project lookup, then POST /reports' duplicate-objectUrl check. + mockDb.selectFrom = jest.fn().mockReturnValueOnce(mockQuery(project)).mockReturnValue(mockQuery(undefined)); } beforeEach(() => { @@ -758,13 +702,7 @@ describe('POST /reports unit tests', () => { }); test('409: an objectUrl already registered as a report is refused', async () => { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue({ project_id: 1, report_id: 7 } as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery({ project_id: 1, report_id: 7 })); const res = await handler(postEvent({ title: 'T', projectId: 1, objectUrl: fakeObjectUrl })); expect(res.statusCode).toBe(409); expect(mockRecordReport).not.toHaveBeenCalled(); @@ -829,13 +767,7 @@ describe('GET /reports/{id} unit tests', () => { }; function setupReportMock(report: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(report as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery(report)); } beforeEach(() => { @@ -928,13 +860,7 @@ describe('GET /reports/{id}/download unit tests', () => { }; function setupReportMock(report: Record | undefined) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(report as any), - }), - }), - }); + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery(report)); } beforeEach(() => { @@ -1014,21 +940,8 @@ describe('DELETE /reports/{id} unit tests', () => { date_created: new Date('2025-01-01'), }; - function setupReportMock( - report: Record | undefined, - sharedWith?: Record, - ) { - mockDb.selectFrom = jest.fn().mockReturnValue({ - where: jest.fn().mockReturnValue({ - selectAll: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(report as any), - }), - // Whether another row still points at the same object. - select: jest.fn().mockReturnValue({ - executeTakeFirst: jest.fn().mockReturnValue(sharedWith as any), - }), - }), - }); + function setupReportMock(report: Record | undefined) { + mockDb.selectFrom = jest.fn().mockReturnValue(mockQuery(report)); } function setupDeleteMock(numDeletedRows: bigint) { @@ -1104,78 +1017,18 @@ describe('DELETE /reports/{id} unit tests', () => { expect(res.statusCode).toBe(403); }); - test('200: a report with no object_url deletes cleanly, fileDeleted is true, and S3 is never called', async () => { - setupReportMock({ ...fakeReport, object_url: null }); - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).fileDeleted).toBe(true); - expect(mockS3Send).not.toHaveBeenCalled(); - }); - - describe('the generated file goes with the row', () => { - const storedReport = { + test('200: the generated file is left in S3', async () => { + process.env.REPORTS_BUCKET_NAME = 'bucket'; + setupReportMock({ ...fakeReport, object_url: 'https://bucket.s3.us-east-2.amazonaws.com/reports/2/gen.pdf', - }; - - beforeEach(() => { - process.env.REPORTS_BUCKET_NAME = 'bucket'; - setupReportMock(storedReport); - mockS3Send.mockResolvedValue({}); - }); - - test('deletes the object behind the report', async () => { - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).fileDeleted).toBe(true); - expect(mockS3Send).toHaveBeenCalledWith( - expect.objectContaining({ - __type: 'DeleteObject', - Bucket: 'bucket', - Key: 'reports/2/gen.pdf', - }), - ); }); - test('keeps the object while another report still points at it', async () => { - setupReportMock(storedReport, { report_id: 6 }); - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).fileDeleted).toBe(false); - expect(mockS3Send).not.toHaveBeenCalled(); - }); - - test('a failing S3 delete still deletes the row', async () => { - // An orphaned object is recoverable; a row that cannot be deleted is - // not, so S3 trouble must not turn a successful delete into a 500. - mockS3Send.mockRejectedValue(new Error('AccessDenied')); - - const res = await handler(idEvent('DELETE', '5')); - - expect(res.statusCode).toBe(200); - expect(JSON.parse(res.body).fileDeleted).toBe(false); - }); + const res = await handler(idEvent('DELETE', '5')); - test('the row is deleted before the object', async () => { - const order: string[] = []; - mockRemoveReport.mockImplementation(async () => { - order.push('row'); - return 1n; - }); - mockS3Send.mockImplementation(async () => { - order.push('object'); - return {}; - }); - - await handler(idEvent('DELETE', '5')); - - // Reversed, a failed row delete would leave a row pointing at a file - // that no longer exists. - expect(order).toEqual(['row', 'object']); - }); + expect(res.statusCode).toBe(200); + expect(mockRemoveReport).toHaveBeenCalledWith(5); + expect(mockS3Send).not.toHaveBeenCalledWith(expect.objectContaining({ __type: 'DeleteObject' })); }); }); }); \ No newline at end of file diff --git a/apps/backend/lambdas/reports/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/reports/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..82c04074 --- /dev/null +++ b/apps/backend/lambdas/reports/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,127 @@ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); +jest.mock('@aws-sdk/client-s3', () => ({ + S3Client: jest.fn().mockImplementation(() => ({ + send: jest.fn().mockReturnValue({} as any), + })), + PutObjectCommand: jest.fn().mockImplementation((params: unknown) => params), + GetObjectCommand: jest.fn().mockImplementation((params: unknown) => params), +})); +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: jest.fn().mockReturnValue('https://presigned.example.com/upload' as any), +})); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +process.env.REPORTS_BUCKET_NAME = 'bucket'; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const LIST_QUERIES: Record[] = [ + {}, + { page: '1', limit: '2' }, + { page: '2', limit: '2' }, + { page: '1', limit: '100' }, + ...[1, 2, 3, 4].flatMap((projectId): Record[] => [ + { projectId: String(projectId) }, + { projectId: String(projectId), page: '1', limit: '100' }, + ]), +]; + +const REQUESTS: [string, Record][] = [ + ...LIST_QUERIES.map((query): [string, Record] => ['/reports', query]), + ...[1, 2, 3, 4, 5].flatMap((id): [string, Record][] => [ + [`/reports/${id}`, {}], + [`/reports/${id}/download`, {}], + ]), +]; + +async function snapshot(): Promise> { + const out: Record = {}; + for (const [rawPath, queryStringParameters] of REQUESTS) { + const res = await handler({ + rawPath, + requestContext: { http: { method: 'GET' } }, + headers: { Authorization: 'Bearer fake-token' }, + queryStringParameters, + } as any); + out[`${rawPath}?${new URLSearchParams(queryStringParameters)}`] = { status: res.statusCode, body: res.body }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every reports GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + expect(soft[`/reports/${PARITY_DELETES.report}?`].status).toBe(404); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/users/controllers/users.ts b/apps/backend/lambdas/users/controllers/users.ts index 3c2a210a..f3ab0c73 100644 --- a/apps/backend/lambdas/users/controllers/users.ts +++ b/apps/backend/lambdas/users/controllers/users.ts @@ -64,12 +64,14 @@ export const listUsers: RouteHandler = async ({ event }) => { const [totalCount, users] = await Promise.all([ db .selectFrom('branch.users') + .where('deleted_at', 'is', null) .where('is_staff', 'is not', true) .select(db.fn.count('user_id').as('count')) .executeTakeFirst(), db .selectFrom('branch.users') .where('is_staff', 'is not', true) + .where('deleted_at', 'is', null) .select(USER_COLUMNS) .orderBy('user_id', 'asc') .limit(limit) @@ -93,6 +95,7 @@ export const listUsers: RouteHandler = async ({ event }) => { const users = await db .selectFrom('branch.users') .where('is_staff', 'is not', true) + .where('deleted_at', 'is', null) .select(USER_COLUMNS) .execute(); @@ -110,6 +113,7 @@ export const getUser: RouteHandler = async ({ params, auth }) => { .selectFrom('branch.users') .where('user_id', '=', Number(userId)) .where('is_staff', 'is not', true) + .where('deleted_at', 'is', null) .select(USER_COLUMNS) .executeTakeFirst(); if (!user) return json(404, { message: 'User not found' }); @@ -240,6 +244,7 @@ export const deleteUser: RouteHandler = async ({ params }) => { .selectFrom('branch.users') .where('user_id', '=', Number(userId)) .where('is_staff', 'is not', true) + .where('deleted_at', 'is', null) .select('email') .executeTakeFirst(); if (!user) return json(404, { message: 'User not found' }); @@ -300,10 +305,11 @@ export const createUser: RouteHandler = async ({ event }) => { const isAdmin = isAdminResult.value as boolean; const profile_image = profileImageResult.value ?? undefined; - // Check if user with this email already exists in DB + // Live users only: a soft-deleted row keeps its email, and its Cognito account is gone. const existingUser = await db .selectFrom('branch.users') .where('email', '=', email) + .where('deleted_at', 'is', null) .selectAll() .executeTakeFirst(); diff --git a/apps/backend/lambdas/users/jest.config.js b/apps/backend/lambdas/users/jest.config.js index 7fc0bb23..008e78c1 100644 --- a/apps/backend/lambdas/users/jest.config.js +++ b/apps/backend/lambdas/users/jest.config.js @@ -3,5 +3,7 @@ module.exports = { testEnvironment: 'node', roots: ['/test'], testMatch: ['**/*.test.ts'], + // Suites share one database; parallel workers truncate each other's fixtures. + maxWorkers: 1, moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], }; \ No newline at end of file diff --git a/apps/backend/lambdas/users/test/soft-delete-parity.e2e.test.ts b/apps/backend/lambdas/users/test/soft-delete-parity.e2e.test.ts new file mode 100644 index 00000000..a3c60d8f --- /dev/null +++ b/apps/backend/lambdas/users/test/soft-delete-parity.e2e.test.ts @@ -0,0 +1,120 @@ +import { describe, test, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Pool } from 'pg'; +import { ensureSchema, resetData, purgeSoftDeleted, PARITY_DELETES } from '../../../db/testkit'; + +jest.mock('@aws-sdk/client-cognito-identity-provider', () => ({ + CognitoIdentityProviderClient: jest.fn().mockImplementation(() => ({ + send: jest.fn().mockResolvedValue({ + User: { Attributes: [{ Name: 'sub', Value: 'test-cognito-sub-123' }] }, + } as never), + })), + AdminCreateUserCommand: jest.fn().mockImplementation((args) => args), + AdminDeleteUserCommand: jest.fn().mockImplementation((args) => args), +})); + +jest.mock('../auth', () => { + const { createAuthResolver } = jest.requireActual( + '@branch/lambda-http', + ); + const { loadRbacSubject } = jest.requireActual( + '@branch/lambda-auth', + ); + const db = jest.requireActual('@branch/store').db; + const authenticateRequest = jest.fn(); + return { + ...jest.requireActual('../auth'), + authenticateRequest, + resolveAuth: createAuthResolver( + authenticateRequest as never, + (context) => loadRbacSubject(db as never, context), + ), + }; +}); + +import { handler } from '../handler'; +import { + closeConnection, + removeDonation, + removeDonor, + removeExpenditure, + removeProject, + removeReport, + removeUser, +} from '@branch/store'; +import { authenticateRequest } from '../auth'; + +const mockAuthenticateRequest = authenticateRequest as jest.MockedFunction; + +const pool = new Pool({ + host: 'localhost', + port: 5432, + user: 'branch_dev', + password: 'password', + database: 'branch_db', + ssl: false, +}); + +const REQUESTS: [string, Record | null][] = [ + ['/users', null], + ['/users', { page: '1', limit: '3' }], + ['/users', { page: '2', limit: '3' }], + ['/users', { page: '1', limit: '100' }], + ...[1, 2, 3, 4, 5, 6].map((id): [string, null] => [`/users/${id}`, null]), +]; + +async function snapshot(): Promise> { + const out: Record = {}; + for (const [rawPath, queryStringParameters] of REQUESTS) { + const res = await handler({ + rawPath, + path: rawPath, + requestContext: { http: { method: 'GET' } }, + httpMethod: 'GET', + body: null, + queryStringParameters, + headers: {}, + } as any); + out[`${rawPath}?${new URLSearchParams(queryStringParameters ?? {})}`] = { + status: res.statusCode, + body: res.body, + }; + } + return out; +} + +beforeAll(async () => { + const client = await pool.connect(); + try { + await ensureSchema(client); + await resetData(client); + } finally { + client.release(); + } + mockAuthenticateRequest.mockResolvedValue({ + isAuthenticated: true as const, + user: { cognitoSub: 'admin-sub', userId: 1, email: 'ashley@branch.org', isAdmin: true }, + }); +}); + +afterAll(async () => { + await pool.end(); + await closeConnection(); +}); + +describe('soft-delete read parity', () => { + test('every users GET reads the same as if the rows were hard-deleted', async () => { + await removeExpenditure(PARITY_DELETES.expenditure); + await removeDonation(PARITY_DELETES.donation); + await removeDonor(PARITY_DELETES.donor); + await removeReport(PARITY_DELETES.report); + await removeProject(PARITY_DELETES.project); + await removeUser(PARITY_DELETES.user); + + const soft = await snapshot(); + expect(soft[`/users/${PARITY_DELETES.user}?`].status).toBe(404); + expect(Object.values(soft).some(({ body }) => body.includes('deleted_at'))).toBe(false); + + await purgeSoftDeleted(pool); + expect(await snapshot()).toEqual(soft); + }); +}); diff --git a/apps/backend/lambdas/users/test/user.unit.test.ts b/apps/backend/lambdas/users/test/user.unit.test.ts index ae76a2de..7eb09dae 100644 --- a/apps/backend/lambdas/users/test/user.unit.test.ts +++ b/apps/backend/lambdas/users/test/user.unit.test.ts @@ -330,6 +330,7 @@ describe('POST /users unit tests', () => { // Setup mocks for successful user creation // Mock the email check to return null (user doesn't exist) const whereChain = { + where: jest.fn().mockReturnThis(), selectAll: jest.fn().mockReturnValue({ executeTakeFirst: (jest.fn() as any).mockResolvedValue(null), }), @@ -359,6 +360,7 @@ describe('POST /users unit tests', () => { test('409: POST returns 409 when user already exists', async () => { // Mock: user already exists const whereChain = { + where: jest.fn().mockReturnThis(), selectAll: jest.fn().mockReturnValue({ executeTakeFirst: (jest.fn() as any).mockResolvedValue({ user_id: 1, @@ -384,6 +386,7 @@ describe('POST /users unit tests', () => { expect(res.statusCode).toBe(409); const json = JSON.parse(res.body); expect(json).toHaveProperty('message'); + expect(whereChain.where).toHaveBeenCalledWith('deleted_at', 'is', null); }); }); }); diff --git a/apps/backend/lambdas/users/test/users.test.ts b/apps/backend/lambdas/users/test/users.test.ts index c7939356..a57f4185 100644 --- a/apps/backend/lambdas/users/test/users.test.ts +++ b/apps/backend/lambdas/users/test/users.test.ts @@ -609,6 +609,46 @@ test("regular user cannot delete users", async () => { const res = await handler(event); expect(res.statusCode).toBe(403); }); +test("POST user succeeds for the email of a deleted user, which keeps its row", async () => { + mockAdminAuth(); + + const del = await handler(createEvent({ method: 'DELETE', path: '/2' })); + expect(del.statusCode).toBe(200); + + const res = await handler(createEvent({ + method: 'POST', + path: '/users', + body: { name: "Renee Again", email: "renee@branch.org", isAdmin: false }, + })); + expect(res.statusCode).toBe(201); + expect(JSON.parse(res.body).body.email).toBe("renee@branch.org"); + + const client = await pool.connect(); + try { + const old = await client.query('SELECT email, deleted_at FROM branch.users WHERE user_id = 2'); + expect(old.rows[0].email).toBe('renee@branch.org'); + expect(old.rows[0].deleted_at).not.toBeNull(); + const live = await client.query( + "SELECT user_id FROM branch.users WHERE email = 'renee@branch.org' AND deleted_at IS NULL", + ); + expect(live.rows).toHaveLength(1); + expect(live.rows[0].user_id).not.toBe(2); + } finally { + client.release(); + } +}); + +test("POST user 409 when a live user has the email", async () => { + mockAdminAuth(); + + const res = await handler(createEvent({ + method: 'POST', + path: '/users', + body: { name: "Sam Again", email: "sam@branch.org", isAdmin: false }, + })); + expect(res.statusCode).toBe(409); + expect(JSON.parse(res.body).message).toBe('User with this email already exists'); +}); describe('staff accounts', () => { async function seedStaff(): Promise { @@ -657,4 +697,4 @@ describe('staff accounts', () => { const { rows } = await pool.query('SELECT name FROM branch.users WHERE user_id = $1', [staffId]); expect(rows[0].name).toBe('Hidden Staff'); }); -}); \ No newline at end of file +}); diff --git a/apps/frontend/AGENTS.md b/apps/frontend/AGENTS.md index 35961658..98d714d8 100644 --- a/apps/frontend/AGENTS.md +++ b/apps/frontend/AGENTS.md @@ -111,7 +111,7 @@ The animations live in `globals.css` (`.branch-spinner`, `.branch-skeleton`, and **Popovers — `hooks/useAnchoredPopover.ts`.** Anything that floats next to a trigger (`DatePickerField`, `StaffPicker`) goes through this hook. The caller owns the open state and passes it in with `onDismiss` and an `estimatedHeight`; the hook returns `{ anchorRef, popoverRef, boundaryRef, position }`, where `position` is viewport coordinates to spread onto a `position: fixed` panel. It flips above the anchor when the viewport would clip it, repositions on scroll and resize, and dismisses on outside-click and `Escape`. Render the panel through `createPortal` into `document.body` — a popover left in normal flow is clipped by the modal body's scroll container, which is the bug this hook exists to prevent. Mark the panel `data-anchored-popover`, and give any Chakra `Dialog.Root` that hosts one `onInteractOutside={(e) => { if (isInAnchoredPopover(e.detail.target)) e.preventDefault(); }}` — otherwise a click on the part of the panel hanging past the dialog's edge closes the dialog (see `ProjectFormModal`). -**Deletes — `components/ConfirmDeleteDialog.tsx` + `components/RowDeleteButton.tsx`.** No destructive action goes straight to the API. The dialog owns its own in-flight and error state: pass an `onConfirm` that returns a promise and it closes on success, or stays open and shows the reason on rejection — so the page never needs its own "failed to delete" banner. Give it `consequences` whenever the delete cascades; every foreign key in the schema is `ON DELETE CASCADE`, so deleting a project also destroys its expenses, donations, memberships and reports, and the user has to be told before it happens, not after. `requireTypedConfirmation` gates the confirm button behind retyping the record's name — use it where the cascade reaches financial history. `RowDeleteButton` is the icon-only trash for a table row or card; it stops click propagation, because every list that has row actions also has an `onRowClick` that opens the record. +**Deletes — `components/ConfirmDeleteDialog.tsx` + `components/RowDeleteButton.tsx`.** No destructive action goes straight to the API. The dialog owns its own in-flight and error state: pass an `onConfirm` that returns a promise and it closes on success, or stays open and shows the reason on rejection — so the page never needs its own "failed to delete" banner. Give it `consequences` whenever the delete reaches other records: deleting a project also removes its expenses, donations, memberships and reports, and a donor takes its donations, so the user has to be told before it happens, not after. Deletes are soft on the backend (rows are kept with `deleted_at`, recoverable by SQL only), but the UI treats them as gone. `requireTypedConfirmation` gates the confirm button behind retyping the record's name — use it where the cascade reaches financial history. `RowDeleteButton` is the icon-only trash for a table row or card; it stops click propagation, because every list that has row actions also has an `onRowClick` that opens the record. Gate the affordance on the same rule the backend enforces, not a looser one — deleting a project is admin-only (`projects/auth.ts`), which is narrower than the `canEdit` that governs the Edit button. diff --git a/apps/frontend/src/app/components/ConfirmDeleteDialog.tsx b/apps/frontend/src/app/components/ConfirmDeleteDialog.tsx index b2b5df00..7b4adc05 100644 --- a/apps/frontend/src/app/components/ConfirmDeleteDialog.tsx +++ b/apps/frontend/src/app/components/ConfirmDeleteDialog.tsx @@ -16,14 +16,14 @@ interface ConfirmDeleteDialogProps { /** The record being removed, echoed back so the user can check the row. */ itemName?: string; /** - * What else disappears. Every foreign key in the schema is ON DELETE CASCADE, - * so a delete here can take rows the user never sees — say so explicitly. + * What else disappears. A delete here can take rows the user never sees + * (a project's expenses, a donor's donations) — say so explicitly. */ consequences?: React.ReactNode; confirmLabel?: string; /** * Gate the confirm button behind retyping `itemName`. For deletes that - * cascade into financial history, where a misclick is unrecoverable. + * reach into financial history, where a misclick is costly to undo. */ requireTypedConfirmation?: boolean; } diff --git a/apps/frontend/src/app/projects/ProjectDetailView.tsx b/apps/frontend/src/app/projects/ProjectDetailView.tsx index ac743e60..851d95d3 100644 --- a/apps/frontend/src/app/projects/ProjectDetailView.tsx +++ b/apps/frontend/src/app/projects/ProjectDetailView.tsx @@ -106,9 +106,9 @@ export default function ProjectDetailView({ id }: { id: string }) { Edit Project )} - {/* Deleting a project cascades to its memberships, donations, - expenditures and reports, so it is its own permission even - though both currently resolve to admin. */} + {/* Deleting a project takes its memberships, donations, + expenditures and reports with it, so it is its own permission + even though both currently resolve to admin. */} {can('project:delete') && (