diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2b20df8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,40 @@ +name: CI +on: [push, pull_request] + +jobs: + server: + runs-on: ubuntu-latest + services: + mongo: + image: mongo:7 + ports: ["27017:27017"] + defaults: + run: + working-directory: server + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + cache-dependency-path: server/package-lock.json + - run: npm ci + - run: npm run typecheck + - run: npm test + + client: + runs-on: ubuntu-latest + defaults: + run: + working-directory: client + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: npm + cache-dependency-path: client/package-lock.json + - run: npm ci + - run: npm run lint + - run: npx tsc --noEmit + - run: npm run build diff --git a/.gitignore b/.gitignore index 3debacf..104d493 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,4 @@ yarn-debug.log* .agents/ client/AGENTS.md client/CLAUDE.md +.claude/ diff --git a/README.md b/README.md index 8f0ece7..99e9fe0 100644 --- a/README.md +++ b/README.md @@ -1,104 +1,180 @@ # EventHive -A full-stack event management platform where organizers create events and attendees discover & book tickets. +A full-stack event platform: organizers publish events and sell General and VIP tickets; attendees discover events, book seats, get QR-coded tickets, and review events they attended. -## Tech Stack +**Live demo:** https://event-hive-zeta.vercel.app + +## Tech stack | Layer | Technology | |-------|------------| -| Frontend | Next.js 14, TypeScript | -| Backend | Express, TypeScript | -| Database | MongoDB | -| Auth | JWT + bcrypt | -| Architecture | Layered (Controller → Service → Repository) | +| Frontend | Next.js 16 (App Router, server components, CSS Modules), TypeScript, Phosphor icons, qrcode.react | +| Backend | Express 5, TypeScript, zod validation | +| Database | MongoDB with Mongoose (indexes enforce one ticket and one review per user per event) | +| Auth | JWT, stored in an httpOnly cookie on the Next.js origin and forwarded to the API by a same-origin proxy | +| Tests / CI | `node:test` API suite against a local MongoDB, GitHub Actions | +| Architecture | Layered (Controller → Service → Repository) with a single error middleware | + +## Design system -## Project Structure +- **Palette:** the default light theme is colourful: each category owns one colour (music pink, tech blue, sports lime, art orange, food yellow, business violet, other teal) used on its cards, chips, rows and tickets, with ink buttons. The optional dark theme keeps a single stage-light magenta accent. Every text colour pair is at least 4.5:1; ratios are noted in `client/src/app/globals.css`. +- **Type:** Archivo (condensed via its width axis) for display, Geist for body and UI, Geist Mono for ticket codes. +- **Signature:** the admission ticket. Event cards, the booking panel, My Tickets and the organizer band use real notch cut-outs (CSS masks) and a perforated tear line. +- **Motion:** the landing page is deliberately loud: letters that pop in and jump under the cursor, a rotating colour-changing headline word, a cursor-following glow, parallax shapes, floating tickets with 3D tilt, magnetic buttons, crossing marquee bands, count-up stats, a pinned horizontal-scroll "Coming up" gallery, categories that slide in from alternating sides, a holographic organizer ticket whose stub tears on hover, and a rainbow scroll-progress bar, a live countdown sticker for the next event, a "Surprise Me" slot-machine pick with confetti, a statement whose words paint in as you scroll while event photos trail the cursor, and a sticky-stack "How it works" with live mini previews (chips, a stamped ticket, a scanning QR). Elsewhere: the theme switch grows out of its button as a circle (View Transitions API), confetti on a successful booking, event cards tilt toward the cursor, a navbar that turns into a glass pill on scroll, a card-to-page image morph (React ``), and a stamp when a booking succeeds. All pure CSS plus one delegated pointer listener; everything settles under `prefers-reduced-motion`. +- **Photography:** seed events and categories use subject-matched Unsplash photos (Unsplash License). +## How a request flows + +``` +Browser ──► Next.js server ──► Express API ──► MongoDB + │ server components fetch data with the user's token + │ /api/* proxy forwards browser mutations and sets the auth cookie + └─ proxy.ts guards /dashboard and /bookings ``` -├── client/ # Next.js frontend + +- The browser never calls Express directly, so there is no CORS layer and the token never touches JavaScript. +- `POST /api/auth/login` and `/register` return the user; the Next.js proxy keeps the token in an httpOnly cookie (`SameSite=Lax`, 7 days). +- Public pages (home, events, event detail) are server-rendered with real metadata (title, description, Open Graph image). +- Every write is validated with zod on the server; unknown fields are stripped, so clients cannot set `organizerId` or `bookedCount`. + +## Project structure + +``` +├── client/ # Next.js frontend │ └── src/ -│ ├── app/ # Pages (Home, Events, Auth, Dashboard, Bookings) -│ ├── components/ # Navbar, Footer, EventCard -│ ├── lib/ # API client -│ └── types/ # TypeScript interfaces -├── server/ # Express backend +│ ├── app/ # Routes (server components) + client islands +│ │ ├── api/[...path]/ # Same-origin proxy to the Express API (sets/clears the auth cookie) +│ │ ├── events/ # Listing with filters + pagination, event detail (booking, reviews) +│ │ ├── bookings/ # My tickets with QR codes and cancellation +│ │ ├── dashboard/ # Organizer: stats, create/edit events, attendees +│ │ └── auth/ # Login / register +│ ├── components/ # Navbar, Footer, EventCard, EventForm, ConfirmButton, … +│ ├── lib/ # server.ts (SSR fetch + session), api.ts (browser mutations), session.ts, categories.ts +│ ├── proxy.ts # Route protection (Next 16 "proxy", formerly middleware) +│ └── types/ +├── server/ # Express backend │ └── src/ -│ ├── config/ # Database singleton -│ ├── controllers/ -│ ├── interfaces/ # IPaymentGateway abstraction -│ ├── middleware/ # Auth + RBAC -│ ├── models/ # Mongoose schemas (User, Event, Booking, Review) -│ ├── repositories/ -│ ├── routes/ -│ └── services/ -├── idea.md # Project concept document -└── *Diagram.* # UML diagrams (Class, ER, Sequence, Use Case) +│ ├── index.ts # App (exported for Vercel and tests); server.ts listens locally +│ ├── schemas.ts # zod request schemas +│ ├── config/ # Database singleton +│ ├── controllers/ # Thin: parse input, call a service, send JSON +│ ├── services/ # Business rules (ownership, booking and review rules) +│ ├── repositories/ # Mongoose queries +│ ├── models/ # User, Event, Booking, Review (+ indexes), Ticket factory +│ ├── middleware/ # auth (JWT), rbac, errorHandler +│ ├── interfaces/ # IPaymentGateway + mock gateways +│ ├── seed.ts # Demo data +│ └── tests/ # API tests (node:test) +├── .github/workflows/ci.yml +├── idea.md # Project concept document +└── *Diagram.* # UML diagrams (Class, ER, Sequence, Use Case) ``` -## OOP & Design Patterns +## Features + +- **Discover:** search, category and date filters (all in the URL), pagination, past events, "More like this" on every event, and a ⌘K / Ctrl+K quick search across events, categories and pages. +- **Save:** heart any event; saved events live on `/saved`. +- **Book:** General or VIP tickets, confetti on success, QR-coded tickets under My Tickets, cancellation with refund. +- **Plan:** add an event to Google Calendar or download an `.ics` file (Apple Calendar, Outlook); share via the native share sheet or copy the link. +- **Host:** create and edit events, see revenue and sales, list attendees, and run a **check-in desk** at the door (type the code or scan the QR with the camera where the browser supports `BarcodeDetector`); each ticket can only be admitted once. +- **Review:** attendees rate events after they end. + +## Business rules + +- **Check-in:** only the event's organizer (or an admin) can admit tickets; codes are case-insensitive; the update is atomic so a ticket scanned twice is admitted once; cancelled tickets are refused. +- **Booking:** only published, upcoming events; one confirmed ticket per user per event (database unique index, race-safe); seats are decremented atomically and returned if anything fails after the decrement; VIP costs double; the mock payment's transaction id is stored and refunded on cancellation; no cancellation once the event has started. +- **Reviews:** only attendees with a confirmed ticket, only after the event has ended, one review per user; the endpoint returns the average and count. +- **Events:** organizers manage only their own events (admins can manage any); the attendee list (names, emails) is visible only to the event's organizer. +- **Registration** can only create `attendee` or `organizer` accounts. + +## OOP and design patterns - **Inheritance**: `User` ← `Attendee` / `Organizer` / `Admin`; `Event` ← `OnlineEvent` / `VenueEvent` -- **Abstraction**: `IPaymentGateway` interface with `MockPaymentGateway` implementation +- **Abstraction**: `IPaymentGateway` interface with mock Stripe/PayPal implementations - **Factory**: `TicketFactory` creates VIP / General tickets -- **Singleton**: `Database` connection +- **Singleton**: `Database` connection (cached across serverless invocations) +- **Encapsulation**: `BaseController` response helpers; services hide rules from controllers -## Setup (Local Development) +## Local development ### Prerequisites -- Node.js ≥ 18 -- MongoDB running locally (or a MongoDB Atlas URI) + +- Node.js 20 or newer +- MongoDB running locally (`brew services start mongodb-community` on macOS) or a MongoDB Atlas URI ### Backend + ```bash cd server npm install -cp .env.example .env # Then edit .env with your values -npm run dev # Starts on http://localhost:5001 +cp .env.example .env # set MONGODB_URI and a random JWT_SECRET +npm run seed # demo users, 11 events, bookings and reviews +npm run dev # http://localhost:5001/api ``` +Demo logins created by the seed (password `password123`): `organizer@eventhive.dev`, `organizer2@eventhive.dev`, `attendee@eventhive.dev`, `attendee2@eventhive.dev`. + ### Frontend + ```bash cd client npm install -npm run dev # Starts on http://localhost:3000 +cp .env.example .env.local # API_URL=http://localhost:5001/api +npm run dev # http://localhost:3000 +``` + +### Checks + +```bash +cd server && npm run typecheck && npm test # tests use mongodb://localhost:27017/eventhive_test +cd client && npm run lint && npx tsc --noEmit && npm run build ``` -## Deployment +CI runs the same checks on every push (`.github/workflows/ci.yml`) with a MongoDB service container. + +## Deployment (Vercel, two projects) + +**Backend** — root directory `server`, deployed as a serverless function (`vercel.json`): + +| Variable | Value | +|----------|-------| +| `MONGODB_URI` | MongoDB Atlas connection string (allow Vercel's IPs in Atlas Network Access) | +| `JWT_SECRET` | a long random string | +| `JWT_EXPIRES_IN` | `7d` | + +**Frontend** — root directory `client`: + +| Variable | Value | +|----------|-------| +| `API_URL` | `https://.vercel.app/api` | -### Backend (Vercel) -1. Push code to GitHub -2. Create a new Project on [Vercel](https://vercel.com) -3. Set root directory to `server` -4. Add environment variables in settings: - - `MONGODB_URI` = your MongoDB Atlas connection string - - `JWT_SECRET` = a strong random string - - `JWT_EXPIRES_IN` = `7d` - - `CORS_ORIGIN` = your Vercel frontend URL -5. Deploy (Vercel will use `vercel.json` to deploy it as a Serverless API) +`API_URL` is server-only; the browser talks to the frontend's own `/api/*` proxy. -### Frontend (Vercel) -1. Import the GitHub repo on [Vercel](https://vercel.com) -2. Set root directory to `client` -3. Add environment variable: - - `NEXT_PUBLIC_API_URL` = `https://your-backend-url.onrender.com/api` -4. Deploy +## API -## API Endpoints +All routes are under `/api`. Responses are `{ success, data }` or `{ success: false, error }`; list endpoints add `pagination`. | Method | Endpoint | Auth | Description | |--------|----------|------|-------------| -| POST | `/api/auth/register` | No | Register user | -| POST | `/api/auth/login` | No | Login | -| GET | `/api/events` | No | List events | -| GET | `/api/events/search` | No | Search events | +| POST | `/api/auth/register` | No | Register (`attendee` or `organizer`) | +| POST | `/api/auth/login` | No | Login, returns user + token | +| GET | `/api/events` | No | List published upcoming events: `q`, `category`, `eventType`, `from`, `to`, `page`, `limit` | | GET | `/api/events/:id` | No | Event detail | | POST | `/api/events` | Organizer/Admin | Create event | -| GET | `/api/events/my/events` | Organizer/Admin | My managed events | -| PUT | `/api/events/:id` | Organizer/Admin | Update event | -| DELETE | `/api/events/:id` | Organizer/Admin | Delete event | -| POST | `/api/bookings` | User | Book ticket | +| GET | `/api/events/my/events` | Organizer/Admin | My events with revenue | +| PUT | `/api/events/:id` | Owner/Admin | Update event | +| DELETE | `/api/events/:id` | Owner/Admin | Delete event (cancels its bookings) | +| POST | `/api/bookings` | User | Book a ticket (`eventId`, `ticketType`) | | GET | `/api/bookings/my` | User | My bookings | -| PATCH | `/api/bookings/:id/cancel` | User | Cancel booking | -| GET | `/api/bookings/event/:eventId` | Organizer/Admin | Event attendees/bookings | -| POST | `/api/reviews` | User | Leave review | -| GET | `/api/reviews/event/:eventId` | No | List reviews for event | +| PATCH | `/api/bookings/:id/cancel` | User | Cancel a booking (refund, seat released) | +| GET | `/api/bookings/event/:eventId` | Owner/Admin | Attendees of an event | +| POST | `/api/bookings/check-in` | Owner/Admin | Admit a ticket at the door (`eventId`, `code`); once only | +| GET | `/api/me/saved` | User | My saved events | +| GET | `/api/me/saved/ids` | User | Ids of my saved events | +| PUT | `/api/me/saved/:eventId` | User | Save an event (idempotent) | +| DELETE | `/api/me/saved/:eventId` | User | Remove a saved event | +| POST | `/api/reviews` | Attendee of the event | Leave a review after the event ends | +| GET | `/api/reviews/event/:eventId` | No | Reviews with `averageRating` and `reviewCount` | +| GET | `/api/health` | No | Health check | + +Errors use proper status codes: 400 validation, 401 unauthenticated, 403 forbidden, 404 not found, 409 conflict (duplicate ticket, sold out, duplicate review). diff --git a/client/.env.example b/client/.env.example index 896c5cf..4708089 100644 --- a/client/.env.example +++ b/client/.env.example @@ -1,6 +1,6 @@ # Client Environment Variables -# Copy this file to .env.local and fill in your actual values -# Next.js requires browser-available variables to start with NEXT_PUBLIC_ +# Copy this file to .env.local and fill in your values -# The URL of your backend API -NEXT_PUBLIC_API_URL=http://localhost:5001/api +# Server-only: the Next.js server (pages + /api proxy) calls the Express API here. +# The browser never talks to Express directly. +API_URL=http://localhost:5001/api diff --git a/client/next.config.ts b/client/next.config.ts index e9ffa30..8211c4b 100644 --- a/client/next.config.ts +++ b/client/next.config.ts @@ -1,7 +1,12 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { - /* config options here */ + // Lighthouse and crawlers that do not run JavaScript get metadata in instead of streamed into the body + htmlLimitedBots: /Chrome-Lighthouse|Bingbot|DuckDuckBot|Slurp|Baiduspider|YandexBot|facebookexternalhit|Twitterbot|LinkedInBot|Applebot/i, + images: { + // Organizers paste any https image URL for their event + remotePatterns: [{ protocol: "https", hostname: "**" }], + }, }; export default nextConfig; diff --git a/client/package-lock.json b/client/package-lock.json index 156cf26..50d6288 100644 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -8,7 +8,9 @@ "name": "client", "version": "0.1.0", "dependencies": { + "@phosphor-icons/react": "^2.1.10", "next": "16.2.1", + "qrcode.react": "^4.2.0", "react": "19.2.4", "react-dom": "19.2.4" }, @@ -1211,6 +1213,19 @@ "node": ">=12.4.0" } }, + "node_modules/@phosphor-icons/react": { + "version": "2.1.10", + "resolved": "https://registry.npmjs.org/@phosphor-icons/react/-/react-2.1.10.tgz", + "integrity": "sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "react": ">= 16.8", + "react-dom": ">= 16.8" + } + }, "node_modules/@rtsao/scc": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", @@ -4795,6 +4810,15 @@ "node": ">=6" } }, + "node_modules/qrcode.react": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz", + "integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==", + "license": "ISC", + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/queue-microtask": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", diff --git a/client/package.json b/client/package.json index 0119482..751bf35 100644 --- a/client/package.json +++ b/client/package.json @@ -9,7 +9,9 @@ "lint": "eslint" }, "dependencies": { + "@phosphor-icons/react": "^2.1.10", "next": "16.2.1", + "qrcode.react": "^4.2.0", "react": "19.2.4", "react-dom": "19.2.4" }, diff --git a/client/src/app/HowItWorks.tsx b/client/src/app/HowItWorks.tsx new file mode 100644 index 0000000..05ef19f --- /dev/null +++ b/client/src/app/HowItWorks.tsx @@ -0,0 +1,88 @@ +import type { CSSProperties } from "react"; +import { MagnifyingGlass, Sparkle } from "@phosphor-icons/react/ssr"; +import TicketQR from "@/components/TicketQR"; +import { CATEGORY_META } from "@/lib/categories"; +import s from "./how.module.css"; + +const vars = (v: Record) => v as CSSProperties; + +// Three cards that stick and stack as you scroll. Each carries a small working preview of the +// real UI (category chips, the booking ticket, a scannable QR) rather than a picture of it. +export default function HowItWorks({ sampleCode }: { sampleCode: string }) { + const cards = [ + { + tone: "pink", + title: "Find your thing", + body: "Search by city, date or vibe. Filters live in the link, so you can send a friend exactly what you found.", + visual: ( +
+
+
+
+ {Object.entries(CATEGORY_META).map(([key, meta]) => ( + + + ))} +
+
+ ), + }, + { + tone: "yellow", + title: "Grab a seat", + body: "General or VIP in one tap. Seats are held atomically, so two people never end up with the same one.", + visual: ( +
+
+ VIP ticket + ₹2,398 + + General + + + +
+
+ 149 of 150 seats left +
+ Booked +
+ ), + }, + { + tone: "blue", + title: "Walk right in", + body: "Your ticket lives under My Tickets with a QR code for the door. Plans changed? Cancel and the seat goes back.", + visual: ( +
+ + + + {sampleCode} +
+ ), + }, + ]; + + return ( +
+

How it works

+
    + {cards.map((c, i) => ( +
  1. +
    +

    {c.title}

    +

    {c.body}

    +
    + +
  2. + ))} +
+
+ ); +} diff --git a/client/src/app/api/[...path]/route.ts b/client/src/app/api/[...path]/route.ts new file mode 100644 index 0000000..5724a7b --- /dev/null +++ b/client/src/app/api/[...path]/route.ts @@ -0,0 +1,50 @@ +import { NextRequest, NextResponse } from "next/server"; + +// Same-origin proxy in front of the Express API. +// The JWT lives in an httpOnly cookie on this origin; the browser never sees it +// and never calls Express directly, so no cross-site cookies or CORS are needed. + +const API_URL = process.env.API_URL ?? "http://localhost:5001/api"; +const TOKEN_COOKIE = "token"; +const MAX_AGE = 60 * 60 * 24 * 7; // keep in sync with the server's JWT_EXPIRES_IN + +type ApiJson = { success?: boolean; data?: { token?: string } & Record; error?: string }; + +async function proxy(req: NextRequest, ctx: { params: Promise<{ path: string[] }> }) { + const route = (await ctx.params).path.join("/"); + + if (route === "auth/logout") { + const res = NextResponse.json({ success: true, data: null }); + res.cookies.delete(TOKEN_COOKIE); + return res; + } + + const token = req.cookies.get(TOKEN_COOKIE)?.value; + const upstream = await fetch(`${API_URL}/${route}${req.nextUrl.search}`, { + method: req.method, + headers: { + "content-type": "application/json", + ...(token ? { authorization: `Bearer ${token}` } : {}), + }, + body: req.method === "GET" || req.method === "HEAD" ? undefined : await req.text(), + cache: "no-store", + }); + const json: ApiJson = await upstream.json().catch(() => ({ success: false, error: "Invalid response from API" })); + + const issuedToken = upstream.ok && route.startsWith("auth/") ? json.data?.token : undefined; + if (issuedToken) delete json.data!.token; // the token stays in the cookie only + + const res = NextResponse.json(json, { status: upstream.status }); + if (issuedToken) { + res.cookies.set(TOKEN_COOKIE, issuedToken, { + httpOnly: true, + sameSite: "lax", + secure: process.env.NODE_ENV === "production", + path: "/", + maxAge: MAX_AGE, + }); + } + return res; +} + +export { proxy as GET, proxy as POST, proxy as PUT, proxy as PATCH, proxy as DELETE }; diff --git a/client/src/app/auth/AuthShell.tsx b/client/src/app/auth/AuthShell.tsx new file mode 100644 index 0000000..d1799e9 --- /dev/null +++ b/client/src/app/auth/AuthShell.tsx @@ -0,0 +1,17 @@ +import Image from "next/image"; +import s from "./auth.module.css"; + +// Shared split layout for login/register: event photography on one side, the form on the other +export default function AuthShell({ image, title, children }: { image: string; title: string; children: React.ReactNode }) { + return ( +
+ +
{children}
+
+ ); +} diff --git a/client/src/app/auth/auth.module.css b/client/src/app/auth/auth.module.css new file mode 100644 index 0000000..0569f38 --- /dev/null +++ b/client/src/app/auth/auth.module.css @@ -0,0 +1,144 @@ +.page { + display: grid; + gap: 24px; + padding-block: 16px 24px; + min-height: calc(100dvh - var(--nav-h)); +} +@media (min-width: 900px) { + .page { + grid-template-columns: 1fr 1fr; + gap: 48px; + align-items: stretch; + } +} +.visual { + position: relative; + min-height: 220px; + border-radius: var(--radius-xl); + overflow: hidden; + display: flex; + align-items: flex-end; + background: #111; +} +:global([data-theme="light"]) .visual { + background: linear-gradient(135deg, #ff3d8b, #7a4df5 55%, #2f5bff); +} +.visual img { + object-fit: cover; + animation: settle 1.6s var(--ease-out) backwards; +} +@keyframes settle { + from { + transform: scale(1.08); + } +} +.visual::after { + content: ""; + position: absolute; + inset: 0; + background: linear-gradient(180deg, transparent 35%, rgba(8, 8, 12, 0.85)); +} +.visualText { + position: relative; + z-index: 1; + padding: 32px; +} +.visualTitle { + color: #fff; + font-size: clamp(2.4rem, 5vw, 4.4rem); + line-height: 0.92; + max-width: 11ch; +} +@media (max-width: 899px) { + .visualText { + padding: 20px 24px; + } + .visualTitle { + font-size: 2.4rem; + } +} +.formSide { + display: flex; + align-items: center; + justify-content: center; + padding: 16px 0 24px; +} +.form { + width: 100%; + max-width: 420px; + display: grid; + gap: 18px; +} +.form h1 { + margin-bottom: 4px; +} +.sub { + color: var(--text-3); + margin-top: -8px; +} +.passwordWrap { + position: relative; +} +.passwordWrap input { + padding-right: 52px; +} +.eye { + position: absolute; + right: 4px; + top: 50%; + transform: translateY(-50%); + width: 44px; + height: 44px; + display: grid; + place-items: center; + color: var(--text-3); + border-radius: var(--radius-sm); + transition: color var(--dur-fast); +} +.eye:hover { + color: var(--text); +} +.roles { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; +} +.role { + padding: 14px; + border-radius: var(--radius-md); + border: 1px solid var(--line-strong); + background: var(--surface); + text-align: left; + display: grid; + gap: 4px; + transition: border-color var(--dur-fast), background-color var(--dur-fast), transform var(--dur) var(--ease-spring); +} +.role:hover { + border-color: var(--text-3); +} +.role:active { + transform: scale(0.98); +} +.role[aria-checked="true"] { + border-color: var(--accent-ink); + background: var(--accent-soft); +} +.role strong { + display: flex; + align-items: center; + gap: 6px; + font-size: 0.93rem; +} +.role span { + font-size: 0.8rem; + color: var(--text-3); +} +.switch { + text-align: center; + font-size: 0.93rem; + color: var(--text-3); +} +.switch a { + color: var(--accent-ink); + font-weight: 600; +} diff --git a/client/src/app/auth/login/LoginForm.tsx b/client/src/app/auth/login/LoginForm.tsx new file mode 100644 index 0000000..496dfe6 --- /dev/null +++ b/client/src/app/auth/login/LoginForm.tsx @@ -0,0 +1,61 @@ +"use client"; + +import { useState, type FormEvent } from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { Eye, EyeSlash, WarningCircle } from "@phosphor-icons/react"; +import { api } from "@/lib/api"; +import s from "../auth.module.css"; + +export default function LoginForm({ next }: { next: string }) { + const router = useRouter(); + const [form, setForm] = useState({ email: "", password: "" }); + const [show, setShow] = useState(false); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + + async function submit(e: FormEvent) { + e.preventDefault(); + setError(""); + setBusy(true); + try { + await api.login(form); + router.push(next); + router.refresh(); + } catch (err) { + setError(err instanceof Error ? err.message : "Login failed. Check your email and password."); + setBusy(false); + } + } + + return ( +
+

Log in

+

Welcome back. Enter your details to continue.

+ {error && ( +

+

+ )} +
+ + setForm({ ...form, email: e.target.value })} required /> +
+
+ +
+ setForm({ ...form, password: e.target.value })} required /> + +
+
+ +

