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 ( -
- - - - -
+ ); } 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 && ( +
+

Resource Links

+ +
+ )} +
+
+
+ ); } 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 ? ( + + ) : ( +

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. +

+
+ + + 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 ( -
- - - - -
+ ); } 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 (
- - - -
- +
+

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 && ( + + )}
); 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 ( -