cpe241-booking-website-server

Public
OVERVIEW.md

The cinema API turns seat selection into a sequence of database decisions.

The companion client lets staff schedule showings and customers choose seats. In this database-course final project, I wanted to see whether the underlying rules would still hold as the system expanded: a hall cannot host overlapping showings, a seat cannot be held twice at checkout, and cancellation has to release what a booking held. This repository puts those rules in Express services and MySQL transactions.

Following a seat from free to confirmed

Creating a showing checks for a venue/time conflict and creates seat-state rows for that event in one transaction. A customer can inspect the resulting seat map and create a preliminary booking. That first step records the requested seats but does not reserve them. At checkout, the service locks the booking and still-free seat rows, marks those seats Reserved, and advances the booking state. Completion marks them Confirmed; admin cancellation releases them to Free. If a transaction fails, its partial writes are rolled back.

The same API serves movie, venue, schedule, account, and reporting operations. Dashboard and report queries aggregate bookings and revenue, including periods with no activity so a chart does not silently skip them. Routes and controllers handle requests, services hold the booking rules, and models issue SQL against the shared schema.

This is a database-course system with a demonstrable admin/customer flow. The checkout's proof strings are generated markers, not evidence of a real payment. The important result is a concrete transaction model for scheduling and seats, with the distinction between a preliminary booking and an actual seat hold kept visible.

README.md

Cinema Admin — Server

The Express 5 + Node.js API for the Cinema Admin System. Serves both the admin portal and the customer booking flow over a MySQL database.

  • Base URL: http://localhost:5000/api
  • Database: MySQL — CPE241_final_project
  • Auth: JWT (8-hour expiry, Authorization: Bearer <token>)

Table of Contents

  1. Tech Stack
  2. Prerequisites
  3. Setup
  4. Environment Variables
  5. Database Setup
  6. Scripts
  7. Project Structure
  8. API Reference
  9. Database Schema
  10. Business Logic
  11. Performance Indexes
  12. Seed Data

Tech Stack

PackageVersionPurpose
express^5.2HTTP framework
mysql2^3.22MySQL driver (Promise API, connection pool)
jsonwebtoken^9.0JWT sign/verify
bcryptjs^2.4Password hashing
cors^2.8Cross-origin requests
dotenv^17Environment variable loading
nodemon^3.1Dev runner (watches src/ and .env)

Module system: CommonJS ("type": "commonjs").


Prerequisites

  • Node.js 20+
  • MySQL 8.0+ running locally (default port 3306)

Setup

cd server
npm install
cp .env.example .env   # then fill in your credentials (see Environment Variables)

Environment Variables

Create server/.env:

MYSQL_HOST=127.0.0.1
MYSQL_PORT=3306
MYSQL_USER=root
MYSQL_PASSWORD=your_mysql_password
MYSQL_DATABASE=CPE241_final_project
PORT=5000
JWT_SECRET=cinema-admin-secret-change-in-prod
VariableRequiredDefaultNotes
MYSQL_HOSTYes—MySQL host
MYSQL_PORTYes—MySQL port
MYSQL_USERYes—MySQL user
MYSQL_PASSWORDYes—MySQL password
MYSQL_DATABASEYes—Database name
PORTYes3000Must be 5000 to match the client
JWT_SECRETYes—Server logs a warning on startup if missing

Database Setup

Run these scripts once, in order:

npm run db:create   # creates CPE241_final_project (no tables)
npm run db:schema   # drops and recreates all 9 tables + indexes (re-runnable)
npm run db:seed     # hashes passwords and inserts demo data (re-runnable)

Scripts

ScriptCommandPurpose
devnodemonDev server; restarts on src/ or .env change
startnode src/app.jsProduction start
db:createnode scripts/001_create_database.jsCreate the database
db:schemanode scripts/002_schema.jsRun schema SQL (safe to re-run)
db:seednode scripts/003_seed.jsRun seed SQL (safe to re-run)

Project Structure

