diff --git a/.env.example b/.env.example index cd38ec4..82cf41b 100644 --- a/.env.example +++ b/.env.example @@ -1,8 +1,9 @@ # Local PostgreSQL, supplied by `docker compose up -d postgres minio`. -DATABASE_URL="postgresql://sidecause:sidecause@localhost:5432/sidecause?schema=public" +DATABASE_URL="postgresql://sidecause:sidecause@localhost:5433/sidecause?schema=public" # Local S3-compatible object storage, supplied by AIStor. S3_ENDPOINT="http://localhost:9000" +S3_REGION="us-east-1" S3_BUCKET="sidecause" S3_ACCESS_KEY_ID="minioadmin" S3_SECRET_ACCESS_KEY="minioadmin" diff --git a/AGENTS.md b/AGENTS.md index 4ce11a6..e0823ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,7 +45,7 @@ npm run test:smoke ## Docker lifecycle -Start local services with `npm run docker:up`, apply migrations with `npm run prisma:deploy`, and optionally add local sample records with `npm run db:seed:examples`. Stop services with `npm run docker:down`; this retains named volumes. The example seed is limited to local database hosts. The smoke test uses a separate Compose project and removes its volumes automatically. Run `docker compose down --volumes` only when intentionally resetting local PostgreSQL and AIStor data. Start the profile-gated application container with `docker compose --profile app up --build`. +Start local services with `npm run docker:up`, apply migrations with `npm run prisma:deploy`, and optionally add local sample records with `npm run db:seed:examples`. PostgreSQL is published on host port `5433` to avoid common local database port conflicts; it listens on `5432` inside Compose. Stop services with `npm run docker:down`; this retains named volumes. The example seed is limited to local database hosts. The smoke test uses a separate Compose project and removes its volumes automatically. Run `docker compose down --volumes` only when intentionally resetting local PostgreSQL and AIStor data. Start the profile-gated application container with `docker compose --profile app up --build`. ## Change checklist diff --git a/README.md b/README.md index 9bc2e02..4537e42 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ This repository contains the development foundation and initial App Router shell npm ci ``` -4. Start local PostgreSQL on `5432` and AIStor on `9000` (console `9001`). +4. Start local PostgreSQL on host port `5433` and AIStor on `9000` (console `9001`). PostgreSQL listens on `5432` inside Compose; host port `5433` avoids collisions with other local databases. ```sh npm run docker:up @@ -89,7 +89,7 @@ Dependabot checks npm, Docker, and GitHub Actions dependencies weekly. Releases ## Troubleshooting - **`npm ci` rejects the lockfile:** use Node `26.8.2` and npm 11, then retry without editing `package-lock.json`. -- **A local port is occupied:** free or remap port `5432`, `9000`, or `9001` before starting Compose. Update `.env` if you remap a service used by application code. +- **A local port is occupied:** free or remap host port `5433`, `9000`, or `9001` before starting Compose. Update `.env` if you remap a service used by application code. - **Docker permission/daemon error:** start Docker Desktop (or the Docker daemon) and ensure your account can run `docker compose`. - **Prisma reports `DATABASE_URL` missing:** copy `.env.example` to `.env`, then run the command from the repository root. diff --git a/app/api/bounties/route.ts b/app/api/bounties/route.ts new file mode 100644 index 0000000..fe7b042 --- /dev/null +++ b/app/api/bounties/route.ts @@ -0,0 +1,147 @@ +import { randomUUID } from 'node:crypto' + +import { Prisma } from '../../../generated/prisma/client' +import { auth } from '../../../auth' +import { + maxBountyImageBytes, + parseBountyCreationInput, + validateBountyImage, +} from '../../../lib/bounty-creation-input' +import { deleteObject, uploadObject } from '../../../lib/object-storage' +import { prisma } from '../../../lib/prisma' + +export async function POST(request: Request) { + const session = await auth() + const posterId = session?.user?.id + if (!posterId) { + return apiError(401, 'UNAUTHENTICATED', 'Sign in to create a post.') + } + + const declaredLength = Number(request.headers.get('content-length') ?? 0) + if (declaredLength > maxBountyImageBytes + 64 * 1024) { + return apiError( + 422, + 'VALIDATION_ERROR', + 'The image must be 5 MB or smaller.', + ) + } + + let formData: FormData + try { + formData = await request.formData() + } catch { + return apiError(422, 'VALIDATION_ERROR', 'Enter valid post details.') + } + + const parsed = parseBountyCreationInput(formData) + if ('error' in parsed) { + return apiError(422, 'VALIDATION_ERROR', parsed.error) + } + + const imageValue = formData.get('image') + let upload: { + key: string + url: string + type: string + body: Uint8Array + } | null = null + + if (imageValue instanceof File && imageValue.size > 0) { + const validatedImage = await validateBountyImage(imageValue) + if (!validatedImage) { + return apiError( + 422, + 'VALIDATION_ERROR', + 'Choose a JPEG, PNG, or WebP image smaller than 5 MB.', + ) + } + const key = `bounties/${randomUUID()}.${validatedImage.extension}` + upload = { + key, + url: `/api/media/${key}`, + type: imageValue.type, + body: validatedImage.body, + } + } else if ( + imageValue && + typeof imageValue === 'string' && + imageValue !== '' + ) { + return apiError(422, 'VALIDATION_ERROR', 'Choose a valid image file.') + } + + try { + if (upload) { + await uploadObject(upload.key, upload.body, upload.type) + } + + const bounty = await prisma.bounty.create({ + data: { + title: parsed.title, + description: parsed.description, + locationLabel: parsed.location, + imageUrl: upload?.url ?? null, + latitude: + parsed.latitude === null ? null : new Prisma.Decimal(parsed.latitude), + longitude: + parsed.longitude === null + ? null + : new Prisma.Decimal(parsed.longitude), + scheduledAt: parsed.scheduledAt, + deadline: parsed.deadline, + maxVolunteers: parsed.maximumVolunteers, + payPerVolunteer: new Prisma.Decimal(parsed.payPerVolunteer), + difficulty: parsed.difficulty, + posterId, + skillRequirements: { + create: parsed.skills, + }, + equipmentRequirements: { + create: parsed.equipment, + }, + }, + select: { + id: true, + title: true, + description: true, + locationLabel: true, + status: true, + imageUrl: true, + latitude: true, + longitude: true, + scheduledAt: true, + deadline: true, + maxVolunteers: true, + payPerVolunteer: true, + difficulty: true, + createdAt: true, + skillRequirements: { select: { name: true, level: true } }, + equipmentRequirements: { select: { name: true, level: true } }, + }, + }) + + return Response.json( + { + data: { + ...bounty, + payPerVolunteer: bounty.payPerVolunteer.toString(), + currentVolunteers: 0, + }, + }, + { status: 201 }, + ) + } catch { + if (upload) { + try { + await deleteObject(upload.key) + } catch { + // Keep the API response generic if cleanup cannot remove an orphan. + } + } + return apiError(500, 'INTERNAL_ERROR', 'The post could not be created.') + } +} + +function apiError(status: number, code: string, message: string) { + return Response.json({ error: { code, message, details: {} } }, { status }) +} diff --git a/app/api/media/[...key]/route.ts b/app/api/media/[...key]/route.ts new file mode 100644 index 0000000..3c7ba0b --- /dev/null +++ b/app/api/media/[...key]/route.ts @@ -0,0 +1,82 @@ +import { auth } from '../../../../auth' +import { canViewBounty } from '../../../../lib/bounty-visibility' +import { prisma } from '../../../../lib/prisma' +import { readObject } from '../../../../lib/object-storage' + +type MediaRouteProps = { + params: Promise<{ key: string[] }> +} + +export async function GET(_request: Request, { params }: MediaRouteProps) { + const { key: parts } = await params + const key = parts.join('/') + if (!isBountyImageKey(key)) return new Response(null, { status: 404 }) + + const imageUrl = `/api/media/${key}` + const session = await auth() + const viewerId = session?.user?.id ?? null + const bounty = await prisma.bounty.findFirst({ + where: { imageUrl }, + select: { + id: true, + status: true, + deadline: true, + posterId: true, + maxVolunteers: true, + volunteerAttendances: { + where: { volunteerId: viewerId ?? '' }, + select: { status: true }, + take: 1, + }, + _count: { + select: { + volunteerAttendances: { + where: { status: 'JOINED' }, + }, + }, + }, + }, + }) + + if ( + !bounty || + !canViewBounty({ + status: bounty.status, + deadline: bounty.deadline, + posterId: bounty.posterId, + viewerId, + viewerAttendance: bounty.volunteerAttendances[0]?.status ?? null, + currentVolunteers: bounty._count.volunteerAttendances, + maximumVolunteers: bounty.maxVolunteers, + }) + ) { + return new Response(null, { status: 404 }) + } + + try { + const image = await readObject(key) + if ( + !['image/jpeg', 'image/png', 'image/webp'].includes(image.contentType) + ) { + return new Response(null, { status: 404 }) + } + + const responseBody = new ArrayBuffer(image.body.byteLength) + new Uint8Array(responseBody).set(image.body) + + return new Response(responseBody, { + headers: { + 'Cache-Control': 'private, no-store', + 'Content-Length': String(image.body.byteLength), + 'Content-Type': image.contentType, + 'X-Content-Type-Options': 'nosniff', + }, + }) + } catch { + return new Response(null, { status: 404 }) + } +} + +function isBountyImageKey(key: string): boolean { + return /^bounties\/[0-9a-f-]{36}\.(?:jpg|png|webp)$/.test(key) +} diff --git a/app/posts/[id]/detail-data.ts b/app/posts/[id]/detail-data.ts index 9490505..687a2dc 100644 --- a/app/posts/[id]/detail-data.ts +++ b/app/posts/[id]/detail-data.ts @@ -1,3 +1,5 @@ +import { canViewBounty } from '../../../lib/bounty-visibility' + export type PostRequirement = { name: string level: 'REQUIRED' | 'RECOMMENDED' @@ -79,36 +81,33 @@ const databaseSource: PostDetailSource = { return null } - const now = new Date() - const viewerIsPoster = viewerId !== null && bounty.posterId === viewerId const viewerAttendance = bounty.volunteerAttendances[0]?.status ?? null - const viewerIsActiveAttendee = viewerAttendance === 'JOINED' const currentVolunteers = bounty._count.volunteerAttendances - - const openAndAvailable = - bounty.status === 'OPEN' && - bounty.deadline > now && - currentVolunteers < bounty.maxVolunteers - const fullAndUnexpired = bounty.status === 'FULL' && bounty.deadline > now - const finished = bounty.status === 'FINISHED' - const restrictedViewer = viewerIsPoster || viewerIsActiveAttendee - if ( - !openAndAvailable && - !(fullAndUnexpired && restrictedViewer) && - !(finished && restrictedViewer) + !canViewBounty({ + status: bounty.status, + deadline: bounty.deadline, + posterId: bounty.posterId, + viewerId, + viewerAttendance, + currentVolunteers, + maximumVolunteers: bounty.maxVolunteers, + }) ) { return null } - const posterEmail = restrictedViewer - ? (( - await prisma.user.findUnique({ - where: { id: bounty.posterId }, - select: { email: true }, - }) - )?.email ?? null) - : null + const viewerIsPoster = viewerId !== null && bounty.posterId === viewerId + const viewerIsActiveAttendee = viewerAttendance === 'JOINED' + const posterEmail = + viewerIsPoster || viewerIsActiveAttendee + ? (( + await prisma.user.findUnique({ + where: { id: bounty.posterId }, + select: { email: true }, + }) + )?.email ?? null) + : null return { id: bounty.id, diff --git a/app/posts/new/CreatePostForm.tsx b/app/posts/new/CreatePostForm.tsx new file mode 100644 index 0000000..e2bffa2 --- /dev/null +++ b/app/posts/new/CreatePostForm.tsx @@ -0,0 +1,138 @@ +'use client' + +import { useState, type FormEvent } from 'react' +import { useRouter } from 'next/navigation' + +import { CreatePostSpecifications } from './CreatePostSpecifications' +import { RequirementEditor, type RequirementRow } from './RequirementEditor' +import styles from './create.module.css' + +export function CreatePostForm({ accountEmail }: { accountEmail: string }) { + const router = useRouter() + const [skills, setSkills] = useState([{ id: 0 }]) + const [equipment, setEquipment] = useState([{ id: 0 }]) + const [pending, setPending] = useState(false) + const [error, setError] = useState('') + + async function handleSubmit(event: FormEvent) { + event.preventDefault() + if (pending) return + + const form = event.currentTarget + const data = new FormData(form) + for (const fieldName of ['scheduledAt', 'deadline']) { + const localDateTime = data.get(fieldName) + if (typeof localDateTime === 'string' && localDateTime) { + const date = new Date(localDateTime) + if (Number.isNaN(date.getTime())) { + setError('Enter a valid date and time.') + return + } + data.set(fieldName, date.toISOString()) + } + } + + setPending(true) + setError('') + + try { + const response = await fetch('/api/bounties', { + method: 'POST', + body: data, + }) + const result = (await response.json()) as { + error?: { message?: string } + } + + if (!response.ok) { + setError(result.error?.message ?? 'The post could not be created.') + setPending(false) + return + } + + router.replace('/posts') + } catch { + setError( + 'The post could not be created. Check your connection and try again.', + ) + setPending(false) + } + } + + function addRequirement( + rows: RequirementRow[], + setRows: (rows: RequirementRow[]) => void, + ) { + if (rows.length < 3) { + setRows([...rows, { id: Math.max(...rows.map((row) => row.id)) + 1 }]) + } + } + + function removeRequirement( + rows: RequirementRow[], + setRows: (rows: RequirementRow[]) => void, + id: number, + ) { + if (rows.length > 1) setRows(rows.filter((row) => row.id !== id)) + } + + return ( +
+
+
+

New community opportunity

+ + +