diff --git a/app/api/bounties/[id]/volunteers/route.ts b/app/api/bounties/[id]/volunteers/route.ts new file mode 100644 index 0000000..2af65ce --- /dev/null +++ b/app/api/bounties/[id]/volunteers/route.ts @@ -0,0 +1,65 @@ +import { auth } from '../../../../../auth' +import { + joinBounty, + withdrawFromBounty, + type AttendanceResult, +} from '../../../../../lib/bounties/attendance' + +type RouteContext = { params: Promise<{ id: string }> } + +export async function POST(_request: Request, { params }: RouteContext) { + const session = await auth() + const volunteerId = session?.user?.id + if (!volunteerId) { + return errorResponse( + 401, + 'UNAUTHENTICATED', + 'Sign in to join this opportunity.', + ) + } + + const { id } = await params + return resultResponse(joinBounty(id, volunteerId), 201) +} + +export async function DELETE(_request: Request, { params }: RouteContext) { + const session = await auth() + const volunteerId = session?.user?.id + if (!volunteerId) { + return errorResponse(401, 'UNAUTHENTICATED', 'Sign in to withdraw.') + } + + const { id } = await params + return resultResponse(withdrawFromBounty(id, volunteerId), 200) +} + +async function resultResponse( + resultPromise: Promise, + successStatus: number, +): Promise { + let result: AttendanceResult + try { + result = await resultPromise + } catch { + return errorResponse( + 500, + 'INTERNAL_ERROR', + 'We could not update your sign-up. Please try again.', + ) + } + + if (!result.ok) { + const status = result.code === 'BOUNTY_NOT_FOUND' ? 404 : 409 + return errorResponse(status, result.code, result.message) + } + + return Response.json({ data: { success: true } }, { status: successStatus }) +} + +function errorResponse( + status: number, + code: string, + message: string, +): Response { + return Response.json({ error: { code, message } }, { status }) +} diff --git a/app/login/LoginForm.tsx b/app/login/LoginForm.tsx index 268cc7c..3afa95e 100644 --- a/app/login/LoginForm.tsx +++ b/app/login/LoginForm.tsx @@ -5,7 +5,7 @@ import { useActionState, useState } from 'react' import { initialLoginFormState } from '../../lib/auth/form-state' import { loginAction } from './actions' -export function LoginForm() { +export function LoginForm({ returnTo = '/' }: { returnTo?: string }) { const [state, formAction, isPending] = useActionState( loginAction, initialLoginFormState, @@ -14,6 +14,7 @@ export function LoginForm() { return (
+ {state.error && (

{state.error} diff --git a/app/login/actions.ts b/app/login/actions.ts index 4c90b97..0a0e24e 100644 --- a/app/login/actions.ts +++ b/app/login/actions.ts @@ -7,6 +7,7 @@ import { initialLoginFormState, type LoginFormState, } from '../../lib/auth/form-state' +import { getSafePostReturnTo } from '../../lib/auth/return-to' import { validateLogin } from '../../lib/auth/validation' export async function loginAction( @@ -14,6 +15,7 @@ export async function loginAction( formData: FormData, ): Promise { const values = { email: String(formData.get('email') ?? '').trim() } + const returnTo = getSafePostReturnTo(formData.get('returnTo')) let credentials: { email: string; password: string } try { @@ -29,7 +31,7 @@ export async function loginAction( } try { - await signIn('credentials', { ...credentials, redirectTo: '/' }) + await signIn('credentials', { ...credentials, redirectTo: returnTo }) } catch (error) { if (error instanceof AuthError) { return { diff --git a/app/login/page.tsx b/app/login/page.tsx index ed7d4a3..e2f8cb6 100644 --- a/app/login/page.tsx +++ b/app/login/page.tsx @@ -1,18 +1,37 @@ import Link from 'next/link' +import { getSafePostReturnTo } from '../../lib/auth/return-to' import { LoginForm } from './LoginForm' -export default function LoginPage() { +type LoginPageProps = { + searchParams?: Promise<{ returnTo?: string }> +} + +export default async function LoginPage({ + searchParams = Promise.resolve({}), +}: LoginPageProps) { + const { returnTo: requestedReturnTo } = await searchParams + const returnTo = getSafePostReturnTo(requestedReturnTo) + return (

Welcome back!

Log In

- +

- New to SideCause? Create an account + New to SideCause?{' '} + + Create an account +

diff --git a/app/posts/[id]/VolunteerAction.tsx b/app/posts/[id]/VolunteerAction.tsx new file mode 100644 index 0000000..90192a0 --- /dev/null +++ b/app/posts/[id]/VolunteerAction.tsx @@ -0,0 +1,89 @@ +'use client' + +import Link from 'next/link' +import { useRouter } from 'next/navigation' +import { useState } from 'react' + +import styles from './detail.module.css' + +type VolunteerActionProps = { + bountyId: string + status: 'OPEN' | 'FULL' | 'FINISHED' + attendance: 'JOINED' | 'WITHDRAWN' | null + signedIn: boolean +} + +export function VolunteerAction({ + bountyId, + status, + attendance, + signedIn, +}: VolunteerActionProps) { + const router = useRouter() + const [pending, setPending] = useState(false) + const [error, setError] = useState(null) + const returnTo = `/posts/${bountyId}` + const accountHref = `/login?returnTo=${encodeURIComponent(returnTo)}` + + let label = 'Sign up' + let disabled = false + if (attendance === 'WITHDRAWN') { + label = 'Unenrolled' + disabled = true + } else if (status === 'FINISHED') { + label = attendance === 'JOINED' ? 'Unenroll' : 'Sign up' + disabled = true + } else if (status === 'FULL' && attendance !== 'JOINED') { + disabled = true + } else if (attendance === 'JOINED') { + label = 'Unenroll' + } + + if (!signedIn && !disabled) { + return ( + + Sign up + + ) + } + + async function updateAttendance() { + setPending(true) + setError(null) + try { + const response = await fetch(`/api/bounties/${bountyId}/volunteers`, { + method: attendance === 'JOINED' ? 'DELETE' : 'POST', + }) + const result = (await response.json()) as { + error?: { message?: string } + } + if (!response.ok) { + setError(result.error?.message ?? 'Your sign-up could not be updated.') + return + } + router.refresh() + } catch { + setError('Your sign-up could not be updated. Please try again.') + } finally { + setPending(false) + } + } + + return ( + <> + + {error && ( +

+ {error} +

+ )} + + ) +} diff --git a/app/posts/[id]/detail.module.css b/app/posts/[id]/detail.module.css index 11846fe..805b1e9 100644 --- a/app/posts/[id]/detail.module.css +++ b/app/posts/[id]/detail.module.css @@ -213,9 +213,12 @@ } .signupButton { + display: inline-flex; width: 100%; min-height: 2.75rem; margin-top: 1rem; + align-items: center; + justify-content: center; border: 1px solid var(--ink); border-radius: 0; color: var(--ink); @@ -223,6 +226,7 @@ font: inherit; font-weight: 700; cursor: pointer; + text-decoration: none; } .signupButton:hover { @@ -236,6 +240,17 @@ opacity: 0.7; } +.signupButton:focus-visible { + outline: 3px solid #236e69; + outline-offset: 3px; +} + +.signupError { + margin-top: 0.75rem; + color: #9b2f24; + font-weight: 700; +} + @media (min-width: 48rem) { .page { padding: 3rem; diff --git a/app/posts/[id]/page.tsx b/app/posts/[id]/page.tsx index 009d452..f38a845 100644 --- a/app/posts/[id]/page.tsx +++ b/app/posts/[id]/page.tsx @@ -4,6 +4,7 @@ import { notFound } from 'next/navigation' import { auth } from '../../../auth' import { getAccessiblePostDetail, type PostDifficulty } from './detail-data' +import { VolunteerAction } from './VolunteerAction' import styles from './detail.module.css' type PostDetailPageProps = { @@ -16,7 +17,6 @@ export default async function PostDetailPage({ params }: PostDetailPageProps) { const post = await getAccessiblePostDetail(id, session?.user?.id ?? null) if (!post) notFound() - const action = getPostAction(post.status, post.viewerAttendance) const statusClassName = { OPEN: styles.statusOpen, FULL: styles.statusFull, @@ -114,13 +114,12 @@ export default async function PostDetailPage({ params }: PostDetailPageProps) { - + @@ -193,32 +192,6 @@ function RequirementList({ ) } -function getPostAction( - status: 'OPEN' | 'FULL' | 'FINISHED', - attendance: 'JOINED' | 'WITHDRAWN' | null, -): { label: string; disabled: boolean } { - if (attendance === 'WITHDRAWN') { - return { label: 'Unenrolled', disabled: true } - } - - if (status === 'FINISHED') { - return { - label: attendance === 'JOINED' ? 'Unenroll' : 'Sign up', - disabled: true, - } - } - - if (status === 'FULL' && attendance !== 'JOINED') { - return { label: 'Sign up', disabled: true } - } - - if (attendance === 'JOINED') { - return { label: 'Unenroll', disabled: false } - } - - return { label: 'Sign up', disabled: false } -} - function formatStatus(status: 'OPEN' | 'FULL' | 'FINISHED'): string { return status.charAt(0) + status.slice(1).toLowerCase() } diff --git a/app/register/RegisterForm.tsx b/app/register/RegisterForm.tsx index 3240009..6db5407 100644 --- a/app/register/RegisterForm.tsx +++ b/app/register/RegisterForm.tsx @@ -5,7 +5,7 @@ import { useActionState, useState } from 'react' import { initialRegisterFormState } from '../../lib/auth/form-state' import { registerAction } from './actions' -export function RegisterForm() { +export function RegisterForm({ returnTo = '/' }: { returnTo?: string }) { const [state, formAction, isPending] = useActionState( registerAction, initialRegisterFormState, @@ -17,6 +17,7 @@ export function RegisterForm() { return ( + {state.error && (

{state.error} diff --git a/app/register/actions.ts b/app/register/actions.ts index de0c056..cd0e117 100644 --- a/app/register/actions.ts +++ b/app/register/actions.ts @@ -8,6 +8,7 @@ import { initialRegisterFormState, type RegisterFormState, } from '../../lib/auth/form-state' +import { getSafePostReturnTo } from '../../lib/auth/return-to' import { assertWithinAuthRateLimit } from '../../lib/auth/rate-limit' import { hashPassword } from '../../lib/auth/password' import { validateRegistration } from '../../lib/auth/validation' @@ -21,6 +22,7 @@ export async function registerAction( displayName: String(formData.get('displayName') ?? '').trim(), email: String(formData.get('email') ?? '').trim(), } + const returnTo = getSafePostReturnTo(formData.get('returnTo')) let input: { displayName: string; email: string; password: string } try { @@ -68,7 +70,7 @@ export async function registerAction( } try { - await signIn('credentials', { email, password, redirectTo: '/' }) + await signIn('credentials', { email, password, redirectTo: returnTo }) } catch (error) { if (error instanceof AuthError) { return { diff --git a/app/register/page.tsx b/app/register/page.tsx index 7e89410..688d7b3 100644 --- a/app/register/page.tsx +++ b/app/register/page.tsx @@ -1,18 +1,37 @@ import Link from 'next/link' +import { getSafePostReturnTo } from '../../lib/auth/return-to' import { RegisterForm } from './RegisterForm' -export default function RegisterPage() { +type RegisterPageProps = { + searchParams?: Promise<{ returnTo?: string }> +} + +export default async function RegisterPage({ + searchParams = Promise.resolve({}), +}: RegisterPageProps) { + const { returnTo: requestedReturnTo } = await searchParams + const returnTo = getSafePostReturnTo(requestedReturnTo) + return (

Join the cause

Create an Account

- +

- Already have an account? Log in + Already have an account?{' '} + + Log in +

diff --git a/docs/implementation-plan.md b/docs/implementation-plan.md index 335f5fe..43fef5b 100644 --- a/docs/implementation-plan.md +++ b/docs/implementation-plan.md @@ -118,11 +118,22 @@ pages and components, unit/integration/e2e tests. **Acceptance criteria:** -- [ ] A member can immediately join an open, unexpired bounty while capacity +- [x] The bounty detail page offers eligible volunteers a sign-up action. A + signed-out visitor is sent to the sign-in page, can sign in or create an + account, and returns to the same bounty detail page. Returning does not + join them automatically; they must select `Sign up` again. +- [x] A member can immediately join an open, unexpired bounty while capacity remains. -- [ ] A duplicate, late, or over-capacity join returns `409` and does not +- [x] The sign-up operation takes the volunteer ID from the authenticated + server session, creates one `BountyVolunteer` record linking that user + and bounty, queryable through both the bounty's and user's attendance + relations. +- [x] A duplicate, late, or over-capacity join returns `409` and does not exceed `maxVolunteers`. -- [ ] A joined volunteer can withdraw; withdrawing from a full bounty returns +- [x] After joining, the bounty action changes to `Unenroll`; selecting it + withdraws the member. After withdrawal, the action is disabled and reads + `Unenrolled`, because the member cannot rejoin that bounty. +- [x] A joined volunteer can withdraw; withdrawing from a full bounty returns it to `OPEN` and revokes access to the poster's contact information. **Verify:** Concurrent integration test for last-slot join attempts; browser diff --git a/docs/product-spec.md b/docs/product-spec.md index 922895f..16d4ed9 100644 --- a/docs/product-spec.md +++ b/docs/product-spec.md @@ -45,6 +45,17 @@ OPEN or FULL --deadline passes--> EXPIRED `OPEN`. - A member may sign up for a bounty only once. After withdrawing, they cannot sign up for that bounty again. +- The bounty detail page provides a sign-up action for eligible volunteers. + A visitor who selects it is sent to the sign-in page, where they can sign in + or create an account. After authentication, they return to the same bounty + detail page. Returning does not join them automatically; they select the + bounty's sign-up action again to join. +- After joining, the bounty action changes to `Unenroll`. After withdrawing, + it changes to disabled `Unenrolled`; that member cannot join the same bounty + again. +- A successful sign-up creates a volunteer-attendance record linking the + authenticated user and bounty. The relationship can be queried from either + the bounty or user record. - Only the poster may finish a bounty. Finishing requires no note, photograph, or attendee approval. - A poster may optionally verify a finished bounty. Verification is separate @@ -82,6 +93,12 @@ Each bounty has: - The poster, zero or more attending volunteers, status, creation time, finish time, optional verification time, and optional cancellation reason. +Volunteer sign-ups are stored in the relational `BountyVolunteer` table, with +foreign keys to both `User` and `Bounty`. The composite key prevents duplicate +sign-ups, and each model exposes the relation so joined bounties can be queried +from either side. The authenticated user ID comes from the server session; it +is never accepted from the sign-up form or request body. + Display names are public where a poster or attendee is shown. The poster's account email is available only to the poster and authenticated volunteers with active attendance on that bounty; withdrawing immediately revokes access. diff --git a/lib/auth/return-to.ts b/lib/auth/return-to.ts new file mode 100644 index 0000000..f881f8a --- /dev/null +++ b/lib/auth/return-to.ts @@ -0,0 +1,8 @@ +const postPathPattern = /^\/posts\/[A-Za-z0-9_-]{1,128}$/ + +export function getSafePostReturnTo(value: unknown): string { + if (typeof value === 'string' && postPathPattern.test(value)) { + return value + } + return '/' +} diff --git a/lib/bounties/attendance.ts b/lib/bounties/attendance.ts new file mode 100644 index 0000000..bebddab --- /dev/null +++ b/lib/bounties/attendance.ts @@ -0,0 +1,147 @@ +import type { Prisma } from '../../generated/prisma/client' +import { prisma } from '../prisma' + +export type AttendanceResult = + | { ok: true } + | { + ok: false + code: + | 'BOUNTY_NOT_FOUND' + | 'BOUNTY_NOT_OPEN' + | 'DEADLINE_PASSED' + | 'CAPACITY_REACHED' + | 'ALREADY_SIGNED_UP' + | 'NOT_JOINED' + message: string + } + +type TransactionClient = Prisma.TransactionClient + +async function lockBounty( + tx: TransactionClient, + bountyId: string, +): Promise { + const rows = await tx.$queryRaw>` + SELECT "id" FROM "Bounty" WHERE "id" = ${bountyId} FOR UPDATE + ` + return rows.length > 0 +} + +export async function joinBounty( + bountyId: string, + volunteerId: string, +): Promise { + return prisma.$transaction(async (tx) => { + if (!(await lockBounty(tx, bountyId))) { + return { + ok: false, + code: 'BOUNTY_NOT_FOUND', + message: 'This opportunity could not be found.', + } + } + + const bounty = await tx.bounty.findUniqueOrThrow({ + where: { id: bountyId }, + select: { status: true, deadline: true, maxVolunteers: true }, + }) + const previousAttendance = await tx.bountyVolunteer.findUnique({ + where: { bountyId_volunteerId: { bountyId, volunteerId } }, + select: { status: true }, + }) + + if (previousAttendance) { + return { + ok: false, + code: 'ALREADY_SIGNED_UP', + message: 'You cannot sign up for this opportunity again.', + } + } + if (bounty.status !== 'OPEN') { + return { + ok: false, + code: 'BOUNTY_NOT_OPEN', + message: 'This opportunity is no longer open for sign-ups.', + } + } + if (bounty.deadline <= new Date()) { + return { + ok: false, + code: 'DEADLINE_PASSED', + message: 'The sign-up deadline has passed.', + } + } + + const activeCount = await tx.bountyVolunteer.count({ + where: { bountyId, status: 'JOINED' }, + }) + if (activeCount >= bounty.maxVolunteers) { + return { + ok: false, + code: 'CAPACITY_REACHED', + message: 'All volunteer places have been filled.', + } + } + + await tx.bountyVolunteer.create({ data: { bountyId, volunteerId } }) + if (activeCount + 1 === bounty.maxVolunteers) { + await tx.bounty.update({ + where: { id: bountyId }, + data: { status: 'FULL' }, + }) + } + + return { ok: true } + }) +} + +export async function withdrawFromBounty( + bountyId: string, + volunteerId: string, +): Promise { + return prisma.$transaction(async (tx) => { + if (!(await lockBounty(tx, bountyId))) { + return { + ok: false, + code: 'BOUNTY_NOT_FOUND', + message: 'This opportunity could not be found.', + } + } + + const bounty = await tx.bounty.findUniqueOrThrow({ + where: { id: bountyId }, + select: { status: true }, + }) + const attendance = await tx.bountyVolunteer.findUnique({ + where: { bountyId_volunteerId: { bountyId, volunteerId } }, + select: { status: true }, + }) + + if (!attendance || attendance.status !== 'JOINED') { + return { + ok: false, + code: 'NOT_JOINED', + message: 'You are not currently signed up for this opportunity.', + } + } + if (bounty.status !== 'OPEN' && bounty.status !== 'FULL') { + return { + ok: false, + code: 'BOUNTY_NOT_OPEN', + message: 'This opportunity can no longer be changed.', + } + } + + await tx.bountyVolunteer.update({ + where: { bountyId_volunteerId: { bountyId, volunteerId } }, + data: { status: 'WITHDRAWN', withdrawnAt: new Date() }, + }) + if (bounty.status === 'FULL') { + await tx.bounty.update({ + where: { id: bountyId }, + data: { status: 'OPEN' }, + }) + } + + return { ok: true } + }) +} diff --git a/tests/unit/account-pages.test.tsx b/tests/unit/account-pages.test.tsx index 1806653..b0cfe65 100644 --- a/tests/unit/account-pages.test.tsx +++ b/tests/unit/account-pages.test.tsx @@ -17,8 +17,8 @@ import RegisterPage from '../../app/register/page' afterEach(cleanup) describe('account page templates', () => { - it('links the login page to account creation', () => { - render() + it('links the login page to account creation', async () => { + render(await LoginPage({})) expect( screen @@ -27,8 +27,8 @@ describe('account page templates', () => { ).toBe('/register') }) - it('links the account-creation page back to login', () => { - render() + it('links the account-creation page back to login', async () => { + render(await RegisterPage({})) expect( screen.getByRole('link', { name: 'Log in' }).getAttribute('href'), @@ -40,7 +40,7 @@ describe('account page templates', () => { error: 'The email address or password is incorrect.', values: { email: 'maya@example.com' }, }) - render() + render(await LoginPage({})) fireEvent.change(screen.getByLabelText('Email address'), { target: { value: 'maya@example.com' }, @@ -63,7 +63,7 @@ describe('account page templates', () => { 'An account already exists with this email address. Log in instead.', values: { displayName: 'Maya Chen', email: 'maya@example.com' }, }) - render() + render(await RegisterPage({})) fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Maya Chen' },