+ New here? Create an account +

+
+ ); +} diff --git a/client/src/app/auth/login/page.tsx b/client/src/app/auth/login/page.tsx index 169eaed..2d2122c 100644 --- a/client/src/app/auth/login/page.tsx +++ b/client/src/app/auth/login/page.tsx @@ -1,176 +1,20 @@ -"use client"; +import type { Metadata } from "next"; +import { redirect } from "next/navigation"; +import LoginForm from "./LoginForm"; +import AuthShell from "../AuthShell"; +import { getSessionUser } from "@/lib/server"; +import { PHOTOS } from "@/lib/photos"; +import { safeNext } from "../safeNext"; -import { useState } from "react"; -import { useRouter } from "next/navigation"; -import Link from "next/link"; -import { api, setToken, setUser } from "@/lib/api"; +export const metadata: Metadata = { title: "Log in" }; -export default function LoginPage() { - const router = useRouter(); - const [form, setForm] = useState({ email: "", password: "" }); - const [error, setError] = useState(""); - const [loading, setLoading] = useState(false); - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(""); - setLoading(true); - try { - const data = (await api.login(form)) as { user: Record; token: string }; - setToken(data.token); - setUser(data.user); - router.push("/"); - } catch (err: unknown) { - setError(err instanceof Error ? err.message : "Login failed"); - } finally { - setLoading(false); - } - } +export default async function LoginPage({ searchParams }: { searchParams: Promise<{ next?: string }> }) { + const next = safeNext((await searchParams).next); + if (await getSessionUser()) redirect(next); return ( -
-
-
-

Welcome back to
EventHive

-

Your gateway to amazing events. Sign in to access your tickets and discover new experiences.

-
-
- -
-
-

Sign In

-

Enter your credentials to continue

- - {error &&
{error}
} - -
-
- - setForm({ ...form, email: e.target.value })} - required - /> -
-
- - setForm({ ...form, password: e.target.value })} - required - /> -
- -
- -

