Skip to content
All repositories

github.com/Bloop31/ticket-booking-system

Ticket Booking System

A full-stack ticket booking platform for movies and concerts: visual seat maps, TTL-based seat holds with auto-release, sold-out waitlists with automatic seat reassignment, and QR-code email tickets.

README

A full-stack ticket booking platform for movies and concerts: visual seat maps, TTL-based seat holds with auto-release, sold-out waitlists with automatic seat reassignment, and QR-code email tickets.

Stack: Node.js/Express + SQLite (better-sqlite3) on the backend, React (Vite) on the frontend. No external database server to provision — the whole thing runs from two npm install && npm run commands.


1. Project Structure

ticket-booking-system/
├── backend/
│   ├── src/
│   │   ├── server.js              # Express app entrypoint
│   │   ├── db.js                  # SQLite connection + schema (auto-migrates on boot)
│   │   ├── seedAdminOnce.js        # CLI helper to create an admin user
│   │   ├── middleware/auth.js      # JWT auth + role guard
│   │   ├── routes/
│   │   │   ├── auth.js             # register / login
│   │   │   ├── venues.js           # admin: venue + seat layout
│   │   │   ├── events.js           # organiser: events, showtimes, revenue
│   │   │   ├── shows.js            # seat map, hold, release
│   │   │   ├── bookings.js         # confirm booking, history, cancel
│   │   │   └── waitlist.js         # join, list, claim offer
│   │   └── services/
│   │       ├── seatEngine.js       # shared hold-expiry + waitlist hand-off logic
│   │       ├── scheduler.js        # cron job: sweeps expired holds every 30s
│   │       └── qrEmail.js          # QR generation + email delivery
│   ├── uploads/qrcodes/            # generated QR PNGs
│   ├── .env.example
│   └── package.json
├── frontend/
│   ├── src/
│   │   ├── pages/                  # Login, Register, Events, EventDetail,
│   │   │                           # SeatMap, Bookings, WaitlistOffer,
│   │   │                           # OrganiserDashboard, OrganiserNewEvent, AdminVenues
│   │   ├── components/Navbar.jsx
│   │   ├── context/AuthContext.jsx
│   │   ├── api.js                  # axios instance with JWT interceptor
│   │   └── App.jsx / main.jsx / styles.css
│   ├── .env.example
│   └── package.json
├── DESIGN.md                       # system design write-up (seat hold, concurrency, waitlist)
└── README.md

2. Setup Guide (local)

Prerequisites

  • Node.js 18+ and npm

Backend

cd backend
cp .env.example .env      # edit values if needed (defaults work out of the box)
npm install
npm start                 # http://localhost:4000

On first boot, db.js creates data/booking.db and all tables automatically — no migration step needed. Create your first admin account with:

node src/seedAdminOnce.js admin@yourcompany.com yourpassword

(Admin accounts aren’t self-registrable through the API by design — only customer and organiser roles can sign up via /api/auth/register.)

Frontend

cd frontend
cp .env.example .env      # points VITE_API_URL at the backend
npm install
npm run dev                # http://localhost:5173

Quick walkthrough once both are running

  1. Register as an admin (via seedAdminOnce.js) → log in → Admin → Venues → create a venue with a seat grid.
  2. Register as an organiser → Organiser → New Event → pick the venue, add a showtime with per-category pricing.
  3. Register as a customer → browse Events → pick a showtime → select seats on the visual map → Hold → Confirm & Book. You’ll get a confirmation email (see “Email delivery” below) with a QR ticket attached.
  4. To see the waitlist flow: book out every seat in a category as one customer, then join the waitlist for that category as a second customer, then cancel the first customer’s booking from My Bookings — the second customer will get an email + an in-app offer with a countdown.

Email delivery

If you don’t set SMTP_USER/SMTP_PASS in backend/.env, the backend automatically falls back to a free Ethereal test inbox and logs a preview URL to the server console for every email sent — nothing is actually delivered, but you can view the exact email in a browser. For real delivery, set any SMTP provider’s credentials (Gmail App Password, Mailtrap, Brevo, etc.) in .env.


3. .env.example reference

backend/.env.example

PORT=4000
JWT_SECRET=change_this_to_a_long_random_string
CLIENT_URL=http://localhost:5173
SEAT_HOLD_TTL_MINUTES=10
WAITLIST_OFFER_TTL_MINUTES=15
DB_PATH=./data/booking.db
SMTP_HOST=smtp.ethereal.email
SMTP_PORT=587
SMTP_USER=
SMTP_PASS=
EMAIL_FROM="Ticket Booking <no-reply@ticketbooking.com>"

frontend/.env.example

VITE_API_URL=http://localhost:4000/api

4. Database Schema