server/
├── src/
│   ├── app.js                    # Express app: cors → json → routes → notFound → errorHandler
│   ├── config/
│   │   └── env.js                # dotenv.config() — must be the first require
│   ├── db/
│   │   └── pool.js               # mysql2/promise pool (dateStrings, decimalNumbers)
│   ├── middleware/
│   │   ├── auth.middleware.js    # requireAuth, requireAdmin, requireCustomer
│   │   └── error.middleware.js   # notFound (404) and errorHandler (500/4xx)
│   ├── routes/
│   ├── controllers/
│   ├── services/
│   └── models/
└── scripts/
    ├── 001_create_database.js / .sql
    ├── 002_schema.js / .sql      # all 9 tables + 5 indexes
    └── 003_seed.js / .sql        # demo data with hashed passwords

Every feature follows the same four-layer chain:

routes/*.routes.js
  → controllers/*.controller.js   (parse req, call service, send res)
    → services/*.service.js       (business logic and validation)
      → models/*.model.js         (SQL queries only)
        → db/pool.js

API Reference

All routes are under /api. Endpoints marked 🔒Admin require a JWT with role = 'Admin'. Endpoints marked 🔒Customer require a JWT with role = 'Customer'.

Health

MethodPathAuthDescription
GET/healthopenMySQL version + host + database

Auth

MethodPathAuthDescription
POST/auth/loginopen{ email, password } → { token, user } (Admin role only)
POST/auth/customer/loginopen{ email, password } → { token, user } (Customer role only)

Movies

MethodPathAuthDescription
GET/moviesopenList movies; ?search= ?status=
POST/movies🔒AdminCreate movie
PUT/movies/:id🔒AdminUpdate movie
DELETE/movies/:id🔒AdminDelete movie (409 if showings exist)

Venues

MethodPathAuthDescription
GET/venuesopenList venues with seat counts
POST/venues🔒AdminCreate venue
PUT/venues/:id🔒AdminUpdate venue
DELETE/venues/:id🔒AdminDelete venue
GET/venues/:id/seatsopenList seat numbers in a venue
POST/venues/:id/seats🔒AdminAssign seat number strings
DELETE/venues/:id/seats/:seatId🔒AdminRemove a seat from a venue

Showings

MethodPathAuthDescription
GET/showingsopenList showings; ?venueId= ?date=; includes movie title, venue name, sold/capacity
POST/showings🔒AdminCreate showing + auto-populate reserved_seats (atomic transaction, FOR UPDATE overlap check)
PUT/showings/:id🔒AdminUpdate showing (overlap check)
DELETE/showings/:id🔒AdminDelete showing (409 if bookings exist)

Bookings (Admin)

MethodPathAuthDescription
GET/bookings🔒AdminList bookings; ?search= ?status= ?dateFrom= ?dateTo= ?page= ?limit= (max 200)
PUT/bookings/:id/cancel🔒AdminCancel booking (transaction: reserved_seats → Free + booking → Cancel)

Customer

MethodPathAuthDescription
GET/customer/showings/:showingId/seats🔒CustomerAvailable seat map for a screening
POST/customer/bookings🔒CustomerCreate booking (reserves seats)
GET/customer/bookings/latest🔒CustomerLatest booking for the current customer
GET/customer/bookings/:id🔒CustomerBooking detail
POST/customer/bookings/:id/checkout🔒CustomerAdvance booking to Checkout status
POST/customer/bookings/:id/complete🔒CustomerComplete payment (→ Successful)

Dashboard

MethodPathAuthDescription
GET/dashboard/stats🔒AdminActive movies + screens online today + today's bookings + today's revenue
GET/dashboard/trend🔒AdminBooking count per day, last 7 days (CTE zero-filled)
GET/dashboard/upcoming🔒AdminToday's showings with sold/capacity

Reports

MethodPathAuthDescription
GET/reports/stats🔒Admin?period=weekly|monthly|yearly → revenue + top movie + occupancy %
GET/reports/revenue/daily🔒Admin?period= → daily revenue (CTE zero-filled)
GET/reports/revenue/monthly🔒AdminMonthly revenue for last 12 months (CTE zero-filled)
GET/reports/breakdown🔒Admin?period= ?groupBy=date|movie|venue ?metric=sales|occupancy

Database Schema

Tables

TablePKPurpose
users_profileuser_idAccounts for both admins and customers. role ENUM(Customer, Admin). password is a bcrypt hash.
venuesvenues_idPhysical cinema halls
seatsseat_idIndividual seat labels (e.g. A1, B5)
showtimesshow_idMovie catalog (table is named showtimes but stores movies)
contain_seats(venues_id, seat_id)Seating plan: which seats exist in which venue
showingshowing_idScreening schedule: movie + venue + date + time
reserved_seats(showing_id, seat_id)Seat status per screening: Free, Reserved, Confirmed
bookingbooking_idBooking transaction: customer + showing + status
booking_items(booking_id, seat_id)Individual seats within a booking

Key constraints

ConstraintDetail
showing UNIQUE(venues_id, showtime_date, start_time) — one show per hall per timeslot
reserved_seats PK(showing_id, seat_id) — seat status is per screening
booking_items PK(booking_id, seat_id) — same seat cannot appear twice in one booking
All foreign keysON DELETE RESTRICT — child rows must be removed first

Movie effective status

The stored status column is overridden by dates in every query:

CASE
  WHEN status IN ('Hidden', 'Ended') THEN status
  WHEN end_date IS NOT NULL AND CURDATE() > end_date THEN 'Ended'
  WHEN release_date IS NOT NULL AND CURDATE() < release_date THEN 'Upcoming'
  WHEN status = 'Open' THEN 'Open'
  ELSE 'Upcoming'
END

Booking status flow

Booking → Checkout → Successful
                   ↘ Cancel (admin action)

Business Logic

Auto-populate seats on showing create

When a new showing is created, the server wraps three operations in one transaction:

  1. SELECT … FOR UPDATE on showing — overlap check (prevents two concurrent inserts for the same hall/time).
  2. INSERT INTO showing — the new screening row.
  3. INSERT INTO reserved_seats SELECT … FROM contain_seats — one row per seat in that venue, all status = 'Free'.

If any step fails the transaction rolls back completely.

Cancel booking transaction

BEGIN;
  UPDATE reserved_seats SET status = 'Free'
    WHERE showing_id = ? AND seat_id IN (SELECT seat_id FROM booking_items WHERE booking_id = ?);
  UPDATE booking SET status = 'Cancel' WHERE booking_id = ?;
COMMIT;

Both updates succeed together or neither does.

CTE zero-fill for charts

Trend and revenue queries use recursive CTEs to generate a complete date/month range, then LEFT JOIN actual data so days with no activity appear as 0 rather than being missing from the chart.


Performance Indexes

Five indexes added in 002_schema.sql:

IndexTableColumnsUsed by
idx_booking_datebooking(date)Dashboard today stats, trend chart, booking list
idx_booking_status_datebooking(status, date)Report revenue queries (Successful + date range)
idx_showing_dateshowing(showtime_date)Dashboard upcoming, screen management filter
idx_showing_venue_dateshowing(venues_id, showtime_date)Overlap check on every showing create/update
idx_rs_showing_statusreserved_seats(showing_id, status)Sold/capacity aggregation (covering index)

Seed Data

TableRowsNotes
users_profile222 Admin, 20 Customer
venues4CineMax Hall A, StarPlex Hall B, MegaScreen Hall C, Galaxy Hall D
seats160Multiple layouts per venue
showtimes12Mix of Open / Upcoming / Ended
showing168Spread across multiple dates
reserved_seats~6 720168 showings × 40 seats
booking~170Mix of all four statuses

Seed credentials:

RoleEmailPassword
Adminadmin@cinema.comAdmin@1234
Cinema Managermanager@cinema.comManager@1234
Customer (×20)john@example.com …User@1234

Notes and Gotchas

  • pool.js config — dateStrings: ['DATE'] keeps MySQL DATE columns as plain YYYY-MM-DD strings (prevents ISO datetime conversion). decimalNumbers: true returns DECIMAL/SUM() results as JavaScript numbers (prevents .toFixed() crashes).
  • showtimes naming — The table stores the movie catalog, not showtimes. showing is the actual schedule. This naming inversion exists in the schema and is preserved for now.
  • PORT fallback — app.js falls back to 3000 if PORT is unset. Always set PORT=5000 in .env.
  • JWT_SECRET warning — server logs a startup warning if JWT_SECRET is missing but still starts.

License

Original code and documentation authored by Jakkarin Promsee are licensed under the MIT License. Third-party code, assets, datasets, and other materials are not covered by this license; their original terms apply.