diff --git a/.env.local.example b/.env.local.example
index 08ede4e..1219acc 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -12,6 +12,10 @@ PLUNK_API_KEY=""
# Needed by the Notion-backed chapters/partners/projects/volunteers pages
NOTION_API_KEY=""
+# Project archive uploads. Defaults to .data/project-media; must be persistent
+# storage (e.g. a Railway volume) in production.
+# PROJECT_MEDIA_DIR=""
+
# db:seed / db:deploy refuse non-localhost databases unless "true". Railway sets ALLOW_REMOTE_DEPLOY.
# ALLOW_REMOTE_SEED="false"
# ALLOW_REMOTE_DEPLOY="false"
diff --git a/.gitignore b/.gitignore
index 4dc7d1c..c087f72 100644
--- a/.gitignore
+++ b/.gitignore
@@ -56,6 +56,9 @@ skills-lock.json
# regenerated by next dev
AGENTS.md
+# private local project uploads
+/.data/
+
# playwright
/test-results/
/playwright-report/
diff --git a/README.md b/README.md
index 393f476..7cd8bfa 100644
--- a/README.md
+++ b/README.md
@@ -4,12 +4,13 @@ Internal platform (the National IMA) for Hack4Impact chapters: a member and alum
## What's in the app
-| Area | Pages / API | Data |
-| ---------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
-| Sign-in | `/sign-in`, `/api/auth/*` | Postgres (`User`, `Session`, `MagicLinkToken`) |
-| Member & alumni directory | `/members`, `/admin/directory-audit` | Postgres (`Member`, `Alumni`, …) |
-| Sourced Project Exchange | `/exchange`, `/exchange/claims`, `/api/graphql` | Postgres (`SourcedProject`, `ProjectClaim`, …) |
-| Chapters, projects, volunteers, partners | `/chapters`, `/projects`, `/volunteers`, `/partners` | Notion, read-only. The create and edit pages don't save yet. |
+| Area | Pages / API | Data |
+| ------------------------------ | -------------------------------------------------- | -------------------------------------------------------------- |
+| Sign-in | `/sign-in`, `/api/auth/*` | Postgres (`User`, `Session`, `MagicLinkToken`) |
+| Member & alumni directory | `/members`, `/admin/directory-audit` | Postgres (`Member`, `Alumni`, …) |
+| Sourced Project Exchange | `/exchange`, `/exchange/claims`, `/api/graphql` | Postgres (`SourcedProject`, `ProjectClaim`, …) |
+| Project archive | `/projects`, `/projects/drafts`, `/api/projects/*` | Postgres (`Project`, …); uploads on disk (`PROJECT_MEDIA_DIR`) |
+| Chapters, volunteers, partners | `/chapters`, `/volunteers`, `/partners` | Notion, read-only. The create and edit pages don't save yet. |
Built with Next.js 16 (App Router), Prisma 7 on PostgreSQL, Tailwind and GraphQL Yoga.
@@ -30,12 +31,13 @@ Optional: `ALLOW_DIRECTORY_SEED=true pnpm db:seed:directory` adds about 60 membe
### Environment variables
-| Variable | Needed for |
-| ---------------- | ---------------------------------------------------------------------------------------------- |
-| `DATABASE_URL` | Everything. The example value matches `docker-compose.yml`. |
-| `PUBLIC_URL` | Links in magic-link emails (`http://localhost:3000` locally) |
-| `PLUNK_API_KEY` | Sending magic-link and claim emails. Leave empty locally: they are printed in the dev console. |
-| `NOTION_API_KEY` | The Notion-backed pages. Without it they load but show no rows. |
+| Variable | Needed for |
+| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `DATABASE_URL` | Everything. The example value matches `docker-compose.yml`. |
+| `PUBLIC_URL` | Links in magic-link emails (`http://localhost:3000` locally) |
+| `PLUNK_API_KEY` | Sending magic-link and claim emails. Leave empty locally: they are printed in the dev console. |
+| `NOTION_API_KEY` | The Notion-backed pages and the project form's partner search. Without it they load but show no rows. |
+| `PROJECT_MEDIA_DIR` | Where project uploads are stored. Defaults to `.data/project-media` (Git-ignored). In production it must be persistent storage, e.g. a Railway volume. |
`db:seed` and `db:deploy` refuse to run against a non-local database unless `ALLOW_REMOTE_SEED` / `ALLOW_REMOTE_DEPLOY` is `"true"`.
@@ -284,6 +286,20 @@ scripts/expire-claims.ts
e2e/ # Playwright end-to-end tests
```
+## Project archive
+
+Projects live in Postgres (`Project`, `ProjectTeamMember`, `ProjectResourceLink`) and are linked to `Chapter` and `User`.
+
+- Members see published projects at `/projects` and their detail pages. Drafts are never shown to them.
+- Project leads and chapter leads create, edit and publish projects for their own chapter; the chapter is always set from their account. National Admins can do this for any chapter and are the only ones who can delete.
+- The add/edit form autosaves drafts. **Publish Changes** checks the stage's required fields and lists everything missing at once. Leads find unpublished work under **Resume a draft** (`/projects/drafts`).
+- Team members are picked from visible Member Directory profiles; partners from the Notion Partner Directory, with a free-text fallback and an optional uploaded photo.
+- Uploads (PNG, JPEG, WebP, GIF, MP4, WebM, up to 20 MB) are stored under `PROJECT_MEDIA_DIR`. Local paths in media fields must point at an uploaded file.
+
+API reference: [docs/projects-api.md](docs/projects-api.md). Walkthrough for leads and admins: [docs/projects-guide.md](docs/projects-guide.md).
+
+`pnpm test:e2e:projects` runs an opt-in browser check against a running local app (`PROJECT_E2E_URL`, default `http://localhost:3108`) using the same local `DATABASE_URL`.
+
## Contributing
Branch off `develop` and open PRs into `develop`, not `main`. CI must pass before merging.
diff --git a/docs/projects-api.md b/docs/projects-api.md
new file mode 100644
index 0000000..414c55f
--- /dev/null
+++ b/docs/projects-api.md
@@ -0,0 +1,57 @@
+# Project archive API reference
+
+All routes use the existing session cookie and live database roles. Pages are under `/projects`; JSON routes are under `/api/projects`. Responses use camelCase. Same-origin browser writes are required; CLI clients may omit Origin. Do not copy session tokens into documentation or Git.
+
+## Browse and search
+
+`GET /api/projects` returns an array. Defaults: published records, page 1, 12 per page, newest public update first. Headers provide `X-Total-Count`, `X-Page`, `X-Page-Size`, and `X-Total-Pages`. Out-of-range positive pages clamp to the last page; an empty result has page 1 of 1. Sorting and filtering happen before pagination.
+
+| Parameter | Values / behavior |
+| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `q` | Up to 200 characters; case-insensitive substring in project name, tagline, partner name, or Chapter name. Public fields only. |
+| `chapter_id` | Canonical Chapter ID. Unknown IDs yield an empty API result; unknown chapter IDs in the page URL yield 404. |
+| `stage` | `design`, `development`, `launched`, `maintenance` |
+| `project_length` | `short`: 0–180 days; `medium`: 181–365 days; `long`: over 365 days; `unknown`: missing start or end date. Uses end date minus start date. |
+| `impact_area` | Exact cause-area tag, including case; dropdown values come only from published projects. |
+| `sort` | `last_updated` (default), `name`, `year`. Year uses descending start date. Missing dates sort last; IDs break ties. |
+| `page`, `page_size` | Positive integers; page maximum 100000, page size maximum 100. |
+| `include_drafts` | Only literal `true` includes authorized drafts: own chapter for Leads, every chapter for Admins, none for Members. The dashboard always excludes drafts. |
+
+Filters combine with AND; search matches its supported fields with OR. Blank text/select filters are ignored. Invalid recognized query values return 400. Example:
+
+```text
+/api/projects?chapter_id=chapter-cornell&stage=development&project_length=short&impact_area=Education&q=community&page=1&page_size=12
+```
+
+`GET /api/projects/:id` returns a public record or an authorized draft. `?draft=true` returns a proposed revision for permitted editors. Hidden/missing records return 404. Pending fields never affect public search, tags, results counts, or sorting.
+
+## Write and reference routes
+
+| Method and route | Purpose | Success |
+| --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | --------- |
+| `POST /api/projects` | Create a draft; name required. Leads get their chapter; Admins must supply chapterId. | 201 |
+| `PATCH /api/projects/:id` | Partial save; arrays replace their collection when supplied. Published records retain a separate private revision. | 200 |
+| `POST /api/projects/:id/publish` | Validate proposed fields and make them public. No editable body; save first. | 200 |
+| `DELETE /api/projects/:id` | National Admin only; deletes project, team/link rows and attempts private media cleanup. | 204 |
+| `POST /api/projects/:id/media` | Multipart `file`; optional `purpose=partner-photo` restricts to images. PNG/JPEG/WebP/GIF/MP4/WebM, 20 MB maximum. Returns `{url}`. | 201 |
+| `GET /api/projects/:id/media/:file` | Authenticated media; unpublished files hidden from members; video byte ranges supported. | 200 / 206 |
+| `GET /api/projects/references/members?q=...` | Editors only; visible canonical member records, at most 100 search characters. | 200 |
+| `GET /api/projects/references/partners?q=...` | Editors only; Partner Directory projection or `{partners:[], available:false}` for free-text fallback. | 200 |
+
+Example create payload for an Admin (a Lead may omit chapterId):
+
+```json
+{
+ "name": "Community Portal",
+ "chapterId": "chapter-cornell",
+ "stage": "design"
+}
+```
+
+Editable fields: name, chapterId, stage, tagline (180 chars), techStack, causeAreas, nonprofitPartnerId/Name/Photo, startDate/endDate (`YYYY-MM-DD`), problemStatement, goalStatement, solutionDescription, demoMedia, teamMembers (`userId`, optional `memberId`, `role`) and resourceLinks (`type`, `url`). Resource types are `Slack`, `GitHub`, `GoogleDrive`, `Other`. HTTP(S) URLs only; media also accepts safe local paths. Snake-case aliases are supported for write fields; conflicting aliases and server-owned fields are rejected. Omit fields to retain them; nullable scalars may be cleared with null and collections with `[]`.
+
+Project/Chapter Leads may create, edit, publish and upload only in their current chapter. Members are read-only. Admins manage every chapter. Team membership alone grants no write permission. Role/chapter changes are rechecked on every write, including after a slow upload.
+
+Design publishing requires name, tagline, partner ID or name, start date, problem, goal, and at least one real team member with a role. Other stages also require solution and a resource link. Missing required fields do not block draft saves.
+
+Errors are `{error, details?}`: 400 invalid formats/references/query, 401 expired/missing session, 403 forbidden write, 404 hidden/missing record, 409 relation changed, 413 upload too large, 416 unsatisfiable media range, 422 publish requirements (`details.missingFields`), 500 generic failure. Uploads are stored under `PROJECT_MEDIA_DIR` (default `.data/project-media`); production needs persistent storage such as a Railway volume, or uploaded files are lost on redeploy.
diff --git a/docs/projects-guide.md b/docs/projects-guide.md
new file mode 100644
index 0000000..b26269f
--- /dev/null
+++ b/docs/projects-guide.md
@@ -0,0 +1,43 @@
+# Project directory: Lead and Admin guide
+
+## Open the directory
+
+Sign in and open **Projects**. Search by project, nonprofit or chapter name; chapter suggestions appear as you type. Filters combine across Chapter, Stage, Project length and Impact area. Results update after a short pause. Remove a chip to clear one filter, or choose **Clear filters**. Sort and page links preserve your filters; URLs can be bookmarked or shared with another signed-in member.
+
+Length is calculated from the saved start/end dates: up to 180 days, 181–365 days, or over 365 days. A missing date is **Length not set**. These explicit day ranges are the implementation baseline because the PRD does not define semester boundaries. A project without a thumbnail or partner displays a fallback. Open a card's project name to see its narrative, team, media and links.
+
+## Lead: create, resume and publish
+
+1. Choose **Add Project**. Your chapter is assigned automatically. Project and Chapter Leads can edit any project in their own chapter.
+2. Fill the six sections. Pick the stage; required markers change with it. Select actual Member Directory records and enter their project roles. If a person is missing, their directory profile must complete its visibility/approval workflow; typing an account email does not create a member record.
+3. Search the Nonprofit Partner field. Select a directory result, or use its name as free text when the directory is unavailable. Partner photo, end date and demo media are optional.
+4. Wait for **Draft saved · Just now**. Autosave runs after 750 ms; **Save Draft** retries a temporary failure. Invalid URLs and incomplete dynamic rows need correction. Incomplete publish-required fields can still be saved.
+5. Use **Resume a draft** to return to an unpublished project. Its URL also resumes it directly. Drafts never appear on the dashboard, even for an Admin.
+6. Choose **Publish Changes**. Follow linked field errors to their sections, correct them, and retry. Success opens the detail page. Editing a live project keeps the current public version unchanged until republishing.
+
+Design requires a name, tagline, partner, start date, problem, goal and team member with a role. Development, Launched and Maintenance also require solution text and a valid resource link. External link sharing is managed by GitHub/Drive/etc.; publication cannot grant those permissions.
+
+If your role changes or the project moves to another chapter, the editor preserves unsaved text but stops writes and asks you to reload. Previously published projects remain in the archive. Do not close a page with unsaved changes until you have copied any text you need to retain.
+
+## Admin: manage any chapter
+
+Choose the correct Chapter when creating a project. Use **Edit** on any detail page; changing its chapter is saved privately until publication. Old chapter Leads cannot publish a pending transfer into a foreign chapter. After publication, the new chapter's Leads manage it.
+
+**Delete Project** opens a permanent-deletion confirmation. Cancel leaves it intact; **Delete permanently** removes the project and its drafts, team/link rows and local media. Use a disposable demo project when trying this. Leads cannot delete. Canonical directory member/partner records are retained.
+
+## Local demo setup
+
+```bash
+pnpm install
+pnpm db:up
+pnpm db:generate
+pnpm db:deploy
+pnpm db:seed
+pnpm dev
+```
+
+Open `http://localhost:3000/sign-in`. Local seed accounts use password `password`: `projectlead@hack4impact.org` (Cornell Project Lead), `lead.uiuc@hack4impact.org` (UIUC Chapter Lead), `admin@hack4impact.org`, and `member@hack4impact.org`. Seed commands are development fixtures, not production account provisioning.
+
+The archive seed creates 15 `[Demo]` projects across three chapters/all stages (12 published and three drafts on a fresh database). Rerunning preserves existing archive fixtures and your edits; it recreates any deleted fixture. They are database rows, not files to commit. The regular seed does not create Member Directory profiles; populate them through that feature's own workflow before demoing a new team selection. The Notion project table is no longer part of this page; partner search still uses the Partner Directory and falls back to plain text without Notion configuration.
+
+If no projects appear, clear filters, check for published records, and run the seed on the same local database used by the app. Database connection errors mean the local Postgres container must be started. A `.next/dev/lock` error means another development server is already running; stop that server before starting another.
diff --git a/package.json b/package.json
index 3989032..ad83575 100644
--- a/package.json
+++ b/package.json
@@ -24,7 +24,8 @@
"db:verify:directory-workflows": "tsx prisma/verify-directory-workflows.ts",
"db:reset": "prisma migrate reset",
"claims:expire": "tsx scripts/expire-claims.ts",
- "prepare": "husky"
+ "prepare": "husky",
+ "test:e2e:projects": "vitest run --config vitest.browser.config.mts"
},
"dependencies": {
"@base-ui/react": "^1.9.0",
diff --git a/prisma/migrations/20261113000100_project_write_foundations/migration.sql b/prisma/migrations/20261113000100_project_write_foundations/migration.sql
new file mode 100644
index 0000000..2f4ccf7
--- /dev/null
+++ b/prisma/migrations/20261113000100_project_write_foundations/migration.sql
@@ -0,0 +1,80 @@
+-- CreateEnum
+CREATE TYPE "ProjectStage" AS ENUM ('design', 'development', 'launched', 'maintenance');
+
+-- CreateEnum
+CREATE TYPE "ProjectResourceType" AS ENUM ('Slack', 'GitHub', 'GoogleDrive', 'Other');
+
+-- CreateTable
+CREATE TABLE "projects" (
+ "id" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "tagline" VARCHAR(180),
+ "chapter_id" TEXT NOT NULL,
+ "stage" "ProjectStage" NOT NULL DEFAULT 'design',
+ "tech_stack" TEXT[] DEFAULT ARRAY[]::TEXT[],
+ "cause_areas" TEXT[] DEFAULT ARRAY[]::TEXT[],
+ "nonprofit_partner_id" TEXT,
+ "nonprofit_partner_name" TEXT,
+ "nonprofit_partner_photo" TEXT,
+ "start_date" DATE,
+ "end_date" DATE,
+ "last_updated" TIMESTAMP(3),
+ "problem_statement" TEXT,
+ "goal_statement" TEXT,
+ "solution_description" TEXT,
+ "demo_media" TEXT[] DEFAULT ARRAY[]::TEXT[],
+ "is_draft" BOOLEAN NOT NULL DEFAULT true,
+ "pending_changes" JSONB,
+ "created_by" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "projects_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "project_team_members" (
+ "id" TEXT NOT NULL,
+ "project_id" TEXT NOT NULL,
+ "user_id" TEXT NOT NULL,
+ "role" TEXT NOT NULL,
+
+ CONSTRAINT "project_team_members_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateTable
+CREATE TABLE "project_resource_links" (
+ "id" TEXT NOT NULL,
+ "project_id" TEXT NOT NULL,
+ "type" "ProjectResourceType" NOT NULL,
+ "url" TEXT NOT NULL,
+
+ CONSTRAINT "project_resource_links_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "projects_is_draft_chapter_id_stage_idx" ON "projects"("is_draft", "chapter_id", "stage");
+
+-- CreateIndex
+CREATE INDEX "project_team_members_user_id_idx" ON "project_team_members"("user_id");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "project_team_members_project_id_user_id_role_key" ON "project_team_members"("project_id", "user_id", "role");
+
+-- CreateIndex
+CREATE INDEX "project_resource_links_project_id_idx" ON "project_resource_links"("project_id");
+
+-- AddForeignKey
+ALTER TABLE "projects" ADD CONSTRAINT "projects_chapter_id_fkey" FOREIGN KEY ("chapter_id") REFERENCES "Chapter"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "projects" ADD CONSTRAINT "projects_created_by_fkey" FOREIGN KEY ("created_by") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "project_team_members" ADD CONSTRAINT "project_team_members_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "project_team_members" ADD CONSTRAINT "project_team_members_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "project_resource_links" ADD CONSTRAINT "project_resource_links_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/migrations/20261122203847_project_member_reference/migration.sql b/prisma/migrations/20261122203847_project_member_reference/migration.sql
new file mode 100644
index 0000000..480dc3b
--- /dev/null
+++ b/prisma/migrations/20261122203847_project_member_reference/migration.sql
@@ -0,0 +1,5 @@
+-- AlterTable
+ALTER TABLE "project_team_members" ADD COLUMN "member_id" TEXT;
+
+-- AddForeignKey
+ALTER TABLE "project_team_members" ADD CONSTRAINT "project_team_members_member_id_fkey" FOREIGN KEY ("member_id") REFERENCES "Member"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index c51256f..a841fb9 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -31,6 +31,9 @@ model User {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
+ createdProjects Project[]
+ projectMemberships ProjectTeamMember[]
+
sessions Session[]
magicLinkTokens MagicLinkToken[]
@@ -63,6 +66,7 @@ model Chapter {
members Member[]
alumni Alumni[]
hackInvolvements AlumniHackInvolvement[]
+ projects Project[]
}
// One row per signed-in device. id is a random token set by the auth routes.
@@ -325,6 +329,8 @@ model Member {
@@index([chapterId])
@@index([approvalStatus, directoryOptIn, adminHidden, userId])
@@index([graduationYear])
+ projectTeams ProjectTeamMember[]
+
}
// =============================================================================
@@ -448,3 +454,76 @@ model DirectoryClaimToken {
@@index([profileKind, profileId])
@@index([expiresAt])
}
+
+enum ProjectStage {
+ design
+ development
+ launched
+ maintenance
+}
+
+enum ProjectResourceType {
+ Slack
+ GitHub
+ GoogleDrive
+ Other
+}
+
+model Project {
+ id String @id @default(cuid())
+ name String
+ tagline String? @db.VarChar(180)
+ chapterId String @map("chapter_id")
+ chapter Chapter @relation(fields: [chapterId], references: [id], onDelete: Restrict)
+ stage ProjectStage @default(design)
+ techStack String[] @default([]) @map("tech_stack")
+ causeAreas String[] @default([]) @map("cause_areas")
+ nonprofitPartnerId String? @map("nonprofit_partner_id")
+ nonprofitPartnerName String? @map("nonprofit_partner_name")
+ nonprofitPartnerPhoto String? @map("nonprofit_partner_photo")
+ startDate DateTime? @map("start_date") @db.Date
+ endDate DateTime? @map("end_date") @db.Date
+ lastUpdated DateTime? @map("last_updated")
+ problemStatement String? @map("problem_statement")
+ goalStatement String? @map("goal_statement")
+ solutionDescription String? @map("solution_description")
+ demoMedia String[] @default([]) @map("demo_media")
+ isDraft Boolean @default(true) @map("is_draft")
+ // Published columns remain live while partial edits await a successful publish.
+ pendingChanges Json? @map("pending_changes")
+ createdBy String @map("created_by")
+ creator User @relation(fields: [createdBy], references: [id], onDelete: Restrict)
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @updatedAt @map("updated_at")
+ teamMembers ProjectTeamMember[]
+ resourceLinks ProjectResourceLink[]
+
+ @@index([isDraft, chapterId, stage])
+ @@map("projects")
+}
+
+model ProjectTeamMember {
+ memberId String? @map("member_id")
+ member Member? @relation(fields: [memberId], references: [id], onDelete: SetNull)
+ id String @id @default(cuid())
+ projectId String @map("project_id")
+ userId String @map("user_id")
+ role String
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ user User @relation(fields: [userId], references: [id], onDelete: Restrict)
+
+ @@unique([projectId, userId, role])
+ @@index([userId])
+ @@map("project_team_members")
+}
+
+model ProjectResourceLink {
+ id String @id @default(cuid())
+ projectId String @map("project_id")
+ type ProjectResourceType
+ url String
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ @@index([projectId])
+ @@map("project_resource_links")
+}
diff --git a/prisma/seed.ts b/prisma/seed.ts
index 475e5db..3793d46 100644
--- a/prisma/seed.ts
+++ b/prisma/seed.ts
@@ -3,6 +3,7 @@
import { createSeedClient } from "./seed/client";
import { seedChapters } from "./seed/chapters";
import { SEED_PASSWORD, SEED_USERS, seedUsers } from "./seed/users";
+import { seedProjects } from "./seed/projects";
import { seedSourcedProjects } from "./seed/sourced-projects";
const db = createSeedClient();
@@ -11,8 +12,12 @@ async function main() {
const chapters = await seedChapters(db);
const users = await seedUsers(db);
const sourced = await seedSourcedProjects(db);
+ const projects = await seedProjects(db);
console.log(`Seeded ${chapters} chapters and ${users} users.`);
+ console.log(
+ `Project archive: ${projects} fixtures (12 published, 3 drafts on a fresh database).`
+ );
console.log(
`Sourced Project Exchange: ${sourced.listings} listings, ` +
`${sourced.claims} claims, ${sourced.links} links.`
diff --git a/prisma/seed/projects.ts b/prisma/seed/projects.ts
new file mode 100644
index 0000000..aa8fd75
--- /dev/null
+++ b/prisma/seed/projects.ts
@@ -0,0 +1,80 @@
+import type { ProjectStage } from "@prisma/client";
+import type { SeedClient } from "./client";
+
+// Fictional archive fixtures. Existing records are never overwritten on rerun,
+// so edits made while demonstrating the editor remain intact.
+const chapters = ["chapter-cornell", "chapter-uiuc", "chapter-berkeley"];
+const stages: ProjectStage[] = [
+ "design",
+ "development",
+ "launched",
+ "maintenance",
+];
+const names = [
+ "Community Food Pantry",
+ "Volunteer Shift Planner",
+ "Literacy Tutor Match",
+ "Neighborhood Resource Map",
+ "Animal Shelter Portal",
+ "Community Garden Tracker",
+ "Accessible Transit Guide",
+ "Donation Inventory",
+ "Youth Mentoring Hub",
+ "Housing Support Portal",
+ "Watershed Monitor",
+ "Meal Delivery Planner",
+ "Legal Aid Intake",
+ "Arts Access Directory",
+ "Community Health Outreach",
+];
+
+export async function seedProjects(db: SeedClient) {
+ const creator = await db.user.findUniqueOrThrow({
+ where: { email: "admin@hack4impact.org" },
+ select: { id: true },
+ });
+ const teammate = await db.user.findUniqueOrThrow({
+ where: { email: "member@hack4impact.org" },
+ select: { id: true },
+ });
+ for (const [index, name] of names.entries()) {
+ const isDraft = index >= 12;
+ const id = `seed-archive-project-${String(index + 1).padStart(2, "0")}`;
+ await db.project.upsert({
+ where: { id },
+ update: {},
+ create: {
+ id,
+ name: `[Demo] ${name}`,
+ chapterId: chapters[index % chapters.length],
+ createdBy: creator.id,
+ stage: stages[index % stages.length],
+ isDraft,
+ tagline:
+ "A fictional community project for testing the project archive.",
+ techStack:
+ index % 2 ? ["React", "PostgreSQL"] : ["TypeScript", "Next.js"],
+ causeAreas: [index % 2 ? "Education" : "Community Support"],
+ nonprofitPartnerName: `Demo Community Partner ${index + 1}`,
+ startDate: new Date(Date.UTC(2023 + (index % 4), index % 12, 1)),
+ endDate:
+ index % 2
+ ? new Date(Date.UTC(2023 + (index % 4), (index % 12) + 4, 1))
+ : null,
+ lastUpdated: isDraft ? null : new Date(Date.UTC(2026, 9, index + 1)),
+ problemStatement:
+ "Community volunteers need a simpler way to coordinate their work.",
+ goalStatement:
+ "Reduce administrative work and help more community members.",
+ solutionDescription:
+ "An accessible web application for volunteers and nonprofit staff.",
+ // No remote stock images: these fixtures also exercise thumbnail fallbacks.
+ teamMembers: { create: [{ userId: teammate.id, role: "Developer" }] },
+ resourceLinks: {
+ create: [{ type: "Other", url: "https://example.org/" }],
+ },
+ },
+ });
+ }
+ return names.length;
+}
diff --git a/src/app/(protected)/(directory)/projects/[id]/edit/page.tsx b/src/app/(protected)/(directory)/projects/[id]/edit/page.tsx
index acb065e..ab8a07c 100644
--- a/src/app/(protected)/(directory)/projects/[id]/edit/page.tsx
+++ b/src/app/(protected)/(directory)/projects/[id]/edit/page.tsx
@@ -1,20 +1,51 @@
-import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards";
-import { PageHeader } from "@/components/ui/PageHeader";
-import { Button } from "@/components/ui/Button";
+import { canProjectAction } from "@/lib/projects/permissions";
+import { notFound } from "next/navigation";
+import { requireRole } from "@/lib/auth/guards";
+import { EDITOR_ROLES } from "@/lib/auth/roles";
+import { editorOptions } from "@/lib/projects/editor";
+import { ProjectApiError } from "@/lib/projects/http";
+import { readProject } from "@/lib/projects/service";
+import { formValue } from "@/lib/projects/form";
+import { ProjectForm } from "@/components/projects/ProjectForm";
export default async function EditProjectPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
- await requireRole(EDITOR_ROLES);
- await params;
+ const { user } = await requireRole(EDITOR_ROLES);
+ const { id } = await params;
+ let project;
+ try {
+ project = await readProject(user, id, true);
+ } catch (error) {
+ if (error instanceof ProjectApiError && [403, 404].includes(error.status))
+ notFound();
+ throw error;
+ }
+ const options = await editorOptions(
+ user,
+ project.teamMembers.map((member) => member.userId)
+ );
+ const initial = formValue({
+ ...project,
+ startDate:
+ project.startDate instanceof Date
+ ? project.startDate.toISOString()
+ : project.startDate,
+ endDate:
+ project.endDate instanceof Date
+ ? project.endDate.toISOString()
+ : project.endDate,
+ });
return (
-
-
- Cancel
- Save Changes
-
-
+
);
}
diff --git a/src/app/(protected)/(directory)/projects/[id]/page.tsx b/src/app/(protected)/(directory)/projects/[id]/page.tsx
index af50891..5b3b1a0 100644
--- a/src/app/(protected)/(directory)/projects/[id]/page.tsx
+++ b/src/app/(protected)/(directory)/projects/[id]/page.tsx
@@ -1,8 +1,244 @@
+import { DeleteProject } from "@/components/projects/DeleteProject";
+import Link from "next/link";
+import { notFound } from "next/navigation";
+import { requireSession } from "@/lib/auth/guards";
+import { ProjectApiError } from "@/lib/projects/http";
+import { readProject } from "@/lib/projects/service";
+import { canProjectAction } from "@/lib/projects/permissions";
+import { selectedMemberReferences } from "@/lib/projects/references";
+import { projectUrl } from "@/lib/projects/urls";
+import { MemberAvatar } from "@/components/projects/ReferencePickers";
+import { DetailImage, DetailMedia } from "@/components/projects/DetailMedia";
+import { Badge } from "@/components/ui/Badge";
+import { db } from "@/lib/db";
+
+function date(value: Date | string) {
+ return new Intl.DateTimeFormat("en-US", {
+ timeZone: "UTC",
+ month: "short",
+ day: "numeric",
+ year: "numeric",
+ }).format(new Date(value));
+}
export default async function ProjectPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
+ const { user } = await requireSession();
const { id } = await params;
- return Project: {id}
;
+ let project;
+ try {
+ project = await readProject(user, id);
+ } catch (error) {
+ if (error instanceof ProjectApiError && error.status === 404) notFound();
+ throw error;
+ }
+ const [chapter, members] = await Promise.all([
+ db.chapter.findUnique({
+ where: { id: project.chapterId },
+ select: { name: true },
+ }),
+ selectedMemberReferences(
+ user,
+ project.teamMembers.map((member) => member.userId)
+ ),
+ ]);
+ const photo = projectUrl(project.nonprofitPartnerPhoto, true);
+ const media = project.demoMedia
+ .map((url) => projectUrl(url, true))
+ .filter((url): url is string => Boolean(url));
+ const links = project.resourceLinks
+ .map((link) => ({ ...link, href: projectUrl(link.url) }))
+ .filter((link) => link.href);
+ return (
+
+
+
+ ← Back to projects
+
+
+
+
+
+
+
+ {project.startDate && (
+
+ )}
+ {project.isDraft && (
+
+ )}
+
+
{project.name || "Untitled project"}
+ {project.tagline && (
+
{project.tagline}
+ )}
+
+ {project.techStack.map((tag) => (
+
+ ))}
+ {project.causeAreas.map((tag) => (
+
+ ))}
+
+
+
+ {" "}
+ {canProjectAction(user, "edit", project.chapterId) && (
+
+ Edit
+
+ )}
+ {canProjectAction(user, "delete", project.chapterId) && (
+
+ )}
+
+
+
+
+
+
Nonprofit partner
+
+ {project.nonprofitPartnerName || "Partner not listed"}
+
+ {project.nonprofitPartnerId && (
+
+ Linked to Partner Directory
+
+ )}
+
+
+
+
+
Timeline
+
+ {project.startDate
+ ? date(project.startDate)
+ : "Start date not set"}{" "}
+ – {project.endDate ? date(project.endDate) : "Ongoing"}
+
+
+ {project.lastUpdated && (
+
+
Last updated
+ {date(project.lastUpdated)}
+
+ )}
+
+
+ {(project.problemStatement || project.goalStatement) && (
+
+ Project Goal
+ {project.problemStatement && (
+
+
What problem were we solving?
+
+ {project.problemStatement}
+
+
+ )}
+ {project.goalStatement && (
+
+
What was our goal?
+
+ {project.goalStatement}
+
+
+ )}
+
+ )}
+ {photo && (
+
+
+
+ )}
+ {project.teamMembers.length > 0 && (
+
+ Team
+
+ {project.teamMembers.map((member) => {
+ const person = members.find(
+ (item) => item.id === member.userId
+ );
+ return (
+
+
+
+
{person?.name || "Member"}
+
{member.role}
+
+
+ );
+ })}
+
+
+ )}
+ {project.solutionDescription && (
+
+ Solution
+
+ {project.solutionDescription}
+
+
+ )}
+ {media.length > 0 && (
+
+ Demo Media
+
+ {media.map((src, index) => (
+
+ ))}
+
+
+ )}
+ {links.length > 0 && (
+
+ )}
+
+
+
+ );
}
diff --git a/src/app/(protected)/(directory)/projects/drafts/page.tsx b/src/app/(protected)/(directory)/projects/drafts/page.tsx
new file mode 100644
index 0000000..d749bb9
--- /dev/null
+++ b/src/app/(protected)/(directory)/projects/drafts/page.tsx
@@ -0,0 +1,56 @@
+import Link from "next/link";
+import { requireRole } from "@/lib/auth/guards";
+import { EDITOR_ROLES } from "@/lib/auth/roles";
+import { listDraftProjects } from "@/lib/projects/service";
+import { db } from "@/lib/db";
+
+export default async function DraftsPage() {
+ const { user } = await requireRole(EDITOR_ROLES);
+ const [drafts, chapters] = await Promise.all([
+ listDraftProjects(user),
+ db.chapter.findMany({ select: { id: true, name: true } }),
+ ]);
+ return (
+
+
+ ← Back to published projects
+
+
Project drafts
+
+ Unpublished work available to you. Drafts are never shown on the project
+ dashboard.
+
+ {drafts.length ? (
+
+ {drafts.map((project) => (
+
+
+
+ {project.name || "Untitled project"}
+
+
+ {
+ chapters.find((chapter) => chapter.id === project.chapterId)
+ ?.name
+ }{" "}
+ · {project.stage}
+
+
+
+ Resume draft
+
+
+ ))}
+
+ ) : (
+
No drafts are available.
+ )}
+
+ );
+}
diff --git a/src/app/(protected)/(directory)/projects/error.tsx b/src/app/(protected)/(directory)/projects/error.tsx
new file mode 100644
index 0000000..b6e789e
--- /dev/null
+++ b/src/app/(protected)/(directory)/projects/error.tsx
@@ -0,0 +1,22 @@
+"use client";
+
+import Link from "next/link";
+
+export default function ProjectsError({ retry }: { retry: () => void }) {
+ return (
+
+
Projects could not be loaded
+
+ Please try again. If the problem continues, contact an administrator.
+
+
+
+ Try again
+
+
+ Back to projects
+
+
+
+ );
+}
diff --git a/src/app/(protected)/(directory)/projects/loading.tsx b/src/app/(protected)/(directory)/projects/loading.tsx
new file mode 100644
index 0000000..c8d6a6d
--- /dev/null
+++ b/src/app/(protected)/(directory)/projects/loading.tsx
@@ -0,0 +1,7 @@
+export default function LoadingProjects() {
+ return (
+
+ Loading projects…
+
+ );
+}
diff --git a/src/app/(protected)/(directory)/projects/new/page.tsx b/src/app/(protected)/(directory)/projects/new/page.tsx
index f2617ee..93b9148 100644
--- a/src/app/(protected)/(directory)/projects/new/page.tsx
+++ b/src/app/(protected)/(directory)/projects/new/page.tsx
@@ -1,15 +1,15 @@
-import { requireRole, EDITOR_ROLES } from "@/lib/auth/guards";
-import { PageHeader } from "@/components/ui/PageHeader";
-import { Button } from "@/components/ui/Button";
+import { canProjectAction } from "@/lib/projects/permissions";
+import { requireRole } from "@/lib/auth/guards";
+import { EDITOR_ROLES } from "@/lib/auth/roles";
+import { editorOptions } from "@/lib/projects/editor";
+import { ProjectForm } from "@/components/projects/ProjectForm";
export default async function NewProjectPage() {
- await requireRole(EDITOR_ROLES);
+ const { user } = await requireRole(EDITOR_ROLES);
return (
-
-
- Cancel
- + Add Project
-
-
+
);
}
diff --git a/src/app/(protected)/(directory)/projects/page.tsx b/src/app/(protected)/(directory)/projects/page.tsx
index 4c0bd12..90a9f2a 100644
--- a/src/app/(protected)/(directory)/projects/page.tsx
+++ b/src/app/(protected)/(directory)/projects/page.tsx
@@ -1,20 +1,217 @@
-import { PageHeader } from "@/components/ui/PageHeader";
-import { Button } from "@/components/ui/Button";
-import { getProjects } from "@/actions/projects";
-import { ProjectsTable } from "./ProjectsTable";
+import { notFound } from "next/navigation";
+import {
+ projectListQuery,
+ projectListOptions,
+ projectsUrl,
+} from "@/lib/projects/sort";
+import { ProjectListControls } from "@/components/projects/ProjectListControls";
+import { DetailImage } from "@/components/projects/DetailMedia";
+import { projectThumbnail } from "@/lib/projects/urls";
+import Link from "next/link";
+import { requireSession } from "@/lib/auth/guards";
+import { canProjectAction } from "@/lib/projects/permissions";
+import { searchProjects } from "@/lib/projects/service";
+import { db } from "@/lib/db";
+import { Badge } from "@/components/ui/Badge";
-export default async function ProjectsPage() {
- const { rows } = await getProjects();
+export default async function ProjectsPage({
+ searchParams,
+}: {
+ searchParams: Promise>;
+}) {
+ const { user } = await requireSession();
+ const parsed = projectListQuery.safeParse(await searchParams);
+ const query = parsed.success ? parsed.data : projectListQuery.parse({});
+ const [results, chapters, impactRecords] = await Promise.all([
+ searchProjects(user, false, projectListOptions(query)),
+ db.chapter.findMany({
+ select: { id: true, name: true },
+ orderBy: { name: "asc" },
+ }),
+ db.project.findMany({
+ where: { isDraft: false },
+ select: { causeAreas: true },
+ distinct: ["causeAreas"],
+ }),
+ ]);
+ const records = results.items;
+ const active = Boolean(
+ query.q ||
+ query.chapter_id ||
+ query.stage ||
+ query.project_length ||
+ query.impact_area
+ );
+ if (
+ query.chapter_id &&
+ !chapters.some((chapter) => chapter.id === query.chapter_id)
+ )
+ notFound();
return (
-
-
- + Add Project
-
-
-
-
+
+ Project Directory
+ {canProjectAction(user, "create", user.chapterId ?? undefined) && (
+
+ + Add Project
+
+ )}
+
+
+ {canProjectAction(user, "create", user.chapterId ?? undefined) && (
+
+ Resume a draft
+
+ )}
+
record.causeAreas)),
+ ]}
+ />
+ {!parsed.success && (
+
+ Those filters are not valid. Showing all published projects.
+
+ )}
+
+ Project records
+
+ Results: {results.total}
+
+ {records.length ? (
+
+ {records.map((project) => (
+
+
+
+ {projectThumbnail(
+ project.demoMedia,
+ project.nonprofitPartnerPhoto
+ ) ? (
+
+ ) : (
+ No preview available
+ )}
+
+
+
+ {project.name || "Untitled project"}
+
+
+ {
+ chapters.find(
+ (chapter) => chapter.id === project.chapterId
+ )?.name
+ }{" "}
+ ·{" "}
+ {project.startDate
+ ? new Date(project.startDate).getUTCFullYear()
+ : "Year not set"}
+
+
+ {project.nonprofitPartnerName || "Partner not listed"}
+
+
+
+ {[...project.techStack, ...project.causeAreas].map(
+ (tag, index) => (
+
+ )
+ )}
+
+
+
+ {canProjectAction(user, "edit", project.chapterId) && (
+
+ Edit
+
+ )}
+
+ ))}
+
+ ) : (
+
+
+ {active
+ ? "No projects match these filters"
+ : "No published projects yet"}
+
+
+ {active
+ ? "Try another search or remove a filter."
+ : "Projects appear here after they are published."}
+
+ {active && (
+
+ Clear filters
+
+ )}
+
+ )}
+
+ {results.total > 0 && (
+
+ {results.page > 1 ? (
+
+ Previous page
+
+ ) : (
+
+ )}
+
+ Page {results.page} of {results.pages}
+
+ {results.page < results.pages ? (
+
+ Next page
+
+ ) : (
+
+ )}
+
+ )}
);
diff --git a/src/app/(protected)/layout.tsx b/src/app/(protected)/layout.tsx
index 2e75dae..1832f61 100644
--- a/src/app/(protected)/layout.tsx
+++ b/src/app/(protected)/layout.tsx
@@ -12,9 +12,9 @@ export default async function DashboardLayout({
const session = await requireSession();
return (
-
+
- {children}
+ {children}
);
}
diff --git a/src/app/api/projects/[projectId]/media/[file]/route.ts b/src/app/api/projects/[projectId]/media/[file]/route.ts
new file mode 100644
index 0000000..afed24c
--- /dev/null
+++ b/src/app/api/projects/[projectId]/media/[file]/route.ts
@@ -0,0 +1,32 @@
+import {
+ projectResponse,
+ projectViewer,
+ ProjectApiError,
+} from "@/lib/projects/http";
+import { readProject } from "@/lib/projects/service";
+import { serveMedia } from "@/lib/projects/media";
+
+export const runtime = "nodejs";
+export async function GET(
+ request: Request,
+ context: { params: Promise<{ projectId: string; file: string }> }
+) {
+ return projectResponse(async () => {
+ const viewer = await projectViewer(request);
+ const { projectId, file } = await context.params;
+ const project = await readProject(viewer, projectId);
+ const url = `/api/projects/${encodeURIComponent(projectId)}/media/${file}`;
+ if (
+ !project.demoMedia.includes(url) &&
+ project.nonprofitPartnerPhoto !== url
+ ) {
+ // Scoped editors can preview a just-uploaded file before saving the form.
+ try {
+ await readProject(viewer, projectId, true);
+ } catch {
+ throw new ProjectApiError(404, "Media not found");
+ }
+ }
+ return serveMedia(projectId, file, request.headers.get("range"));
+ });
+}
diff --git a/src/app/api/projects/[projectId]/media/route.ts b/src/app/api/projects/[projectId]/media/route.ts
new file mode 100644
index 0000000..ed3136b
--- /dev/null
+++ b/src/app/api/projects/[projectId]/media/route.ts
@@ -0,0 +1,35 @@
+import { EDITOR_ROLES } from "@/lib/auth/roles";
+import {
+ projectResponse,
+ projectViewer,
+ ProjectApiError,
+} from "@/lib/projects/http";
+import {
+ assertProjectWriteAccess,
+ withProjectWriteAccess,
+} from "@/lib/projects/service";
+import { storeMedia, uploadedFile } from "@/lib/projects/media";
+
+export const runtime = "nodejs";
+export async function POST(
+ request: Request,
+ context: { params: Promise<{ projectId: string }> }
+) {
+ return projectResponse(async () => {
+ const viewer = await projectViewer(request, EDITOR_ROLES);
+ const { projectId } = await context.params;
+ await assertProjectWriteAccess(viewer, projectId);
+ const file = await uploadedFile(request);
+ if (
+ new URL(request.url).searchParams.get("purpose") === "partner-photo" &&
+ !file.type.startsWith("image/")
+ )
+ throw new ProjectApiError(400, "Partner photos must be images");
+ return Response.json(
+ await withProjectWriteAccess(viewer, projectId, () =>
+ storeMedia(projectId, file)
+ ),
+ { status: 201 }
+ );
+ });
+}
diff --git a/src/app/api/projects/[projectId]/publish/route.ts b/src/app/api/projects/[projectId]/publish/route.ts
new file mode 100644
index 0000000..289ae7c
--- /dev/null
+++ b/src/app/api/projects/[projectId]/publish/route.ts
@@ -0,0 +1,21 @@
+import { hasRole, ADMIN_ROLES, EDITOR_ROLES } from "@/lib/auth/roles";
+import {
+ authorizeProject,
+ projectResponse,
+ projectViewer,
+} from "@/lib/projects/http";
+import { publishProject } from "@/lib/projects/service";
+
+export async function POST(
+ request: Request,
+ context: { params: Promise<{ projectId: string }> }
+) {
+ return projectResponse(async () => {
+ const viewer = await projectViewer(request, EDITOR_ROLES);
+ if (!hasRole(viewer.role, ADMIN_ROLES))
+ authorizeProject(viewer, "publish", viewer.chapterId ?? undefined);
+ return Response.json(
+ await publishProject(viewer, (await context.params).projectId)
+ );
+ });
+}
diff --git a/src/app/api/projects/[projectId]/route.ts b/src/app/api/projects/[projectId]/route.ts
new file mode 100644
index 0000000..4c937ab
--- /dev/null
+++ b/src/app/api/projects/[projectId]/route.ts
@@ -0,0 +1,47 @@
+import { hasRole, ADMIN_ROLES, EDITOR_ROLES } from "@/lib/auth/roles";
+import {
+ authorizeProject,
+ projectResponse,
+ projectViewer,
+} from "@/lib/projects/http";
+import {
+ deleteProject,
+ parseProjectBody,
+ patchProject,
+ readProject,
+} from "@/lib/projects/service";
+
+type Context = { params: Promise<{ projectId: string }> };
+export async function GET(request: Request, context: Context) {
+ return projectResponse(async () => {
+ const viewer = await projectViewer(request);
+ return Response.json(
+ await readProject(
+ viewer,
+ (await context.params).projectId,
+ new URL(request.url).searchParams.get("draft") === "true"
+ )
+ );
+ });
+}
+export async function PATCH(request: Request, context: Context) {
+ return projectResponse(async () => {
+ const viewer = await projectViewer(request, EDITOR_ROLES);
+ if (!hasRole(viewer.role, ADMIN_ROLES))
+ authorizeProject(viewer, "edit", viewer.chapterId ?? undefined);
+ return Response.json(
+ await patchProject(
+ viewer,
+ (await context.params).projectId,
+ await parseProjectBody(request)
+ )
+ );
+ });
+}
+export async function DELETE(request: Request, context: Context) {
+ return projectResponse(async () => {
+ const viewer = await projectViewer(request, ADMIN_ROLES);
+ await deleteProject(viewer, (await context.params).projectId);
+ return new Response(null, { status: 204 });
+ });
+}
diff --git a/src/app/api/projects/references/members/route.ts b/src/app/api/projects/references/members/route.ts
new file mode 100644
index 0000000..6068fb2
--- /dev/null
+++ b/src/app/api/projects/references/members/route.ts
@@ -0,0 +1,22 @@
+import { z } from "zod";
+import { EDITOR_ROLES } from "@/lib/auth/roles";
+import {
+ projectResponse,
+ projectViewer,
+ ProjectApiError,
+} from "@/lib/projects/http";
+import { searchMemberReferences } from "@/lib/projects/references";
+
+export async function GET(request: Request) {
+ return projectResponse(async () => {
+ await projectViewer(request, EDITOR_ROLES);
+ const query = z
+ .string()
+ .trim()
+ .max(100)
+ .safeParse(new URL(request.url).searchParams.get("q") || "");
+ if (!query.success)
+ throw new ProjectApiError(400, "Search must be at most 100 characters");
+ return Response.json({ members: await searchMemberReferences(query.data) });
+ });
+}
diff --git a/src/app/api/projects/references/partners/route.test.ts b/src/app/api/projects/references/partners/route.test.ts
new file mode 100644
index 0000000..fd00193
--- /dev/null
+++ b/src/app/api/projects/references/partners/route.test.ts
@@ -0,0 +1,78 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const mocks = vi.hoisted(() => ({ assertRole: vi.fn(), partners: vi.fn() }));
+vi.mock("@/lib/auth/guards", () => ({
+ assertRole: mocks.assertRole,
+ assertSession: vi.fn(),
+}));
+vi.mock("@/lib/notion/api", () => ({ getPartnerReferences: mocks.partners }));
+import { GET } from "./route";
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.assertRole.mockResolvedValue({
+ user: { id: "editor", role: "PROJECT_LEAD", chapterId: "c" },
+ });
+});
+afterEach(() => vi.unstubAllEnvs());
+describe("Partner Directory reference search", () => {
+ it("uses the canonical directory and matches names case-insensitively", async () => {
+ vi.stubEnv("NOTION_API_KEY", "test-only-key");
+ mocks.partners.mockResolvedValue([
+ { id: "p1", name: "Food Bank", photo: null },
+ { id: "p2", name: "Library", photo: null },
+ ]);
+ const response = await GET(
+ new Request("http://localhost/api/projects/references/partners?q=FOOD")
+ );
+ expect(await response.json()).toEqual({
+ available: true,
+ partners: [{ id: "p1", name: "Food Bank", photo: null }],
+ });
+ expect(mocks.partners).toHaveBeenCalledOnce();
+ });
+ it("enables free-text fallback when the directory is unconfigured or offline", async () => {
+ vi.stubEnv("NOTION_API_KEY", "");
+ expect(
+ await (
+ await GET(
+ new Request(
+ "http://localhost/api/projects/references/partners?q=Food"
+ )
+ )
+ ).json()
+ ).toEqual({ available: false, partners: [] });
+ expect(mocks.partners).not.toHaveBeenCalled();
+ vi.stubEnv("NOTION_API_KEY", "test-only-key");
+ mocks.partners.mockRejectedValue(new Error("Unavailable"));
+ expect(
+ await (
+ await GET(
+ new Request(
+ "http://localhost/api/projects/references/partners?q=Food"
+ )
+ )
+ ).json()
+ ).toEqual({ available: false, partners: [] });
+ });
+ it("requires an editor session and validates query lengths", async () => {
+ mocks.assertRole.mockRejectedValueOnce(new Error("Forbidden"));
+ expect(
+ (
+ await GET(
+ new Request(
+ "http://localhost/api/projects/references/partners?q=Food"
+ )
+ )
+ ).status
+ ).toBe(403);
+ expect(
+ (
+ await GET(
+ new Request(
+ `http://localhost/api/projects/references/partners?q=${"x".repeat(101)}`
+ )
+ )
+ ).status
+ ).toBe(400);
+ });
+});
diff --git a/src/app/api/projects/references/partners/route.ts b/src/app/api/projects/references/partners/route.ts
new file mode 100644
index 0000000..53bfbdb
--- /dev/null
+++ b/src/app/api/projects/references/partners/route.ts
@@ -0,0 +1,38 @@
+import { z } from "zod";
+import { EDITOR_ROLES } from "@/lib/auth/roles";
+import {
+ projectResponse,
+ projectViewer,
+ ProjectApiError,
+} from "@/lib/projects/http";
+import { getPartnerReferences } from "@/lib/notion/api";
+
+export async function GET(request: Request) {
+ return projectResponse(async () => {
+ await projectViewer(request, EDITOR_ROLES);
+ const query = z
+ .string()
+ .trim()
+ .max(100)
+ .safeParse(new URL(request.url).searchParams.get("q") || "");
+ if (!query.success)
+ throw new ProjectApiError(400, "Search must be at most 100 characters");
+ if (!process.env.NOTION_API_KEY)
+ return Response.json({ partners: [], available: false });
+ try {
+ const partners = await getPartnerReferences();
+ return Response.json({
+ partners: partners
+ .filter((partner) =>
+ partner.name
+ .toLocaleLowerCase()
+ .includes(query.data.toLocaleLowerCase())
+ )
+ .slice(0, 20),
+ available: true,
+ });
+ } catch {
+ return Response.json({ partners: [], available: false });
+ }
+ });
+}
diff --git a/src/app/api/projects/route.ts b/src/app/api/projects/route.ts
new file mode 100644
index 0000000..52a0027
--- /dev/null
+++ b/src/app/api/projects/route.ts
@@ -0,0 +1,51 @@
+import { projectListQuery, projectListOptions } from "@/lib/projects/sort";
+import { hasRole, ADMIN_ROLES, EDITOR_ROLES } from "@/lib/auth/roles";
+import {
+ authorizeProject,
+ projectResponse,
+ projectViewer,
+ ProjectApiError,
+} from "@/lib/projects/http";
+import {
+ createProject,
+ searchProjects,
+ parseProjectBody,
+} from "@/lib/projects/service";
+
+export async function GET(request: Request) {
+ return projectResponse(async () => {
+ const viewer = await projectViewer(request);
+ const params = new URL(request.url).searchParams;
+ const query = projectListQuery.safeParse(Object.fromEntries(params));
+ if (!query.success)
+ throw new ProjectApiError(
+ 400,
+ "Invalid project search, filters or pagination"
+ );
+ const results = await searchProjects(
+ viewer,
+ params.get("include_drafts") === "true",
+ projectListOptions(query.data)
+ );
+ return Response.json(results.items, {
+ headers: {
+ "X-Total-Count": String(results.total),
+ "X-Page": String(results.page),
+ "X-Page-Size": String(results.pageSize),
+ "X-Total-Pages": String(results.pages),
+ "Cache-Control": "private, no-store",
+ },
+ });
+ });
+}
+export async function POST(request: Request) {
+ return projectResponse(async () => {
+ const viewer = await projectViewer(request, EDITOR_ROLES);
+ if (!hasRole(viewer.role, ADMIN_ROLES))
+ authorizeProject(viewer, "create", viewer.chapterId ?? undefined);
+ return Response.json(
+ await createProject(viewer, await parseProjectBody(request, true)),
+ { status: 201 }
+ );
+ });
+}
diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx
index 349f947..aa75927 100644
--- a/src/components/layout/Sidebar.tsx
+++ b/src/components/layout/Sidebar.tsx
@@ -120,14 +120,14 @@ function NavItem({ href, label, icon, count, excludes }: NavItemProps) {
{icon}
-
{label}
+
{label}
{count !== undefined && (
{count.toLocaleString()}
@@ -142,10 +142,13 @@ export function Sidebar({ user }: { user: SidebarUser }) {
const showClaimRequests = hasRole(user.role, CHAPTER_LEADERSHIP_ROLES);
return (
-
-
+
+
-
+
void;
+ beforeDelete?: () => Promise;
+}) {
+ const router = useRouter();
+ const cancel = useRef(null);
+ const [open, setOpen] = useState(false);
+ const [pending, setPending] = useState(false);
+ const [error, setError] = useState("");
+ const [denied, setDenied] = useState(false);
+ async function remove() {
+ if (pending || denied) return;
+ setPending(true);
+ setError("");
+ try {
+ await beforeDelete?.();
+ try {
+ await projectClient.remove(id);
+ } catch (failure) {
+ if (!(failure instanceof ProjectRequestError && failure.status === 404))
+ throw failure;
+ }
+ setOpen(false);
+ router.replace("/projects");
+ router.refresh();
+ } catch (failure) {
+ if (
+ failure instanceof ProjectRequestError &&
+ [401, 403].includes(failure.status)
+ ) {
+ setDenied(true);
+ setError(
+ "Your access has changed. The project was not deleted. Reload to refresh your permissions."
+ );
+ } else setError("Could not delete this project. Please try again.");
+ } finally {
+ setPending(false);
+ }
+ }
+ return (
+ {
+ if (pending) {
+ details.cancel();
+ return;
+ }
+ setOpen(next);
+ setError("");
+ setDenied(false);
+ onOpenChange?.(next);
+ }}
+ >
+
+ Delete Project
+
+
+
+
+
+ Delete project?
+
+
+ Permanently delete “{name || "Untitled project"}”, including its
+ drafts, team roster, resource links and uploaded media. This cannot
+ be undone.
+
+ {error && (
+
+ {error}
+
+ )}
+
+
+ Cancel
+
+
void remove()}
+ >
+ {pending ? "Deleting…" : "Delete permanently"}
+
+
+
+
+
+ );
+}
diff --git a/src/components/projects/DetailMedia.tsx b/src/components/projects/DetailMedia.tsx
new file mode 100644
index 0000000..35063ec
--- /dev/null
+++ b/src/components/projects/DetailMedia.tsx
@@ -0,0 +1,67 @@
+"use client";
+
+import { useState } from "react";
+
+export function DetailImage({
+ src,
+ alt,
+ className,
+ fallback = "Image unavailable",
+}: {
+ src: string;
+ alt: string;
+ className?: string;
+ fallback?: string;
+}) {
+ const [failedSrc, setFailedSrc] = useState(null);
+ if (failedSrc === src) return {fallback} ;
+ return (
+ // eslint-disable-next-line @next/next/no-img-element
+ setFailedSrc(src)}
+ />
+ );
+}
+export function DetailMedia({ src, index }: { src: string; index: number }) {
+ const [failedSrc, setFailedSrc] = useState(null);
+ return (
+
+ {/\.(mp4|webm)(?:[?#]|$)/i.test(src) ? (
+ failedSrc === src ? (
+
+ Video unavailable. You can try opening the original below.
+
+ ) : (
+ setFailedSrc(src)}
+ controls
+ preload="metadata"
+ className="bg-panel aspect-video w-full"
+ aria-label={`Demo video ${index + 1}`}
+ />
+ )
+ ) : (
+
+ )}
+
+
+ Open media {index + 1}
+
+
+
+ );
+}
diff --git a/src/components/projects/ProjectForm.tsx b/src/components/projects/ProjectForm.tsx
new file mode 100644
index 0000000..359eff5
--- /dev/null
+++ b/src/components/projects/ProjectForm.tsx
@@ -0,0 +1,1055 @@
+"use client";
+
+import { useState, type ReactNode, type MouseEvent } from "react";
+import Link from "next/link";
+import { DeleteProject } from "./DeleteProject";
+import { useRouter } from "next/navigation";
+import { useProjectDraft } from "./useProjectDraft";
+import { MemberPicker, PartnerPicker } from "./ReferencePickers";
+import type { MemberReference } from "@/lib/projects/references";
+import { Button } from "@/components/ui/Button";
+import {
+ draftErrors,
+ draftFieldPath,
+ errorSection,
+ formValue,
+ type ProjectFormValue,
+} from "@/lib/projects/form";
+import { projectClient, ProjectRequestError } from "@/lib/projects/client";
+import {
+ requiredByStage,
+ stages,
+ type ProjectPatch,
+} from "@/lib/projects/validation";
+
+const control =
+ "border-separator bg-control focus-visible:outline-focus w-full rounded-4 border px-12 py-8 focus-visible:outline-2 disabled:opacity-60";
+const stageLabels = {
+ design: "Design",
+ development: "Development",
+ launched: "Launched",
+ maintenance: "Maintenance",
+};
+const labels: Record = {
+ name: "Project name",
+ chapterId: "Chapter",
+ tagline: "Tagline",
+ nonprofitPartner: "Nonprofit partner",
+ nonprofitPartnerName: "Nonprofit partner",
+ startDate: "Start date",
+ endDate: "End date",
+ problemStatement: "Problem statement",
+ goalStatement: "Project goal",
+ teamMembers: "Team members",
+ solutionDescription: "Solution",
+ resourceLinks: "Resource links",
+ demoMedia: "Demo media",
+};
+function fieldLabel(field: string) {
+ const parts = field.split(".");
+ if (parts[0] === "teamMembers" && /^\d+$/.test(parts[1] || ""))
+ return parts[2] === "role"
+ ? `Role for team member ${Number(parts[1]) + 1}`
+ : `Team member ${Number(parts[1]) + 1}`;
+ if (parts[0] === "resourceLinks" && /^\d+$/.test(parts[1] || ""))
+ return `URL for resource link ${Number(parts[1]) + 1}`;
+ return labels[field] || "Project field";
+}
+function fieldId(name: string) {
+ return `project-${name.replaceAll(".", "-")}`;
+}
+function Field({
+ name,
+ label,
+ required,
+ error,
+ children,
+}: {
+ name: string;
+ label: string;
+ required?: boolean;
+ error?: string;
+ children: ReactNode;
+}) {
+ return (
+
+
+ {label}
+ {required && (
+
+ * required to publish
+
+ )}
+
+ {children}
+ {error && (
+
+ {error}
+
+ )}
+
+ );
+}
+function Section({
+ id,
+ title,
+ children,
+ errors = {},
+}: {
+ id: string;
+ title: string;
+ errors?: Record;
+ children: ReactNode;
+}) {
+ return (
+ errorSection(field) === Number(id.slice(-1))) ? "border-red" : "border-separator"}`}
+ >
+
+ {title}
+
+ {children}
+
+ );
+}
+function Tags({
+ name,
+ value,
+ onChange,
+ disabled,
+}: {
+ name: string;
+ value: string[];
+ onChange: (tags: string[]) => void;
+ disabled: boolean;
+}) {
+ const [text, setText] = useState("");
+ function commit() {
+ const next = [...value];
+ for (const tag of text
+ .split(",")
+ .map((part) => part.trim())
+ .filter(Boolean))
+ if (
+ !next.some((existing) => existing.toLowerCase() === tag.toLowerCase())
+ )
+ next.push(tag.slice(0, 100));
+ onChange(next.slice(0, 100));
+ setText("");
+ }
+ return (
+
+
+ {value.map((tag) => (
+ onChange(value.filter((item) => item !== tag))}
+ >
+ {tag} ×
+
+ ))}
+
+
setText(event.target.value)}
+ onBlur={() => {
+ if (text.trim()) commit();
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Enter" || event.key === ",") {
+ event.preventDefault();
+ commit();
+ }
+ }}
+ />
+
+ );
+}
+
+export function ProjectForm({
+ initial,
+ projectId: initialId = null,
+ isDraft: initialDraft = true,
+ chapters,
+ members,
+ canDelete = false,
+}: {
+ initial?: ProjectPatch;
+ projectId?: string | null;
+ isDraft?: boolean;
+ chapters: { id: string; name: string }[];
+ members: MemberReference[];
+ canDelete?: boolean;
+}) {
+ const [value, setValue] = useState(() =>
+ formValue({
+ chapterId: chapters.length === 1 ? chapters[0].id : "",
+ ...initial,
+ })
+ );
+ const [memberOptions, setMemberOptions] = useState(members);
+ const isDraft = initialDraft;
+ const router = useRouter();
+ const [busy, setBusy] = useState(false);
+ const [deleteOpen, setDeleteOpen] = useState(false);
+ const [accessLost, setAccessLost] = useState(false);
+ const [message, setMessage] = useState("");
+ const [errors, setErrors] = useState>({});
+ const draft = useProjectDraft(
+ value,
+ initialId,
+ busy || deleteOpen || accessLost
+ );
+ const projectId = draft.id;
+ const locked = busy || deleteOpen || draft.blocked || accessLost;
+ const required: readonly string[] = requiredByStage[value.stage];
+ function update(
+ name: K,
+ next: ProjectFormValue[K]
+ ) {
+ setValue((previous) => ({ ...previous, [name]: next }));
+ setErrors({});
+ setMessage("");
+ }
+ function inputProps(name: keyof ProjectFormValue) {
+ return {
+ id: fieldId(name),
+ className: control,
+ "aria-invalid": Boolean(errors[name]),
+ "aria-required": required.includes(name),
+ "aria-describedby": errors[name] ? `${fieldId(name)}-error` : undefined,
+ };
+ }
+ function report(error: unknown) {
+ if (error instanceof ProjectRequestError) {
+ if ([401, 403, 404].includes(error.status)) {
+ setAccessLost(true);
+ setMessage(
+ "Your access changed or this project is no longer available. Changes were not saved. Reload to refresh your access."
+ );
+ return;
+ }
+ const missing = error.details?.missingFields;
+ if (missing)
+ setErrors(
+ Object.fromEntries(
+ missing.map((key) => {
+ const field =
+ key === "nonprofitPartner"
+ ? "nonprofitPartnerName"
+ : draftFieldPath(value, key);
+ return [
+ field,
+ `${fieldLabel(field)} is required to publish at ${stageLabels[value.stage]}.`,
+ ];
+ })
+ )
+ );
+ else if (error.details?.fieldErrors)
+ setErrors(
+ Object.fromEntries(
+ Object.entries(error.details.fieldErrors).map(([key, messages]) => [
+ key,
+ messages.join(" "),
+ ])
+ )
+ );
+ setMessage(error.message);
+ } else
+ setMessage(
+ error instanceof Error
+ ? error.message
+ : "Could not save. Please try again."
+ );
+ }
+ async function save(publish: boolean) {
+ const invalid = draftErrors(value);
+ setErrors(invalid);
+ if (Object.keys(invalid).length) {
+ setMessage("Check the fields below. Your changes have not been saved.");
+ return;
+ }
+ draft.suspend();
+ setBusy(true);
+ setMessage(publish ? "Saving and publishing…" : "Saving draft…");
+ try {
+ const saved = await draft.save();
+ if (publish) {
+ await draft.publish();
+ if (draft.isActive()) {
+ router.push(`/projects/${encodeURIComponent(saved.id)}`);
+ router.refresh();
+ }
+ } else setMessage("");
+ } catch (error) {
+ report(error);
+ } finally {
+ draft.resume();
+ setBusy(false);
+ }
+ }
+ async function upload(
+ files: FileList | null,
+ purpose: "demo" | "partner-photo" = "demo"
+ ) {
+ if (!files?.length) return;
+ const selectedFiles = Array.from(files);
+ if (!value.name.trim() || !value.chapterId) {
+ setMessage("Enter a project name and chapter before uploading media.");
+ return;
+ }
+ if (
+ purpose === "demo" &&
+ value.demoMedia.length + selectedFiles.length > 50
+ ) {
+ setMessage("A project may have up to 50 media files.");
+ return;
+ }
+ draft.suspend();
+ setBusy(true);
+ setMessage("Uploading media…");
+ const uploaded: string[] = [];
+ try {
+ const id = await draft.ensureId();
+ for (const file of selectedFiles)
+ uploaded.push((await projectClient.upload(id, file, purpose)).url);
+ setMessage("");
+ } catch (error) {
+ report(error);
+ } finally {
+ if (uploaded.length)
+ setValue((previous) => ({
+ ...previous,
+ ...(purpose === "partner-photo"
+ ? { nonprofitPartnerPhoto: uploaded[0] }
+ : { demoMedia: [...previous.demoMedia, ...uploaded] }),
+ }));
+ draft.resume();
+ setBusy(false);
+ }
+ }
+ async function leave(event: MouseEvent) {
+ if (
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey ||
+ event.button !== 0
+ )
+ return;
+ event.preventDefault();
+ if (busy) return;
+ if (draft.blocked || accessLost || !draft.dirty) {
+ router.push("/projects");
+ return;
+ }
+ const invalid = draftErrors(value);
+ if (Object.keys(invalid).length) {
+ setErrors(invalid);
+ setMessage(
+ "Check these fields before leaving so your changes can be saved."
+ );
+ return;
+ }
+ draft.suspend();
+ setBusy(true);
+ try {
+ await draft.save();
+ if (draft.isActive()) {
+ router.push("/projects");
+ router.refresh();
+ }
+ } catch (error) {
+ report(error);
+ } finally {
+ draft.resume();
+ setBusy(false);
+ }
+ }
+ const sections = [
+ "Basics",
+ "Nonprofit & Timeline",
+ "Project Goal",
+ "Team Members",
+ "Solution",
+ "Resource Links",
+ ];
+ if (!chapters.length)
+ return (
+
+
Chapter assignment needed
+
+ A National Admin must assign you a chapter before you can add
+ projects.
+
+
void leave(event)}
+ className="underline"
+ >
+ Back to projects
+
+
+ );
+ return (
+
+ );
+}
+function MediaPreview({ src, index }: { src: string; index: number }) {
+ const [failed, setFailed] = useState(false);
+ if (failed) return Preview unavailable ;
+ return (
+ // eslint-disable-next-line @next/next/no-img-element
+ setFailed(true)}
+ />
+ );
+}
diff --git a/src/components/projects/ProjectListControls.tsx b/src/components/projects/ProjectListControls.tsx
new file mode 100644
index 0000000..3bb778a
--- /dev/null
+++ b/src/components/projects/ProjectListControls.tsx
@@ -0,0 +1,324 @@
+"use client";
+
+import { useEffect, useRef, useTransition } from "react";
+import { useRouter } from "next/navigation";
+import Link from "next/link";
+import { Search, ChevronDown } from "lucide-react";
+import {
+ projectSortLabels,
+ projectLengthLabels,
+ projectsUrl,
+ type ProjectListQuery,
+} from "@/lib/projects/sort";
+import { stages } from "@/lib/projects/validation";
+const control =
+ "border-separator bg-control min-h-44 w-full rounded-4 border px-8 focus-visible:outline-2 focus-visible:outline-focus";
+
+export function ProjectListControls({
+ query,
+ chapters,
+ impactAreas,
+}: {
+ query: ProjectListQuery;
+ chapters: { id: string; name: string }[];
+ impactAreas: string[];
+}) {
+ const router = useRouter();
+ const [pending, startTransition] = useTransition();
+ const form = useRef(null);
+ const search = useRef(null);
+ const restoreFocus = useRef(false);
+ const timer = useRef | null>(null);
+ useEffect(
+ () => () => {
+ if (timer.current) clearTimeout(timer.current);
+ },
+ []
+ );
+ useEffect(() => {
+ if (search.current && document.activeElement !== search.current)
+ search.current.value = query.q ?? "";
+ if (restoreFocus.current) {
+ search.current?.focus();
+ restoreFocus.current = false;
+ }
+ }, [
+ query.q,
+ query.chapter_id,
+ query.stage,
+ query.project_length,
+ query.impact_area,
+ ]);
+ useEffect(() => {
+ function closeOutside(event: PointerEvent) {
+ form.current?.querySelectorAll("details[open]").forEach((element) => {
+ if (!element.contains(event.target as Node))
+ element.removeAttribute("open");
+ });
+ }
+ document.addEventListener("pointerdown", closeOutside);
+ return () => document.removeEventListener("pointerdown", closeOutside);
+ }, []);
+ function apply() {
+ if (timer.current) clearTimeout(timer.current);
+ if (!form.current) return;
+ const values = Object.fromEntries(new FormData(form.current)) as Record<
+ string,
+ string
+ >;
+ const params = new URLSearchParams();
+ for (const [key, value] of Object.entries(values))
+ if (value.trim()) params.set(key, value.trim());
+ startTransition(() =>
+ router.replace(`/projects?${params}`, { scroll: false })
+ );
+ }
+ const chips = [
+ query.q ? { key: "q" as const, label: `Search: ${query.q}` } : null,
+ query.chapter_id
+ ? {
+ key: "chapter_id" as const,
+ label: `Chapter: ${chapters.find((c) => c.id === query.chapter_id)?.name ?? query.chapter_id}`,
+ }
+ : null,
+ query.stage
+ ? { key: "stage" as const, label: `Stage: ${query.stage}` }
+ : null,
+ query.project_length
+ ? {
+ key: "project_length" as const,
+ label: `Length: ${projectLengthLabels[query.project_length]}`,
+ }
+ : null,
+ query.impact_area
+ ? { key: "impact_area" as const, label: `Impact: ${query.impact_area}` }
+ : null,
+ ].filter((chip) => chip !== null);
+ return (
+
+
{
+ event.preventDefault();
+ // Close the Filter/Sort panel so it doesn't stay over the results
+ // (and the "Clear filters" chip) after applying.
+ form.current
+ ?.querySelectorAll("details[open]")
+ .forEach((element) => element.removeAttribute("open"));
+ apply();
+ }}
+ className="relative flex min-w-0 flex-wrap items-center justify-end gap-12"
+ onKeyDown={(event) => {
+ if (event.key !== "Escape") return;
+ const open = form.current?.querySelector("details[open]");
+ if (open) {
+ event.preventDefault();
+ open.removeAttribute("open");
+ open.querySelector("summary")?.focus();
+ }
+ }}
+ >
+
+ Search projects or chapters
+
+ {
+ if (timer.current) clearTimeout(timer.current);
+ timer.current = setTimeout(apply, 350);
+ }}
+ />
+
+ {chapters.map((c) => (
+
+ ))}
+
+
+ Results update as you type. Chapter names are suggested; you can
+ also select a chapter in Filter.
+
+
+
+
+ Filter{" "}
+
+
+
+
+ Chapter
+
+ All chapters
+ {chapters.map((c) => (
+
+ {c.name}
+
+ ))}
+
+
+
+ Stage
+
+ All stages
+ {stages.map((s) => (
+
+ {s[0].toUpperCase() + s.slice(1)}
+
+ ))}
+
+
+
+ Project length
+
+ All lengths
+ {Object.entries(projectLengthLabels).map(([key, label]) => (
+
+ {label}
+
+ ))}
+
+
+
+ Impact area
+
+ All impact areas
+ {[
+ ...new Set([
+ ...impactAreas,
+ ...(query.impact_area ? [query.impact_area] : []),
+ ]),
+ ]
+ .sort()
+ .map((area) => (
+
+ {area}
+
+ ))}
+
+
+
+
+ Apply filters
+
+
+
+
+
+ Sort{" "}
+
+
+
+
+ Sort projects
+
+ {Object.entries(projectSortLabels).map(([key, label]) => (
+
+ {label}
+
+ ))}
+
+
+
+
+
+
+
+ {pending ? "Updating projects…" : ""}
+
+ {!!chips.length && (
+
+ {chips.map((chip) => (
+ {
+ restoreFocus.current = true;
+ if (timer.current) clearTimeout(timer.current);
+ }}
+ >
+ {chip.label} ×
+
+ ))}
+ {
+ restoreFocus.current = true;
+ if (timer.current) clearTimeout(timer.current);
+ }}
+ >
+ Clear filters
+
+
+ )}
+
+ );
+}
diff --git a/src/components/projects/ReferencePickers.tsx b/src/components/projects/ReferencePickers.tsx
new file mode 100644
index 0000000..acafa18
--- /dev/null
+++ b/src/components/projects/ReferencePickers.tsx
@@ -0,0 +1,312 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { memberReferences, partnerReferences } from "@/lib/projects/client";
+import type {
+ MemberReference,
+ PartnerReference,
+} from "@/lib/projects/references";
+
+const control =
+ "border-separator bg-control focus-visible:outline-focus w-full rounded-4 border px-12 py-8 focus-visible:outline-2";
+export function MemberAvatar({ name }: { name: string }) {
+ const initials = name
+ .split(/\s+/)
+ .filter(Boolean)
+ .slice(0, 2)
+ .map((part) => part[0])
+ .join("");
+ return (
+
+ {initials || "?"}
+
+ );
+}
+export function MemberPicker({
+ id,
+ value,
+ options,
+ onSelect,
+ error,
+}: {
+ id: string;
+ value: string;
+ options: MemberReference[];
+ onSelect: (person: MemberReference) => void;
+ error?: string;
+}) {
+ const [query, setQuery] = useState("");
+ const [open, setOpen] = useState(false);
+ const [active, setActive] = useState(-1);
+ const [found, setFound] = useState<{
+ query: string;
+ members: MemberReference[];
+ error?: string;
+ }>({ query: "", members: options });
+ const [picked, setPicked] = useState(null);
+ const selected =
+ options.find((member) => member.id === value) ||
+ (picked?.id === value ? picked : null);
+ useEffect(() => {
+ if (!open) return;
+ const controller = new AbortController();
+ const timer = setTimeout(() => {
+ memberReferences(query.trim(), controller.signal).then(
+ (data) => {
+ if (!controller.signal.aborted)
+ setFound({ query, members: data.members });
+ },
+ () => {
+ if (!controller.signal.aborted)
+ setFound({
+ query,
+ members: [],
+ error: "Member search is unavailable. Try again.",
+ });
+ }
+ );
+ }, 250);
+ return () => {
+ clearTimeout(timer);
+ controller.abort();
+ };
+ }, [query, open]);
+ const list = found.query === query ? found.members : [];
+ function choose(member: MemberReference) {
+ setPicked(member);
+ onSelect(member);
+ setOpen(false);
+ setActive(-1);
+ }
+ return (
+
+
+
+ = 0 ? `${id}-option-${active}` : undefined
+ }
+ aria-invalid={Boolean(error)}
+ aria-describedby={error ? `${id}-error` : undefined}
+ className={control}
+ placeholder="Search member records…"
+ value={open ? query : selected?.name || ""}
+ onFocus={() => {
+ setQuery("");
+ setOpen(true);
+ setActive(-1);
+ }}
+ onBlur={() => setOpen(false)}
+ onChange={(event) => {
+ setQuery(event.target.value);
+ setOpen(true);
+ setActive(-1);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ setOpen(false);
+ setActive(-1);
+ }
+ if (["ArrowDown", "ArrowUp"].includes(event.key) && list.length) {
+ event.preventDefault();
+ setActive((previous) =>
+ event.key === "ArrowDown"
+ ? (previous + 1) % list.length
+ : previous <= 0
+ ? list.length - 1
+ : previous - 1
+ );
+ }
+ if (event.key === "Enter" && open) {
+ event.preventDefault();
+ if (active >= 0 && list[active]) choose(list[active]);
+ }
+ }}
+ />
+
+ {selected?.memberId && (
+
Linked to Member Directory
+ )}
+ {open && (
+
+
+ {list.map((member, index) => (
+
+ event.preventDefault()}
+ onClick={() => choose(member)}
+ className={`rounded-4 hover:bg-panel flex w-full items-center gap-8 px-8 py-8 text-left ${index === active ? "bg-panel" : ""}`}
+ >
+
+
+ {member.name}
+ {member.role}
+
+
+
+ ))}
+
+ {!list.length && (
+
+ {found.query !== query
+ ? "Searching members…"
+ : found.error || "No shared member profiles found."}
+
+ )}
+
+ )}
+
+ );
+}
+
+export function PartnerPicker({
+ id,
+ name,
+ selectedId,
+ onChange,
+ error,
+}: {
+ id: string;
+ name: string;
+ selectedId: string | null;
+ onChange: (partner: PartnerReference) => void;
+ error?: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const [active, setActive] = useState(-1);
+ const [result, setResult] = useState<{
+ q: string;
+ partners: PartnerReference[];
+ available: boolean;
+ }>({ q: "", partners: [], available: true });
+ useEffect(() => {
+ if (!open || !name.trim()) return;
+ const controller = new AbortController();
+ const timer = setTimeout(() => {
+ partnerReferences(name.trim(), controller.signal).then(
+ (data) => {
+ if (!controller.signal.aborted) setResult({ q: name, ...data });
+ },
+ () => {
+ if (!controller.signal.aborted)
+ setResult({ q: name, partners: [], available: false });
+ }
+ );
+ }, 250);
+ return () => {
+ clearTimeout(timer);
+ controller.abort();
+ };
+ }, [name, open]);
+ const list = result.q === name ? result.partners : [];
+ function choose(partner: PartnerReference) {
+ onChange(partner);
+ setOpen(false);
+ setActive(-1);
+ }
+ return (
+
+
= 0 ? `${id}-option-${active}` : undefined
+ }
+ aria-invalid={Boolean(error)}
+ aria-required={true}
+ aria-describedby={error ? `${id}-error` : undefined}
+ value={name}
+ maxLength={200}
+ placeholder="Search partners or enter a new name"
+ onFocus={() => setOpen(true)}
+ onBlur={() => setOpen(false)}
+ onChange={(event) => {
+ onChange({ id: "", name: event.target.value, photo: null });
+ setOpen(true);
+ setActive(-1);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "Escape") {
+ setOpen(false);
+ setActive(-1);
+ }
+ if (["ArrowDown", "ArrowUp"].includes(event.key) && list.length) {
+ event.preventDefault();
+ setActive((previous) =>
+ event.key === "ArrowDown"
+ ? (previous + 1) % list.length
+ : previous <= 0
+ ? list.length - 1
+ : previous - 1
+ );
+ }
+ if (event.key === "Enter" && open) {
+ event.preventDefault();
+ if (active >= 0 && list[active]) choose(list[active]);
+ else setOpen(false);
+ }
+ }}
+ />
+
+ {selectedId
+ ? "Linked to Partner Directory"
+ : "Free-text partner name; choose a result to link a directory record."}
+
+ {open && name.trim() && (
+
+
+ {list.map((partner, index) => (
+
+ event.preventDefault()}
+ onClick={() => choose(partner)}
+ className={`rounded-4 hover:bg-panel w-full px-12 py-10 text-left ${index === active ? "bg-panel" : ""}`}
+ >
+ {partner.name}
+
+
+ ))}
+
+
+ {result.q !== name
+ ? "Searching Partner Directory…"
+ : !result.available
+ ? "Partner Directory unavailable. You can save this name as free text."
+ : !list.length
+ ? "No matching partner. You can save this name as free text."
+ : "Choose a partner, or keep your typed name."}
+
+
+ )}
+
+ );
+}
diff --git a/src/components/projects/useProjectDraft.ts b/src/components/projects/useProjectDraft.ts
new file mode 100644
index 0000000..4764b99
--- /dev/null
+++ b/src/components/projects/useProjectDraft.ts
@@ -0,0 +1,143 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { DraftQueue } from "@/lib/projects/draft-queue";
+import { projectClient, ProjectRequestError } from "@/lib/projects/client";
+import {
+ autosaveValue,
+ formErrors,
+ formPayload,
+ type ProjectFormValue,
+} from "@/lib/projects/form";
+import type { ProjectPatch } from "@/lib/projects/validation";
+
+export function useProjectDraft(
+ value: ProjectFormValue,
+ initialId: string | null,
+ disabled: boolean
+) {
+ const [queue] = useState(() => new DraftQueue(initialId, projectClient.save));
+ const key = JSON.stringify(formPayload(autosaveValue(value)));
+ const invalid = Object.keys(formErrors(autosaveValue(value))).length > 0;
+ const [ack, setAck] = useState({
+ key,
+ id: initialId,
+ savedAt: null as number | null,
+ });
+ const [pending, setPending] = useState(0);
+ const [error, setError] = useState(null);
+ const [now, setNow] = useState(Date.now);
+ const suspended = useRef(false);
+ const mounted = useRef(true);
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ };
+ }, []);
+ const dirty = ack.key !== key;
+ const blocked =
+ error instanceof ProjectRequestError &&
+ [401, 403, 404].includes(error.status);
+ const recordId = useCallback((id: string) => {
+ if (!mounted.current) return;
+ setAck((previous) => ({ ...previous, id }));
+ if (window.location.pathname === "/projects/new")
+ window.history.replaceState(
+ null,
+ "",
+ `/projects/${encodeURIComponent(id)}/edit`
+ );
+ }, []);
+ const persist = useCallback(
+ async (fields: ProjectPatch, snapshotKey: string) => {
+ setPending((n) => n + 1);
+ setError(null);
+ try {
+ const saved = await queue.save(fields);
+ if (mounted.current) {
+ setError(null);
+ setAck({ id: saved.id, key: snapshotKey, savedAt: Date.now() });
+ }
+ recordId(saved.id);
+ return saved;
+ } catch (failure) {
+ if (mounted.current)
+ setError(
+ failure instanceof Error
+ ? failure
+ : new Error("Draft could not be saved.")
+ );
+ throw failure;
+ } finally {
+ if (mounted.current) setPending((n) => n - 1);
+ }
+ },
+ [queue, recordId]
+ );
+ useEffect(() => {
+ if (disabled || blocked || suspended.current || !dirty || invalid) return;
+ const timer = setTimeout(() => {
+ if (!suspended.current)
+ void persist(JSON.parse(key), key).catch(() => undefined);
+ }, 750);
+ return () => clearTimeout(timer);
+ }, [key, disabled, dirty, invalid, blocked, persist]);
+ useEffect(() => {
+ if (!ack.savedAt) return;
+ const timer = setInterval(() => setNow(Date.now()), 30000);
+ return () => clearInterval(timer);
+ }, [ack.savedAt]);
+ useEffect(() => {
+ if (!dirty) return;
+ const warn = (event: BeforeUnloadEvent) => {
+ event.preventDefault();
+ };
+ window.addEventListener("beforeunload", warn);
+ return () => window.removeEventListener("beforeunload", warn);
+ }, [dirty]);
+ const minutes = ack.savedAt
+ ? Math.max(0, Math.floor((now - ack.savedAt) / 60000))
+ : 0;
+ const status = blocked
+ ? "Access changed · Unsaved changes were not saved. Reload to refresh your access."
+ : pending
+ ? "Saving draft…"
+ : dirty && invalid
+ ? "Autosave paused · Check incomplete or invalid fields"
+ : error
+ ? "Draft not saved · Retry Save Draft"
+ : dirty
+ ? "Unsaved changes"
+ : ack.savedAt
+ ? `Draft saved · ${minutes ? `${minutes} min ago` : "Just now"}`
+ : initialId
+ ? "Draft loaded"
+ : "Start typing to save a draft";
+ return {
+ isActive: () => mounted.current,
+ id: ack.id,
+ status,
+ blocked,
+ waitForSaves: () => queue.wait(),
+ error,
+ dirty,
+ suspend: () => {
+ suspended.current = true;
+ },
+ resume: () => {
+ suspended.current = false;
+ },
+ save: () => persist(formPayload(autosaveValue(value)), key),
+ publish: () => queue.run(projectClient.publish),
+ ensureId: async () => {
+ const id = await queue.ensureId({
+ name: value.name,
+ chapterId: value.chapterId,
+ stage: value.stage,
+ });
+ recordId(id);
+ return id;
+ },
+ };
+}
diff --git a/src/lib/auth/guards.ts b/src/lib/auth/guards.ts
index f3484e6..d69fb02 100644
--- a/src/lib/auth/guards.ts
+++ b/src/lib/auth/guards.ts
@@ -1,6 +1,6 @@
import { headers } from "next/headers";
import { redirect } from "next/navigation";
-import { getCurrentSession } from "@/lib/auth/session";
+import { getSessionFromRequest, getCurrentSession } from "@/lib/auth/session";
import { hasRole } from "@/lib/auth/roles";
import type { AppRole } from "@/types";
@@ -49,8 +49,10 @@ export async function requireRole(allowed: readonly AppRole[]) {
* For server actions and route handlers, which can be called without rendering
* a page, so layout protection does not cover them. Throws instead of redirecting.
*/
-export async function assertSession() {
- const session = await getCurrentSession();
+export async function assertSession(request?: Request) {
+ const session = await (request
+ ? getSessionFromRequest(request)
+ : getCurrentSession());
if (!session) {
throw new Error("Unauthorized");
@@ -59,8 +61,11 @@ export async function assertSession() {
return session;
}
-export async function assertRole(allowed: readonly AppRole[]) {
- const session = await assertSession();
+export async function assertRole(
+ allowed: readonly AppRole[],
+ request?: Request
+) {
+ const session = await assertSession(request);
if (!hasRole(session.user.role, allowed)) {
throw new Error("Forbidden");
diff --git a/src/lib/notion/api.ts b/src/lib/notion/api.ts
index 16ab89d..204d2d5 100644
--- a/src/lib/notion/api.ts
+++ b/src/lib/notion/api.ts
@@ -1,3 +1,4 @@
+import { partnerFromNotion } from "@/lib/projects/partner-reference";
/* eslint-disable @typescript-eslint/no-explicit-any */
import { unstable_cache } from "next/cache";
import { flattenNotionPage } from "./flatten";
@@ -71,3 +72,14 @@ export const getVolunteers = createGetter(
VOLUNTEERS_DATA_SOURCE_ID,
"notion-volunteers"
);
+
+// Strict, minimal projection for the Partner Directory picker. Failures reach
+// the picker route so it can offer explicit free-text fallback.
+export const getPartnerReferences = unstable_cache(
+ async () => {
+ const pages = await fetchAllPages(PARTNERS_DATA_SOURCE_ID);
+ return pages.map(partnerFromNotion).filter((partner) => partner !== null);
+ },
+ ["notion-project-partner-references"],
+ { revalidate: 300 }
+);
diff --git a/src/lib/projects/api.int.test.ts b/src/lib/projects/api.int.test.ts
new file mode 100644
index 0000000..7d3490b
--- /dev/null
+++ b/src/lib/projects/api.int.test.ts
@@ -0,0 +1,1272 @@
+import { editorOptions } from "@/lib/projects/editor";
+import { listDraftProjects } from "@/lib/projects/service";
+import { GET as memberReferences } from "@/app/api/projects/references/members/route";
+import { randomUUID } from "node:crypto";
+import { mkdtemp, rm, stat } from "node:fs/promises";
+import path from "node:path";
+import { tmpdir } from "node:os";
+import { POST as uploadMedia } from "@/app/api/projects/[projectId]/media/route";
+import { GET as readMedia } from "@/app/api/projects/[projectId]/media/[file]/route";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { db } from "@/lib/db";
+import { SESSION_COOKIE } from "@/lib/auth/cookies";
+import { GET as list, POST as create } from "@/app/api/projects/route";
+import {
+ GET as read,
+ PATCH as patch,
+ DELETE as remove,
+} from "@/app/api/projects/[projectId]/route";
+import { POST as publish } from "@/app/api/projects/[projectId]/publish/route";
+import type { AppRole } from "@/types";
+
+const prefix = `ticket4-${randomUUID()}`;
+const own = `${prefix}-c1`,
+ other = `${prefix}-c2`;
+let fixtureSetupStarted = false;
+let uploadDirectory: string | undefined;
+const previousUploadDirectory = process.env.PROJECT_MEDIA_DIR;
+let visibleMemberId: string;
+let hiddenMemberId: string;
+const actors: Record = {};
+const context = (id: string) => ({
+ params: Promise.resolve({ projectId: id }),
+});
+function req(actor: string | null, method = "GET", body?: unknown, query = "") {
+ return new Request(`http://localhost/api/projects${query}`, {
+ method,
+ headers: {
+ ...(actor ? { cookie: `${SESSION_COOKIE}=${actors[actor].cookie}` } : {}),
+ "content-type": "application/json",
+ },
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
+ });
+}
+async function newDraft(actor = "lead", chapterId?: string) {
+ const response = await create(
+ req(actor, "POST", {
+ name: `${prefix}-${randomUUID()}`,
+ ...(chapterId ? { chapterId } : {}),
+ })
+ );
+ expect(response.status).toBe(201);
+ return response.json();
+}
+function complete(stage = "design") {
+ return {
+ name: "Community Project",
+ stage,
+ tagline: "Help our community",
+ nonprofitPartnerName: "Partner",
+ startDate: "2026-01-15",
+ problemStatement: "Manual administration",
+ goalStatement: "Reduce paperwork",
+ solutionDescription: "An accessible portal",
+ teamMembers: [{ userId: actors.member.id, role: "Developer" }],
+ resourceLinks: [{ type: "GitHub", url: "https://example.org/code" }],
+ };
+}
+
+beforeAll(async () => {
+ const url = new URL(process.env.DATABASE_URL!);
+ // Writes fixtures (cleaned up in afterAll by their own ids), so refuse
+ // anything but a local database.
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(url.hostname))
+ throw new Error("Project API tests need a local DATABASE_URL");
+ fixtureSetupStarted = true;
+ uploadDirectory = await mkdtemp(path.join(tmpdir(), "project-form-media-"));
+ process.env.PROJECT_MEDIA_DIR = uploadDirectory;
+ await db.chapter.createMany({
+ data: [
+ { id: own, name: `${prefix} One` },
+ { id: other, name: `${prefix} Two` },
+ ],
+ });
+ const fixtures: [string, AppRole, string | null][] = [
+ ["admin", "NATIONAL_ADMIN", null],
+ ["lead", "PROJECT_LEAD", own],
+ ["sameLead", "PROJECT_LEAD", own],
+ ["chapterLead", "CHAPTER_LEAD", own],
+ ["otherLead", "PROJECT_LEAD", other],
+ ["unassigned", "PROJECT_LEAD", null],
+ ["member", "MEMBER", own],
+ ["revokedLead", "PROJECT_LEAD", own],
+ ];
+ for (const [name, role, chapterId] of fixtures) {
+ const user = await db.user.create({
+ data: { email: `${prefix}-${name}@example.org`, role, chapterId },
+ });
+ const cookie = randomUUID();
+ await db.session.create({
+ data: {
+ id: cookie,
+ userId: user.id,
+ expiresAt: new Date(Date.now() + 3600000),
+ },
+ });
+ actors[name] = { id: user.id, cookie };
+ }
+ const visible = await db.member.create({
+ data: {
+ userId: actors.member.id,
+ chapterId: own,
+ displayName: `${prefix} Shared Developer`,
+ approvalStatus: "APPROVED",
+ },
+ });
+ await db.member.update({
+ where: { id: visible.id },
+ data: { directoryOptIn: true },
+ });
+ visibleMemberId = visible.id;
+ const hidden = await db.member.create({
+ data: {
+ userId: actors.sameLead.id,
+ chapterId: own,
+ displayName: `${prefix} Hidden Person`,
+ adminHidden: true,
+ },
+ });
+ hiddenMemberId = hidden.id;
+});
+afterAll(async () => {
+ if (!fixtureSetupStarted) {
+ await db.$disconnect();
+ return;
+ }
+ await db.project.deleteMany({ where: { chapterId: { in: [own, other] } } });
+ await db.member.deleteMany({
+ where: { userId: { in: Object.values(actors).map((actor) => actor.id) } },
+ });
+ await db.user.deleteMany({ where: { email: { startsWith: prefix } } });
+ await db.chapter.deleteMany({ where: { id: { in: [own, other] } } });
+ await db.$disconnect();
+ if (uploadDirectory)
+ await rm(uploadDirectory, { recursive: true, force: true });
+ if (previousUploadDirectory === undefined)
+ delete process.env.PROJECT_MEDIA_DIR;
+ else process.env.PROJECT_MEDIA_DIR = previousUploadDirectory;
+});
+
+describe("project write APIs with real sessions and PostgreSQL", () => {
+ it("returns 401 for every unauthenticated endpoint", async () => {
+ const id = "missing";
+ for (const response of await Promise.all([
+ list(req(null)),
+ create(req(null, "POST", { name: "No" })),
+ read(req(null), context(id)),
+ patch(req(null, "PATCH", {}), context(id)),
+ publish(req(null, "POST"), context(id)),
+ remove(req(null, "DELETE"), context(id)),
+ ]))
+ expect(response.status).toBe(401);
+ });
+ it("creates a minimal draft in the server-assigned chapter and prevents chapter spoofing", async () => {
+ const project = await newDraft();
+ expect(project).toMatchObject({
+ isDraft: true,
+ chapterId: own,
+ createdBy: actors.lead.id,
+ lastUpdated: null,
+ });
+ expect(
+ (
+ await create(
+ req("lead", "POST", { name: "Wrong chapter", chapter_id: other })
+ )
+ ).status
+ ).toBe(403);
+ expect(
+ (await create(req("unassigned", "POST", { name: "No chapter" }))).status
+ ).toBe(403);
+ expect(
+ (await create(req("member", "POST", { name: "Not allowed" }))).status
+ ).toBe(403);
+ expect(
+ (await create(req("admin", "POST", { name: "Needs a chapter" }))).status
+ ).toBe(400);
+ expect(
+ (
+ await create(
+ req("admin", "POST", { name: "Unknown", chapterId: "not-real" })
+ )
+ ).status
+ ).toBe(400);
+ expect((await newDraft("admin", other)).chapterId).toBe(other);
+ });
+ it("enforces every Section 14 operation at the endpoint boundary", async () => {
+ const project = await newDraft();
+ for (const [actor, editable] of [
+ ["lead", true],
+ ["sameLead", true],
+ ["chapterLead", true],
+ ["admin", true],
+ ["otherLead", false],
+ ["member", false],
+ ["unassigned", false],
+ ] as const) {
+ expect((await list(req(actor))).status).toBe(200);
+ expect((await read(req(actor), context(project.id))).status).toBe(
+ editable ? 200 : 404
+ );
+ expect(
+ (
+ await patch(
+ req(actor, "PATCH", { tagline: actor }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(editable ? 200 : 403);
+ expect(
+ (await publish(req(actor, "POST"), context(project.id))).status
+ ).toBe(editable ? 422 : 403);
+ if (actor !== "admin")
+ expect(
+ (await remove(req(actor, "DELETE"), context(project.id))).status
+ ).toBe(403);
+ }
+ // Visibility assertions target this fixture, not page 1 of unrelated seed
+ // data. Published rows sort ahead of new drafts with no lastUpdated value.
+ const draftQuery = `?include_drafts=true&q=${encodeURIComponent(project.name)}`;
+ const draftResponse = await list(
+ req("sameLead", "GET", undefined, draftQuery)
+ );
+ expect(draftResponse.headers.get("x-total-count")).toBe("1");
+ expect(
+ (await draftResponse.json()).map((p: { id: string }) => p.id)
+ ).toEqual([project.id]);
+ for (const actor of ["otherLead", "member"]) {
+ const response = await list(req(actor, "GET", undefined, draftQuery));
+ expect(response.headers.get("x-total-count")).toBe("0");
+ expect(await response.json()).toEqual([]);
+ }
+ expect(
+ (await remove(req("admin", "DELETE"), context(project.id))).status
+ ).toBe(204);
+ });
+ it.each(["design", "development", "launched", "maintenance"])(
+ "autosaves incomplete fields at %s and enforces required fields only on publish",
+ async (stage) => {
+ const project = await newDraft();
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { stage, name: "", teamMembers: [] }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(200);
+ const invalid = await publish(req("lead", "POST"), context(project.id));
+ expect(invalid.status).toBe(422);
+ expect((await invalid.json()).details.missingFields).toEqual(
+ expect.arrayContaining([
+ "name",
+ "tagline",
+ "nonprofitPartner",
+ "startDate",
+ "problemStatement",
+ "goalStatement",
+ "teamMembers",
+ ])
+ );
+ expect((await read(req("member"), context(project.id))).status).toBe(404);
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", complete(stage)),
+ context(project.id)
+ )
+ ).status
+ ).toBe(200);
+ const published = await publish(req("lead", "POST"), context(project.id));
+ expect(published.status).toBe(200);
+ const live = await published.json();
+ expect(live.isDraft).toBe(false);
+ expect(live.lastUpdated).not.toBeNull();
+ expect((await read(req("member"), context(project.id))).status).toBe(200);
+ expect(
+ (await (await list(req("member"))).json()).some(
+ (p: { id: string }) => p.id === project.id
+ )
+ ).toBe(true);
+ // An unchanged publish is idempotent, including its published timestamp.
+ expect(
+ (await (await publish(req("lead", "POST"), context(project.id))).json())
+ .lastUpdated
+ ).toBe(live.lastUpdated);
+ }
+ );
+ it("rejects moves and writes into other chapters while allowing admin reassignment", async () => {
+ const project = await newDraft();
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { chapterId: other }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(403);
+ expect(
+ (
+ await patch(
+ req("otherLead", "PATCH", { chapterId: other }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(403);
+ const reassigned = await patch(
+ req("admin", "PATCH", { chapterId: other }),
+ context(project.id)
+ );
+ expect(reassigned.status).toBe(200);
+ expect((await reassigned.json()).chapterId).toBe(other);
+ expect((await read(req("lead"), context(project.id))).status).toBe(404);
+ expect((await read(req("otherLead"), context(project.id))).status).toBe(
+ 200
+ );
+ });
+ it("reserves pending cross-chapter reassignment for National Admins", async () => {
+ const project = await newDraft();
+ await patch(req("lead", "PATCH", complete()), context(project.id));
+ await publish(req("lead", "POST"), context(project.id));
+ expect(
+ (
+ await patch(
+ req("admin", "PATCH", { chapterId: other }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(200);
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { chapterId: own }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(403);
+ expect(
+ (await publish(req("lead", "POST"), context(project.id))).status
+ ).toBe(403);
+ expect(
+ (
+ await read(
+ req("lead", "GET", undefined, "?draft=true"),
+ context(project.id)
+ )
+ ).status
+ ).toBe(404);
+ expect((await read(req("member"), context(project.id))).status).toBe(200);
+ expect(
+ (await publish(req("admin", "POST"), context(project.id))).status
+ ).toBe(200);
+ expect(
+ (await patch(req("lead", "PATCH", {}), context(project.id))).status
+ ).toBe(403);
+ expect(
+ (await patch(req("otherLead", "PATCH", {}), context(project.id))).status
+ ).toBe(200);
+ });
+ it("validates formats, references and merged timelines; rejects server-field tampering", async () => {
+ const project = await newDraft();
+ for (const body of [
+ { tagline: "x".repeat(181) },
+ { is_draft: false },
+ { createdBy: actors.admin.id },
+ { lastUpdated: "2026-01-01" },
+ { pendingChanges: {} },
+ { teamMembers: [{ userId: "missing", role: "Dev" }] },
+ { resourceLinks: [{ type: "GitHub", url: "javascript:alert(1)" }] },
+ { startDate: "2026-02-30" },
+ { chapterId: own, chapter_id: other },
+ ]) {
+ expect(
+ (await patch(req("lead", "PATCH", body), context(project.id))).status
+ ).toBe(400);
+ }
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { startDate: "2026-05-01" }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(200);
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { endDate: "2026-04-01" }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(400);
+ const badJson = new Request("http://localhost/api/projects", {
+ method: "POST",
+ headers: { cookie: `${SESSION_COOKIE}=${actors.lead.cookie}` },
+ body: "{",
+ });
+ expect((await create(badJson)).status).toBe(400);
+ expect(
+ (await patch(req("lead", "PATCH", {}), context("not-found"))).status
+ ).toBe(404);
+ });
+ it("keeps published data live until pending edits pass a full publish", async () => {
+ const project = await newDraft();
+ await patch(req("lead", "PATCH", complete()), context(project.id));
+ const original = await (
+ await publish(req("lead", "POST"), context(project.id))
+ ).json();
+ const saved = await (
+ await patch(
+ req("lead", "PATCH", {
+ stage: "development",
+ solutionDescription: null,
+ resourceLinks: [],
+ }),
+ context(project.id)
+ )
+ ).json();
+ expect(saved.hasUnpublishedChanges).toBe(true);
+ expect(saved.stage).toBe("development");
+ const publicView = await (
+ await read(req("member"), context(project.id))
+ ).json();
+ expect(publicView.stage).toBe("design");
+ expect(publicView).not.toHaveProperty("pendingChanges");
+ expect(publicView.lastUpdated).toBe(original.lastUpdated);
+ expect(
+ (
+ await read(
+ req("member", "GET", undefined, "?draft=true"),
+ context(project.id)
+ )
+ ).status
+ ).toBe(404);
+ expect(
+ (
+ await (
+ await read(
+ req("sameLead", "GET", undefined, "?draft=true"),
+ context(project.id)
+ )
+ ).json()
+ ).stage
+ ).toBe("development");
+ expect(
+ (await publish(req("lead", "POST"), context(project.id))).status
+ ).toBe(422);
+ await patch(
+ req("lead", "PATCH", {
+ solutionDescription: "Ready",
+ resourceLinks: [{ type: "Other", url: "https://example.org" }],
+ }),
+ context(project.id)
+ );
+ expect(
+ (await publish(req("lead", "POST"), context(project.id))).status
+ ).toBe(200);
+ expect(
+ (await (await read(req("member"), context(project.id))).json()).stage
+ ).toBe("development");
+ });
+ it("reads updated database roles and chapter assignments on existing sessions", async () => {
+ const project = await newDraft();
+ await db.user.update({
+ where: { id: actors.sameLead.id },
+ data: { role: "MEMBER" },
+ });
+ expect(
+ (await patch(req("sameLead", "PATCH", {}), context(project.id))).status
+ ).toBe(403);
+ await db.user.update({
+ where: { id: actors.sameLead.id },
+ data: { role: "PROJECT_LEAD", chapterId: other },
+ });
+ expect(
+ (await patch(req("sameLead", "PATCH", {}), context(project.id))).status
+ ).toBe(403);
+ await db.user.update({
+ where: { id: actors.sameLead.id },
+ data: { chapterId: own },
+ });
+ });
+ it("does not lose separate concurrent autosaves", async () => {
+ const project = await newDraft();
+ const responses = await Promise.all([
+ patch(
+ req("lead", "PATCH", { tagline: "Saved tagline" }),
+ context(project.id)
+ ),
+ patch(
+ req("lead", "PATCH", { goalStatement: "Saved goal" }),
+ context(project.id)
+ ),
+ ]);
+ expect(responses.map((r) => r.status)).toEqual([200, 200]);
+ expect(
+ await (await read(req("lead"), context(project.id))).json()
+ ).toMatchObject({ tagline: "Saved tagline", goalStatement: "Saved goal" });
+ });
+ it("deletes relationships atomically for a National Admin", async () => {
+ const project = await newDraft();
+ await patch(req("lead", "PATCH", complete()), context(project.id));
+ expect(
+ (await remove(req("admin", "DELETE"), context(project.id))).status
+ ).toBe(204);
+ expect(
+ await db.projectTeamMember.count({ where: { projectId: project.id } })
+ ).toBe(0);
+ expect(
+ await db.projectResourceLink.count({ where: { projectId: project.id } })
+ ).toBe(0);
+ });
+ it("uploads real media with scoped previews, private publication, range support and validation", async () => {
+ const project = await newDraft();
+ const png = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1cAAAAASUVORK5CYII=",
+ "base64"
+ );
+ const uploadRequest = (
+ actor: string | null,
+ data: Uint8Array = png,
+ type = "image/png"
+ ) => {
+ const body = new FormData();
+ body.set("file", new File([data as BlobPart], "demo.png", { type }));
+ return new Request("http://localhost/api/projects/media", {
+ method: "POST",
+ headers: actor
+ ? { cookie: `${SESSION_COOKIE}=${actors[actor].cookie}` }
+ : {},
+ body,
+ });
+ };
+ expect(
+ (await uploadMedia(uploadRequest(null), context(project.id))).status
+ ).toBe(401);
+ expect(
+ (await uploadMedia(uploadRequest("member"), context(project.id))).status
+ ).toBe(403);
+ expect(
+ (await uploadMedia(uploadRequest("otherLead"), context(project.id)))
+ .status
+ ).toBe(403);
+ expect(
+ (
+ await uploadMedia(
+ uploadRequest("lead", Buffer.from("fake")),
+ context(project.id)
+ )
+ ).status
+ ).toBe(400);
+ const oversized = uploadRequest("lead");
+ oversized.headers.set("content-length", String(22 * 1024 * 1024));
+ expect((await uploadMedia(oversized, context(project.id))).status).toBe(
+ 413
+ );
+ const uploaded = await uploadMedia(
+ uploadRequest("lead"),
+ context(project.id)
+ );
+ expect(uploaded.status).toBe(201);
+ const { url } = await uploaded.json();
+ const file = url.split("/").pop();
+ const mediaContext = {
+ params: Promise.resolve({ projectId: project.id, file }),
+ };
+ const preview = await readMedia(req("lead"), mediaContext);
+ expect(preview.status).toBe(200);
+ expect(preview.headers.get("content-type")).toBe("image/png");
+ expect(preview.headers.get("cache-control")).toBe("private, no-store");
+ expect(Buffer.from(await preview.arrayBuffer())).toEqual(png);
+ expect((await readMedia(req("member"), mediaContext)).status).toBe(404);
+ await patch(req("lead", "PATCH", complete()), context(project.id));
+ await publish(req("lead", "POST"), context(project.id));
+ // The upload is not published until its URL is explicitly saved and published.
+ expect((await readMedia(req("member"), mediaContext)).status).toBe(404);
+ await patch(
+ req("lead", "PATCH", { demoMedia: [url] }),
+ context(project.id)
+ );
+ expect((await readMedia(req("member"), mediaContext)).status).toBe(404);
+ await publish(req("lead", "POST"), context(project.id));
+ const publicMedia = await readMedia(req("member"), mediaContext);
+ expect(publicMedia.status).toBe(200);
+ await publicMedia.arrayBuffer();
+ const ranged = req("member");
+ ranged.headers.set("range", "bytes=0-7");
+ const response = await readMedia(ranged, mediaContext);
+ expect(response.status).toBe(206);
+ expect((await response.arrayBuffer()).byteLength).toBe(8);
+ const invalid = req("member");
+ invalid.headers.set("range", "bytes=10000-");
+ expect((await readMedia(invalid, mediaContext)).status).toBe(416);
+ });
+ it("uses canonical Member records while enforcing directory visibility for every role", async () => {
+ expect((await memberReferences(req(null))).status).toBe(401);
+ expect((await memberReferences(req("member"))).status).toBe(403);
+ for (const actor of ["lead", "admin"]) {
+ const result = await memberReferences(
+ req(actor, "GET", undefined, `?q=${prefix}`)
+ );
+ expect(result.status).toBe(200);
+ const json = await result.json();
+ expect(json.members).toHaveLength(1);
+ expect(json.members[0]).toMatchObject({
+ id: actors.member.id,
+ memberId: visibleMemberId,
+ name: `${prefix} Shared Developer`,
+ });
+ expect(JSON.stringify(json)).not.toContain("Hidden Person");
+ expect(JSON.stringify(json)).not.toContain("@example.org");
+ }
+ const project = await newDraft();
+ const row = {
+ userId: actors.member.id,
+ memberId: visibleMemberId,
+ role: "Developer",
+ };
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { teamMembers: [row] }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(200);
+ expect(
+ await db.projectTeamMember.findFirst({ where: { projectId: project.id } })
+ ).toMatchObject({ memberId: visibleMemberId });
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", {
+ teamMembers: [{ ...row, userId: actors.lead.id }],
+ }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(400);
+ const hidden = {
+ userId: actors.sameLead.id,
+ memberId: hiddenMemberId,
+ role: "Designer",
+ };
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { teamMembers: [hidden] }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(400);
+ expect(
+ (
+ await patch(
+ req("admin", "PATCH", { teamMembers: [hidden] }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(200);
+ // Existing hidden references can be retained, but their names stay private.
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { teamMembers: [hidden] }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(200);
+ const options = await editorOptions(
+ { id: actors.lead.id, role: "PROJECT_LEAD", chapterId: own },
+ [actors.sameLead.id]
+ );
+ expect(
+ options.members.find((member) => member.id === actors.sameLead.id)?.name
+ ).toBe("Member record unavailable");
+ });
+ it("keeps drafts off the default list and provides chapter-scoped resume lists", async () => {
+ const project = await newDraft();
+ for (const actor of ["lead", "admin", "member"]) {
+ const records = await (
+ await list(
+ req(actor, "GET", undefined, `?q=${encodeURIComponent(project.name)}`)
+ )
+ ).json();
+ expect(records.some((row: { id: string }) => row.id === project.id)).toBe(
+ false
+ );
+ }
+ expect(
+ (
+ await listDraftProjects({
+ id: actors.lead.id,
+ role: "PROJECT_LEAD",
+ chapterId: own,
+ })
+ ).some((row) => row.id === project.id)
+ ).toBe(true);
+ expect(
+ (
+ await listDraftProjects({
+ id: actors.otherLead.id,
+ role: "PROJECT_LEAD",
+ chapterId: other,
+ })
+ ).some((row) => row.id === project.id)
+ ).toBe(false);
+ });
+ it("protects partner photos until their revision is published", async () => {
+ const project = await newDraft();
+ await patch(req("lead", "PATCH", complete()), context(project.id));
+ await publish(req("lead", "POST"), context(project.id));
+ const body = new FormData();
+ body.set(
+ "file",
+ new File(
+ [Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10])],
+ "logo.png",
+ { type: "image/png" }
+ )
+ );
+ const upload = new Request(
+ "http://localhost/api/projects/media?purpose=partner-photo",
+ {
+ method: "POST",
+ headers: { cookie: `${SESSION_COOKIE}=${actors.lead.cookie}` },
+ body,
+ }
+ );
+ const uploaded = await uploadMedia(upload, context(project.id));
+ expect(uploaded.status).toBe(201);
+ const { url } = await uploaded.json();
+ const fileContext = {
+ params: Promise.resolve({
+ projectId: project.id,
+ file: url.split("/").pop(),
+ }),
+ };
+ await patch(
+ req("lead", "PATCH", { nonprofitPartnerPhoto: url }),
+ context(project.id)
+ );
+ expect((await readMedia(req("member"), fileContext)).status).toBe(404);
+ await publish(req("lead", "POST"), context(project.id));
+ const photo = await readMedia(req("member"), fileContext);
+ expect(photo.status).toBe(200);
+ await photo.arrayBuffer();
+ });
+});
+
+describe("Ticket 7 security audit", () => {
+ it.each(["lead", "chapterLead"])(
+ "blocks every foreign-chapter write by %s",
+ async (actor) => {
+ for (const published of [false, true]) {
+ const project = await newDraft("otherLead");
+ if (published) {
+ await patch(
+ req("otherLead", "PATCH", complete()),
+ context(project.id)
+ );
+ expect(
+ (await publish(req("otherLead", "POST"), context(project.id)))
+ .status
+ ).toBe(200);
+ }
+ const before = await db.project.findUniqueOrThrow({
+ where: { id: project.id },
+ });
+ const responses = [
+ await create(req(actor, "POST", { name: "Spoof", chapterId: other })),
+ await patch(
+ req(actor, "PATCH", { name: "Stolen", chapterId: own }),
+ context(project.id)
+ ),
+ await publish(req(actor, "POST"), context(project.id)),
+ await remove(req(actor, "DELETE"), context(project.id)),
+ ];
+ for (const purpose of ["demo", "partner-photo"]) {
+ const form = new FormData();
+ form.set(
+ "file",
+ new File(["invalid"], "image.png", { type: "image/png" })
+ );
+ responses.push(
+ await uploadMedia(
+ new Request(
+ `http://localhost/api/projects/media?purpose=${purpose}`,
+ {
+ method: "POST",
+ headers: {
+ cookie: `${SESSION_COOKIE}=${actors[actor].cookie}`,
+ },
+ body: form,
+ }
+ ),
+ context(project.id)
+ )
+ );
+ }
+ expect(responses.map((r) => r.status)).toEqual([
+ 403, 403, 403, 403, 403, 403,
+ ]);
+ expect(
+ await db.project.findUniqueOrThrow({ where: { id: project.id } })
+ ).toEqual(before);
+ expect((await read(req(actor), context(project.id))).status).toBe(
+ published ? 200 : 404
+ );
+ await expect(
+ stat(path.join(uploadDirectory!, project.id))
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ }
+ }
+ );
+ it("revokes existing-session write access immediately without removing projects", async () => {
+ const project = await newDraft("revokedLead");
+ await db.user.update({
+ where: { id: actors.revokedLead.id },
+ data: { role: "MEMBER" },
+ });
+ const responses = await Promise.all([
+ create(req("revokedLead", "POST", { name: "No" })),
+ patch(req("revokedLead", "PATCH", { name: "No" }), context(project.id)),
+ publish(req("revokedLead", "POST"), context(project.id)),
+ remove(req("revokedLead", "DELETE"), context(project.id)),
+ ]);
+ expect(responses.map((r) => r.status)).toEqual([403, 403, 403, 403]);
+ expect((await read(req("revokedLead"), context(project.id))).status).toBe(
+ 404
+ );
+ expect((await read(req("admin"), context(project.id))).status).toBe(200);
+ });
+ it("rejects cross-origin writes before any side effects", async () => {
+ const project = await newDraft();
+ const evil = (method: string, body?: unknown) => {
+ const request = req("admin", method, body);
+ request.headers.set("origin", "https://untrusted.example");
+ return request;
+ };
+ expect(
+ (await create(evil("POST", { name: "No", chapterId: own }))).status
+ ).toBe(403);
+ expect(
+ (await patch(evil("PATCH", { name: "No" }), context(project.id))).status
+ ).toBe(403);
+ expect((await publish(evil("POST"), context(project.id))).status).toBe(403);
+ expect((await remove(evil("DELETE"), context(project.id))).status).toBe(
+ 403
+ );
+ expect((await read(req("lead"), context(project.id))).status).toBe(200);
+ });
+ it("removes private files and handles repeated deletion without resurrection", async () => {
+ const project = await newDraft();
+ const { mkdir, writeFile } = await import("node:fs/promises");
+ const directory = path.join(uploadDirectory!, project.id);
+ await mkdir(directory, { recursive: true });
+ await writeFile(path.join(directory, "private.png"), "private");
+ expect(
+ (await remove(req("admin", "DELETE"), context(project.id))).status
+ ).toBe(204);
+ await expect(stat(directory)).rejects.toMatchObject({ code: "ENOENT" });
+ expect(
+ (await remove(req("admin", "DELETE"), context(project.id))).status
+ ).toBe(404);
+ expect(
+ (
+ await patch(
+ req("lead", "PATCH", { name: "Resurrect" }),
+ context(project.id)
+ )
+ ).status
+ ).toBe(404);
+ });
+ it("sorts public results before applying the limit and excludes drafts", async () => {
+ const ids: string[] = [];
+ for (const [name, startDate, lastUpdated] of [
+ ["Zulu", null, "2026-03-01"],
+ ["Alpha", "2026-01-01", "2026-02-01"],
+ ["Beta", "2025-01-01", "2026-01-01"],
+ ] as const) {
+ const p = await db.project.create({
+ data: {
+ name,
+ chapterId: other,
+ createdBy: actors.admin.id,
+ isDraft: false,
+ startDate: startDate ? new Date(startDate) : null,
+ lastUpdated: new Date(lastUpdated),
+ },
+ });
+ ids.push(p.id);
+ }
+ for (const [sort, expected] of [
+ ["name", [ids[1], ids[2], ids[0]]],
+ ["year", [ids[1], ids[2], ids[0]]],
+ ["last_updated", ids],
+ ] as const) {
+ const response = await list(
+ req("member", "GET", undefined, `?chapter_id=${other}&sort=${sort}`)
+ );
+ expect(response.status).toBe(200);
+ const items = await response.json();
+ expect(
+ items
+ .filter((p: { id: string }) => ids.includes(p.id))
+ .map((p: { id: string }) => p.id)
+ ).toEqual(expected);
+ expect(items.every((p: { isDraft: boolean }) => !p.isDraft)).toBe(true);
+ }
+ expect(
+ (await list(req("member", "GET", undefined, "?sort=unsafe"))).status
+ ).toBe(400);
+ });
+});
+
+describe("upload authorization races", () => {
+ it.each(["chapter", "role"])(
+ "rechecks %s access after receiving a slow upload",
+ async (change) => {
+ await db.user.update({
+ where: { id: actors.revokedLead.id },
+ data: { role: "PROJECT_LEAD", chapterId: own },
+ });
+ const project = await newDraft("revokedLead");
+ const form = new FormData();
+ form.set(
+ "file",
+ new File(
+ [
+ Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1cAAAAASUVORK5CYII=",
+ "base64"
+ ),
+ ],
+ "demo.png",
+ { type: "image/png" }
+ )
+ );
+ const encoded = new Request("http://localhost", {
+ method: "POST",
+ body: form,
+ });
+ const bytes = new Uint8Array(await encoded.arrayBuffer());
+ let began!: () => void;
+ let release!: () => void;
+ const reading = new Promise((resolve) => {
+ began = resolve;
+ });
+ const gate = new Promise((resolve) => {
+ release = resolve;
+ });
+ const body = new ReadableStream(
+ {
+ async pull(controller) {
+ began();
+ await gate;
+ controller.enqueue(bytes);
+ controller.close();
+ },
+ },
+ { highWaterMark: 0 }
+ );
+ const request = new Request("http://localhost/api/projects/media", {
+ method: "POST",
+ headers: {
+ cookie: `${SESSION_COOKIE}=${actors.revokedLead.cookie}`,
+ "content-type": encoded.headers.get("content-type")!,
+ },
+ body,
+ duplex: "half",
+ } as RequestInit);
+ const result = uploadMedia(request, context(project.id));
+ await reading;
+ try {
+ if (change === "chapter")
+ await db.project.update({
+ where: { id: project.id },
+ data: { chapterId: other },
+ });
+ else
+ await db.user.update({
+ where: { id: actors.revokedLead.id },
+ data: { role: "MEMBER" },
+ });
+ } finally {
+ release();
+ }
+ expect((await result).status).toBe(403);
+ await expect(
+ stat(path.join(uploadDirectory!, project.id))
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ }
+ );
+});
+
+describe("Ticket 8 combined filtering, pagination and privacy", () => {
+ const marker = `${prefix}-browse`;
+ const fixtures: Record = {};
+ beforeAll(async () => {
+ const base = {
+ chapterId: own,
+ createdBy: actors.admin.id,
+ isDraft: false,
+ stage: "development" as const,
+ causeAreas: ["Education"],
+ startDate: new Date("2026-01-01"),
+ endDate: new Date("2026-04-01"),
+ tagline: "Community tool",
+ nonprofitPartnerName: "Local Partner",
+ };
+ const variants = [
+ { key: "match", data: {} },
+ { key: "chapter", data: { chapterId: other } },
+ { key: "stage", data: { stage: "design" as const } },
+ { key: "length", data: { endDate: new Date("2027-04-01") } },
+ { key: "impact", data: { causeAreas: ["Health"] } },
+ { key: "draft", data: { isDraft: true } },
+ {
+ key: "pending",
+ data: {
+ stage: "design" as const,
+ pendingChanges: {
+ stage: "development",
+ name: `${marker} Secret revision`,
+ causeAreas: ["Secret impact"],
+ },
+ },
+ },
+ ];
+ for (const variant of variants) {
+ const row = await db.project.create({
+ data: { ...base, name: `${marker} ${variant.key}`, ...variant.data },
+ });
+ fixtures[variant.key] = row.id;
+ }
+ });
+ const browse = (actor = "member", params: Record = {}) =>
+ list(
+ req(
+ actor,
+ "GET",
+ undefined,
+ `?${new URLSearchParams({ q: marker, page_size: "100", ...params })}`
+ )
+ );
+ it("ANDs chapter, stage, length, impact and search, with exact total counts", async () => {
+ const filters = {
+ chapter_id: own,
+ stage: "development",
+ project_length: "short",
+ impact_area: "Education",
+ };
+ const expected: Record = {
+ chapter_id: ["match", "stage", "length", "impact", "pending"],
+ stage: ["match", "chapter", "length", "impact"],
+ project_length: ["match", "chapter", "stage", "impact", "pending"],
+ impact_area: ["match", "chapter", "stage", "length", "pending"],
+ };
+ for (const [key, value] of Object.entries(filters)) {
+ const response = await browse("member", { [key]: value });
+ expect(
+ (await response.json()).map((p: { id: string }) => p.id).sort()
+ ).toEqual(expected[key].map((k) => fixtures[k]).sort());
+ }
+ const response = await browse("member", filters);
+ expect(response.headers.get("x-total-count")).toBe("1");
+ expect((await response.json()).map((p: { id: string }) => p.id)).toEqual([
+ fixtures.match,
+ ]);
+ const empty = await browse("member", {
+ ...filters,
+ impact_area: "No such area",
+ });
+ expect(empty.headers.get("x-total-count")).toBe("0");
+ expect(await empty.json()).toEqual([]);
+ });
+ it("never exposes draft fields through search, filters or default lists for any role", async () => {
+ for (const actor of ["member", "lead", "chapterLead", "admin"]) {
+ const rows = await (await browse(actor)).json();
+ expect(rows.some((p: { id: string }) => p.id === fixtures.draft)).toBe(
+ false
+ );
+ expect(
+ rows.every(
+ (p: { pendingChanges?: unknown }) => !("pendingChanges" in p)
+ )
+ ).toBe(true);
+ expect(
+ await (await browse(actor, { q: `${marker} Secret revision` })).json()
+ ).toEqual([]);
+ expect(
+ await (await browse(actor, { impact_area: "Secret impact" })).json()
+ ).toEqual([]);
+ }
+ expect(
+ (await (await browse("lead", { include_drafts: "true" })).json()).some(
+ (p: { id: string }) => p.id === fixtures.draft
+ )
+ ).toBe(true);
+ expect(
+ (
+ await (await browse("otherLead", { include_drafts: "true" })).json()
+ ).some((p: { id: string }) => p.id === fixtures.draft)
+ ).toBe(false);
+ expect(
+ (await (await browse("member", { include_drafts: "true" })).json()).some(
+ (p: { id: string }) => p.id === fixtures.draft
+ )
+ ).toBe(false);
+ });
+ it("searches chapter names case-insensitively and searches partner/tagline without leaking pending values", async () => {
+ const chapterSearch = await list(
+ req(
+ "member",
+ "GET",
+ undefined,
+ `?q=${encodeURIComponent(`${prefix} ONE`.toUpperCase())}&page_size=100`
+ )
+ );
+ expect(
+ (await chapterSearch.json()).every(
+ (p: { chapterId: string }) => p.chapterId === own
+ )
+ ).toBe(true);
+ const byPartner = await browse("member", {
+ q: "Local Partner",
+ chapter_id: own,
+ });
+ expect(
+ (await byPartner.json()).some(
+ (p: { id: string }) => p.id === fixtures.match
+ )
+ ).toBe(true);
+ const byTagline = await browse("member", {
+ q: "community TOOL",
+ chapter_id: own,
+ });
+ expect(
+ (await byTagline.json()).some(
+ (p: { id: string }) => p.id === fixtures.match
+ )
+ ).toBe(true);
+ });
+ it("paginates without duplicates, retains totals, and clamps stale page numbers", async () => {
+ const all = await (await browse("member", { sort: "name" })).json();
+ const seen: string[] = [];
+ for (let page = 1; page <= 3; page++) {
+ const response = await browse("member", {
+ sort: "name",
+ page: String(page),
+ page_size: "2",
+ });
+ expect(response.headers.get("x-total-count")).toBe("6");
+ expect(response.headers.get("x-total-pages")).toBe("3");
+ seen.push(...(await response.json()).map((p: { id: string }) => p.id));
+ }
+ expect(seen).toEqual(all.map((p: { id: string }) => p.id));
+ expect(new Set(seen).size).toBe(6);
+ const stale = await browse("member", { page: "999", page_size: "2" });
+ expect(stale.headers.get("x-page")).toBe("3");
+ });
+ it("defines exact length boundaries and excludes missing dates from known lengths", async () => {
+ const lengthMarker = `${prefix}-length`;
+ const start = new Date("2026-01-01");
+ for (const days of [0, 180, 181, 365, 366, null])
+ await db.project.create({
+ data: {
+ name: `${lengthMarker} ${days}`,
+ chapterId: own,
+ createdBy: actors.admin.id,
+ isDraft: false,
+ startDate: start,
+ endDate:
+ days === null ? null : new Date(start.getTime() + days * 86400000),
+ },
+ });
+ for (const [length, names] of [
+ ["short", [0, 180]],
+ ["medium", [181, 365]],
+ ["long", [366]],
+ ["unknown", [null]],
+ ] as const) {
+ const rows = await (
+ await browse("member", { q: lengthMarker, project_length: length })
+ ).json();
+ expect(rows.map((p: { name: string }) => p.name).sort()).toEqual(
+ names.map((n) => `${lengthMarker} ${n}`).sort()
+ );
+ }
+ });
+ it.each([
+ "stage=draft",
+ "project_length=forever",
+ "page=0",
+ "page=-1",
+ "page=1.5",
+ "page=NaN",
+ "page_size=0",
+ "page_size=101",
+ "page_size=2.5",
+ `q=${"x".repeat(201)}`,
+ `impact_area=${"x".repeat(101)}`,
+ ])("rejects invalid query %s", async (query) => {
+ expect(
+ (await list(req("member", "GET", undefined, `?${query}`))).status
+ ).toBe(400);
+ });
+ it.each(["null", "[]", "{broken"])(
+ "rejects malformed create payload %s",
+ async (body) => {
+ const response = await create(
+ new Request("http://localhost/api/projects", {
+ method: "POST",
+ headers: {
+ cookie: `${SESSION_COOKIE}=${actors.lead.cookie}`,
+ "content-type": "application/json",
+ },
+ body,
+ })
+ );
+ expect(response.status).toBe(400);
+ }
+ );
+});
+
+describe("authorized draft pagination regression", () => {
+ it("keeps a readable draft on its later page when published records fill page one", async () => {
+ const name = `${prefix}-draft-pagination`;
+ await db.project.createMany({
+ data: Array.from({ length: 12 }, (_, index) => ({
+ name: `${name} published ${index}`,
+ chapterId: own,
+ createdBy: actors.admin.id,
+ isDraft: false,
+ lastUpdated: new Date("2026-01-01"),
+ })),
+ });
+ const draft = await create(req("lead", "POST", { name: `${name} draft` }));
+ expect(draft.status).toBe(201);
+ const { id } = await draft.json();
+ const query = `?include_drafts=true&q=${encodeURIComponent(name)}`;
+ const first = await list(req("sameLead", "GET", undefined, query));
+ expect(first.headers.get("x-total-count")).toBe("13");
+ expect(first.headers.get("x-total-pages")).toBe("2");
+ const firstPage = await first.json();
+ expect(firstPage).toHaveLength(12);
+ expect(firstPage.some((p: { id: string }) => p.id === id)).toBe(false);
+ const second = await list(
+ req("sameLead", "GET", undefined, `${query}&page=2`)
+ );
+ expect((await second.json()).map((p: { id: string }) => p.id)).toEqual([
+ id,
+ ]);
+ const member = await list(
+ req("member", "GET", undefined, `${query}&page=2`)
+ );
+ expect(member.headers.get("x-total-count")).toBe("12");
+ expect(
+ (await member.json()).every((p: { isDraft: boolean }) => !p.isDraft)
+ ).toBe(true);
+ });
+});
diff --git a/src/lib/projects/browse.test.ts b/src/lib/projects/browse.test.ts
new file mode 100644
index 0000000..182135c
--- /dev/null
+++ b/src/lib/projects/browse.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, it } from "vitest";
+import { projectListQuery, projectsUrl } from "./sort";
+
+describe("shareable project filter URLs", () => {
+ it("removes one chip while preserving other filters and sort", () => {
+ const query = projectListQuery.parse({
+ q: "Food & care",
+ chapter_id: "cornell",
+ stage: "development",
+ impact_area: "Health",
+ project_length: "short",
+ sort: "name",
+ page: 3,
+ });
+ const url = projectsUrl({ ...query, stage: undefined, page: 1 });
+ const params = new URL(url, "http://localhost").searchParams;
+ expect(params.get("q")).toBe("Food & care");
+ expect(params.get("chapter_id")).toBe("cornell");
+ expect(params.get("sort")).toBe("name");
+ expect(params.has("stage")).toBe(false);
+ expect(params.has("page")).toBe(false);
+ expect(params.get("project_length")).toBe("short");
+ });
+ it("normalizes blank controls without treating blank numeric parameters as valid pages", () => {
+ expect(
+ projectListQuery.parse({
+ q: " ",
+ stage: "",
+ project_length: "",
+ chapter_id: "",
+ impact_area: "",
+ })
+ ).toEqual({ sort: "last_updated", page: 1, page_size: 12 });
+ expect(projectListQuery.safeParse({ page: "" }).success).toBe(false);
+ });
+});
diff --git a/src/lib/projects/client.ts b/src/lib/projects/client.ts
new file mode 100644
index 0000000..8465fa6
--- /dev/null
+++ b/src/lib/projects/client.ts
@@ -0,0 +1,81 @@
+import type { ProjectPatch } from "./validation";
+
+export class ProjectRequestError extends Error {
+ constructor(
+ message: string,
+ public status: number,
+ public details?: {
+ missingFields?: string[];
+ fieldErrors?: Record;
+ }
+ ) {
+ super(message);
+ }
+}
+export type ProjectSaveResult = ProjectPatch & {
+ id: string;
+ isDraft: boolean;
+ hasUnpublishedChanges?: boolean;
+};
+async function request(url: string, options: RequestInit): Promise {
+ const response = await fetch(url, {
+ credentials: "same-origin",
+ cache: "no-store",
+ ...options,
+ });
+ const data = await response.json().catch(() => ({}));
+ if (!response.ok)
+ throw new ProjectRequestError(
+ data.error || `Request failed (${response.status})`,
+ response.status,
+ data.details
+ );
+ return data;
+}
+export const projectClient = {
+ save: (id: string | null, fields: ProjectPatch) =>
+ request(
+ id ? `/api/projects/${encodeURIComponent(id)}` : "/api/projects",
+ {
+ method: id ? "PATCH" : "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(fields),
+ }
+ ),
+ publish: (id: string) =>
+ request(
+ `/api/projects/${encodeURIComponent(id)}/publish`,
+ { method: "POST" }
+ ),
+ remove: (id: string) =>
+ request(`/api/projects/${encodeURIComponent(id)}`, {
+ method: "DELETE",
+ }),
+ upload: (
+ id: string,
+ file: File,
+ purpose: "demo" | "partner-photo" = "demo"
+ ) => {
+ const body = new FormData();
+ body.set("file", file);
+ return request<{ url: string }>(
+ `/api/projects/${encodeURIComponent(id)}/media?purpose=${purpose}`,
+ { method: "POST", body }
+ );
+ },
+};
+
+export async function memberReferences(q: string, signal?: AbortSignal) {
+ return request<{ members: import("./references").MemberReference[] }>(
+ `/api/projects/references/members?q=${encodeURIComponent(q)}`,
+ { signal }
+ );
+}
+export async function partnerReferences(q: string, signal?: AbortSignal) {
+ return request<{
+ partners: import("./references").PartnerReference[];
+ available: boolean;
+ }>(`/api/projects/references/partners?q=${encodeURIComponent(q)}`, {
+ signal,
+ });
+}
diff --git a/src/lib/projects/draft-queue.test.ts b/src/lib/projects/draft-queue.test.ts
new file mode 100644
index 0000000..e71dfe8
--- /dev/null
+++ b/src/lib/projects/draft-queue.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it, vi } from "vitest";
+import { DraftQueue } from "./draft-queue";
+import type { ProjectPatch } from "./validation";
+
+describe("draft write serialization", () => {
+ it("creates once while typing during an in-flight request, then patches newer snapshots", async () => {
+ let release!: () => void;
+ const hold = new Promise((resolve) => {
+ release = resolve;
+ });
+ const write = vi.fn(async (id: string | null, fields: ProjectPatch) => {
+ if (!id) await hold;
+ return { ...fields, id: id || "draft-1", isDraft: true };
+ });
+ const queue = new DraftQueue(null, write);
+ const first = queue.save({ name: "First" });
+ const second = queue.save({ name: "Latest" });
+ await Promise.resolve();
+ expect(write).toHaveBeenCalledTimes(1);
+ release();
+ await Promise.all([first, second]);
+ expect(write.mock.calls.map(([id, fields]) => [id, fields.name])).toEqual([
+ [null, "First"],
+ ["draft-1", "Latest"],
+ ]);
+ });
+ it("uploads reuse a draft being created by autosave", async () => {
+ const write = vi.fn(async (id: string | null, fields: ProjectPatch) => ({
+ ...fields,
+ id: id || "draft",
+ isDraft: true,
+ }));
+ const queue = new DraftQueue(null, write);
+ await Promise.all([
+ queue.save({ name: "Draft" }),
+ queue.ensureId({ name: "Minimum" }),
+ ]);
+ expect(write).toHaveBeenCalledTimes(1);
+ });
+ it("copies queued data and publishes only after its final save", async () => {
+ const events: string[] = [];
+ const queue = new DraftQueue("draft", async (id, fields) => {
+ events.push(fields.name!);
+ return { ...fields, id: id!, isDraft: true };
+ });
+ const fields = { name: "Original" };
+ const saved = queue.save(fields);
+ fields.name = "Changed locally";
+ const published = queue.run(async () => {
+ events.push("publish");
+ });
+ await Promise.all([saved, published]);
+ expect(events).toEqual(["Original", "publish"]);
+ });
+ it("allows retry after a failed save without poisoning later operations", async () => {
+ const write = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("Offline"))
+ .mockResolvedValueOnce({ id: "draft", isDraft: true });
+ const queue = new DraftQueue(null, write);
+ await expect(queue.save({ name: "Draft" })).rejects.toThrow("Offline");
+ await expect(queue.save({ name: "Retry" })).resolves.toMatchObject({
+ id: "draft",
+ });
+ });
+});
diff --git a/src/lib/projects/draft-queue.ts b/src/lib/projects/draft-queue.ts
new file mode 100644
index 0000000..9dcf213
--- /dev/null
+++ b/src/lib/projects/draft-queue.ts
@@ -0,0 +1,43 @@
+import type { ProjectPatch } from "./validation";
+import type { ProjectSaveResult } from "./client";
+
+// All draft creation/writes are serialized, including manual saves and uploads.
+// A response acknowledges a snapshot; it never replaces newer editor input.
+export class DraftQueue {
+ private tail: Promise = Promise.resolve();
+ constructor(
+ public id: string | null,
+ private write: (
+ id: string | null,
+ fields: ProjectPatch
+ ) => Promise
+ ) {}
+ private enqueue(work: () => Promise): Promise {
+ const next = this.tail.then(work);
+ this.tail = next.catch(() => undefined);
+ return next;
+ }
+ save(fields: ProjectPatch) {
+ const snapshot = structuredClone(fields);
+ return this.enqueue(async () => {
+ const saved = await this.write(this.id, snapshot);
+ this.id = saved.id;
+ return saved;
+ });
+ }
+ ensureId(minimum: ProjectPatch) {
+ return this.enqueue(async () => {
+ if (!this.id) this.id = (await this.write(null, minimum)).id;
+ return this.id;
+ });
+ }
+ wait() {
+ return this.tail.then(() => undefined);
+ }
+ run(work: (id: string) => Promise) {
+ return this.enqueue(() => {
+ if (!this.id) throw new Error("Save this draft first.");
+ return work(this.id);
+ });
+ }
+}
diff --git a/src/lib/projects/edge-cases.test.ts b/src/lib/projects/edge-cases.test.ts
new file mode 100644
index 0000000..291bb85
--- /dev/null
+++ b/src/lib/projects/edge-cases.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from "vitest";
+import { projectUrl, projectThumbnail } from "./urls";
+import { patchSchema } from "./validation";
+import { projectListQuery } from "./sort";
+
+describe("archive edge-case input boundaries", () => {
+ it.each([
+ "javascript:alert(1)",
+ "data:text/html,",
+ "file:///etc/passwd",
+ "ftp://example.org/file",
+ "not-a-url",
+ ])("rejects unsafe or malformed resource link %s", (url) => {
+ expect(
+ patchSchema.safeParse({ resourceLinks: [{ type: "Other", url }] }).success
+ ).toBe(false);
+ expect(projectUrl(url)).toBeNull();
+ });
+ it("defines thumbnail fallbacks for missing, video-only and unsafe media", () => {
+ expect(projectThumbnail([], null)).toBeNull();
+ expect(projectThumbnail(["https://example.org/demo.mp4"], null)).toBeNull();
+ expect(
+ projectThumbnail(
+ ["javascript:bad.png", "https://example.org/demo.png"],
+ null
+ )
+ ).toBe("https://example.org/demo.png");
+ expect(
+ projectThumbnail([], "/api/projects/project/media/logo.png")
+ ).toContain("logo.png");
+ expect(projectThumbnail([], "javascript:alert(1)")).toBeNull();
+ });
+ it("accepts only whitelisted sort values and treats the empty chapter option as all chapters", () => {
+ expect(projectListQuery.parse({ chapter_id: "" })).toEqual({
+ sort: "last_updated",
+ page: 1,
+ page_size: 12,
+ });
+ expect(
+ projectListQuery.safeParse({ sort: "name; DROP TABLE projects" }).success
+ ).toBe(false);
+ for (const sort of ["name", "year", "last_updated"])
+ expect(projectListQuery.safeParse({ sort }).success).toBe(true);
+ });
+});
diff --git a/src/lib/projects/editor.ts b/src/lib/projects/editor.ts
new file mode 100644
index 0000000..8623c8c
--- /dev/null
+++ b/src/lib/projects/editor.ts
@@ -0,0 +1,27 @@
+import { searchMemberReferences, selectedMemberReferences } from "./references";
+import { db } from "@/lib/db";
+import { ADMIN_ROLES, hasRole } from "@/lib/auth/roles";
+import type { ProjectViewer } from "./permissions";
+
+export async function editorOptions(
+ viewer: ProjectViewer,
+ existingUserIds: string[] = []
+) {
+ const admin = hasRole(viewer.role, ADMIN_ROLES);
+ const [chapters, available, selected] = await Promise.all([
+ db.chapter.findMany({
+ where: admin ? {} : { id: viewer.chapterId ?? "" },
+ select: { id: true, name: true },
+ orderBy: { name: "asc" },
+ }),
+ searchMemberReferences(),
+ selectedMemberReferences(viewer, existingUserIds),
+ ]);
+ const members = [
+ ...selected,
+ ...available.filter(
+ (member) => !selected.some((item) => item.id === member.id)
+ ),
+ ];
+ return { chapters, members };
+}
diff --git a/src/lib/projects/form.test.ts b/src/lib/projects/form.test.ts
new file mode 100644
index 0000000..dc4669e
--- /dev/null
+++ b/src/lib/projects/form.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from "vitest";
+import { formValue, formPayload, formErrors } from "./form";
+import { stages } from "./validation";
+
+describe("project form payloads", () => {
+ it("round trips existing dates, team and links without server metadata", () => {
+ const value = formValue({
+ name: "Existing",
+ chapterId: "c1",
+ stage: "maintenance",
+ startDate: "2026-01-15T00:00:00.000Z",
+ teamMembers: [{ userId: "real-user", role: "Developer" }],
+ resourceLinks: [{ type: "GitHub", url: "https://example.org/repo" }],
+ });
+ expect(value.startDate).toBe("2026-01-15");
+ const payload = formPayload(value);
+ expect(payload.endDate).toBeNull();
+ expect(payload.teamMembers).toEqual([
+ { userId: "real-user", role: "Developer" },
+ ]);
+ expect(payload).not.toHaveProperty("isDraft");
+ expect(payload).not.toHaveProperty("id");
+ });
+ it.each(stages)(
+ "allows a partial %s draft with just name and chapter",
+ (stage) => {
+ expect(
+ formErrors(formValue({ name: "Partial", chapterId: "c1", stage }))
+ ).toEqual({});
+ }
+ );
+ it("reports invalid URLs on the exact resource row", () => {
+ expect(
+ formErrors(
+ formValue({
+ name: "Test",
+ chapterId: "c1",
+ resourceLinks: [{ type: "GitHub", url: "javascript:alert(1)" }],
+ })
+ )
+ ).toHaveProperty("resourceLinks.0.url");
+ });
+ it("requires the create minimum and validates the timeline", () => {
+ expect(formErrors(formValue())).toHaveProperty("name");
+ expect(formErrors(formValue())).toHaveProperty("chapterId");
+ expect(
+ formErrors(
+ formValue({
+ name: "Test",
+ chapterId: "c1",
+ startDate: "2026-05-01",
+ endDate: "2026-04-01",
+ })
+ )
+ ).toHaveProperty("endDate");
+ });
+});
+
+describe("autosave placeholders and section errors", () => {
+ it("omits empty UI rows without dropping partially typed team roles", async () => {
+ const { autosaveValue } = await import("./form");
+ const value = formValue({
+ name: "Draft",
+ chapterId: "c",
+ teamMembers: [
+ { userId: "", role: "" },
+ { userId: "", role: "Designer" },
+ ],
+ resourceLinks: [{ type: "GitHub", url: "" }],
+ });
+ expect(autosaveValue(value).teamMembers).toEqual([
+ { userId: "", role: "Designer" },
+ ]);
+ expect(autosaveValue(value).resourceLinks).toEqual([]);
+ expect(formErrors(autosaveValue(value))).toHaveProperty(
+ "teamMembers.0.userId"
+ );
+ });
+ it("routes server field errors to the corresponding form section", async () => {
+ const { errorSection } = await import("./form");
+ expect(errorSection("nonprofitPartner")).toBe(1);
+ expect(errorSection("startDate")).toBe(1);
+ expect(errorSection("goalStatement")).toBe(2);
+ expect(errorSection("teamMembers.0.role")).toBe(3);
+ expect(errorSection("solutionDescription")).toBe(4);
+ expect(errorSection("resourceLinks.0.url")).toBe(5);
+ });
+});
+
+it("keeps server and client errors on the correct visible rows after blank placeholders", async () => {
+ const { draftFieldPath, draftErrors } = await import("./form");
+ const value = formValue({
+ name: "Draft",
+ chapterId: "c",
+ teamMembers: [
+ { userId: "", role: "" },
+ { userId: "person", role: "" },
+ ],
+ resourceLinks: [
+ { type: "GitHub", url: "" },
+ { type: "Other", url: "not a URL" },
+ ],
+ });
+ expect(draftFieldPath(value, "teamMembers.0.role")).toBe(
+ "teamMembers.1.role"
+ );
+ expect(draftErrors(value)).toHaveProperty("resourceLinks.1.url");
+ expect(draftErrors(value)).not.toHaveProperty("resourceLinks.0.url");
+});
diff --git a/src/lib/projects/form.ts b/src/lib/projects/form.ts
new file mode 100644
index 0000000..086f7f1
--- /dev/null
+++ b/src/lib/projects/form.ts
@@ -0,0 +1,102 @@
+import type { ProjectPatch } from "./validation";
+import { patchSchema } from "./validation";
+
+export type ProjectFormValue = Required<
+ Omit
+> & {
+ teamMembers: { userId: string; memberId?: string | null; role: string }[];
+ resourceLinks: {
+ type: "Slack" | "GitHub" | "GoogleDrive" | "Other";
+ url: string;
+ }[];
+};
+export function formValue(project: ProjectPatch = {}): ProjectFormValue {
+ return {
+ name: project.name ?? "",
+ chapterId: project.chapterId ?? "",
+ stage: project.stage ?? "design",
+ tagline: project.tagline ?? "",
+ techStack: project.techStack ?? [],
+ causeAreas: project.causeAreas ?? [],
+ nonprofitPartnerId: project.nonprofitPartnerId ?? null,
+ nonprofitPartnerName: project.nonprofitPartnerName ?? "",
+ nonprofitPartnerPhoto: project.nonprofitPartnerPhoto ?? null,
+ startDate: project.startDate?.slice(0, 10) ?? "",
+ endDate: project.endDate?.slice(0, 10) ?? "",
+ problemStatement: project.problemStatement ?? "",
+ goalStatement: project.goalStatement ?? "",
+ solutionDescription: project.solutionDescription ?? "",
+ demoMedia: project.demoMedia ?? [],
+ teamMembers: project.teamMembers ?? [],
+ resourceLinks: project.resourceLinks ?? [],
+ };
+}
+export function formPayload(value: ProjectFormValue): ProjectPatch {
+ return {
+ ...value,
+ startDate: value.startDate || null,
+ endDate: value.endDate || null,
+ };
+}
+export function formErrors(value: ProjectFormValue): Record {
+ const errors: Record = {};
+ const parsed = patchSchema.safeParse(formPayload(value));
+ if (!parsed.success)
+ for (const issue of parsed.error.issues)
+ errors[issue.path.join(".")] ??= issue.message;
+ if (!value.name.trim()) errors.name = "Enter a project name to save a draft.";
+ if (!value.chapterId) errors.chapterId = "Select a permitted chapter.";
+ if (value.startDate && value.endDate && value.endDate < value.startDate)
+ errors.endDate = "End date must not precede start date.";
+ return errors;
+}
+
+// Completely blank UI rows are placeholders, not meaningful draft data.
+export function autosaveValue(value: ProjectFormValue): ProjectFormValue {
+ return {
+ ...value,
+ teamMembers: value.teamMembers.filter(
+ (row) => row.userId || row.role.trim()
+ ),
+ resourceLinks: value.resourceLinks.filter((row) => row.url.trim()),
+ };
+}
+export function errorSection(field: string): number {
+ const root = field.split(".")[0];
+ if (
+ [
+ "nonprofitPartner",
+ "nonprofitPartnerId",
+ "nonprofitPartnerName",
+ "nonprofitPartnerPhoto",
+ "startDate",
+ "endDate",
+ ].includes(root)
+ )
+ return 1;
+ if (["problemStatement", "goalStatement"].includes(root)) return 2;
+ if (root === "teamMembers") return 3;
+ if (["solutionDescription", "demoMedia"].includes(root)) return 4;
+ if (root === "resourceLinks") return 5;
+ return 0;
+}
+
+// Server indexes refer to persisted rows. Empty UI placeholders may precede
+// those rows, so translate errors back to the row actually shown to the editor.
+export function draftFieldPath(value: ProjectFormValue, path: string): string {
+ const match = /^(teamMembers|resourceLinks)\.(\d+)(.*)$/.exec(path);
+ if (!match) return path;
+ const group = match[1] as "teamMembers" | "resourceLinks";
+ const clean = autosaveValue(value);
+ const row = clean[group][Number(match[2])];
+ const index = (value[group] as unknown[]).indexOf(row);
+ return index < 0 ? path : `${group}.${index}${match[3]}`;
+}
+export function draftErrors(value: ProjectFormValue): Record {
+ return Object.fromEntries(
+ Object.entries(formErrors(autosaveValue(value))).map(([path, error]) => [
+ draftFieldPath(value, path),
+ error,
+ ])
+ );
+}
diff --git a/src/lib/projects/http.ts b/src/lib/projects/http.ts
new file mode 100644
index 0000000..400047a
--- /dev/null
+++ b/src/lib/projects/http.ts
@@ -0,0 +1,77 @@
+import { allowedProjectOrigin } from "./security";
+import { Prisma } from "@prisma/client";
+import { assertSession, assertRole } from "@/lib/auth/guards";
+import type { AppRole } from "@/types";
+import {
+ canProjectAction,
+ type ProjectAction,
+ type ProjectViewer,
+} from "./permissions";
+
+export class ProjectApiError extends Error {
+ constructor(
+ public status: number,
+ message: string,
+ public details?: unknown
+ ) {
+ super(message);
+ }
+}
+export async function projectViewer(
+ request: Request,
+ allowed?: readonly AppRole[]
+): Promise {
+ if (!allowedProjectOrigin(request, process.env.PUBLIC_URL))
+ throw new ProjectApiError(
+ 403,
+ "Cross-origin project writes are not allowed"
+ );
+ let session;
+ try {
+ session = await (allowed
+ ? assertRole(allowed, request)
+ : assertSession(request));
+ } catch (error) {
+ if (error instanceof Error && error.message === "Unauthorized")
+ throw new ProjectApiError(401, "Unauthorized");
+ if (error instanceof Error && error.message === "Forbidden")
+ throw new ProjectApiError(403, "Forbidden");
+ throw error;
+ }
+ const { id, role, chapterId } = session.user;
+ return { id, role, chapterId };
+}
+export function authorizeProject(
+ viewer: ProjectViewer,
+ action: ProjectAction,
+ chapterId?: string
+) {
+ if (!canProjectAction(viewer, action, chapterId))
+ throw new ProjectApiError(403, "Forbidden");
+}
+export async function projectResponse(
+ work: () => Promise
+): Promise {
+ try {
+ return await work();
+ } catch (error) {
+ if (error instanceof ProjectApiError)
+ return Response.json(
+ {
+ error: error.message,
+ ...(error.details ? { details: error.details } : {}),
+ },
+ { status: error.status }
+ );
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ ["P2003", "P2025"].includes(error.code)
+ )
+ return Response.json(
+ { error: "A referenced record changed. Reload and try again." },
+ { status: 409 }
+ );
+ console.error("Project API failed", error);
+ return Response.json({ error: "Project request failed" }, { status: 500 });
+ }
+}
diff --git a/src/lib/projects/media.test.ts b/src/lib/projects/media.test.ts
new file mode 100644
index 0000000..b1ade0f
--- /dev/null
+++ b/src/lib/projects/media.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { mediaKind } from "./media";
+
+describe("project upload format checks", () => {
+ it("matches content signatures to the declared media type", () => {
+ expect(
+ mediaKind(Uint8Array.from([137, 80, 78, 71, 13, 10, 26, 10]), "image/png")
+ ).toBe("png");
+ expect(mediaKind(Uint8Array.from([255, 216, 255, 0]), "image/jpeg")).toBe(
+ "jpg"
+ );
+ expect(mediaKind(Buffer.from("GIF89a"), "image/gif")).toBe("gif");
+ expect(mediaKind(Buffer.from("RIFF1234WEBP"), "image/webp")).toBe("webp");
+ expect(mediaKind(Uint8Array.from([26, 69, 223, 163]), "video/webm")).toBe(
+ "webm"
+ );
+ expect(mediaKind(Buffer.from("1234ftypisom"), "video/mp4")).toBe("mp4");
+ });
+ it("rejects renamed HTML, unsupported formats and mismatched MIME types", () => {
+ expect(
+ mediaKind(Buffer.from("not an image"), "image/png")
+ ).toBeNull();
+ expect(mediaKind(Buffer.from(" "), "image/svg+xml")).toBeNull();
+ expect(mediaKind(Uint8Array.from([255, 216, 255]), "video/mp4")).toBeNull();
+ expect(mediaKind(new Uint8Array(), "image/png")).toBeNull();
+ });
+});
diff --git a/src/lib/projects/media.ts b/src/lib/projects/media.ts
new file mode 100644
index 0000000..fa8eccb
--- /dev/null
+++ b/src/lib/projects/media.ts
@@ -0,0 +1,179 @@
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import { mkdir, rm, stat, writeFile } from "node:fs/promises";
+import { createReadStream } from "node:fs";
+import { Readable } from "node:stream";
+import { ProjectApiError } from "./http";
+
+export const MAX_MEDIA_BYTES = 20 * 1024 * 1024;
+const types = {
+ "image/png": "png",
+ "image/jpeg": "jpg",
+ "image/gif": "gif",
+ "image/webp": "webp",
+ "video/mp4": "mp4",
+ "video/webm": "webm",
+} as const;
+export function mediaKind(bytes: Uint8Array, mime: string): string | null {
+ const starts = (...prefix: number[]) =>
+ prefix.every((value, index) => bytes[index] === value);
+ const ascii = (start: number, end: number) =>
+ Buffer.from(bytes.subarray(start, end)).toString("ascii");
+ const valid =
+ mime === "image/png"
+ ? starts(137, 80, 78, 71, 13, 10, 26, 10)
+ : mime === "image/jpeg"
+ ? starts(255, 216, 255)
+ : mime === "image/gif"
+ ? ["GIF87a", "GIF89a"].includes(ascii(0, 6))
+ : mime === "image/webp"
+ ? ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP"
+ : mime === "video/webm"
+ ? starts(26, 69, 223, 163)
+ : mime === "video/mp4"
+ ? ascii(4, 8) === "ftyp" &&
+ [
+ "isom",
+ "iso2",
+ "mp41",
+ "mp42",
+ "avc1",
+ "M4V ",
+ "MSNV",
+ ].includes(ascii(8, 12))
+ : false;
+ return valid ? types[mime as keyof typeof types] : null;
+}
+function folder(projectId: string) {
+ if (!/^[\w-]+$/.test(projectId))
+ throw new ProjectApiError(404, "Media not found");
+ // Uploads are runtime data on a persistent volume, never build artifacts.
+ return path.join(
+ /* turbopackIgnore: true */
+ process.env.PROJECT_MEDIA_DIR ||
+ path.join(process.cwd(), ".data", "project-media"),
+ projectId
+ );
+}
+export async function uploadedFile(request: Request): Promise {
+ if (!request.headers.get("content-type")?.startsWith("multipart/form-data;"))
+ throw new ProjectApiError(400, "Upload a file using multipart/form-data");
+ const limit = MAX_MEDIA_BYTES + 1024 * 1024;
+ if (Number(request.headers.get("content-length")) > limit)
+ throw new ProjectApiError(413, "Media must be 20 MB or smaller");
+ if (!request.body) throw new ProjectApiError(400, "Choose a file");
+ const reader = request.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let size = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ size += value.byteLength;
+ if (size > limit) {
+ await reader.cancel();
+ throw new ProjectApiError(413, "Media must be 20 MB or smaller");
+ }
+ chunks.push(value);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ let data: FormData;
+ try {
+ data = await new Response(Buffer.concat(chunks), {
+ headers: { "content-type": request.headers.get("content-type")! },
+ }).formData();
+ } catch {
+ throw new ProjectApiError(400, "Invalid upload");
+ }
+ const file = data.get("file");
+ if (!(file instanceof File) || file.size === 0)
+ throw new ProjectApiError(400, "Choose a non-empty file");
+ if (file.size > MAX_MEDIA_BYTES)
+ throw new ProjectApiError(413, "Media must be 20 MB or smaller");
+ return file;
+}
+export async function storeMedia(projectId: string, file: File) {
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ const extension = mediaKind(bytes, file.type);
+ if (!extension)
+ throw new ProjectApiError(
+ 400,
+ "Use a valid PNG, JPEG, WebP, GIF, MP4 or WebM file"
+ );
+ const directory = folder(projectId);
+ await mkdir(directory, { recursive: true });
+ const name = `${randomUUID()}.${extension}`;
+ await writeFile(
+ path.join(/* turbopackIgnore: true */ directory, name),
+ bytes,
+ { flag: "wx" }
+ );
+ return {
+ url: `/api/projects/${encodeURIComponent(projectId)}/media/${name}`,
+ };
+}
+export async function serveMedia(
+ projectId: string,
+ name: string,
+ range: string | null
+) {
+ if (!/^[\da-f-]{36}\.(png|jpg|webp|gif|mp4|webm)$/.test(name))
+ throw new ProjectApiError(404, "Media not found");
+ const file = path.join(/* turbopackIgnore: true */ folder(projectId), name);
+ let size: number;
+ try {
+ size = (await stat(/* turbopackIgnore: true */ file)).size;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT")
+ throw new ProjectApiError(404, "Media not found");
+ throw error;
+ }
+ // Read permissions are checked by the route before touching the file.
+ const extension = path.extname(name).slice(1);
+ const mime = Object.entries(types).find(([, ext]) => ext === extension)![0];
+ const headers: Record = {
+ "Content-Type": mime,
+ "Cache-Control": "private, no-store",
+ "X-Content-Type-Options": "nosniff",
+ "Accept-Ranges": "bytes",
+ "Content-Security-Policy": "default-src 'none'; sandbox",
+ };
+ let start = 0,
+ end = size - 1;
+ if (range) {
+ const match = /^bytes=(\d*)-(\d*)$/.exec(range);
+ if (!match || (!match[1] && !match[2]))
+ return new Response(null, {
+ status: 416,
+ headers: { ...headers, "Content-Range": `bytes */${size}` },
+ });
+ start = match[1] ? Number(match[1]) : Math.max(0, size - Number(match[2]));
+ end =
+ match[1] && match[2] ? Math.min(Number(match[2]), size - 1) : size - 1;
+ if (
+ !Number.isSafeInteger(start) ||
+ !Number.isSafeInteger(end) ||
+ start > end ||
+ start >= size
+ )
+ return new Response(null, {
+ status: 416,
+ headers: { ...headers, "Content-Range": `bytes */${size}` },
+ });
+ headers["Content-Range"] = `bytes ${start}-${end}/${size}`;
+ }
+ headers["Content-Length"] = String(end - start + 1);
+ const stream = Readable.toWeb(
+ createReadStream(/* turbopackIgnore: true */ file, { start, end })
+ ) as ReadableStream;
+ return new Response(stream, { status: range ? 206 : 200, headers });
+}
+
+export async function removeProjectMedia(projectId: string) {
+ await rm(/* turbopackIgnore: true */ folder(projectId), {
+ recursive: true,
+ force: true,
+ });
+}
diff --git a/src/lib/projects/partner-reference.test.ts b/src/lib/projects/partner-reference.test.ts
new file mode 100644
index 0000000..2437cba
--- /dev/null
+++ b/src/lib/projects/partner-reference.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+import { partnerFromNotion } from "./partner-reference";
+
+describe("Partner Directory projection", () => {
+ it("returns only canonical ID, name and optional logo, never contact data", () => {
+ const partner = partnerFromNotion({
+ id: "partner-1",
+ properties: {
+ Name: {
+ type: "title",
+ title: [{ plain_text: "Community " }, { plain_text: "Center" }],
+ },
+ Email: { type: "email", email: "private@example.org" },
+ Logo: {
+ type: "files",
+ files: [{ external: { url: "https://example.org/logo.png" } }],
+ },
+ },
+ });
+ expect(partner).toEqual({
+ id: "partner-1",
+ name: "Community Center",
+ photo: "https://example.org/logo.png",
+ });
+ expect(JSON.stringify(partner)).not.toContain("private@example.org");
+ });
+ it("handles missing names and ignores unsafe image URL schemes", () => {
+ expect(partnerFromNotion({ id: "p", properties: {} })).toBeNull();
+ expect(partnerFromNotion(null)).toBeNull();
+ expect(
+ partnerFromNotion({
+ id: "p",
+ properties: { Name: { title: [{ plain_text: "Partner" }] } },
+ icon: { external: { url: "javascript:alert(1)" } },
+ })
+ ).toEqual({ id: "p", name: "Partner", photo: null });
+ });
+ it("skips Notion-hosted files, whose signed URLs expire", () => {
+ expect(
+ partnerFromNotion({
+ id: "p",
+ properties: {
+ Name: { title: [{ plain_text: "Partner" }] },
+ Logo: {
+ files: [
+ {
+ file: {
+ url: "https://prod-files-secure.s3.us-west-2.amazonaws.com/x.png?X-Amz-Expires=3600",
+ },
+ },
+ ],
+ },
+ },
+ icon: { external: { url: "https://example.org/icon.png" } },
+ })
+ ).toEqual({
+ id: "p",
+ name: "Partner",
+ photo: "https://example.org/icon.png",
+ });
+ });
+});
diff --git a/src/lib/projects/partner-reference.ts b/src/lib/projects/partner-reference.ts
new file mode 100644
index 0000000..6b3e027
--- /dev/null
+++ b/src/lib/projects/partner-reference.ts
@@ -0,0 +1,48 @@
+import type { PartnerReference } from "./references";
+
+export function partnerFromNotion(value: unknown): PartnerReference | null {
+ if (!value || typeof value !== "object") return null;
+ const page = value as Record;
+ if (
+ typeof page.id !== "string" ||
+ !page.properties ||
+ typeof page.properties !== "object"
+ )
+ return null;
+ const props = page.properties as Record<
+ string,
+ {
+ type?: string;
+ title?: { plain_text?: string; text?: { content?: string } }[];
+ files?: unknown[];
+ }
+ >;
+ const title =
+ props.Name?.title ||
+ Object.values(props).find((prop) => prop.type === "title")?.title;
+ const name = title
+ ?.map((part) => part.plain_text ?? part.text?.content ?? "")
+ .join("")
+ .trim();
+ if (!name) return null;
+ function image(source: unknown): string | null {
+ if (!source || typeof source !== "object") return null;
+ // Only external links: Notion-hosted files come back as signed URLs that
+ // expire after about an hour, so a saved one would break on the published
+ // project. Leads can upload a partner photo instead.
+ const item = source as { external?: { url?: unknown } };
+ const url = item.external?.url;
+ if (typeof url !== "string") return null;
+ try {
+ return ["https:", "http:"].includes(new URL(url).protocol) ? url : null;
+ } catch {
+ return null;
+ }
+ }
+ const photo =
+ image(props.Logo?.files?.[0]) ||
+ image(props.Photo?.files?.[0]) ||
+ image(page.icon) ||
+ image(page.cover);
+ return { id: page.id, name, photo };
+}
diff --git a/src/lib/projects/permissions.test.ts b/src/lib/projects/permissions.test.ts
new file mode 100644
index 0000000..039e977
--- /dev/null
+++ b/src/lib/projects/permissions.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from "vitest";
+import {
+ canProjectAction,
+ type ProjectAction,
+ type ProjectViewer,
+} from "./permissions";
+
+// Section 14: each row is asserted for every supported role and chapter scope.
+const table: {
+ action: ProjectAction;
+ member: boolean;
+ ownLead: boolean;
+ otherLead: boolean;
+ admin: boolean;
+}[] = [
+ {
+ action: "browse",
+ member: true,
+ ownLead: true,
+ otherLead: true,
+ admin: true,
+ },
+ { action: "read", member: true, ownLead: true, otherLead: true, admin: true },
+ {
+ action: "readDraft",
+ member: false,
+ ownLead: true,
+ otherLead: false,
+ admin: true,
+ },
+ {
+ action: "create",
+ member: false,
+ ownLead: true,
+ otherLead: false,
+ admin: true,
+ },
+ {
+ action: "edit",
+ member: false,
+ ownLead: true,
+ otherLead: false,
+ admin: true,
+ },
+ {
+ action: "publish",
+ member: false,
+ ownLead: true,
+ otherLead: false,
+ admin: true,
+ },
+ // Lead deletion was left open in the PRD; default to National Admin only.
+ {
+ action: "delete",
+ member: false,
+ ownLead: false,
+ otherLead: false,
+ admin: true,
+ },
+];
+describe("Section 14 project permissions", () => {
+ it.each(table)("$action", ({ action, member, ownLead, otherLead, admin }) => {
+ const viewer = (
+ role: ProjectViewer["role"],
+ chapterId: string | null
+ ): ProjectViewer => ({ id: "user", role, chapterId });
+ expect(canProjectAction(viewer("MEMBER", "c1"), action, "c1")).toBe(member);
+ expect(canProjectAction(viewer("NATIONAL_ADMIN", null), action, "c1")).toBe(
+ admin
+ );
+ expect(canProjectAction(viewer("NATIONAL_ADMIN", "c2"), action, "c1")).toBe(
+ admin
+ );
+ for (const role of ["PROJECT_LEAD", "CHAPTER_LEAD"] as const) {
+ expect(canProjectAction(viewer(role, "c1"), action, "c1")).toBe(ownLead);
+ expect(canProjectAction(viewer(role, "c2"), action, "c1")).toBe(
+ otherLead
+ );
+ expect(canProjectAction(viewer(role, null), action, "c1")).toBe(
+ action === "browse" || action === "read"
+ );
+ }
+ });
+});
diff --git a/src/lib/projects/permissions.ts b/src/lib/projects/permissions.ts
new file mode 100644
index 0000000..172ca7d
--- /dev/null
+++ b/src/lib/projects/permissions.ts
@@ -0,0 +1,27 @@
+import type { AppRole } from "@/types";
+import { ADMIN_ROLES, EDITOR_ROLES, hasRole } from "@/lib/auth/roles";
+
+export type ProjectViewer = {
+ id: string;
+ role: AppRole;
+ chapterId: string | null;
+};
+export type ProjectAction =
+ "browse" | "read" | "readDraft" | "create" | "edit" | "publish" | "delete";
+
+// Do not change the shared chapter leadership guard: project leads have project
+// permissions, not the chapter administration permissions of CHAPTER_LEAD.
+export function canProjectAction(
+ viewer: ProjectViewer,
+ action: ProjectAction,
+ chapterId?: string
+): boolean {
+ if (hasRole(viewer.role, ADMIN_ROLES)) return true;
+ if (action === "browse" || action === "read") return true;
+ if (action === "delete") return false;
+ return (
+ hasRole(viewer.role, EDITOR_ROLES) &&
+ Boolean(viewer.chapterId) &&
+ viewer.chapterId === chapterId
+ );
+}
diff --git a/src/lib/projects/references.ts b/src/lib/projects/references.ts
new file mode 100644
index 0000000..04b10ca
--- /dev/null
+++ b/src/lib/projects/references.ts
@@ -0,0 +1,81 @@
+import { db } from "@/lib/db";
+import {
+ directoryDetailWhere,
+ directoryListWhere,
+} from "@/lib/directory/visibility";
+import type { ProjectViewer } from "./permissions";
+
+export type MemberReference = {
+ id: string;
+ memberId: string | null;
+ name: string;
+ role: string;
+};
+export type PartnerReference = {
+ id: string;
+ name: string;
+ photo: string | null;
+};
+const memberSelect = {
+ id: true,
+ userId: true,
+ displayName: true,
+ position: true,
+} as const;
+const roles = {
+ PM: "Project Lead",
+ TL: "Tech Lead",
+ DEVELOPER: "Developer",
+ DESIGNER: "Designer",
+ BUSINESS: "Business",
+};
+function memberReference(member: {
+ id: string;
+ userId: string | null;
+ displayName: string | null;
+ position: keyof typeof roles | null;
+}): MemberReference {
+ return {
+ id: member.userId!,
+ memberId: member.id,
+ name: member.displayName || "Unnamed member",
+ role: member.position ? roles[member.position] : "Developer",
+ };
+}
+export async function searchMemberReferences(q = "") {
+ const members = await db.member.findMany({
+ where: {
+ ...directoryListWhere(),
+ ...(q ? { displayName: { contains: q, mode: "insensitive" } } : {}),
+ },
+ select: memberSelect,
+ orderBy: [{ displayName: "asc" }, { id: "asc" }],
+ take: 50,
+ });
+ return members.map(memberReference);
+}
+export async function selectedMemberReferences(
+ viewer: ProjectViewer,
+ userIds: string[]
+) {
+ if (!userIds.length) return [];
+ const members = await db.member.findMany({
+ where: {
+ AND: [
+ { userId: { in: userIds } },
+ directoryDetailWhere({ userId: viewer.id, role: viewer.role }),
+ ],
+ },
+ select: memberSelect,
+ });
+ const visible = members.map(memberReference);
+ return userIds.map(
+ (id) =>
+ visible.find((member) => member.id === id) ?? {
+ id,
+ memberId: null,
+ name: "Member record unavailable",
+ role: "Developer",
+ }
+ );
+}
diff --git a/src/lib/projects/security.test.ts b/src/lib/projects/security.test.ts
new file mode 100644
index 0000000..a5bf190
--- /dev/null
+++ b/src/lib/projects/security.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+import { allowedProjectOrigin } from "./security";
+
+describe("project write origin checks", () => {
+ const req = (method: string, origin?: string, site?: string) =>
+ new Request("https://app.example.org/api/projects", {
+ method,
+ headers: {
+ ...(origin ? { origin } : {}),
+ ...(site ? { "sec-fetch-site": site } : {}),
+ },
+ });
+ it.each(["POST", "PATCH", "DELETE"])(
+ "blocks cross-origin %s, including same-site sibling origins",
+ (method) => {
+ expect(allowedProjectOrigin(req(method, "https://app.example.org"))).toBe(
+ true
+ );
+ expect(
+ allowedProjectOrigin(
+ req(method, "https://attacker.example.org", "same-site")
+ )
+ ).toBe(false);
+ expect(
+ allowedProjectOrigin(req(method, "https://untrusted.invalid"))
+ ).toBe(false);
+ expect(allowedProjectOrigin(req(method, "null"))).toBe(false);
+ }
+ );
+ it("supports CLI callers and the configured reverse-proxy origin", () => {
+ expect(allowedProjectOrigin(req("POST"))).toBe(true);
+ expect(allowedProjectOrigin(req("POST", undefined, "cross-site"))).toBe(
+ false
+ );
+ const proxy = new Request("http://internal:3000/api/projects", {
+ method: "POST",
+ headers: { origin: "https://public.example.org" },
+ });
+ expect(
+ allowedProjectOrigin(proxy, "https://public.example.org/some-path")
+ ).toBe(true);
+ expect(allowedProjectOrigin(proxy, "not-a-url")).toBe(false);
+ });
+ it("does not substitute origin checks for authenticated read permissions", () => {
+ expect(allowedProjectOrigin(req("GET", "https://untrusted.invalid"))).toBe(
+ true
+ );
+ });
+});
diff --git a/src/lib/projects/security.ts b/src/lib/projects/security.ts
new file mode 100644
index 0000000..075ce0a
--- /dev/null
+++ b/src/lib/projects/security.ts
@@ -0,0 +1,22 @@
+const safeMethods = new Set(["GET", "HEAD", "OPTIONS"]);
+
+// Browser requests declare their Origin; CLI/API callers may omit it. PUBLIC_URL
+// supports the canonical browser origin when a reverse proxy uses an internal URL.
+export function allowedProjectOrigin(
+ request: Request,
+ publicUrl?: string
+): boolean {
+ if (safeMethods.has(request.method.toUpperCase())) return true;
+ if (request.headers.get("sec-fetch-site") === "cross-site") return false;
+ const origin = request.headers.get("origin");
+ if (!origin) return true;
+ const allowed = new Set([new URL(request.url).origin]);
+ if (publicUrl) {
+ try {
+ allowed.add(new URL(publicUrl).origin);
+ } catch {
+ /* Invalid configuration grants no additional origin. */
+ }
+ }
+ return allowed.has(origin);
+}
diff --git a/src/lib/projects/service.ts b/src/lib/projects/service.ts
new file mode 100644
index 0000000..6b0bd81
--- /dev/null
+++ b/src/lib/projects/service.ts
@@ -0,0 +1,469 @@
+import { removeProjectMedia } from "./media";
+import { projectOrderBy, type ProjectListOptions } from "./sort";
+import { Prisma } from "@prisma/client";
+import { db } from "@/lib/db";
+import { directoryDetailWhere } from "@/lib/directory/visibility";
+import { hasRole, ADMIN_ROLES } from "@/lib/auth/roles";
+import { authorizeProject, ProjectApiError } from "./http";
+import { canProjectAction, type ProjectViewer } from "./permissions";
+import {
+ createSchema,
+ patchSchema,
+ normalizeInput,
+ missingPublishFields,
+ type ProjectPatch,
+} from "./validation";
+
+const include = { teamMembers: true, resourceLinks: true } as const;
+type StoredProject = Prisma.ProjectGetPayload<{ include: typeof include }>;
+type Tx = Prisma.TransactionClient;
+
+export async function parseProjectBody(
+ request: Request,
+ create = false
+): Promise {
+ let raw: unknown;
+ try {
+ raw = normalizeInput(await request.json());
+ } catch (error) {
+ throw new ProjectApiError(
+ 400,
+ error instanceof SyntaxError
+ ? "Invalid JSON"
+ : error instanceof Error
+ ? error.message
+ : "Invalid JSON"
+ );
+ }
+ const parsed = (create ? createSchema : patchSchema).safeParse(raw);
+ if (!parsed.success)
+ throw new ProjectApiError(
+ 400,
+ "Invalid project fields",
+ parsed.error.flatten()
+ );
+ const patch = parsed.data;
+ if (patch.startDate && patch.endDate && patch.endDate < patch.startDate)
+ throw new ProjectApiError(400, "End date must not precede start date");
+ return patch;
+}
+
+function pending(project: StoredProject): ProjectPatch {
+ return project.pendingChanges
+ ? patchSchema.parse(project.pendingChanges)
+ : {};
+}
+function editable(project: StoredProject): ProjectPatch {
+ return {
+ name: project.name,
+ chapterId: project.chapterId,
+ stage: project.stage,
+ tagline: project.tagline,
+ techStack: project.techStack,
+ causeAreas: project.causeAreas,
+ nonprofitPartnerId: project.nonprofitPartnerId,
+ nonprofitPartnerName: project.nonprofitPartnerName,
+ nonprofitPartnerPhoto: project.nonprofitPartnerPhoto,
+ startDate: project.startDate?.toISOString().slice(0, 10) ?? null,
+ endDate: project.endDate?.toISOString().slice(0, 10) ?? null,
+ problemStatement: project.problemStatement,
+ goalStatement: project.goalStatement,
+ solutionDescription: project.solutionDescription,
+ demoMedia: project.demoMedia,
+ teamMembers: project.teamMembers.map(({ userId, memberId, role }) => ({
+ userId,
+ memberId,
+ role,
+ })),
+ resourceLinks: project.resourceLinks.map(({ type, url }) => ({
+ type,
+ url,
+ })),
+ };
+}
+function response(project: StoredProject, draft = false) {
+ const { pendingChanges, ...record } = project;
+ return {
+ ...record,
+ ...(draft
+ ? {
+ ...editable(project),
+ ...pending(project),
+ hasUnpublishedChanges: Boolean(pendingChanges),
+ }
+ : {}),
+ };
+}
+
+export function assertTargetChapter(
+ viewer: ProjectViewer,
+ chapterId: string | undefined
+): string {
+ if (hasRole(viewer.role, ADMIN_ROLES)) {
+ if (!chapterId)
+ throw new ProjectApiError(
+ 400,
+ "chapterId is required for National Admins"
+ );
+ return chapterId;
+ }
+ if (
+ !viewer.chapterId ||
+ (chapterId !== undefined && chapterId !== viewer.chapterId)
+ )
+ throw new ProjectApiError(403, "Cannot post to another chapter");
+ authorizeProject(viewer, "create", viewer.chapterId);
+ return viewer.chapterId;
+}
+async function checkReferences(
+ tx: Tx,
+ patch: ProjectPatch,
+ viewer: ProjectViewer,
+ existing: ProjectPatch = {}
+) {
+ if (
+ patch.chapterId &&
+ !(await tx.chapter.findUnique({
+ where: { id: patch.chapterId },
+ select: { id: true },
+ }))
+ )
+ throw new ProjectApiError(400, "Unknown chapterId");
+ if (patch.teamMembers) {
+ const ids = [...new Set(patch.teamMembers.map((member) => member.userId))];
+ const count = await tx.user.count({ where: { id: { in: ids } } });
+ for (const row of patch.teamMembers) {
+ if (!row.memberId) continue;
+ const retained = existing.teamMembers?.some(
+ (old) => old.userId === row.userId && old.memberId === row.memberId
+ );
+ const member = await tx.member.findFirst({
+ where: {
+ AND: [
+ { id: row.memberId, userId: row.userId },
+ retained
+ ? {}
+ : directoryDetailWhere({ userId: viewer.id, role: viewer.role }),
+ ],
+ },
+ select: { id: true },
+ });
+ if (!member)
+ throw new ProjectApiError(
+ 400,
+ "Choose an accessible member record linked to this user"
+ );
+ }
+ if (count !== ids.length)
+ throw new ProjectApiError(
+ 400,
+ "Team members must reference existing users"
+ );
+ }
+}
+function checkTimeline(project: ProjectPatch) {
+ if (
+ project.startDate &&
+ project.endDate &&
+ project.endDate < project.startDate
+ )
+ throw new ProjectApiError(400, "End date must not precede start date");
+}
+async function save(tx: Tx, id: string, patch: ProjectPatch) {
+ const { teamMembers, resourceLinks, startDate, endDate, ...scalars } = patch;
+ return tx.project.update({
+ where: { id },
+ data: {
+ ...scalars,
+ ...(startDate !== undefined
+ ? { startDate: startDate ? new Date(`${startDate}T00:00:00Z`) : null }
+ : {}),
+ ...(endDate !== undefined
+ ? { endDate: endDate ? new Date(`${endDate}T00:00:00Z`) : null }
+ : {}),
+ ...(teamMembers !== undefined
+ ? { teamMembers: { deleteMany: {}, create: teamMembers } }
+ : {}),
+ ...(resourceLinks !== undefined
+ ? { resourceLinks: { deleteMany: {}, create: resourceLinks } }
+ : {}),
+ },
+ include,
+ });
+}
+async function lockedViewer(
+ tx: Tx,
+ viewer: ProjectViewer
+): Promise {
+ // Keep the authorization snapshot valid until the write commits. Role/chapter
+ // updates wait for this shared row lock, and every project write locks in this order.
+ await tx.$queryRaw`SELECT id FROM "User" WHERE id = ${viewer.id} FOR SHARE`;
+ const actor = await tx.user.findUnique({
+ where: { id: viewer.id },
+ select: { id: true, role: true, chapterId: true },
+ });
+ if (!actor) throw new ProjectApiError(401, "Unauthorized");
+ return actor;
+}
+async function lockedProject(tx: Tx, id: string) {
+ // Serialize PATCH, publish and delete, preventing an autosave from being lost
+ // or becoming visible halfway through a concurrent publish.
+ await tx.$queryRaw`SELECT id FROM projects WHERE id = ${id} FOR UPDATE`;
+ const project = await tx.project.findUnique({ where: { id }, include });
+ if (!project) throw new ProjectApiError(404, "Project not found");
+ return project;
+}
+
+export async function createProject(
+ viewer: ProjectViewer,
+ patch: ProjectPatch
+) {
+ assertTargetChapter(viewer, patch.chapterId);
+ return db.$transaction(async (tx) => {
+ const actor = await lockedViewer(tx, viewer);
+ const targetChapter = assertTargetChapter(actor, patch.chapterId);
+ await checkReferences(tx, { ...patch, chapterId: targetChapter }, actor);
+ const project = await tx.project.create({
+ data: {
+ name: patch.name!,
+ chapterId: targetChapter,
+ createdBy: actor.id,
+ },
+ });
+ return response(
+ await save(tx, project.id, { ...patch, chapterId: targetChapter }),
+ true
+ );
+ });
+}
+export async function patchProject(
+ viewer: ProjectViewer,
+ id: string,
+ patch: ProjectPatch
+) {
+ return db.$transaction(async (tx) => {
+ const actor = await lockedViewer(tx, viewer);
+ const project = await lockedProject(tx, id);
+ authorizeProject(actor, "edit", project.chapterId);
+ const current = { ...editable(project), ...pending(project) };
+ assertTargetChapter(actor, current.chapterId);
+ const next = { ...current, ...patch };
+ assertTargetChapter(actor, next.chapterId);
+ checkTimeline(next);
+ await checkReferences(tx, patch, actor, current);
+ if (project.isDraft) return response(await save(tx, id, patch), true);
+ const changes = { ...pending(project), ...patch };
+ const updated = await tx.project.update({
+ where: { id },
+ data: { pendingChanges: changes as Prisma.InputJsonValue },
+ include,
+ });
+ return response(updated, true);
+ });
+}
+export async function publishProject(viewer: ProjectViewer, id: string) {
+ return db.$transaction(async (tx) => {
+ const actor = await lockedViewer(tx, viewer);
+ const project = await lockedProject(tx, id);
+ authorizeProject(actor, "publish", project.chapterId);
+ const next = { ...editable(project), ...pending(project) };
+ assertTargetChapter(actor, next.chapterId);
+ const missingFields = missingPublishFields(next);
+ if (missingFields.length)
+ throw new ProjectApiError(422, "Project is incomplete for its stage", {
+ missingFields,
+ });
+ checkTimeline(next);
+ await checkReferences(tx, next, actor, next);
+ if (!project.isDraft && !project.pendingChanges) return response(project);
+ if (project.pendingChanges) await save(tx, id, pending(project));
+ return response(
+ await tx.project.update({
+ where: { id },
+ data: {
+ isDraft: false,
+ lastUpdated: new Date(),
+ pendingChanges: Prisma.DbNull,
+ },
+ include,
+ })
+ );
+ });
+}
+export async function deleteProject(viewer: ProjectViewer, id: string) {
+ authorizeProject(viewer, "delete");
+ await db.$transaction(async (tx) => {
+ const actor = await lockedViewer(tx, viewer);
+ authorizeProject(actor, "delete");
+ await lockedProject(tx, id);
+ await tx.project.delete({ where: { id } });
+ });
+ try {
+ await removeProjectMedia(id);
+ } catch (error) {
+ console.error("Project deleted; private media cleanup needs retry", {
+ projectId: id,
+ error,
+ });
+ }
+}
+export async function readProject(
+ viewer: ProjectViewer,
+ id: string,
+ draft = false
+) {
+ const project = await db.project.findUnique({ where: { id }, include });
+ if (
+ !project ||
+ ((project.isDraft || draft) &&
+ !canProjectAction(viewer, "readDraft", project.chapterId))
+ )
+ throw new ProjectApiError(404, "Project not found");
+ if (
+ draft &&
+ !canProjectAction(
+ viewer,
+ "readDraft",
+ pending(project).chapterId ?? project.chapterId
+ )
+ )
+ throw new ProjectApiError(404, "Project not found");
+ return response(project, draft);
+}
+// Array-returning wrapper retained for existing consumers.
+export async function listProjects(
+ viewer: ProjectViewer,
+ includeDrafts: boolean,
+ options: ProjectListOptions = {}
+) {
+ return (
+ await searchProjects(viewer, includeDrafts, { pageSize: 100, ...options })
+ ).items;
+}
+export async function searchProjects(
+ viewer: ProjectViewer,
+ includeDrafts: boolean,
+ options: ProjectListOptions = {}
+) {
+ const visibility: Prisma.ProjectWhereInput[] = [{ isDraft: false }];
+ if (includeDrafts && hasRole(viewer.role, ADMIN_ROLES))
+ visibility.push({ isDraft: true });
+ else if (
+ includeDrafts &&
+ viewer.chapterId &&
+ canProjectAction(viewer, "readDraft", viewer.chapterId)
+ )
+ visibility.push({ isDraft: true, chapterId: viewer.chapterId });
+ const pageSize = Math.min(100, Math.max(1, options.pageSize ?? 12));
+ return db.$transaction(
+ async (tx) => {
+ const where: Prisma.ProjectWhereInput = {
+ AND: [{ OR: visibility }],
+ ...(options.chapterId ? { chapterId: options.chapterId } : {}),
+ ...(options.stage ? { stage: options.stage } : {}),
+ ...(options.impactArea
+ ? { causeAreas: { has: options.impactArea } }
+ : {}),
+ };
+ const and = where.AND as Prisma.ProjectWhereInput[];
+ if (options.q)
+ and.push({
+ OR: [
+ { name: { contains: options.q, mode: "insensitive" } },
+ { tagline: { contains: options.q, mode: "insensitive" } },
+ {
+ nonprofitPartnerName: {
+ contains: options.q,
+ mode: "insensitive",
+ },
+ },
+ { chapter: { name: { contains: options.q, mode: "insensitive" } } },
+ ],
+ });
+ if (options.projectLength) {
+ // Date subtraction in PostgreSQL yields an exact number of days. Missing
+ // dates are explicitly unknown rather than silently treated as ongoing.
+ const days = Prisma.sql`("end_date" - "start_date")`;
+ const condition =
+ options.projectLength === "short"
+ ? Prisma.sql`${days} BETWEEN 0 AND 180`
+ : options.projectLength === "medium"
+ ? Prisma.sql`${days} BETWEEN 181 AND 365`
+ : options.projectLength === "long"
+ ? Prisma.sql`${days} > 365`
+ : Prisma.sql`"start_date" IS NULL OR "end_date" IS NULL`;
+ const ids = await tx.$queryRaw<{ id: string }[]>(
+ Prisma.sql`SELECT id FROM projects WHERE ${condition}`
+ );
+ and.push({ id: { in: ids.map((row) => row.id) } });
+ }
+ const total = await tx.project.count({ where });
+ const pages = Math.max(1, Math.ceil(total / pageSize));
+ const page = Math.min(pages, Math.max(1, options.page ?? 1));
+ const projects = await tx.project.findMany({
+ where,
+ include,
+ orderBy: projectOrderBy(options.sort),
+ skip: (page - 1) * pageSize,
+ take: pageSize,
+ });
+ return {
+ items: projects.map((project) => response(project)),
+ total,
+ page,
+ pageSize,
+ pages,
+ };
+ },
+ { isolationLevel: Prisma.TransactionIsolationLevel.RepeatableRead }
+ );
+}
+
+export async function listDraftProjects(viewer: ProjectViewer) {
+ if (!hasRole(viewer.role, ADMIN_ROLES) && !viewer.chapterId) return [];
+ if (
+ !hasRole(viewer.role, ADMIN_ROLES) &&
+ !canProjectAction(viewer, "readDraft", viewer.chapterId!)
+ )
+ return [];
+ const projects = await db.project.findMany({
+ where: {
+ isDraft: true,
+ ...(hasRole(viewer.role, ADMIN_ROLES)
+ ? {}
+ : { chapterId: viewer.chapterId! }),
+ },
+ include,
+ orderBy: [{ updatedAt: "desc" }, { id: "asc" }],
+ });
+ return projects.map((project) => response(project));
+}
+
+export async function assertProjectWriteAccess(
+ viewer: ProjectViewer,
+ id: string
+) {
+ const project = await db.project.findUnique({
+ where: { id },
+ select: { chapterId: true, pendingChanges: true },
+ });
+ if (!project) throw new ProjectApiError(404, "Project not found");
+ authorizeProject(viewer, "edit", project.chapterId);
+ const changes = project.pendingChanges
+ ? patchSchema.parse(project.pendingChanges)
+ : {};
+ assertTargetChapter(viewer, changes.chapterId ?? project.chapterId);
+}
+export async function withProjectWriteAccess(
+ viewer: ProjectViewer,
+ id: string,
+ write: () => Promise
+): Promise {
+ return db.$transaction(async (tx) => {
+ const actor = await lockedViewer(tx, viewer);
+ const project = await lockedProject(tx, id);
+ authorizeProject(actor, "edit", project.chapterId);
+ assertTargetChapter(actor, pending(project).chapterId ?? project.chapterId);
+ return write();
+ });
+}
diff --git a/src/lib/projects/sort.ts b/src/lib/projects/sort.ts
new file mode 100644
index 0000000..d6420da
--- /dev/null
+++ b/src/lib/projects/sort.ts
@@ -0,0 +1,83 @@
+import type { Prisma } from "@prisma/client";
+import { z } from "zod";
+import { stages } from "./validation";
+
+export const projectSortLabels = {
+ last_updated: "Last updated (newest)",
+ name: "Name (A–Z)",
+ year: "Year (newest)",
+} as const;
+export const projectLengthLabels = {
+ short: "Up to 180 days",
+ medium: "181–365 days",
+ long: "Over 365 days",
+ unknown: "Length not set",
+} as const;
+const optionalText = (max: number) =>
+ z.preprocess(
+ (value) => (typeof value === "string" && !value.trim() ? undefined : value),
+ z.string().trim().min(1).max(max).optional()
+ );
+const optionalEnum = (
+ values: T
+) =>
+ z.preprocess(
+ (value) => (value === "" ? undefined : value),
+ z.enum(values).optional()
+ );
+export const projectListQuery = z.object({
+ sort: z.enum(["last_updated", "name", "year"]).default("last_updated"),
+ chapter_id: optionalText(200),
+ q: optionalText(200),
+ stage: optionalEnum(stages),
+ project_length: optionalEnum(["short", "medium", "long", "unknown"]),
+ impact_area: optionalText(100),
+ page: z.coerce.number().int().min(1).max(100000).default(1),
+ page_size: z.coerce.number().int().min(1).max(100).default(12),
+});
+export type ProjectListQuery = z.infer;
+export type ProjectListOptions = {
+ sort?: keyof typeof projectSortLabels;
+ chapterId?: string;
+ q?: string;
+ stage?: ProjectListQuery["stage"];
+ projectLength?: keyof typeof projectLengthLabels;
+ impactArea?: string;
+ page?: number;
+ pageSize?: number;
+};
+export function projectListOptions(
+ query: ProjectListQuery
+): ProjectListOptions {
+ return {
+ sort: query.sort,
+ chapterId: query.chapter_id,
+ q: query.q,
+ stage: query.stage,
+ projectLength: query.project_length,
+ impactArea: query.impact_area,
+ page: query.page,
+ pageSize: query.page_size,
+ };
+}
+export function projectsUrl(query: Partial) {
+ const params = new URLSearchParams();
+ for (const [key, value] of Object.entries(query)) {
+ if (value === undefined || value === "" || (key === "page" && value === 1))
+ continue;
+ params.set(key, String(value));
+ }
+ return `/projects${params.size ? `?${params}` : ""}`;
+}
+export function projectOrderBy(
+ sort: ProjectListOptions["sort"]
+): Prisma.ProjectOrderByWithRelationInput[] {
+ if (sort === "name") return [{ name: "asc" }, { id: "asc" }];
+ if (sort === "year")
+ return [
+ { startDate: { sort: "desc", nulls: "last" } },
+ { name: "asc" },
+ { id: "asc" },
+ ];
+ return [{ lastUpdated: { sort: "desc", nulls: "last" } }, { id: "asc" }];
+}
diff --git a/src/lib/projects/urls.ts b/src/lib/projects/urls.ts
new file mode 100644
index 0000000..bcd6bfa
--- /dev/null
+++ b/src/lib/projects/urls.ts
@@ -0,0 +1,24 @@
+export function projectUrl(
+ value: string | null | undefined,
+ local = false
+): string | null {
+ if (!value) return null;
+ if (local && /^\/(?!\/)[^\\\s]*$/.test(value)) return value;
+ try {
+ return ["http:", "https:"].includes(new URL(value).protocol) ? value : null;
+ } catch {
+ return null;
+ }
+}
+
+export function projectThumbnail(
+ media: string[],
+ partnerPhoto: string | null | undefined
+): string | null {
+ const preview = media.find(
+ (url) =>
+ /\.(png|jpe?g|webp|gif|avif)(?:[?#]|$)/i.test(url) &&
+ projectUrl(url, true)
+ );
+ return projectUrl(preview || partnerPhoto, true);
+}
diff --git a/src/lib/projects/validation.test.ts b/src/lib/projects/validation.test.ts
new file mode 100644
index 0000000..59a0f61
--- /dev/null
+++ b/src/lib/projects/validation.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it } from "vitest";
+import {
+ createSchema,
+ patchSchema,
+ normalizeInput,
+ missingPublishFields,
+ stages,
+ type ProjectPatch,
+} from "./validation";
+
+const design: ProjectPatch = {
+ name: "Community Tools",
+ stage: "design",
+ tagline: "Helping communities",
+ nonprofitPartnerName: "Community Center",
+ startDate: "2026-01-15",
+ problemStatement: "Manual processes",
+ goalStatement: "Reduce paperwork",
+ teamMembers: [{ userId: "member-id", role: "Developer" }],
+};
+describe("stage-dependent publish validation", () => {
+ it("publishes a complete design without solution, links, media, tags or end date", () => {
+ expect(missingPublishFields(design)).toEqual([]);
+ });
+ it.each(["development", "launched", "maintenance"] as const)(
+ "requires solution and resources at %s",
+ (stage) => {
+ expect(missingPublishFields({ ...design, stage })).toEqual([
+ "solutionDescription",
+ "resourceLinks",
+ ]);
+ expect(
+ missingPublishFields({
+ ...design,
+ stage,
+ solutionDescription: "A portal",
+ resourceLinks: [{ type: "GitHub", url: "https://example.org/repo" }],
+ })
+ ).toEqual([]);
+ }
+ );
+ it("returns all missing fields in one result", () => {
+ expect(missingPublishFields({ stage: "launched" })).toEqual([
+ "name",
+ "tagline",
+ "nonprofitPartner",
+ "startDate",
+ "problemStatement",
+ "goalStatement",
+ "teamMembers",
+ "solutionDescription",
+ "resourceLinks",
+ ]);
+ });
+ it("accepts a directory partner ID instead of a fallback name", () => {
+ expect(
+ missingPublishFields({
+ ...design,
+ nonprofitPartnerName: null,
+ nonprofitPartnerId: "partner-1",
+ })
+ ).toEqual([]);
+ });
+ it("rejects blank required text and incomplete team roles on publish", () => {
+ expect(
+ missingPublishFields({
+ ...design,
+ tagline: " ",
+ teamMembers: [{ userId: "u", role: "" }],
+ })
+ ).toEqual(["tagline", "teamMembers.0.role"]);
+ });
+});
+describe("autosave format validation", () => {
+ it.each(stages)("accepts incomplete %s drafts", (stage) => {
+ expect(
+ patchSchema.safeParse({
+ stage,
+ name: "",
+ tagline: null,
+ startDate: null,
+ teamMembers: [],
+ resourceLinks: [],
+ }).success
+ ).toBe(true);
+ });
+ it("accepts uploaded project media paths and HTTP(S) URLs as media", () => {
+ expect(
+ patchSchema.safeParse({
+ demoMedia: [
+ "/api/projects/p1/media/85c3e96d-4a14-4814-b599-ce0ae7643526.png",
+ "https://example.org/demo.mp4",
+ ],
+ }).success
+ ).toBe(true);
+ });
+ it("creates a draft with only a name", () => {
+ expect(createSchema.safeParse({ name: "New Project" }).success).toBe(true);
+ expect(createSchema.safeParse({ name: " " }).success).toBe(false);
+ });
+ it.each([
+ { tagline: "x".repeat(181) },
+ { startDate: "2026-02-30" },
+ { stage: "draft" },
+ { resourceLinks: [{ type: "GitHub", url: "javascript:alert(1)" }] },
+ { demoMedia: ["//evil.example/image.png"] },
+ { demoMedia: ["/api/auth/magic-link/verify?token=abc"] },
+ { demoMedia: ["/api/projects/p1/media/../../secret.png"] },
+ { nonprofitPartnerPhoto: "/logo.svg" },
+ { isDraft: false },
+ { createdBy: "other-user" },
+ { lastUpdated: "2026-01-01" },
+ { pendingChanges: {} },
+ {
+ teamMembers: [
+ { userId: "u", role: "Dev" },
+ { userId: "u", role: "Dev" },
+ ],
+ },
+ ])("rejects malformed or server-owned fields: %j", (input) => {
+ expect(patchSchema.safeParse(input).success).toBe(false);
+ });
+ it("accepts snake_case input without ambiguous aliases", () => {
+ expect(
+ patchSchema.parse(
+ normalizeInput({
+ chapter_id: "c1",
+ team_members: [{ user_id: "u", role: "Dev" }],
+ })
+ )
+ ).toEqual({ chapterId: "c1", teamMembers: [{ userId: "u", role: "Dev" }] });
+ expect(() => normalizeInput({ chapterId: "c1", chapter_id: "c2" })).toThrow(
+ "Duplicate field"
+ );
+ });
+});
diff --git a/src/lib/projects/validation.ts b/src/lib/projects/validation.ts
new file mode 100644
index 0000000..5953dc9
--- /dev/null
+++ b/src/lib/projects/validation.ts
@@ -0,0 +1,194 @@
+import { z } from "zod";
+
+export const stages = [
+ "design",
+ "development",
+ "launched",
+ "maintenance",
+] as const;
+const text = z.string().trim().max(20000);
+const optionalText = text.nullable().optional();
+const httpUrl = z.url().refine((value) => {
+ try {
+ return ["http:", "https:"].includes(new URL(value).protocol);
+ } catch {
+ return false;
+ }
+}, "Use an HTTP or HTTPS URL");
+// Local paths must point at a file uploaded through the project media API.
+// Any other same-site path would be rendered as / for every
+// viewer, which could trigger app URLs (e.g. a sign-in link) on their behalf.
+const uploadedMediaPath =
+ /^\/api\/projects\/[\w-]+\/media\/[\da-f-]{36}\.(png|jpg|webp|gif|mp4|webm)$/;
+const mediaUrl = z
+ .string()
+ .max(2000)
+ .refine((value) => {
+ if (uploadedMediaPath.test(value)) return true;
+ return httpUrl.safeParse(value).success;
+ }, "Use an uploaded file or an HTTP(S) URL");
+const date = z
+ .string()
+ .regex(/^\d{4}-\d{2}-\d{2}$/, "Use YYYY-MM-DD")
+ .refine((value) => {
+ const parsed = new Date(`${value}T00:00:00Z`);
+ return (
+ !Number.isNaN(parsed.getTime()) &&
+ parsed.toISOString().slice(0, 10) === value
+ );
+ }, "Invalid calendar date");
+export const patchSchema = z
+ .object({
+ name: z.string().trim().max(200).optional(),
+ chapterId: z.string().min(1).max(200).optional(),
+ stage: z.enum(stages).optional(),
+ tagline: z.string().trim().max(180).nullable().optional(),
+ techStack: z.array(z.string().trim().min(1).max(100)).max(100).optional(),
+ causeAreas: z.array(z.string().trim().min(1).max(100)).max(100).optional(),
+ nonprofitPartnerId: z.string().trim().max(200).nullable().optional(),
+ nonprofitPartnerName: z.string().trim().max(200).nullable().optional(),
+ nonprofitPartnerPhoto: mediaUrl.nullable().optional(),
+ startDate: date.nullable().optional(),
+ endDate: date.nullable().optional(),
+ problemStatement: optionalText,
+ goalStatement: optionalText,
+ solutionDescription: optionalText,
+ demoMedia: z.array(mediaUrl).max(50).optional(),
+ teamMembers: z
+ .array(
+ z
+ .object({
+ userId: z.string().min(1).max(200),
+ memberId: z.string().min(1).max(200).nullable().optional(),
+ role: z.string().trim().max(100),
+ })
+ .strict()
+ )
+ .max(100)
+ .refine(
+ (rows) =>
+ new Set(rows.map((row) => `${row.userId}\0${row.role}`)).size ===
+ rows.length,
+ "Duplicate team member and role"
+ )
+ .optional(),
+ resourceLinks: z
+ .array(
+ z
+ .object({
+ type: z.enum(["Slack", "GitHub", "GoogleDrive", "Other"]),
+ url: httpUrl.max(2000),
+ })
+ .strict()
+ )
+ .max(100)
+ .optional(),
+ })
+ .strict();
+export const createSchema = patchSchema.extend({
+ name: z.string().trim().min(1).max(200),
+});
+export type ProjectPatch = z.infer;
+
+// The PRD names fields in snake_case; Prisma and the app use camelCase. Support
+// both at the boundary, and reject ambiguous aliases instead of overriding them.
+const aliases: Record = {
+ chapter_id: "chapterId",
+ tech_stack: "techStack",
+ cause_areas: "causeAreas",
+ nonprofit_partner_id: "nonprofitPartnerId",
+ nonprofit_partner_name: "nonprofitPartnerName",
+ nonprofit_partner_photo: "nonprofitPartnerPhoto",
+ start_date: "startDate",
+ end_date: "endDate",
+ problem_statement: "problemStatement",
+ goal_statement: "goalStatement",
+ solution_description: "solutionDescription",
+ demo_media: "demoMedia",
+ team_members: "teamMembers",
+ resource_links: "resourceLinks",
+ user_id: "userId",
+};
+export function normalizeInput(input: unknown): unknown {
+ if (Array.isArray(input)) return input.map(normalizeInput);
+ if (!input || typeof input !== "object") return input;
+ const output: Record = {};
+ for (const [key, value] of Object.entries(input)) {
+ const target = aliases[key] ?? key;
+ if (Object.hasOwn(output, target))
+ throw new Error(`Duplicate field: ${target}`);
+ Object.defineProperty(output, target, {
+ value: normalizeInput(value),
+ enumerable: true,
+ configurable: true,
+ });
+ }
+ return output;
+}
+
+export const requiredByStage = {
+ design: [
+ "name",
+ "tagline",
+ "nonprofitPartner",
+ "startDate",
+ "problemStatement",
+ "goalStatement",
+ "teamMembers",
+ ],
+ development: [
+ "name",
+ "tagline",
+ "nonprofitPartner",
+ "startDate",
+ "problemStatement",
+ "goalStatement",
+ "teamMembers",
+ "solutionDescription",
+ "resourceLinks",
+ ],
+ launched: [
+ "name",
+ "tagline",
+ "nonprofitPartner",
+ "startDate",
+ "problemStatement",
+ "goalStatement",
+ "teamMembers",
+ "solutionDescription",
+ "resourceLinks",
+ ],
+ maintenance: [
+ "name",
+ "tagline",
+ "nonprofitPartner",
+ "startDate",
+ "problemStatement",
+ "goalStatement",
+ "teamMembers",
+ "solutionDescription",
+ "resourceLinks",
+ ],
+} as const;
+
+// PATCH checks formats only. These requirements are exclusively for publish.
+export function missingPublishFields(project: ProjectPatch): string[] {
+ const missing: string[] = [];
+ for (const field of requiredByStage[project.stage ?? "design"]) {
+ if (field === "nonprofitPartner") {
+ if (
+ !project.nonprofitPartnerId?.trim() &&
+ !project.nonprofitPartnerName?.trim()
+ )
+ missing.push(field);
+ } else if (field === "teamMembers") {
+ if (!project.teamMembers?.length) missing.push(field);
+ project.teamMembers?.forEach((member, index) => {
+ if (!member.role.trim()) missing.push(`teamMembers.${index}.role`);
+ });
+ } else if (field === "resourceLinks") {
+ if (!project.resourceLinks?.length) missing.push(field);
+ } else if (!project[field]?.trim()) missing.push(field);
+ }
+ return missing;
+}
diff --git a/tests/projects.browser.int.test.ts b/tests/projects.browser.int.test.ts
new file mode 100644
index 0000000..a6b0dbf
--- /dev/null
+++ b/tests/projects.browser.int.test.ts
@@ -0,0 +1,512 @@
+import { chromium, type Browser, type Page } from "@playwright/test";
+import { PrismaClient, type Prisma, type Role } from "@prisma/client";
+import { PrismaPg } from "@prisma/adapter-pg";
+import { it } from "vitest";
+import assert from "node:assert/strict";
+import { randomUUID } from "node:crypto";
+it("covers project browsing, mobile keyboard use and Lead/Admin publishing", async () => {
+ const databaseUrl = process.env.DATABASE_URL;
+ if (!databaseUrl)
+ throw new Error(
+ "DATABASE_URL is required for the isolated browser fixtures"
+ );
+ const database = new URL(databaseUrl);
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(database.hostname))
+ throw new Error("Browser tests need a local DATABASE_URL");
+ const db = new PrismaClient({
+ adapter: new PrismaPg({ connectionString: databaseUrl }),
+ });
+ const origin = process.env.PROJECT_E2E_URL || "http://localhost:3108";
+ if (!["localhost", "127.0.0.1", "[::1]"].includes(new URL(origin).hostname))
+ throw new Error(
+ "Browser checks require a local app using the isolated test database"
+ );
+ const prefix = `T8-${Date.now()}`,
+ own = prefix + "-one",
+ other = prefix + "-two";
+ let browser!: Browser;
+ const users: string[] = [],
+ errors: string[] = [];
+ async function actor(role: Role, chapterId: string | null) {
+ const u = await db.user.create({
+ data: { email: `${prefix}-${role}@example.org`, role, chapterId },
+ });
+ users.push(u.id);
+ const id = randomUUID();
+ await db.session.create({
+ data: { id, userId: u.id, expiresAt: new Date(Date.now() + 3600000) },
+ });
+ const c = await browser.newContext({
+ viewport: { width: 1280, height: 900 },
+ colorScheme: "light",
+ });
+ await c.addCookies([{ name: "sessionToken", value: id, url: origin }]);
+ return c;
+ }
+ async function settle(page: Page, params: Record) {
+ await page.waitForFunction((expected) => {
+ const p = new URLSearchParams(location.search);
+ return Object.entries(expected).every(([k, v]) => p.get(k) === v);
+ }, params);
+ await page
+ .getByText("Updating projects…", { exact: true })
+ .waitFor({ state: "hidden" });
+ }
+ try {
+ browser = await chromium.launch({
+ headless: true,
+ ...(process.env.CHROMIUM_EXECUTABLE
+ ? { executablePath: process.env.CHROMIUM_EXECUTABLE }
+ : {}),
+ });
+ await db.chapter.createMany({
+ data: [
+ { id: own, name: prefix + " Chapter" },
+ { id: other, name: prefix + " Other" },
+ ],
+ });
+ const member = await actor("MEMBER", own);
+ const admin = await actor("NATIONAL_ADMIN", null);
+ assert.equal(
+ (await member.request.get(origin + "/api/projects")).status(),
+ 200,
+ "App must use the same isolated database as these fixture sessions"
+ );
+ const base = {
+ chapterId: own,
+ createdBy: users[1],
+ stage: "development" as const,
+ isDraft: false,
+ causeAreas: ["Education"],
+ techStack: ["React"],
+ startDate: new Date("2026-01-01"),
+ endDate: new Date("2026-03-01"),
+ lastUpdated: new Date("2026-10-01"),
+ };
+ const ids = [];
+ for (const [name, data] of [
+ ["Alpha", {}],
+ ["Beta", { stage: "design" }],
+ ["Gamma", { endDate: new Date("2027-04-01") }],
+ ["Delta", { causeAreas: ["Health"] }],
+ ["Epsilon", { chapterId: other }],
+ ["Hidden", { isDraft: true, causeAreas: ["Private draft tag"] }],
+ ] as [string, Partial][])
+ ids.push(
+ (
+ await db.project.create({
+ data: { ...base, name: prefix + " " + name, ...data },
+ })
+ ).id
+ );
+ const p = await member.newPage();
+ p.setDefaultTimeout(15000);
+ p.on("pageerror", (e) => errors.push(e.message));
+ await p.goto(origin + `/projects?q=${prefix}&page_size=2&sort=name`);
+ assert.equal(
+ await p.getByText("Notion project directory", { exact: true }).count(),
+ 0
+ );
+ const region = p.getByRole("region", { name: "Project records" });
+ await region
+ .getByRole("status")
+ .filter({ hasText: "Results: 5" })
+ .waitFor();
+ assert.equal(await region.locator("li").count(), 2);
+ assert.ok(!(await region.innerText()).includes("Hidden"));
+ assert.equal(
+ await p.getByRole("combobox", { name: "Chapter", exact: true }).count(),
+ 0
+ );
+ await p.getByText("Filter", { exact: true }).click();
+ assert.ok(
+ !(
+ await p
+ .getByRole("combobox", { name: "Impact area", exact: true })
+ .innerText()
+ ).includes("Private draft tag")
+ );
+ await p.getByRole("link", { name: "Next page", exact: true }).click();
+ await settle(p, { page: "2", q: prefix, sort: "name", page_size: "2" });
+ assert.equal(await region.locator("li").count(), 2);
+ await p.getByText("Filter", { exact: true }).click();
+ await p
+ .getByRole("combobox", { name: "Chapter", exact: true })
+ .selectOption(own);
+ await settle(p, { chapter_id: own });
+ assert.equal(new URL(p.url()).searchParams.has("page"), false);
+ await p
+ .getByRole("combobox", { name: "Stage", exact: true })
+ .selectOption("development");
+ await settle(p, { stage: "development" });
+ await p
+ .getByRole("combobox", { name: "Project length", exact: true })
+ .selectOption("short");
+ await settle(p, { project_length: "short" });
+ await p
+ .getByRole("combobox", { name: "Impact area", exact: true })
+ .selectOption("Education");
+ await settle(p, { impact_area: "Education" });
+ await region
+ .getByRole("status")
+ .filter({ hasText: "Results: 1" })
+ .waitFor();
+ assert.ok((await region.innerText()).includes(prefix + " Alpha"));
+ const chip = p.getByRole("link", {
+ name: "Remove Stage: development",
+ exact: true,
+ });
+ await chip.focus();
+ await p.keyboard.press("Enter");
+ await p
+ .getByRole("link", { name: "Remove Stage: development", exact: true })
+ .waitFor({ state: "hidden" });
+ await region
+ .getByRole("status")
+ .filter({ hasText: "Results: 2" })
+ .waitFor();
+ assert.equal(new URL(p.url()).searchParams.get("chapter_id"), own);
+ // The Filter panel stays open while filters apply; close it like a user
+ // would before reaching the chips underneath.
+ await p.keyboard.press("Escape");
+ await p.getByRole("link", { name: "Clear filters", exact: true }).click();
+ await p
+ .getByRole("combobox", {
+ name: "Search projects or chapters",
+ exact: true,
+ })
+ .fill(prefix + " Alpha");
+ await settle(p, { q: prefix + " Alpha" });
+ await region
+ .getByRole("status")
+ .filter({ hasText: "Results: 1" })
+ .waitFor();
+ const search = p.getByRole("combobox", {
+ name: "Search projects or chapters",
+ exact: true,
+ });
+ await search.fill(prefix + " Chapter");
+ await settle(p, { q: prefix + " Chapter" });
+ await region
+ .getByRole("status")
+ .filter({ hasText: "Results: 4" })
+ .waitFor();
+ assert.ok(
+ await p
+ .locator("#project-chapter-suggestions option")
+ .evaluateAll(
+ (nodes, text) =>
+ nodes.some((n) => (n as HTMLOptionElement).value === text),
+ prefix + " Chapter"
+ )
+ );
+ await search.fill(prefix + " Missing");
+ await settle(p, { q: prefix + " Missing" });
+ await p
+ .getByRole("heading", {
+ name: "No projects match these filters",
+ exact: true,
+ })
+ .waitFor();
+ await region
+ .getByRole("status")
+ .filter({ hasText: "Results: 0" })
+ .waitFor();
+ console.log(
+ "PASS: all combined filters, search, chapter suggestions, removable chips via keyboard, exact counts, pagination, draft/tag privacy, empty state"
+ );
+ for (const width of [320, 390, 768, 1280]) {
+ await p.setViewportSize({ width, height: 900 });
+ await p.goto(origin + `/projects?q=${prefix}`);
+ await region
+ .getByRole("status")
+ .filter({ hasText: "Results: 5" })
+ .waitFor();
+ assert.equal(
+ await p.evaluate(
+ () => document.documentElement.scrollWidth <= innerWidth
+ ),
+ true,
+ `No horizontal page overflow at ${width}`
+ );
+ const controls = p.getByRole("form", {
+ name: "Search and filter projects",
+ });
+ for (const select of await controls
+ .locator("input[type=search],select:visible,button:visible,summary")
+ .all()) {
+ const box = await select.boundingBox();
+ assert.ok(box && box.width >= 44 && box.height >= 44);
+ }
+ await p.screenshot({
+ path: `${process.env.TMPDIR || "/tmp"}/projects-browser-${width}.png`,
+ });
+ }
+ await p.setViewportSize({ width: 390, height: 900 });
+ await p.goto(origin + "/projects");
+ await search.focus();
+ await p.keyboard.press("Tab");
+ assert.equal(
+ await p
+ .locator("summary")
+ .first()
+ .evaluate((e) => e === document.activeElement),
+ true
+ );
+ await p.keyboard.press("Enter");
+ await p.keyboard.press("Tab");
+ assert.equal(
+ await p
+ .getByRole("combobox", { name: "Chapter", exact: true })
+ .evaluate((e) => e === document.activeElement),
+ true
+ );
+ await p.keyboard.press("Escape");
+ assert.equal(await p.locator("details[open]").count(), 0);
+ assert.equal(
+ await p
+ .locator("summary")
+ .first()
+ .evaluate((e) => e === document.activeElement),
+ true
+ );
+ await p.getByText("Sort", { exact: true }).click();
+ await p
+ .getByRole("combobox", { name: "Sort projects", exact: true })
+ .selectOption("name");
+ await settle(p, { sort: "name" });
+ await search.click();
+ assert.equal(await p.locator("details[open]").count(), 0);
+ const ap = await admin.newPage();
+ await ap.setViewportSize({ width: 320, height: 900 });
+ await ap.goto(origin + `/projects?q=${prefix}`);
+ assert.equal(
+ await ap.evaluate(
+ () => document.documentElement.scrollWidth <= innerWidth
+ ),
+ true,
+ "Admin header mobile overflow"
+ );
+ await ap.getByRole("link", { name: "+ Add Project", exact: true }).click();
+ await ap.locator("#project-name").waitFor();
+ assert.equal(
+ await ap.evaluate(
+ () => document.documentElement.scrollWidth <= innerWidth
+ ),
+ true,
+ "Editor mobile overflow"
+ );
+ await ap.screenshot({
+ path: `${process.env.TMPDIR || "/tmp"}/projects-browser-editor-320.png`,
+ });
+ console.log(
+ "PASS: 320/390/768/1280 layouts, control sizes, keyboard tab order, mobile admin entry and editor"
+ );
+ const lead = await actor("PROJECT_LEAD", own);
+ const memberRecord = await db.member.create({
+ data: {
+ userId: users[0],
+ chapterId: own,
+ displayName: prefix + " Developer",
+ approvalStatus: "APPROVED",
+ },
+ });
+ await db.member.update({
+ where: { id: memberRecord.id },
+ data: { directoryOptIn: true },
+ });
+ for (const [role, context] of [
+ ["Lead", lead],
+ ["Admin", admin],
+ ] as const) {
+ const page = await context.newPage();
+ page.on("pageerror", (e) => errors.push(e.message));
+ page.on("dialog", (d) => d.accept());
+ await page.setViewportSize({ width: 390, height: 900 });
+ await page.goto(origin + "/projects/new");
+ if (role === "Admin")
+ await page.locator("#project-chapterId").selectOption(own);
+ const title = prefix + " " + role + " publication";
+ await page.locator("#project-name").fill(title);
+ const saved = page
+ .locator("form")
+ .getByRole("status")
+ .filter({ hasText: "Draft saved · Just now" });
+ await saved.waitFor();
+ const id = page.url().split("/").at(-2);
+ assert.equal(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= innerWidth
+ ),
+ true,
+ "Saved draft actions fit mobile"
+ );
+ assert.equal(
+ (await member.request.get(origin + `/api/projects/${id}`)).status(),
+ 404
+ );
+ await page.goto(origin + "/projects/drafts");
+ await page
+ .getByRole("listitem")
+ .filter({
+ has: page.getByRole("heading", { name: title, exact: true }),
+ })
+ .getByRole("link", { name: "Resume draft", exact: true })
+ .click();
+ await page
+ .getByRole("button", { name: "Publish Changes", exact: true })
+ .first()
+ .click();
+ await page.locator("#project-tagline-error").waitFor();
+ await page.getByRole("button", { name: /Development/ }).click();
+ await page.locator("#project-tagline").fill("Community tools");
+ await page.locator("#project-startDate").fill("2026-01-01");
+ await page.locator("#project-endDate").fill("2026-04-01");
+ await page
+ .locator("#project-problemStatement")
+ .fill("Volunteer coordination is manual.");
+ await page.locator("#project-goalStatement").fill("Help more families.");
+ await page
+ .locator("#project-solutionDescription")
+ .fill("An accessible shared portal.");
+ await page.route("**/api/projects/references/partners?*", (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify(
+ role === "Lead"
+ ? {
+ available: true,
+ partners: [
+ {
+ id: "fixture-partner",
+ name: prefix + " Partner",
+ photo: null,
+ },
+ ],
+ }
+ : { available: false, partners: [] }
+ ),
+ })
+ );
+ await page
+ .locator("#project-nonprofitPartnerName")
+ .fill(prefix + " Partner");
+ if (role === "Lead")
+ await page
+ .getByRole("option", { name: prefix + " Partner", exact: true })
+ .click();
+ else
+ await page
+ .getByText(
+ "Partner Directory unavailable. You can save this name as free text.",
+ { exact: true }
+ )
+ .waitFor();
+ await page
+ .getByRole("button", { name: "+ Add Team Member", exact: true })
+ .click();
+ await page.locator("#project-teamMembers-0-userId").fill(prefix);
+ await page
+ .getByRole("option", { name: new RegExp(prefix + " Developer") })
+ .click();
+ await page.locator("#project-teamMembers-0-role").fill("Developer");
+ await page
+ .getByRole("button", { name: "+ Add Link", exact: true })
+ .click();
+ await page.locator("#project-resourceLinks-0-url").fill("not a url");
+ await page
+ .getByRole("button", { name: "Save Draft", exact: true })
+ .first()
+ .click();
+ await page.locator("#project-resourceLinks-0-url-error").waitFor();
+ await page
+ .locator("#project-resourceLinks-0-url")
+ .fill("https://example.org/code");
+ await page
+ .getByRole("button", { name: "Publish Changes", exact: true })
+ .first()
+ .click();
+ await page.waitForURL(origin + `/projects/${id}`);
+ await page.getByRole("heading", { name: title, exact: true }).waitFor();
+ assert.equal(
+ (
+ await (
+ await member.request.get(origin + `/api/projects/${id}`)
+ ).json()
+ ).isDraft,
+ false
+ );
+ await page.getByRole("link", { name: "Edit", exact: true }).click();
+ await page.locator("#project-tagline").fill("Private revision");
+ await saved.waitFor();
+ assert.equal(
+ (
+ await (
+ await member.request.get(origin + `/api/projects/${id}`)
+ ).json()
+ ).tagline,
+ "Community tools"
+ );
+ await page.reload();
+ assert.equal(
+ await page.locator("#project-tagline").inputValue(),
+ "Private revision"
+ );
+ await page
+ .getByRole("button", { name: "Publish Changes", exact: true })
+ .first()
+ .click();
+ await page.waitForURL(origin + `/projects/${id}`);
+ assert.equal(
+ (
+ await (
+ await member.request.get(origin + `/api/projects/${id}`)
+ ).json()
+ ).tagline,
+ "Private revision"
+ );
+ if (role === "Admin") {
+ await page
+ .getByRole("button", { name: "Delete Project", exact: true })
+ .click();
+ await page.getByRole("button", { name: "Cancel", exact: true }).click();
+ assert.ok(await db.project.findUnique({ where: { id } }));
+ await page
+ .getByRole("button", { name: "Delete Project", exact: true })
+ .click();
+ await page
+ .getByRole("button", { name: "Delete permanently", exact: true })
+ .click();
+ await page.waitForURL(origin + "/projects");
+ assert.equal(await db.project.findUnique({ where: { id } }), null);
+ } else
+ assert.equal(
+ await page
+ .getByRole("button", { name: "Delete Project", exact: true })
+ .count(),
+ 0
+ );
+ console.log(
+ `PASS: ${role} mobile create → autosave → resume → validation → member/partner selectors → publish → private edit → republish`
+ );
+ }
+ assert.deepEqual(errors, []);
+ } catch (e) {
+ console.log("BROWSER ERRORS", errors);
+ for (const c of browser?.contexts() || [])
+ for (const p of c.pages())
+ console.log(
+ p.url(),
+ (await p.locator("body").innerText()).slice(-2200)
+ );
+ throw e;
+ } finally {
+ await browser?.close();
+ await db.project.deleteMany({ where: { chapterId: { in: [own, other] } } });
+ await db.member.deleteMany({ where: { userId: { in: users } } });
+ await db.user.deleteMany({ where: { id: { in: users } } });
+ await db.chapter.deleteMany({ where: { id: { in: [own, other] } } });
+ await db.$disconnect();
+ }
+}, 180_000);
diff --git a/vitest.browser.config.mts b/vitest.browser.config.mts
new file mode 100644
index 0000000..2026809
--- /dev/null
+++ b/vitest.browser.config.mts
@@ -0,0 +1,12 @@
+import { defineConfig } from "vitest/config";
+
+// Explicit opt-in: requires a running local app connected to the same isolated
+// DATABASE_URL. Do not load .env.local (which usually points at the normal DB).
+export default defineConfig({
+ test: {
+ environment: "node",
+ include: ["tests/projects.browser.int.test.ts"],
+ fileParallelism: false,
+ testTimeout: 180_000,
+ },
+});