Table Purpose
users id, name, email, password_hash, role (customer/organiser/admin)
venues id, name, address, created_by (admin)
venue_seats Physical seat layout per venue: row_label, seat_number, category. Reused across every show at that venue.
events id, organiser_id, title, description, type (movie/concert), venue_id
shows A specific date/time screening/performance of an event, with pricing_json (per-category price map)
show_seats One row per venue_seat per show. Tracks live status: available / held / booked, plus held_by and hold_expires_at. This is the table the concurrency and TTL logic revolves around.
bookings id, booking_ref (unique, QR payload), user_id, show_id, status (confirmed/cancelled), total_amount, qr_path
booking_seats Join table: which show_seats belong to which booking
waitlist id, user_id, show_id, category, status (waiting/offered/expired/fulfilled/cancelled), offered_show_seat_id, offer_expires_at

Full DDL lives in backend/src/db.js (runs automatically on server start — CREATE TABLE IF NOT EXISTS, so it’s safe to restart repeatedly).


5. API Documentation

All endpoints except /api/auth/* and /api/health require Authorization: Bearer <jwt>. Roles in brackets indicate an additional requireRole guard.

Auth

Method Path Body Notes
POST /api/auth/register {name, email, password, role?} role is customer or organiser only
POST /api/auth/login {email, password} returns {user, token}

Venues [admin]

Method Path Body
POST /api/venues {name, address, seats: [{row_label, seat_number, category}]}
GET /api/venues — (any authenticated role)
GET /api/venues/:id/seats — (any authenticated role)

Events / Shows

Method Path Role Body
POST /api/events organiser {title, description, type, venue_id}
POST /api/events/:id/shows organiser (own event) {date_time, pricing: {Premium: 500, ...}} — materializes show_seats from the venue layout
GET /api/events any query: type, venue_id, q
GET /api/events/:id any returns event + its shows
GET /api/events/organiser/mine organiser booking count + revenue per show

Shows — seat map & holds

Method Path Body
GET /api/shows/:id/seatmap —
POST /api/shows/:id/hold {show_seat_ids: [...]} — places a TTL hold
POST /api/shows/:id/release {show_seat_ids: [...]} — voluntary release

Bookings

Method Path Body
POST /api/bookings {show_id, show_seat_ids} — confirms seats currently held by you
GET /api/bookings/mine —
POST /api/bookings/:id/cancel — triggers waitlist hand-off

Waitlist

Method Path Body
POST /api/waitlist {show_id, category}
GET /api/waitlist/mine —
DELETE /api/waitlist/:id —
POST /api/waitlist/:id/claim — completes booking from an active offer

6. Seat Hold, Concurrency & Waitlist Logic

See DESIGN.md for the full write-up. Short version:

  • Seat hold TTL: better-sqlite3 is synchronous and single-connection, so every hold/booking check-and-update runs inside one atomic transaction — two simultaneous requests for the same seat can never both succeed. A background cron job (services/scheduler.js) sweeps every 30s for holds past hold_expires_at and releases them; the same check also runs lazily on every seat-map/hold/booking request so the UI is never more than a few seconds stale.
  • Waitlist: scoped per (show_id, category), FIFO by created_at. On cancellation, the freed seat is immediately re-offered (not released to the general pool) to the earliest waiting entry, with its own TTL (WAITLIST_OFFER_TTL_MINUTES). If that offer also expires, the same sweep logic passes it to the next person in line — see seatEngine.js’s advanceOrRelease().

7. Deployment

I can’t push to an external host from this sandbox (no network route out to Render/Vercel/Railway), but here’s the exact path — each of these has a generous free tier:

Backend → Render

  1. Push this repo to GitHub (see submission guidelines below).
  2. On render.com → New → Web Service → connect the repo, root directory backend.
  3. Build command: npm install. Start command: npm start.
  4. Add the env vars from .env.example (set CLIENT_URL to your deployed frontend URL once you have it).
  5. Note on SQLite + Render free tier: the free tier’s filesystem is ephemeral (wiped on redeploy/restart). For a persistent grading deployment, either upgrade to a paid instance with a persistent disk, or point DB_PATH at a Render Disk mount. This is called out explicitly since the assignment evaluates a live hosted app.

Frontend → Vercel

  1. On vercel.com → New Project → import the repo, root directory frontend.
  2. Framework preset: Vite. Build command: npm run build. Output dir: dist.
  3. Add env var VITE_API_URL = your Render backend URL + /api.
  4. Once deployed, go back to Render and set CLIENT_URL to the Vercel URL (needed for CORS and the waitlist-offer email links), then redeploy the backend.

8. Submission checklist (per assignment guidelines)

  • No node_modules/, .env, dist/, or DB files committed (see .gitignore)
  • Minimal dependencies only — nothing added beyond what each feature needs
  • Push to a public GitHub repo on branch main
  • Hosted URL (see §7)
  • This README + DESIGN.md included