- New here? Create an account -

-
-
- - -
+ + + ); } diff --git a/client/src/app/auth/register/RegisterForm.tsx b/client/src/app/auth/register/RegisterForm.tsx new file mode 100644 index 0000000..8b3a1fa --- /dev/null +++ b/client/src/app/auth/register/RegisterForm.tsx @@ -0,0 +1,78 @@ +"use client"; + +import { useState, type FormEvent } from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { CalendarPlus, Eye, EyeSlash, Ticket, WarningCircle } from "@phosphor-icons/react"; +import { api } from "@/lib/api"; +import s from "../auth.module.css"; + +export default function RegisterForm({ next }: { next: string }) { + const router = useRouter(); + const [form, setForm] = useState({ name: "", email: "", password: "", role: "attendee" }); + const [show, setShow] = useState(false); + const [error, setError] = useState(""); + const [busy, setBusy] = useState(false); + + async function submit(e: FormEvent) { + e.preventDefault(); + setError(""); + setBusy(true); + try { + await api.register(form); + router.push(form.role === "organizer" && next === "/" ? "/dashboard" : next); + router.refresh(); + } catch (err) { + setError(err instanceof Error ? err.message : "Registration failed. Please try again."); + setBusy(false); + } + } + + return ( +
+

Create account

+

Free, and it takes less than a minute.

+ {error && ( +

+

+ )} +
+ + setForm({ ...form, name: e.target.value })} required maxLength={80} /> +
+
+ + setForm({ ...form, email: e.target.value })} required /> +
+
+ +
+ setForm({ ...form, password: e.target.value })} required minLength={6} /> + +
+
+
+ I want to +
+ + +
+
+ +

+ Already have an account? Log in +

+
+ ); +} diff --git a/client/src/app/auth/register/page.tsx b/client/src/app/auth/register/page.tsx index ad203ab..c40541c 100644 --- a/client/src/app/auth/register/page.tsx +++ b/client/src/app/auth/register/page.tsx @@ -1,188 +1,20 @@ -"use client"; +import type { Metadata } from "next"; +import { redirect } from "next/navigation"; +import RegisterForm from "./RegisterForm"; +import AuthShell from "../AuthShell"; +import { getSessionUser } from "@/lib/server"; +import { PHOTOS } from "@/lib/photos"; +import { safeNext } from "../safeNext"; -import { useState } from "react"; -import { useRouter } from "next/navigation"; -import Link from "next/link"; -import { api, setToken, setUser } from "@/lib/api"; +export const metadata: Metadata = { title: "Create account" }; -export default function RegisterPage() { - const router = useRouter(); - const [form, setForm] = useState({ name: "", email: "", password: "", role: "attendee" }); - const [error, setError] = useState(""); - const [loading, setLoading] = useState(false); - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(""); - setLoading(true); - try { - const data = (await api.register(form)) as { user: Record; token: string }; - setToken(data.token); - setUser(data.user); - router.push("/"); - } catch (err: unknown) { - setError(err instanceof Error ? err.message : "Registration failed"); - } finally { - setLoading(false); - } - } +export default async function RegisterPage({ searchParams }: { searchParams: Promise<{ next?: string }> }) { + const next = safeNext((await searchParams).next); + if (await getSessionUser()) redirect(next); return ( -
-
-
-

Join the
EventHive Community

-

Create an account and start discovering incredible events or become an organizer today.

-
-
- -
-
-

Create Account

-

Fill in your details to get started

- - {error &&
{error}
} - -
-
- - setForm({ ...form, name: e.target.value })} required /> -
-
- - setForm({ ...form, email: e.target.value })} required /> -
-
- - setForm({ ...form, password: e.target.value })} minLength={6} required /> -
- -
- -
- - -
-
- - -
- -

- Already have an account? Sign in -

-
-
- - -
+ + + ); } diff --git a/client/src/app/auth/safeNext.ts b/client/src/app/auth/safeNext.ts new file mode 100644 index 0000000..bab2dc6 --- /dev/null +++ b/client/src/app/auth/safeNext.ts @@ -0,0 +1,5 @@ +// Only allow same-site relative redirects after sign-in (no open redirects) +export const safeNext = (next: string | string[] | undefined) => { + const value = Array.isArray(next) ? next[0] : next; + return value && value.startsWith("/") && !value.startsWith("//") ? value : "/"; +}; diff --git a/client/src/app/bookings/CancelBookingButton.tsx b/client/src/app/bookings/CancelBookingButton.tsx new file mode 100644 index 0000000..5c88fc2 --- /dev/null +++ b/client/src/app/bookings/CancelBookingButton.tsx @@ -0,0 +1,23 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import ConfirmButton from "@/components/ConfirmButton"; +import { api } from "@/lib/api"; + +export default function CancelBookingButton({ id }: { id: string }) { + const router = useRouter(); + return ( + { + await api.cancelBooking(id); + router.refresh(); + }} + > + Cancel Ticket + + ); +} diff --git a/client/src/app/bookings/bookings.module.css b/client/src/app/bookings/bookings.module.css new file mode 100644 index 0000000..8196e66 --- /dev/null +++ b/client/src/app/bookings/bookings.module.css @@ -0,0 +1,152 @@ +.head { + display: flex; + justify-content: space-between; + align-items: flex-end; + flex-wrap: wrap; + gap: 12px; + padding-block: 40px 32px; +} +.list { + display: grid; + gap: 18px; + max-width: 940px; +} +.ticket { + display: grid; + grid-template-columns: 1fr; + filter: drop-shadow(0 16px 30px rgba(0, 0, 0, 0.22)); +} +@media (min-width: 720px) { + .ticket { + grid-template-columns: 1fr 168px; + } +} +.past { + opacity: 0.7; +} +.main { + display: grid; + grid-template-columns: 1fr; + background: var(--surface); + border-radius: var(--radius-lg) var(--radius-lg) 0 0; + overflow: hidden; + -webkit-mask: radial-gradient(circle var(--notch) at 0 100%, #0000 97%, #000) 0 0 / 51% 100% no-repeat, radial-gradient(circle var(--notch) at 100% 100%, #0000 97%, #000) 100% 0 / 51% 100% no-repeat; + mask: radial-gradient(circle var(--notch) at 0 100%, #0000 97%, #000) 0 0 / 51% 100% no-repeat, radial-gradient(circle var(--notch) at 100% 100%, #0000 97%, #000) 100% 0 / 51% 100% no-repeat; +} +.stub { + display: grid; + justify-items: center; + align-content: center; + gap: 10px; + padding: 20px; + background: var(--surface); + border-radius: 0 0 var(--radius-lg) var(--radius-lg); + border-top: 1px dashed var(--line-strong); + -webkit-mask: radial-gradient(circle var(--notch) at 0 0, #0000 97%, #000) 0 0 / 51% 100% no-repeat, radial-gradient(circle var(--notch) at 100% 0, #0000 97%, #000) 100% 0 / 51% 100% no-repeat; + mask: radial-gradient(circle var(--notch) at 0 0, #0000 97%, #000) 0 0 / 51% 100% no-repeat, radial-gradient(circle var(--notch) at 100% 0, #0000 97%, #000) 100% 0 / 51% 100% no-repeat; +} +@media (min-width: 720px) { + .main { + grid-template-columns: 160px 1fr; + border-radius: var(--radius-lg) 0 0 var(--radius-lg); + -webkit-mask: radial-gradient(circle var(--notch) at 100% 0, #0000 97%, #000) 0 0 / 100% 51% no-repeat, radial-gradient(circle var(--notch) at 100% 100%, #0000 97%, #000) 0 100% / 100% 51% no-repeat; + mask: radial-gradient(circle var(--notch) at 100% 0, #0000 97%, #000) 0 0 / 100% 51% no-repeat, radial-gradient(circle var(--notch) at 100% 100%, #0000 97%, #000) 0 100% / 100% 51% no-repeat; + } + .stub { + border-radius: 0 var(--radius-lg) var(--radius-lg) 0; + border-top: 0; + border-left: 1px dashed var(--line-strong); + -webkit-mask: radial-gradient(circle var(--notch) at 0 0, #0000 97%, #000) 0 0 / 100% 51% no-repeat, radial-gradient(circle var(--notch) at 0 100%, #0000 97%, #000) 0 100% / 100% 51% no-repeat; + mask: radial-gradient(circle var(--notch) at 0 0, #0000 97%, #000) 0 0 / 100% 51% no-repeat, radial-gradient(circle var(--notch) at 0 100%, #0000 97%, #000) 0 100% / 100% 51% no-repeat; + } +} +.thumb { + position: relative; + min-height: 140px; + background: var(--surface-2); +} +.thumb img { + object-fit: cover; +} +.thumbIcon { + position: absolute; + inset: 0; + display: grid; + place-items: center; + color: var(--accent-ink); +} +.info { + min-width: 0; + padding: 20px 22px; + display: grid; + gap: 8px; + align-content: start; +} +.badges { + display: flex; + gap: 6px; + flex-wrap: wrap; +} +.title { + font-family: var(--font-display); + font-stretch: 75%; + font-weight: 800; + font-size: 1.75rem; + line-height: 1.05; + overflow-wrap: anywhere; +} +.title a:hover { + color: var(--accent-ink); +} +.rows { + display: flex; + flex-wrap: wrap; + gap: 6px 16px; + font-size: 0.875rem; + color: var(--text-2); +} +.rows span { + display: inline-flex; + align-items: center; + gap: 6px; +} +.actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 6px; +} +.qr { + display: block; + padding: 8px; + border-radius: var(--radius-sm); + background: #fff; +} +.code { + font-size: 0.75rem; + font-weight: 600; + color: var(--text-2); + overflow-wrap: anywhere; + text-align: center; +} +.groupTitle { + margin: 48px 0 16px; + font-size: 1rem; + font-weight: 600; + color: var(--text-3); +} + +/* ---------- Light theme: stub tinted with the event's category colour ---------- */ +:global([data-theme="light"]) .ticket { + filter: drop-shadow(0 16px 28px color-mix(in srgb, var(--tone) 22%, transparent)); +} +:global([data-theme="light"]) .stub { + background: var(--tone-tint); + border-color: color-mix(in srgb, var(--tone-deep) 35%, transparent); +} +:global([data-theme="light"]) .code { + color: var(--tone-deep); +} +:global([data-theme="light"]) .title a:hover { + color: var(--tone-deep); +} diff --git a/client/src/app/bookings/loading.tsx b/client/src/app/bookings/loading.tsx new file mode 100644 index 0000000..ad1c13a --- /dev/null +++ b/client/src/app/bookings/loading.tsx @@ -0,0 +1,10 @@ +export default function Loading() { + return ( +
+
+
+ {Array.from({ length: 3 }).map((_, i) =>
)} +
+
+ ); +} diff --git a/client/src/app/bookings/page.tsx b/client/src/app/bookings/page.tsx index e23f200..24b4bb9 100644 --- a/client/src/app/bookings/page.tsx +++ b/client/src/app/bookings/page.tsx @@ -1,310 +1,117 @@ -"use client"; - -import { useState, useEffect } from "react"; -import { useRouter } from "next/navigation"; +import type { Metadata } from "next"; +import Image from "next/image"; import Link from "next/link"; -import { api, getUser } from "@/lib/api"; -import { Booking, Event } from "@/types"; - -export default function BookingsPage() { - const router = useRouter(); - const [bookings, setBookings] = useState([]); - const [loading, setLoading] = useState(true); - const user = getUser(); +import { CalendarBlank, CalendarPlus, MapPin, SealCheck, Sparkle, Ticket } from "@phosphor-icons/react/ssr"; +import TicketQR from "@/components/TicketQR"; +import CancelBookingButton from "./CancelBookingButton"; +import { apiFetch } from "@/lib/server"; +import { categoryMeta } from "@/lib/categories"; +import { formatDate, formatPrice, formatTime, isPast } from "@/lib/format"; +import type { Booking } from "@/types"; +import s from "./bookings.module.css"; - useEffect(() => { - if (!user) { - router.push("/auth/login"); - return; - } - loadBookings(); - }, []); +export const metadata: Metadata = { title: "My tickets" }; - async function loadBookings() { - try { - const data = (await api.getMyBookings()) as Booking[]; - setBookings(data); - } catch { - setBookings([]); - } finally { - setLoading(false); - } - } +export default async function BookingsPage() { + const bookings = await apiFetch("/bookings/my"); + const isLive = (b: Booking) => b.status === "confirmed" && !!b.eventId && !isPast(b.eventId.date); + const upcoming = bookings.filter(isLive); + const history = bookings.filter((b) => !isLive(b)); - async function handleCancel(id: string) { - if (!confirm("Cancel this booking?")) return; - try { - await api.cancelBooking(id); - loadBookings(); - } catch (err: unknown) { - alert(err instanceof Error ? err.message : "Failed to cancel"); - } - } + const ticket = (booking: Booking, i: number) => { + const event = booking.eventId; + const meta = categoryMeta(event?.category ?? "other"); + const live = isLive(booking); + const status = !event ? "Event removed" : booking.status === "cancelled" ? "Cancelled" : isPast(event.date) ? "Attended" : "Confirmed"; + const statusClass = status === "Confirmed" ? "badge-success" : status === "Attended" ? "badge-accent" : ""; - // Generate a stable QR-like pattern from a string (no Math.random in render) - function getQrPattern(seed: string): boolean[] { - return Array.from({ length: 25 }).map((_, i) => { - const ch = seed.charCodeAt(i % seed.length); - return (ch + i * 7) % 10 > 3; - }); - } + return ( +
  • +
    +
    + {event?.imageUrl ? ( + + ) : ( + + + )} +
    +
    +
    + {status} + {booking.checkedInAt && ( + + + )} + + {booking.ticketType === "vip" ? ( + <> + +
    +

    {event ? {event.title} : "Event no longer available"}

    +
    + + + + + Paid {formatPrice(booking.amount)} +
    + {live && ( +
    + View Event + + + +
    + )} +
    +
    +
    + + + + {booking.ticketCode} +
    +
  • + ); + }; return ( -
    -
    -

    My Tickets

    -

    Your booking history and active tickets

    -
    - - {loading ? ( -
    Loading bookings...
    - ) : bookings.length > 0 ? ( -
    - {bookings.map((booking, i) => { - const event = booking.eventId && typeof booking.eventId === "object" ? booking.eventId as Event : null; - // If the event was deleted, treat the booking as cancelled regardless of stored status - const displayStatus = !event && booking.status === "confirmed" ? "cancelled" : booking.status; - const isConfirmed = displayStatus === "confirmed"; - const categoryEmoji = !event ? "🎟️" : event.category === "music" ? "🎵" : event.category === "tech" ? "💻" : event.category === "sports" ? "⚽" : "🎉"; - return ( -
    -
    - -
    -
    -
    -
    - {categoryEmoji} -
    -
    -

    {event?.title || "Event Deleted"}

    -
    - 📅 {new Date(event?.date || booking.bookingDate).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })} - 📍 {event?.location || "—"} -
    -
    -
    +
    +
    +

    My tickets

    + Find more events +
    -
    -
    - Ticket Type - - {booking.ticketType === "vip" ? "✨ VIP" : "General"} - -
    -
    - Amount - ${booking.amount} -
    -
    - Status - {displayStatus} -
    -
    -
    - -
    -
    - TICKET CODE - {booking.ticketCode} -
    -
    - {getQrPattern(booking.ticketCode).map((filled, j) => ( -
    - ))} -
    -
    -
    -
    - - {isConfirmed && event && ( -
    - - View Event - - -
    - )} -
    -
    - ); - })} + {bookings.length === 0 ? ( +
    +
    ) : ( -
    -
    🎟️
    -

    No bookings yet

    -

    Explore events and book your first ticket!

    - - Browse Events - -
    + <> + {upcoming.length > 0 &&
      {upcoming.map(ticket)}
    } + {history.length > 0 && ( + <> +

    Past and cancelled

    +
      {history.map((b, i) => ticket(b, i + upcoming.length))}
    + + )} + )} - -
    ); } diff --git a/client/src/app/dashboard/DeleteEventButton.tsx b/client/src/app/dashboard/DeleteEventButton.tsx new file mode 100644 index 0000000..8aa4380 --- /dev/null +++ b/client/src/app/dashboard/DeleteEventButton.tsx @@ -0,0 +1,23 @@ +"use client"; + +import { useRouter } from "next/navigation"; +import { Trash } from "@phosphor-icons/react"; +import ConfirmButton from "@/components/ConfirmButton"; +import { api } from "@/lib/api"; + +export default function DeleteEventButton({ id, title }: { id: string; title: string }) { + const router = useRouter(); + return ( + { + await api.deleteEvent(id); + router.refresh(); + }} + > + + ); +} diff --git a/client/src/app/dashboard/[id]/attendees/CheckInDesk.module.css b/client/src/app/dashboard/[id]/attendees/CheckInDesk.module.css new file mode 100644 index 0000000..e7eb48b --- /dev/null +++ b/client/src/app/dashboard/[id]/attendees/CheckInDesk.module.css @@ -0,0 +1,88 @@ +.desk { + padding: 24px; + margin-bottom: 24px; + display: grid; + gap: 16px; +} +.top h2 { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 4px; +} +.form { + display: grid; + gap: 8px; +} +@media (min-width: 720px) { + .form { + grid-template-columns: minmax(0, 1fr) auto auto; + } +} +.form .input { + text-transform: uppercase; + letter-spacing: 0.08em; +} +.form .input::placeholder { + text-transform: none; + letter-spacing: normal; +} +.results { + display: grid; + gap: 6px; +} +.result { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 14px; + border-radius: var(--radius-md); + font-weight: 600; + font-size: 0.92rem; + animation: slideIn 360ms var(--ease-spring); +} +.result:not(:first-child) { + opacity: 0.6; + font-weight: 500; +} +.ok { + background: color-mix(in srgb, var(--success-text) 12%, transparent); + color: var(--success-text); +} +.bad { + background: color-mix(in srgb, var(--danger-text) 12%, transparent); + color: var(--danger-text); +} +@keyframes slideIn { + from { + opacity: 0; + transform: translateY(-8px) scale(0.98); + } +} +.scanner { + max-width: 420px; + display: grid; + gap: 12px; + justify-items: center; + position: relative; +} +.scanner:not([open]) { + display: none; +} +.video { + width: 100%; + aspect-ratio: 1; + object-fit: cover; + border-radius: var(--radius-md); + background: #000; +} +.frame { + position: absolute; + top: calc(28px + 15%); + width: 55%; + aspect-ratio: 1; + border: 3px solid #fff; + border-radius: var(--radius-md); + box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.25); + pointer-events: none; +} diff --git a/client/src/app/dashboard/[id]/attendees/CheckInDesk.tsx b/client/src/app/dashboard/[id]/attendees/CheckInDesk.tsx new file mode 100644 index 0000000..9b31b78 --- /dev/null +++ b/client/src/app/dashboard/[id]/attendees/CheckInDesk.tsx @@ -0,0 +1,151 @@ +"use client"; + +import { useEffect, useRef, useState, useSyncExternalStore, type FormEvent } from "react"; +import { useRouter } from "next/navigation"; +import { CheckCircle, QrCode, ScanSmiley, WarningCircle, X } from "@phosphor-icons/react"; +import { api } from "@/lib/api"; +import s from "./CheckInDesk.module.css"; + +type Result = { ok: boolean; text: string; at: number }; + +// BarcodeDetector is not in TypeScript's DOM lib yet +type Detector = { detect: (source: CanvasImageSource) => Promise<{ rawValue: string }[]> }; +declare global { + interface Window { + BarcodeDetector?: new (opts: { formats: string[] }) => Detector; + } +} + +// Door check-in: type the code from a ticket, or scan its QR with the camera where supported +export default function CheckInDesk({ eventId }: { eventId: string }) { + const router = useRouter(); + const [code, setCode] = useState(""); + const [busy, setBusy] = useState(false); + const [results, setResults] = useState([]); + const [scanning, setScanning] = useState(false); + const canScan = useCanScan(); + const video = useRef(null); + const dialog = useRef(null); + + async function admit(raw: string) { + const value = raw.trim(); + if (!value) return; + setBusy(true); + try { + const booking = await api.checkIn({ eventId, code: value }); + const name = typeof booking.userId === "object" ? booking.userId.name : "Attendee"; + setResults((r) => [{ ok: true, text: `${name} admitted (${booking.ticketType === "vip" ? "VIP" : "General"})`, at: Date.now() }, ...r].slice(0, 5)); + setCode(""); + router.refresh(); // update the table and counts + } catch (err) { + setResults((r) => [{ ok: false, text: err instanceof Error ? err.message : "Check-in failed", at: Date.now() }, ...r].slice(0, 5)); + } finally { + setBusy(false); + } + } + + function submit(e: FormEvent) { + e.preventDefault(); + admit(code); + } + + // Camera scanning: open the camera, look for a QR every 250ms, admit the first one found + useEffect(() => { + if (!scanning || !window.BarcodeDetector) return; + const detector = new window.BarcodeDetector({ formats: ["qr_code"] }); + let stream: MediaStream | undefined; + let timer: ReturnType | undefined; + let done = false; + const modal = dialog.current; + modal?.showModal(); + navigator.mediaDevices + .getUserMedia({ video: { facingMode: "environment" } }) + .then((s) => { + stream = s; + if (!video.current) return; + video.current.srcObject = s; + video.current.play(); + timer = setInterval(async () => { + if (done || !video.current || video.current.readyState < 2) return; + const [hit] = await detector.detect(video.current).catch(() => []); + if (hit && !done) { + done = true; + setScanning(false); + admit(hit.rawValue); + } + }, 250); + }) + .catch(() => { + setResults((r) => [{ ok: false, text: "Camera unavailable. Type the code instead.", at: Date.now() }, ...r].slice(0, 5)); + setScanning(false); + }); + return () => { + done = true; + clearInterval(timer); + stream?.getTracks().forEach((t) => t.stop()); + modal?.close(); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [scanning]); + + return ( +
    +
    +

    +

    +

    Admit guests at the door. Each ticket can only be used once.

    +
    +
    + + setCode(e.target.value)} + autoComplete="off" + spellCheck={false} + autoCapitalize="characters" + /> + + {canScan && ( + + )} +
    + +
      + {results.map((r) => ( +
    • + {r.ok ?
    • + ))} +
    + + setScanning(false)} aria-label="Scan a ticket QR code"> + +
    + ); +} + +// Camera scanning needs BarcodeDetector + a camera API; false on the server and during hydration +const noSubscribe = () => () => {}; +function useCanScan() { + return useSyncExternalStore( + noSubscribe, + () => !!window.BarcodeDetector && !!navigator.mediaDevices?.getUserMedia, + () => false + ); +} diff --git a/client/src/app/dashboard/[id]/attendees/page.tsx b/client/src/app/dashboard/[id]/attendees/page.tsx new file mode 100644 index 0000000..79d4155 --- /dev/null +++ b/client/src/app/dashboard/[id]/attendees/page.tsx @@ -0,0 +1,103 @@ +import type { Metadata } from "next"; +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { ArrowLeft, SealCheck, Users } from "@phosphor-icons/react/ssr"; +import CheckInDesk from "./CheckInDesk"; +import { apiFetch, ApiError } from "@/lib/server"; +import { formatDate, formatDateTime, formatPrice } from "@/lib/format"; +import type { Booking, Event } from "@/types"; +import s from "../../dashboard.module.css"; + +export const metadata: Metadata = { title: "Attendees" }; + +export default async function AttendeesPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + let event: Event; + let bookings: Booking[]; + try { + [event, bookings] = await Promise.all([apiFetch(`/events/${id}`), apiFetch(`/bookings/event/${id}`)]); + } catch (err) { + if (err instanceof ApiError && [400, 403, 404].includes(err.status)) notFound(); // not yours, or gone + throw err; + } + + const confirmed = bookings.filter((b) => b.status === "confirmed"); + const checkedIn = confirmed.filter((b) => b.checkedInAt).length; + const time = (iso: string) => new Date(iso).toLocaleTimeString("en-US", { hour: "numeric", minute: "2-digit" }); + const revenue = confirmed.reduce((sum, b) => sum + b.amount, 0); + const attendee = (b: Booking) => (typeof b.userId === "object" ? b.userId : { name: "Unknown", email: "" }); + + return ( +
    + +
    + ); +} diff --git a/client/src/app/dashboard/[id]/edit/page.tsx b/client/src/app/dashboard/[id]/edit/page.tsx new file mode 100644 index 0000000..0e0fb40 --- /dev/null +++ b/client/src/app/dashboard/[id]/edit/page.tsx @@ -0,0 +1,22 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; +import EventForm from "@/components/EventForm"; +import { apiFetch, ApiError, getSessionUser } from "@/lib/server"; +import { refId } from "@/lib/format"; +import type { Event } from "@/types"; + +export const metadata: Metadata = { title: "Edit event" }; + +export default async function EditEventPage({ params }: { params: Promise<{ id: string }> }) { + const { id } = await params; + const [event, user] = await Promise.all([ + apiFetch(`/events/${id}`).catch((err) => { + if (err instanceof ApiError && (err.status === 404 || err.status === 400)) notFound(); + throw err; + }), + getSessionUser(), + ]); + if (!user || (user.role !== "admin" && refId(event.organizerId) !== user.id)) notFound(); + + return ; +} diff --git a/client/src/app/dashboard/create/page.tsx b/client/src/app/dashboard/create/page.tsx index be2e4ec..1799734 100644 --- a/client/src/app/dashboard/create/page.tsx +++ b/client/src/app/dashboard/create/page.tsx @@ -1,249 +1,8 @@ -"use client"; +import type { Metadata } from "next"; +import EventForm from "@/components/EventForm"; -import { useState, useEffect } from "react"; -import { useRouter } from "next/navigation"; -import { api, getUser } from "@/lib/api"; +export const metadata: Metadata = { title: "Create event" }; export default function CreateEventPage() { - const router = useRouter(); - const user = getUser(); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(""); - const [form, setForm] = useState({ - title: "", - description: "", - date: "", - location: "", - capacity: "", - price: "", - category: "tech", - eventType: "venue" as "online" | "venue", - meetingLink: "", - platform: "", - address: "", - }); - - useEffect(() => { - if (!user || (user.role !== "organizer" && user.role !== "admin")) { - router.push("/auth/login"); - } - }, []); - - function handleChange(e: React.ChangeEvent) { - setForm({ ...form, [e.target.name]: e.target.value }); - } - - async function handleSubmit(e: React.FormEvent) { - e.preventDefault(); - setError(""); - setLoading(true); - try { - await api.createEvent({ - ...form, - capacity: parseInt(form.capacity), - price: parseFloat(form.price), - }); - router.push("/dashboard"); - } catch (err: unknown) { - setError(err instanceof Error ? err.message : "Failed to create event"); - } finally { - setLoading(false); - } - } - - return ( -
    -
    -
    -
    ✨
    -

    Create New Event

    -

    Fill in the details to publish your event

    -
    - - {error &&
    {error}
    } - -
    -
    -

    📝 Basic Details

    -
    -
    - - -
    -
    - -