0% found this document useful (0 votes)
4 views54 pages

Implement&Test

The report details the design, implementation, and testing progress of an Online Cinema Ticket Booking System developed by students at Hanoi University of Science and Technology. It outlines the system's architecture, including a multi-tier design with a React.js frontend and a Spring Boot backend, as well as the successful integration of features like secure payment processing and a dynamic pricing engine. The project is currently transitioning into an intensive testing phase after achieving core functional milestones, positioning it for future enhancements and deployment.

Uploaded by

Hoàng Minh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views54 pages

Implement&Test

The report details the design, implementation, and testing progress of an Online Cinema Ticket Booking System developed by students at Hanoi University of Science and Technology. It outlines the system's architecture, including a multi-tier design with a React.js frontend and a Spring Boot backend, as well as the successful integration of features like secure payment processing and a dynamic pricing engine. The project is currently transitioning into an intensive testing phase after achieving core functional milestones, positioning it for future enhancements and deployment.

Uploaded by

Hoàng Minh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

HANOI UNIVERSITY OF SCIENCE AND TECHNOLOGY

SCHOOL OF INFORMATION AND COMMUNICATION TECHNOLOGY

SYSTEM DESIGN, IMPLEMENTATION


AND TESTING PROGRESS REPORT
Online Cinema Ticket Booking System

Course: Software Egineering - IT4082E


Instructors: Ph.D. Bui Thi Mai Anh
Ph.D. Nguyen Quoc Tuan
Students: Luong Hoang Minh - 20235974
Ngo Quang Anh - 20235887
Nguyen Le Hung - 20235942
Nguyen Anh Duc - 20235914
Pham Xuan Tuan - 20236010

Ha Noi, December 2025


Contents

Executive Summary 4

1 Use Case Analysis 6


1.1 Member Use Case Specification . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Admin Use Case Specification . . . . . . . . . . . . . . . . . . . . . . . . 8

2 System Architecture Design 10


2.1 High - level Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2 Component Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

3 Database Design 20
3.1 Entity Relationship Diagram (ERD) . . . . . . . . . . . . . . . . . . . . 20
3.2 Data Schema Specification . . . . . . . . . . . . . . . . . . . . . . . . . . 24

4 Detail Process Design 31


4.1 Login Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.2 Booking Creation Sequence . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.3 Payment Process Sequence . . . . . . . . . . . . . . . . . . . . . . . . . . 40

5 Implementation Progress 45
5.1 Completed Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
5.2 Planned & In-Progress Features . . . . . . . . . . . . . . . . . . . . . . . 46

6 Testing Progress 48
6.1 Test Cases & Coverage Status . . . . . . . . . . . . . . . . . . . . . . . . 48
6.1.1 Backend Tests (Spring Boot) . . . . . . . . . . . . . . . . . . . . . 48
6.1.2 Frontend Tests (ReactJS) . . . . . . . . . . . . . . . . . . . . . . 49
6.2 Testing Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
6.2.1 Current Testing Strategy . . . . . . . . . . . . . . . . . . . . . . . 50
6.2.2 Recommended Testing Strategy . . . . . . . . . . . . . . . . . . . 50
6.2.3 Tools Used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
6.3 Issues Found & Current Resolution Status . . . . . . . . . . . . . . . . . . 51
6.3.1 Known Issues (Resolved) . . . . . . . . . . . . . . . . . . . . . . . . 51

2
6.3.2 Potential Issues (To Be Tested) . . . . . . . . . . . . . . . . . . . . 51
6.3.3 Testing Gaps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
6.4 Testing Roadmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52

7 Conclusion 53

List of Figures

1.1 Member Use Case Diagram of the Online Cinema Booking System . . . . 6
1.2 Admin Use Case Diagram of the Online Cinema Booking System . . . . . 8

2.1 Hight - level Architecture Design of the Online Cinema Booking System . 10
2.2 Component Diagram of the Online Cinema Booking System . . . . . . . 15

3.1 Entity Relationship Diagram of the Online Cinema Booking System . . . 20


3.2 Schema Design of the Online Cinema Booking System . . . . . . . . . . . 24

4.1 Login Sequences of the Online Cinema Booking System . . . . . . . . . . . 31


4.2 Booking Creation Sequence Sequences of the Online Cinema Booking System 35
4.3 Payment Process Sequence Sequences of the Online Cinema Booking System 40

3
Executive Summary

This report presents a comprehensive analysis of the system design, architectural


decisions, and implementation progress of the HDQ Cinema project. The primary
objective of this initiative is to engineer a robust, automated online ticket booking
platform that replaces manual ticketing processes. By digitizing the entire workflow—from
movie discovery and seat selection to secure online payments—the system is designed
to significantly enhance user convenience while providing cinema administrators with
powerful tools for operational management and revenue optimization.
The system is built upon a modern, scalable multi-tier architecture that ensures a
clear separation of concerns between the user interface, business logic, and data persistence
layers. The frontend is developed using [Link] integrated with Ant Design components
to deliver a responsive and intuitive user experience. This communicates via RESTful
APIs with a backend powered by Spring Boot, which encapsulates complex business rules
and security protocols. Data integrity is maintained by a PostgreSQL database, designed
with a normalized schema to handle complex relationships between movies, showtimes,
and bookings. Furthermore, to facilitate consistent deployment across development and
production environments, the entire infrastructure has been containerized using Docker
and orchestrated via Docker Compose.
In terms of implementation, the project has successfully achieved its core functional
milestones. A robust security module has been deployed using Spring Security and
JWT (JSON Web Tokens), enabling stateless authentication, role-based access control
(Admin vs. Member), and secure session management. The core booking engine is fully
operational, featuring a visual seat map that updates in real-time to reflect seat availability
(Available, Held, or Booked). Crucially, the financial transaction flow has been solidified
through the successful integration of the VNPAY payment gateway, which includes
secure URL generation and callback handling to automatically verify and update booking
statuses without manual intervention.
A significant portion of the development effort was dedicated to resolving high-priority
technical challenges inherent in concurrent booking systems. The team successfully
addressed race conditions—where multiple users attempt to book the same seat simul-
taneously—by implementing strict database-level unique constraints on booking details.
To ensure data hygiene and maximize seat inventory, a background scheduler was imple-

4
System Design, Implementation and Testing Progress List of Figures

mented to run every five minutes, automatically releasing seats associated with bookings
that remain pending for more than 15 minutes. Additionally, a complex dynamic pricing
engine was engineered using native SQL queries, allowing the system to calculate ticket
prices accurately based on variable factors such as seat class (VIP/Classic) and day type
(Weekends/Holidays).
Finally, to ensure the reliability and stability of the software, a comprehensive testing
strategy has been adopted. The team is utilizing JUnit 5 for backend logic verification
and React Testing Library for frontend component validation. While the project is
currently moving from feature development to an intensive testing phase, the foundational
work regarding architecture and core functionality is complete. The HDQ Cinema system
stands as a technically feasible, secure, and scalable solution ready for advanced feature
expansion and eventual production deployment.

5
Chapter 1

Use Case Analysis

1.1 Member Use Case Specification

Figure 1.1: Member Use Case Diagram of the Online Cinema Booking System

The Use Case Diagram presented in the figure defines the functional scope and
primary interactions within the Customer module of the Movie Ticket Booking System.
The system interacts with two distinct user actor categories: Guest and Registered
Guest. Both actors inherit from a generalized Customer actor, accurately reflecting
a generalization relationship where basic functionalities are shared. While the Guest
is primarily associated with Create Account and initial exploration, the Registered

6
System Design, Implementation and Testing Progress Chapter 1. Use Case Analysis

Guest possesses elevated privileges to access personal management functions such as


Login, View Booking History, and Get Notification.
Regarding the core business workflow, the Search Movie function serves as the
foundation for content discovery. This use case is extended (<<extend>>) by optional
functionalities like Sort Movie and View Movie Details, designed to enhance the user
experience. The central transactional flow revolves around the Book Ticket use case,
initiated exclusively by the Registered Guest. This use case acts as the primary process
and is extended by specific booking steps, including Select Showtime, Select Seat, and
Create Booking. Crucially, to ensure the integrity of the commercial transaction, the
Book Ticket function maintains a mandatory include (<<include>>) relationship with
the Pay by Online Bank function. This process subsequently includes the Process
Payment step, which interacts directly with the external Payment System actor to
finalize the fund transfer and confirm the ticket.

7
System Design, Implementation and Testing Progress Chapter 1. Use Case Analysis

1.2 Admin Use Case Specification

Figure 1.2: Admin Use Case Diagram of the Online Cinema Booking System

The Use Case Diagram presented in the figure defines the administrative functional
scope and operational privileges within the Admin module of the Movie Ticket Booking
System. The system interacts with a single primary actor, the Admin, who is responsible
for maintaining the system’s core data and business configurations.

8
System Design, Implementation and Testing Progress Chapter 1. Use Case Analysis

The Admin possesses comprehensive authority to execute five key management


functionalities: Manage Movies (handling film content), Manage Cinemas (handling
location data), Manage Rooms (configuring auditorium layouts), Manage Showtime
(scheduling screenings), and Manage Pricing (setting ticket costs).
Crucially, the diagram enforces a strict security constraint through the include
(<<include>>) relationship. Every specific management use case—Manage Movies,
Manage Cinemas, Manage Rooms, Manage Showtime, and Manage Pric-
ing—maintains a mandatory dependency on the Login use case. This signifies that
authentication is a prerequisite condition; the Admin cannot initiate any of these ad-
ministrative tasks without first successfully completing the Login process to verify their
identity.

9
Chapter 2

System Architecture Design

2.1 High - level Architecture

Figure 2.1: Hight - level Architecture Design of the Online Cinema Booking System

System overview

The HDQ Cinema system follows a three-tier architecture: Frontend Layer,


Backend Layer, and Database Layer. The system uses RESTful API communi-
cation between Frontend and Backend, secured with JWT (JSON Web Token)
authentication. The entire system is containerized using Docker and orchestrated
with Docker Compose, enabling easy deployment, scaling, and management. This
architecture ensures separation of concerns, maintainability, and scalability.

10
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

Front - end Layer Operations

The Frontend Layer is built using [Link], a modern JavaScript library for building
user interfaces. React Router manages client-side routing, enabling navigation
between different pages such as HomePage (/), MovieDetail (/movie-detail/:id),
SeatSelection (/seat-selection), ConfirmPayment (/confirm-payment), and Login
(/login). Ant Design provides a comprehensive set of UI components including
Layout, Tabs, Buttons, Forms, and Modals, ensuring a consistent and professional
user interface. The API Service Layer acts as a centralized communication hub be-
tween the Frontend and Backend. It provides abstraction functions like getMovies(),
getShowtimes(), createBooking(), createPayment(), and login() that handle HTTP
requests, error handling, and response parsing. When a user interacts with the UI,
React components trigger these API functions, which send HTTP requests to the
Backend endpoints. The responses are then processed and used to update the React
component state, triggering re-renders to display the updated information to the
user.

Backend Layer - Presentation Tier (Controllers)

The Controller Layer serves as the entry point for all incoming HTTP re-
quests from the Frontend. Controllers such as MovieController, BookingCon-
troller, PaymentController, AuthenticationController, CinemaController,
and ShowTimeController are responsible for handling specific REST endpoints.
Each controller receives HTTP requests, validates the incoming data, extracts re-
quest parameters and body content, and delegates business logic processing to the
appropriate Service layer components. Controllers do not contain business logic;
instead, they act as coordinators that transform HTTP requests into service method
calls and convert service responses into HTTP responses. They handle HTTP
status codes, error responses, and ensure proper data serialization to JSON
format. The controllers also interact with the exception handling mechanism to
provide meaningful error messages to clients.

Backend Layer - Business Tier (Services)

The Service Layer contains the core business logic of the application. BookingSer-
vice manages the entire booking lifecycle: it creates bookings with seat reservations,
sets seats to HELD status to prevent other users from booking them, calculates
total prices using dynamic pricing logic, and handles payment approval to change
booking status from PENDING to CONFIRM. The service also manages the
automatic cleanup of expired bookings through the deleteExpiredBookings() method.

11
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

PaymentService integrates with the VNPAY payment gateway by generating


secure payment URLs with HMAC SHA512 signatures. It constructs payment
parameters including amount, order information, transaction reference, and expira-
tion time, then creates a signed URL that redirects users to VNPAY for payment
processing. After payment completion, VNPAY sends a callback to the backend,
which the PaymentService processes to verify payment status and update booking
accordingly. AuthenticationService handles user authentication by validating
credentials against the database, generating JWT tokens with user information
and roles, managing token refresh mechanisms, and handling logout by invalidating
tokens. The service uses BCrypt password encoding for secure password storage
and verification. TicketPriceService implements complex dynamic pricing logic
that calculates ticket prices based on multiple factors including seat type (VIP or
Classic), day type (Holiday, Weekend, or Weekday), and cinema location. This
service uses native SQL queries to efficiently retrieve pricing information from
the database. Services utilize Mappers (MapStruct) to convert between Entity
objects and DTOs (Data Transfer Objects), ensuring that internal domain
models are not exposed directly to the API layer. Services also manage transac-
tions to ensure data consistency, particularly critical in booking operations where
multiple database operations must succeed or fail together.

Backend Layer - Data Access Tier (Repositories)

The Repository Layer provides an abstraction for data access operations us-
ing JPA (Java Persistence API) and Hibernate ORM. Repositories such as
BookingRepository, MovieRepository, TicketPriceRepository, BookingDe-
tailRepository, and ShowTimeRepository extend JpaRepository, providing
standard CRUD operations and custom query methods. BookingDetailRepository
implements a unique constraint on the combination of seat_id and showtime_id,
preventing the same seat from being booked twice for the same showtime. This
constraint is enforced at the database level, providing a robust solution to race
conditions that could occur when multiple users attempt to book the same seat
simultaneously. TicketPriceRepository contains a complex native SQL query in
the toPrice() method that joins multiple tables (ticket_price, show_time, cin-
ema, and day_type) to calculate dynamic pricing. The query uses COALESCE
functions to handle cases where day types might not match exactly, falling back
to day-of-week calculations. Repositories interact directly with the PostgreSQL
database through JPA, which handles SQL generation, connection management,
and result set mapping. The repositories also support custom queries using @Query
annotations for complex operations that cannot be expressed through standard JPA

12
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

[Link], showtime options, and a call-to-action for booking.

Security and Authentication Flow

Spring Security is configured to protect all endpoints except public ones using JWT
authentication. The Security Filter Chain intercepts every incoming HTTP
request, extracts the JWT token from the Authorization header, validates the
token’s signature and expiration, extracts user information and roles from the token
claims, and allows the request to proceed to the Controller if validation succeeds.
Public endpoints that do not require authentication include /accounts (POST) for
user registration, /auth/token (POST) for login, /auth/introspect (POST) for
token validation, /auth/logout (POST) for logout, and /auth/refresh (POST)
for token refresh. All other endpoints require a valid JWT token in the request
header. CSRF (Cross-Site Request Forgery) protection is disabled because the
system uses stateless JWT authentication with tokens sent in HTTP headers
rather than cookies. This is appropriate for REST APIs and eliminates the
need for CSRF tokens while maintaining security through JWT validation.
CORS (Cross-Origin Resource Sharing) is configured to allow requests from
the Frontend origin ([Link] enabling the React application
to make API calls to the Backend running on a different port. The CORS
configuration allows all HTTP methods and headers, providing flexibility for
API communication.

Scheduled Tasks and Background Processing

The BookingDeleteScheduler is a scheduled task that runs automatically every 5


minutes using Spring’s @Scheduled annotation. This scheduler calls BookingSer-
[Link]() to identify and remove bookings that have been in
PENDING status for more than 15 minutes. The process involves querying the
database for expired bookings, deleting associated booking details through cascade
operations, and releasing the seats back to available status. This automated cleanup
ensures that seats are not held indefinitely when users abandon the payment process,
improving seat availability for other users.

Database Layer Operations

PostgreSQL serves as the persistent storage for all system data, including movies,
showtimes, seats, bookings, cinemas, rooms, members, and ticket prices. JPA/Hiber-
nate manages the Object-Relational Mapping (ORM) between Java entity

13
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

classes and database tables, automatically generating SQL queries and handling
result set mapping. Transactions are crucial for maintaining data consistency,
especially in booking operations where multiple related records must be created
atomically. The @Transactional annotation ensures that all database operations
within a method either complete successfully or are rolled back together, preventing
partial updates that could lead to data inconsistency. Unique constraints at the
database level provide an additional layer of protection against race conditions. The
unique constraint on booking_detail(seat_id, showtime_id) ensures that even
if two requests attempt to book the same seat simultaneously, only one will succeed,
with the other receiving a database constraint violation error.

External Services Integration

The VNPAY Payment Gateway integration enables secure online payment


processing. When a user creates a booking, the PaymentService generates a
payment URL by constructing a parameter map with transaction details, signing the
parameters using HMAC SHA512 with a secret key, and creating a secure URL that
redirects users to VNPAY’s payment interface. After payment processing, VNPAY
sends a callback request to the backend’s /payments/payment_infor endpoint
with payment result information including response code, transaction reference, and
payment amount. The [Link]() method processes
this callback: if the response code is "00" (success), it approves the booking and
updates seat status to BOOKED; if the code is "24" (cancelled), it deletes the
booking and releases seats; for other error codes, it throws an exception to indicate
payment failure.

Deployment Infrastructure

The entire system is containerized using Docker, with separate containers for
Frontend, Backend, and Database. The Frontend container runs the React
application on port 3000, the Backend container runs the Spring Boot
application on port 8080, and the Database container runs PostgreSQL on
port 5433 (mapped from internal port 5432). Docker Compose orchestrates
these containers, managing their lifecycle, networking between containers, and
volume persistence for database data. The compose file defines environment
variables for database credentials, JWT signing keys, and other configuration
parameters. This containerized approach ensures consistent deployment across
different environments and simplifies scaling and maintenance operations.

14
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

Typical Data Flow Scenarios

Booking Flow: When a user selects seats and initiates a booking, the Frontend
sends a POST request to /bookings with booking details. The Booking-
Controller receives the request and calls [Link](). The
service validates the member and showtime, calculates prices for each seat using
[Link](), creates Booking and BookingDetail enti-
ties with HELD status, and saves them to the database. The unique constraint
on booking_detail(seat_id, showtime_id) prevents double booking at the
database level. The response returns the booking ID to the Frontend, which then
redirects to the payment page. Payment Flow: The Frontend calls PaymentSer-
[Link]() with the booking ID. The service retrieves booking details,
constructs VNPAY payment parameters, generates a signed payment URL, and
returns it to the Frontend. The user is redirected to VNPAY for payment. After
payment, VNPAY sends a callback to the backend, which processes the result and
updates the booking status accordingly. Authentication Flow: When a user logs
in, the Frontend sends credentials to /auth/token. The AuthenticationService
finds the user in the database, verifies the password using BCrypt, generates a JWT
token with user information and roles, and returns the token. The Frontend stores
the token in localStorage and includes it in subsequent API requests. Spring
Security validates the token for each protected endpoint request.

2.2 Component Diagram

Figure 2.2: Component Diagram of the Online Cinema Booking System

Frontend Components Layer

The Frontend package contains six main components that handle user interactions
and API communication. The HomePage component displays the main landing page
with movie listings, allowing users to browse available and upcoming movies. The

15
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

MovieDetail component shows comprehensive information about a selected movie,


including description, trailer, showtimes, and booking options. The SeatSelection
component provides an interactive seat map where users can visually select their
preferred seats for a specific showtime. The ConfirmPayment component handles
the payment confirmation process, displaying booking summary and payment options
before redirecting to the payment gateway. The Login component manages user
authentication, collecting credentials and handling the login flow. All these UI
components depend on the APIService component, which serves as a centralized
communication layer that abstracts all HTTP requests to the Backend, handles error
responses, manages authentication tokens, and provides a consistent interface for
API interactions.

Backend Controllers Layer

The Backend Controllers package contains six REST controllers that serve as
entry points for different functional areas of the application. The MovieController
handles movie-related endpoints, processing requests to retrieve movie lists, filter
movies by status (showing/upcoming), and get detailed movie information. The
BookingController manages booking operations, receiving booking creation requests,
handling payment approval, and providing booking status information. The Cinema-
Controller processes requests related to cinema information, allowing clients to
retrieve cinema lists and details. The PaymentController handles payment-related
operations, creating payment URLs and processing payment callbacks from external
gateways. The ShowTimeController manages showtime creation and retrieval
operations. The AuthenticationController handles all authentication-related
endpoints including login, token refresh, logout, and token introspection. Each con-
troller receives HTTP requests from the APIService, validates the incoming
data, and delegates business logic processing to corresponding Service components.
Controllers are responsible for transforming HTTP requests into service method
calls and converting service responses into properly formatted HTTP responses with
appropriate status codes.

Backend Services Layer

The Backend Services package contains the core business logic components
that orchestrate complex operations and coordinate between multiple repositories.
The MovieService handles movie-related business logic, including filtering movies
by release dates and cinema locations. The BookingService is one of the most
critical services, managing the entire booking lifecycle: it creates bookings with

16
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

seat reservations, calculates total prices, manages booking status transitions from
PENDING to CONFIRM, and coordinates with the BookingDeleteScheduler
for automatic cleanup of expired bookings. The CinemaService manages cinema-
related operations, while the PaymentService integrates with external payment
gateways, generating secure payment URLs, processing payment callbacks, and
updating booking statuses based on payment results. The ShowTimeService
handles showtime management operations. The AuthenticationService manages
user authentication, password verification, JWT token generation and validation, and
token refresh mechanisms. The TicketPriceService implements complex dynamic
pricing calculations that consider multiple factors including seat type, day type,
and cinema location. The BookingDeleteScheduler is a specialized component
that runs periodically to clean up expired bookings, ensuring seat availability is
maintained. Services coordinate with multiple repositories to retrieve and persist
data, use mappers to convert between entities and DTOs, and manage transactions
to ensure data consistency.

Backend Repositories Layer

The Backend Repositories package contains data access components that provide
abstraction over database operations. The MovieRepository handles all database
operations related to movies, including queries to find movies by various criteria.
The BookingRepository manages booking data persistence and retrieval, including
queries to find bookings by status and creation time for cleanup operations. The
BookingDetailRepository is particularly important as it manages the relation-
ship between bookings, seats, and showtimes, and enforces the unique constraint
that prevents double booking. The CinemaRepository, ShowTimeRepository,
and SeatRepository handle data access for their respective entities. The Tick-
etPriceRepository contains complex native SQL queries for dynamic price cal-
culation, joining multiple tables to determine the correct price based on various
conditions. The MemberRepository manages user data access, including authen-
tication queries. All repositories extend JpaRepository, providing standard CRUD
operations, and implement custom query methods when needed. Repositories interact
directly with the PostgreSQL database, executing SQL queries and mapping results
to entity objects.

Security Components

The Security package contains components responsible for authentication and


authorization. The SecurityConfig component configures the entire security frame-

17
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

work, setting up JWT authentication, defining public and protected endpoints,


configuring CORS policies, and disabling CSRF protection for REST API com-
patibility. The CustomJwtToken component handles JWT token decoding and
validation, extracting user information and roles from token claims. The Jw-
tAuthenticationEntryPoint component handles unauthorized access attempts,
providing appropriate error responses when authentication fails. These security
components work together to protect the application, with SecurityConfig coordi-
nating the security filter chain, CustomJwtToken validating incoming tokens, and
JwtAuthenticationEntryPoint handling authentication failures gracefully.

Database and External Services

The PostgreSQL database component represents the persistent storage


layer, storing all application data including movies, showtimes, seats, bookings,
users, cinemas, and pricing information. All repository components interact with
this database to perform CRUD operations, execute queries, and maintain data
integrity through transactions and constraints. The VNPAY cloud component
represents the external payment gateway service. The PaymentService
component communicates with VNPAY to generate payment URLs and process
payment callbacks. This external integration enables secure online payment
processing without the application needing to handle sensitive payment information
directly.

Component Interactions and Data Flow

The component interactions follow a clear hierarchical pattern. Frontend compo-


nents communicate with the APIService, which in turn sends HTTP requests
to Backend Controllers. Controllers delegate business logic to Services, which
coordinate operations across multiple Repositories. Repositories interact with
the PostgreSQL database to persist and retrieve data. The BookingService
demonstrates complex interactions: it communicates with BookingRepository to
save bookings, BookingDetailRepository to manage seat reservations, Ticket-
PriceRepository to calculate prices, and BookingDeleteScheduler to trigger
cleanup operations. The PaymentService interacts with BookingRepository
to update booking statuses and communicates with the external VNPAY service
for payment processing. Security components are integrated throughout the flow:
SecurityConfig protects all endpoints, CustomJwtToken validates tokens for
each request, and both BookingService and AuthenticationService interact with
SecurityConfig to ensure proper authentication and authorization.

18
System Design, Implementation and Testing Progress
Chapter 2. System Architecture Design

Transaction Management and Data Consistency

Services manage transactions to ensure data consistency, particularly in booking


operations where multiple database operations must succeed or fail together. When
[Link]() is called, it creates a transaction that includes
validating the member, validating the showtime, calculating prices, creating the book-
ing record, and creating multiple booking detail records. If any step fails, the entire
transaction is rolled back, preventing partial bookings. The unique constraint on
BookingDetail(seat_id, showtime_id) enforced by BookingDetailReposi-
tory provides an additional layer of protection at the database level, ensuring that
even under high concurrency, the same seat cannot be booked twice for the same
showtime.

Scheduled Operations

The BookingDeleteScheduler component operates independently, triggered by


Spring’s scheduling mechanism every 5 minutes. It calls [Link]
to identify and remove bookings that have been in PENDING status for more than
15 minutes. This automated process ensures that seats are released back to available
status when users abandon the payment process, maintaining system efficiency and
seat availability.

19
Chapter 3

Database Design

3.1 Entity Relationship Diagram (ERD)

Figure 3.1: Entity Relationship Diagram of the Online Cinema Booking System

Core Business Entities

Cinema Entity represents physical cinema locations in the system. Each cinema has
a unique identifier (cinema_id), along with location information including name,
city, district, and full address. This entity serves as the top-level organizational
unit, with each cinema containing multiple rooms and having its own pricing
structure. Room Entity represents individual screening auditoriums within a

20
System Design, Implementation and Testing Progress Chapter 3. Database Design

cinema. Each room has a unique identifier (room_id) and a name for identification.
The room belongs to a specific cinema through the cinema_id foreign key,
establishing a one-to-many relationship where one cinema can have multiple
rooms. Each room contains multiple seats and hosts multiple showtimes. Seat
Entity represents individual seats within a room. Each seat has a unique identifier
(seat_id), a seat number, a seat row (typically a character like ’A’, ’B’, ’C’),
and a seat type (VIP or CLASSIC). The seat belongs to a specific room through
the room_id foreign key. Seats can be reserved through booking details, creating
a many-to-many relationship with showtimes through the booking_detail
junction entity. Movie Entity stores information about films available for
screening. It contains a unique identifier (movie_id), title, poster URL, duration in
minutes, release dates (day_start and day_end), director name, genre, description,
trailer URL, and age limitation. Each movie can have multiple showtimes scheduled
at different times and in different rooms. ShowTime Entity represents a scheduled
screening of a movie at a specific time in a specific room. It has a unique identifier
(showtime_id), a start time (timestamp), and foreign keys to both the movie
and room. A unique constraint on the combination of start_time and room_id
ensures that the same room cannot have overlapping showtimes, preventing scheduling
conflicts.

Booking and Transaction Entities

Member Entity represents registered users of the cinema system. Each member has
a unique identifier (member_id), a unique username for login, an encrypted
password (stored using BCrypt), email address, phone number, and date of birth.
Members can create multiple bookings, establishing a one-to-many relationship
with the booking entity. Booking Entity represents a booking transaction made by a
member. It contains a unique identifier (booking_id), total price (calculated from
individual seat prices), creation timestamp, and booking status (PENDING or
CONFIRM). The booking belongs to a specific member through the member_id
foreign key. A booking can contain multiple booking details, each representing a
reserved seat. BookingDetail Entity is a junction entity that connects bookings,
seats, and showtimes. It contains a unique identifier (id), individual seat price,
seat status (AVAILABLE, HELD, or BOOKED), and foreign keys to booking,
seat, and showtime. The critical unique constraint on the combination of
seat_id and showtime_id prevents the same seat from being booked twice for the
same showtime, solving the race condition problem in concurrent booking scenarios.

21
System Design, Implementation and Testing Progress Chapter 3. Database Design

Pricing and Configuration Entities

DayType Entity defines special day categories such as holidays and weekends that
affect ticket pricing. It has a unique identifier (id), a unique day type name,
and date ranges (day_start and day_end) that define when this day type is
active. This allows the system to apply different pricing rules during holidays or
weekends. TicketPrice Entity stores pricing rules that determine ticket costs
based on multiple factors. It contains a unique identifier (id), the price value,
seat type (VIP or CLASSIC), and foreign keys to both day type and cinema.
This design enables dynamic pricing where the same seat type can have different
prices depending on the day type (holiday/weekend) and the cinema location. The
pricing calculation uses complex SQL queries that join these entities to determine
the correct price for a booking.

Employee and Authorization Entities

Employee Entity represents staff members working at cinemas. It contains a


unique identifier (employee_id), position, first name, last name, phone number,
and email address. Each employee can have one employee account for system access.
EmployeeAccount Entity provides login credentials for employees. It has a unique
identifier (id), a unique username, encrypted password, and foreign keys to both
employee and role. This establishes a one-to-one relationship with employee
and a many-to-one relationship with role, allowing employees to have specific
access permissions. Role Entity defines access roles within the system such as
ADMIN or USER. It uses the role name as the primary key and includes a
description. Roles can have multiple permissions through the role_permission
junction entity. Permission Entity defines specific actions or access rights
that can be granted. It uses the permission name as the primary key and
includes a description. Permissions are assigned to roles through the many-to-
many relationship in the role_permission entity. RolePermission Entity is a
junction entity that implements the many-to-many relationship between roles
and permissions. It uses a composite primary key consisting of role_name and
permission_name, allowing flexible permission management where roles can have
multiple permissions and permissions can be assigned to multiple roles.

Supporting Entities

PaymentURL Entity stores VNPAY payment gateway URLs generated for book-
ings. It contains a unique identifier (id), the payment URL string, and foreign
keys to both booking and member. This entity maintains a one-to-one re-
lationship with booking (a booking can have at most one payment URL) and a

22
System Design, Implementation and Testing Progress Chapter 3. Database Design

many-to-one relationship with member (a member can create multiple payment


URLs for different bookings). InvalidatedToken Entity stores JWT tokens that
have been invalidated, typically during logout operations. It contains a unique
identifier (id), the token string, and an expiry time. This allows the system to
maintain a blacklist of invalidated tokens, preventing their reuse even if they
haven’t expired yet.

Relationship Patterns and Business Rules

The ERD demonstrates several important relationship patterns. The hierarchical


structure flows from Cinema to Room to Seat, establishing a clear organizational
hierarchy. The booking flow connects Member to Booking to BookingDetail,
which then links to both Seat and ShowTime, creating a many-to-many rela-
tionship between seats and showtimes through the booking_detail junction
entity. The pricing system uses a flexible design where TicketPrice references
both DayType and Cinema, allowing different cinemas to have different pricing
structures while also considering day types. The employee authorization system uses
a role-based access control (RBAC) pattern with roles, permissions, and
the role_permission junction entity providing flexible permission management.

Data Integrity Constraints

The database design includes several critical constraints that ensure data integrity.
The unique constraint on booking_detail(seat_id, showtime_id) prevents
double booking at the database level, providing a robust solution to race condi-
tions. The unique constraint on show_time(start_time, room_id) prevents
scheduling conflicts where the same room would have overlapping showtimes. The
unique constraint on day_type(day_type) ensures that day type names are
unique across the system. Foreign key constraints maintain referential integrity
throughout the system, ensuring that bookings reference valid members, booking
details reference valid bookings, seats, and showtimes, and all relationships remain
consistent. Cascade delete operations are configured where appropriate, such as
when a booking is deleted, its associated booking details are automatically removed.

Design Patterns and Best Practices

The ERD follows several database design best practices. The use of UUIDs as
primary keys provides globally unique identifiers that are suitable for distributed systems.
Junction entities like booking_detail and role_permission properly implement
many-to-many relationships. The separation of concerns is evident with distinct entities for
business logic (booking, movie) and supporting functionality (employee accounts, tokens).

23
System Design, Implementation and Testing Progress Chapter 3. Database Design

The design supports the application’s business requirements including dynamic


pricing, seat reservation management, and role-based access control. The
structure allows for scalability and maintainability, with clear entity boundaries and well-
defined relationships that support the complex business logic implemented in the service
layer.

3.2 Data Schema Specification

Figure 3.2: Schema Design of the Online Cinema Booking System

Table: cinema

Column Name Data Type Constraints Description


cinema_id VARCHAR(UUID) PRIMARY KEY Unique identifier for cinema
name VARCHAR(255) NOT NULL Cinema name
city VARCHAR(100) NOT NULL City location
district VARCHAR(100) NOT NULL District location

24
System Design, Implementation and Testing Progress Chapter 3. Database Design

Column Name Data Type Constraints Description


address VARCHAR(255) NOT NULL Full address

Table: room

Column Name Data Type Constraints Description


room_id VARCHAR(UUID) PRIMARY KEY Unique identifier for room
room_name VARCHAR(100) NOT NULL Room name/number
cinema_id VARCHAR(UUID) FOREIGN KEY → cin- Reference to parent cinema
ema

Table: seat

Column Name Data Type Constraints Description


seat_id VARCHAR(UUID) PRIMARY KEY Unique identifier for seat
seat_number INTEGER NOT NULL Seat number
seat_row CHAR(1) NOT NULL Seat row (A, B, C, etc.)
seat_type VARCHAR(20) NOT NULL, ENUM(VIP, Type of seat
CLASSIC)
room_id VARCHAR(UUID) FOREIGN KEY → room Reference to parent room

Table: movie

Column Name Data Type Constraints Description


movie_id VARCHAR(UUID) PRIMARY KEY Unique identifier for movie
title VARCHAR(255) NOT NULL Movie title
poster VARCHAR(500) Movie poster URL
duration INTEGER Movie duration in minutes
day_start DATE Movie release start date
day_end DATE Movie release end date
director VARCHAR(100) Director name

25
System Design, Implementation and Testing Progress Chapter 3. Database Design

Column Name Data Type Constraints Description


genre VARCHAR(100) Movie genre
description TEXT Movie description
trailer_url VARCHAR(500) Trailer video URL
limit_age INTEGER Age restriction

Table: show_time

Column Name Data Type Constraints Description


showtime_id VARCHAR(UUID) PRIMARY KEY Unique identifier for
showtime
start_time TIMESTAMP NOT NULL Showtime start date and
time
movie_id VARCHAR(UUID) FOREIGN KEY → Reference to movie
movie
room_id VARCHAR(UUID) FOREIGN KEY → room Reference to room
(start_time, UNIQUE Prevents overlapping
room_id) showtimes

Table: member

Column Name Data Type Constraints Description


member_id VARCHAR(UUID) PRIMARY KEY Unique identifier for member
username VARCHAR(50) NOT NULL, UNIQUE Member username
password VARCHAR(255) NOT NULL Encrypted password
(BCrypt)
email VARCHAR(100) Member email
phone_number VARCHAR(20) Phone number
dob DATE Date of birth

Table: booking

26
System Design, Implementation and Testing Progress Chapter 3. Database Design

Column Name Data Type Constraints Description


booking_id VARCHAR(UUID) PRIMARY KEY Unique identifier for
booking
total_price DECIMAL(10,2) NOT NULL Total booking price
create_time TIMESTAMP NOT NULL Booking creation times-
tamp
booking_status VARCHAR(20) NOT NULL, Booking status
ENUM(PENDING, CON-
FIRM)
member_id VARCHAR(UUID) FOREIGN KEY → member Reference to member

Table: booking_detail

Column Name Data Type Constraints Description


id VARCHAR(UUID) PRIMARY KEY Unique identifier
price DECIMAL(10,2) NOT NULL Individual seat
price
seat_status VARCHAR(20) NOT NULL, Seat reservation sta-
ENUM(AVAILABLE, HELD, tus
BOOKED)
seat_id VARCHAR(UUID) FOREIGN KEY → seat Reference to seat
booking_id VARCHAR(UUID) FOREIGN KEY → booking Reference to book-
ing
showtime_id VARCHAR(UUID) FOREIGN KEY → show_time Reference to show-
time
(seat_id, show- UNIQUE Prevents double
time_id) booking

Table: day_type

Column Name Data Type Constraints Description


id VARCHAR(UUID) PRIMARY KEY Unique identifier

27
System Design, Implementation and Testing Progress Chapter 3. Database Design

Column Name Data Type Constraints Description


day_type VARCHAR(50) NOT NULL, UNIQUE Day type name (HOLIDAY,
WEEKEND, etc.)
day_start DATE Day type start date
day_end DATE Day type end date

Table: ticket_price

Column Name Data Type Constraints Description


id VARCHAR(UUID) PRIMARY KEY Unique identifier
price DECIMAL(10,2) NOT NULL Ticket price
seat_type VARCHAR(20) NOT NULL, ENUM(VIP, Seat type
CLASSIC)
day_type VARCHAR(50) FOREIGN KEY → Reference to day type
day_type
cinema_id VARCHAR(UUID) FOREIGN KEY → cinema Reference to cinema

Table: employee

Column Name Data Type Constraints Description


employee_id VARCHAR(UUID) PRIMARY KEY Unique identifier for em-
ployee
position VARCHAR(100) Employee position
first_name VARCHAR(100) First name
last_name VARCHAR(100) Last name
phone VARCHAR(20) Phone number
email VARCHAR(100) Email address

Table: employee_account

28
System Design, Implementation and Testing Progress Chapter 3. Database Design

Column Name Data Type Constraints Description


id VARCHAR(UUID) PRIMARY KEY Unique identifier
username VARCHAR(50) NOT NULL, UNIQUE Employee username
password VARCHAR(255) NOT NULL Encrypted password
employee_id VARCHAR(UUID) FOREIGN KEY → em- Reference to employee
ployee
role_name VARCHAR(50) FOREIGN KEY → role Reference to role

Table: role

Column Name Data Type Constraints Description


name VARCHAR(50) PRIMARY KEY Role name (ADMIN, USER,
etc.)
description VARCHAR(255) Role description

Table: permission

Column Name Data Type Constraints Description


name VARCHAR(50) PRIMARY KEY Permission name
description VARCHAR(255) Permission description

Table: role_permission

Column Name Data Type Constraints Description


role_name VARCHAR(50) FOREIGN KEY → role Reference to role
permission_name VARCHAR(50) FOREIGN KEY → per- Reference to permission
mission
(role_name, per- PRIMARY KEY Composite primary key
mission_name)

29
System Design, Implementation and Testing Progress Chapter 3. Database Design

Table: payment_url

Column Name Data Type Constraints Description


id VARCHAR(UUID) PRIMARY KEY Unique identifier
payment_url VARCHAR(1000) VNPAY payment URL
booking_id VARCHAR(UUID) FOREIGN KEY → book- Reference to booking
ing
member_id VARCHAR(UUID) FOREIGN KEY → mem- Reference to member
ber

Table: invalidated_token

Column Name Data Type Constraints Description


id VARCHAR(UUID) PRIMARY KEY Unique identifier
token VARCHAR(1000) NOT NULL Invalidated JWT token
expiry_time TIMESTAMP Token expiration time

30
Chapter 4

Detail Process Design

4.1 Login Sequences

Figure 4.1: Login Sequences of the Online Cinema Booking System

31
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

Overview of Authentication Flow

The Login Sequence Diagram illustrates the complete authentication process in


the HDQ Cinema system, showing the interaction between user, frontend com-
ponents, backend services, and the database. The sequence demonstrates how
user credentials are validated, JWT tokens are generated, and authentication
responses are handled, including both successful login scenarios and error cases.

Initial User Interaction

The authentication flow begins when a user interacts with the Login Page
component on the Frontend. The user enters their username and password
credentials into the login form. When the user clicks the Login button, the
Login Page component captures these credentials and initiates the authentication
process by calling the login() function in the API Service layer.

Frontend API Communication

The API Service component receives the login request with username and pass-
word parameters. This component acts as a centralized communication layer that
handles all HTTP requests to the Backend. It constructs a POST request to
the /cinemas/auth/token endpoint, including the credentials in the request body
as JSON. The API Service sends this HTTP request to the Authentication-
Controller on the Backend, establishing the connection between Frontend and
Backend layers.

Backend Controller Processing

The AuthenticationController receives the HTTP POST request at the /cin-


emas/auth/token endpoint. The controller extracts the username and password
from the request body and delegates the authentication logic to the Authentica-
tionService by calling the authenticate() method with the authentication request
object. The controller’s role is limited to request handling and response formatting,
keeping business logic separate in the service layer.

Service Layer Authentication Logic

The AuthenticationController receives the HTTP POST request at the /cin-


emas/auth/token endpoint. The controller extracts the username and password
from the request body and delegates the authentication logic to the Authentica-
tionService by calling the authenticate() method with the authentication request

32
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

object. The controller’s role is limited to request handling and response formatting,
keeping business logic separate in the service layer.

Database Query and Member Retrieval

The PostgreSQL database processes the query and returns the member entity
if found, or indicates that no member exists with that username. The Member-
Repository receives the database response and returns the member entity (or null)
to the AuthenticationService. This database interaction is critical as it retrieves
the stored password hash for comparison.

Password Verification Process

If a member is found, the AuthenticationService proceeds to verify the password.


The service uses BCryptPasswordEncoder to compare the provided password
with the stored password hash. BCrypt is a secure hashing algorithm that allows
password verification without storing plain text passwords. The encoder performs a
secure comparison that prevents timing attacks and ensures password security.

Successful Authentication Path

When the password is verified successfully, the AuthenticationService initiates


JWT token generation by interacting with the SecurityConfig component. The
Security component creates JWT claims including the username, user roles,
token expiration time, and issued-at timestamp. The Security component then
signs the token using HMAC SHA256 with a secret key, generating both an access
token and a refresh token. The generated tokens are returned to the Authentica-
tionService. The AuthenticationService builds an AuthenticationResponse
object containing the JWT token, user information, and user roles. This response
is returned to the AuthenticationController, which formats it as an HTTP 200
OK response with the authentication result in JSON format. The API Service
receives this response, extracts the token and user information, and returns the login
result to the Login Page component.

Token Storage and User Redirect

The Login Page component receives the successful authentication response and
stores the JWT token in the browser’s localStorage for use in subsequent API
requests. The user information is also stored in localStorage to maintain user
context throughout the session. After storing the authentication data, the Login
Page redirects the user to the HomePage, completing the successful login flow.

33
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

Error Handling - Invalid Password

When the password verification fails, the AuthenticationService throws an


AppException with an "Invalid credentials" message. This exception is caught by
the AuthenticationController, which converts it into an HTTP 401 Unautho-
rized response with an appropriate error message. The API Service receives this
error response and forwards it to the Login Page, which displays an error message
to the user indicating that the username or password is incorrect.

Error Handling - User Not Found

If the database query returns no member with the provided username, the Member-
Repository indicates that the user was not found. The AuthenticationService
throws an AppException with a "User not found" message. The Authentica-
tionController handles this exception and returns an HTTP 404 Not Found
response. The API Service forwards this error to the Login Page, which displays
an appropriate error message to inform the user that the account does not exist.

Security Considerations

The sequence diagram demonstrates several security best practices implemented


in the authentication flow. Password verification uses BCrypt, which provides secure
password hashing and comparison. JWT tokens are generated with expiration times
and include user roles for authorization. The token is stored securely in localStorage
(though in production, httpOnly cookies might be preferred). Error messages are
generic to prevent username enumeration attacks, not revealing whether a username
exists or not.

Component Responsibilities

Each component in the sequence has clear responsibilities. The Login Page handles
user interface and local storage management. The API Service manages HTTP
communication and response parsing. The AuthenticationController handles
HTTP request/response formatting. The AuthenticationService contains the
core authentication business logic. The MemberRepository provides data access
abstraction. The SecurityConfig component manages JWT token generation and
security configuration. The PostgreSQL Database provides persistent storage for
member credentials.

34
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

Flow Characteristics

The sequence demonstrates a synchronous request-response pattern where


each step waits for the previous step to complete before proceeding. The flow includes
alternative paths (alt blocks) for different scenarios: successful authentication,
invalid password, and user not found. Error handling is integrated throughout the
flow, ensuring that exceptions are properly caught and converted to appropriate
HTTP responses. The sequence maintains separation of concerns, with each
layer handling its specific responsibilities without mixing concerns.

4.2 Booking Creation Sequence

Figure 4.2: Booking Creation Sequence Sequences of the Online Cinema Booking System

Overview of Booking Flow

The Booking Creation Sequence Diagram illustrates the complete process of


creating a booking in the HDQ Cinema system, from the moment a member selects

35
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

seats to the final confirmation that seats are held. This sequence demonstrates the
interaction between the frontend, backend controllers, services, and database,
showing how the system validates requests, calculates prices, and creates bookings
while preventing race conditions through database-level constraints.

Initial Seat Selection

The booking process begins when a member interacts with the Frontend appli-
cation, specifically the SeatSelection page. The member visually selects their
preferred seats from the seat map displayed for a particular showtime. The Fron-
tend component tracks these selections, maintaining the state of selected seats
including their seat IDs, row numbers, and seat types. This user interaction
represents the first step in the booking journey, where the member makes their seat
choices before proceeding to create the booking.

Booking Request Creation

After selecting seats, the member initiates the booking creation by clicking a confir-
mation button or proceeding to payment. The Frontend component collects all
necessary information including the selected seat IDs, showtime ID, member
ID (from the authenticated session), and cinema ID. The Frontend constructs
a booking request object containing this information and prepares to send it to the
Backend for processing.

HTTP Request to Backend

The Frontend sends a POST request to the /bookings endpoint, including the
booking request in the request body as JSON. This HTTP request travels from the
Frontend to the BookingController on the Backend, establishing communication
between the client and server. The request includes all necessary data for booking
creation: member identification, showtime selection, seat selections, and cinema
[Link] where each step waits for the previous step to complete before
proceeding. The flow includes alternative paths (alt blocks) for different scenarios:
successful authentication, invalid password, and user not found. Error handling is
integrated throughout the flow, ensuring that exceptions are properly caught and
converted to appropriate HTTP responses. The sequence maintains separation
of concerns, with each layer handling its specific responsibilities without mixing
concerns.

36
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

Controller Layer Processing

The BookingController receives the HTTP POST request and extracts the
booking request data from the request body. The controller validates the request
structure and delegates the business logic processing to the BookingService by
calling the createBooking() method with the request object. The controller’s
responsibility is limited to request handling and response formatting, maintaining
separation of concerns with the service layer.

Service Layer Validation - Member

The BookingService begins processing by validating the member who is making


the booking. The service queries the database through the MemberRepository to
verify that the member ID in the request corresponds to an existing and valid member
account. This validation ensures that only registered members can create bookings
and prevents booking creation with invalid member references. The database returns
the member entity if found, confirming the member’s validity.

Service Layer Validation - ShowTime

The BookingService continues validation by checking the showtime specified in the


booking request. The service queries the database through the ShowTimeReposi-
tory to verify that the showtime exists and is valid. This validation ensures that
bookings can only be created for existing showtimes and prevents booking creation
for invalid or cancelled showtimes. The database confirms the showtime’s existence
and validity.

Dynamic Price Calculation

One of the most complex operations in the booking creation process is the dynamic
price calculation. The BookingService calls the TicketPriceRepository’s
toPrice() method for each selected seat. This method executes a sophisticated
native SQL query that joins multiple tables including ticket_price, show_time,
cinema, and day_type. The query considers the seat type (VIP or CLASSIC),
the day type (determined by checking if the showtime date falls within a holiday
period or is a weekend), and the cinema location to calculate the appropriate
price for each seat. The price calculation logic handles various scenarios: if the
showtime date matches a defined day type (like a holiday), it uses that day type’s
pricing; otherwise, it falls back to calculating the day of the week. The query uses
COALESCE functions to handle null values and ensures that a price is always
returned. This dynamic pricing allows the system to charge different rates for VIP

37
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

seats versus classic seats, for holidays versus regular days, and potentially different
rates at different cinema locations.

Booking and BookingDetail Creation

After calculating prices for all selected seats, the BookingService creates the
booking entity with the total price (sum of all individual seat prices), creation
timestamp, and initial status set to PENDING. The service then creates Book-
ingDetail entities for each selected seat, setting the seat status to HELD to
indicate that these seats are temporarily reserved. Each BookingDetail record
links a specific seat to a specific showtime and booking, with the calculated price
for that seat. The service attempts to save these entities to the database within
a transaction. The database enforces a unique constraint on the combination
of seat_id and showtime_id in the booking_detail table. This constraint is
critical for preventing race conditions: if two users simultaneously attempt to
book the same seat for the same showtime, only one will succeed. The database will
reject the second attempt with a constraint violation error, which the service
catches and converts into a user-friendly error message.

Transaction Management and Data Consistency

The entire booking creation process occurs within a database transaction managed
by the @Transactional annotation. This ensures atomicity: either all operations
succeed (member validation, showtime validation, price calculation, booking creation,
and all booking detail creations) or all operations are rolled back. This prevents
partial bookings where some seats might be reserved while others fail, which would
lead to data inconsistency. The transaction also provides isolation, ensuring that
concurrent booking attempts are properly serialized. When the transaction is active,
database locks prevent other transactions from modifying the same records, further
protecting against race conditions. The unique constraint at the database level
provides an additional safety net, ensuring data integrity even if application-level
checks fail.

Response Generation and Return

Upon successful booking creation, the BookingService builds a BookingResponse


object containing the booking ID, total price, booking status, and details about the
reserved seats. This response is returned to the BookingController, which formats
it as an HTTP 200 OK response with the booking data in JSON format. The
Frontend receives this response, extracts the booking information, and updates the
user interface to show that the booking was successfully created.

38
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

Seat Status Management

After successful booking creation, the selected seats have their status set to HELD
in the booking_detail records. This status indicates that the seats are temporarily
reserved for this booking but not yet confirmed. The seats will remain in HELD
status until payment is completed and the booking is approved, at which point the
status changes to BOOKED. If payment is not completed within 15 minutes,
the scheduled cleanup task will delete the booking and release the seats back to
AVAILABLE status.

Error Handling and Edge Cases

The sequence diagram shows the successful path, but the actual implementation
handles various error scenarios. If member validation fails, the service throws
an exception indicating the member does not exist. If showtime validation
fails, an exception indicates the showtime is invalid. If the unique constraint is
violated (double booking attempt), the service catches the DataIntegrityVio-
lationException and converts it to a user-friendly error message indicating that
one or more seats are no longer available.

Race Condition Prevention

The most critical aspect of this sequence is the prevention of race conditions
through the unique constraint. When multiple users simultaneously attempt
to book the same seat, the database ensures that only one booking succeeds. The first
transaction to commit will create the booking_detail record, and subsequent
attempts will fail at the database level due to the unique constraint violation.
This database-level enforcement is more reliable than application-level locking
mechanisms and provides a robust solution to the concurrent booking problem.

Performance Considerations

The booking creation process involves multiple database queries: member


validation, showtime validation, price calculation for each seat, and finally the
insertion of booking and booking detail records. The transaction ensures that
all these operations are coordinated efficiently. The price calculation uses native
SQL queries that are optimized for performance, joining multiple tables in a single
query rather than making multiple separate queries. This design minimizes database
round trips and improves overall system performance.

39
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

4.3 Payment Process Sequence

Figure 4.3: Payment Process Sequence Sequences of the Online Cinema Booking System

Overview of Payment Flow

The Payment Processing Sequence Diagram illustrates the complete payment


workflow in the HDQ Cinema system, from the moment a member initiates
payment for a booking to the final confirmation or cancellation. This sequence
demonstrates the integration between the frontend, backend services, external
VNPAY payment gateway, and database, showing how payment URLs are
generated, payment processing occurs externally, and booking statuses are updated

40
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

based on payment results.

Payment Initiation

The payment process begins when a member, after creating a booking and selecting
seats, decides to proceed with payment. The member interacts with the Frontend
application, typically on the ConfirmPayment page, where they review their
booking details including selected seats, showtime information, and total price.
When the member clicks the payment button or confirms their intention to pay, the
Frontend initiates the payment creation process.

Payment URL Generation Request

The Frontend sends a POST request to the /payments/create_payment endpoint,


including the booking ID in the request body. This request is received by the Pay-
mentController on the Backend, which extracts the booking ID and delegates the
payment URL generation to the PaymentService by calling the createPayment()
method with the booking ID parameter.

Booking Details Retrieval

The PaymentService begins processing by retrieving the booking details from


the database. The service queries the BookingRepository to fetch the complete
booking information, including the total price, booking status, associated booking
details, and member information. This data is essential for constructing the payment
parameters that will be sent to the VNPAY gateway. The database returns the
booking entity with all its related information.

VNPAY Parameter Construction

The PaymentService constructs the VNPAY payment parameters according


to the VNPAY API specification. The service builds a parameter map containing
essential payment information including the transaction amount (converted from
VND to the smallest currency unit, multiplied by 1000000), transaction reference
(using the booking ID), order information describing the transaction, bank code
for the payment method, IP address of the payer, locale settings, and return URL
where VNPAY will redirect after payment completion. The service also sets timing
parameters including creation date and expiration date (typically 15 minutes from
creation).

41
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

Payment URL Generation and Signing

The PaymentService generates the payment URL by sorting all parameters


alphabetically, constructing a query string, and creating a hash data string for signing.
The service then generates a secure hash using HMAC SHA512 algorithm with
the VNPAY secret key. This cryptographic signature ensures that the payment
request cannot be tampered with and verifies the authenticity of the request to
VNPAY. The PaymentService also stores this payment URL in the database by
creating a PaymentURL entity linked to the booking.

Payment URL Response and Redirect

The PaymentService returns the generated payment URL to the PaymentCon-


troller, which formats it as an HTTP 200 OK response with the payment URL
in JSON format. The Frontend receives this response, extracts the payment URL,
and redirects the member’s browser to the VNPAY payment gateway. This
redirect transfers control from the HDQ Cinema application to the VNPAY payment
interface, where the actual payment processing will occur.

External Payment Processing

The member is now on the VNPAY payment gateway website, where they
enter their payment information such as bank account details, card information, or
other payment methods supported by VNPAY. The VNPAY gateway processes the
payment securely, handling all sensitive financial information without exposing it to
the HDQ Cinema system. This external processing ensures PCI DSS compliance
and reduces the security burden on the cinema application.

Payment Callback Processing

After payment processing completes (whether successful, cancelled, or failed), VN-


PAY sends a callback request to the HDQ Cinema backend at the /payments/payment_infor
endpoint. This callback is a GET request containing payment result parameters
including the response code, transaction reference, payment amount, bank code used,
order information, and a secure hash for verification. The PaymentController re-
ceives this callback request and calls the PaymentService’s transactionResult()
method for processing.

Payment Result Processing - Success Scenario

When the response code is "00" (indicating successful payment), the PaymentSer-
vice verifies the payment callback’s authenticity by validating the secure hash. After

42
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

verification, the service calls the BookingService to approve the payment. The
BookingService updates the booking status from PENDING to CONFIRM in
the database and updates all associated BookingDetail records, changing the seat
status from HELD to BOOKED, permanently reserving the seats. The service
also deletes the PaymentURL record and returns a BookingResponse.

Payment Result Processing - Cancellation Scenario

When the response code is "24" (indicating payment cancellation by the user), the
PaymentService handles the cancellation. The service deletes the PaymentURL
record and calls the BookingService to delete the entire booking and all associ-
ated BookingDetail records from the database. This releases the seats back to
AVAILABLE status, making them available for other members to book.

Payment Result Processing - Failure Scenario

When the response code indicates payment failure (any code other than "00" or
"24"), the PaymentService throws an AppException with an appropriate error
code. This exception is caught by the PaymentController, which converts it into
an error response. The booking remains in PENDING status, and seats remain
in HELD status, allowing the member to potentially retry payment or allowing
the system’s scheduled cleanup task to eventually remove expired bookings.

Response to Frontend

The PaymentController formats the payment result (success, cancellation, or


failure) and sends it to the Frontend. In a typical implementation, this might occur
through a redirect URL that VNPAY provides, or through a polling mechanism.
The Frontend receives the payment result and updates the user interface accordingly,
displaying a success message, cancellation notice, or error message to the member.

Security and Verification

Throughout the payment process, security is maintained through cryptographic


signing. The HMAC SHA512 signature ensures that payment requests cannot
be modified, and the callback verification ensures that payment results are authentic.
The system never handles sensitive payment information directly; all financial data
is processed by VNPAY, reducing the security risk and compliance burden on the
HDQ Cinema application.

43
System Design, Implementation and Testing Progress Chapter 4. Detail Process Design

Transaction Integrity

The payment approval process maintains database transaction integrity. When


a payment is successfully processed, the booking status update and seat status
updates occur within a single transaction, ensuring that either all updates succeed
or all are rolled back. This prevents scenarios where a booking might be marked as
confirmed but seats remain in HELD status, or vice versa.

Error Recovery and Edge Cases

The sequence handles various edge cases including payment timeouts (handled by
the 15-minute expiration), payment failures, and network issues during callback
processing. The system’s scheduled cleanup task provides a safety net by removing
bookings that remain in PENDING status for more than 15 minutes, ensuring
that seats are eventually released even if payment processing encounters issues.

44
Chapter 5

Implementation Progress

5.1 Completed Features


The development team has completed and successfully tested the following functional
groups:

• Authentication & Authorization:

– The system supports secure user registration (Member creation) and login
using JWT (JSON Web Token).

– Security mechanisms are fully implemented, including token refresh, token


introspection (validity check), and logout functionality.

– Role-Based Access Control (RBAC) is operational, clearly distinguishing


between ADMIN and USER roles, with protected routes enforced on the
Frontend.

• Core Management (Movies, Cinemas & Showtimes):

– Movies: Users can view movie lists and details, and filter movies by status
(showing/upcoming) or cinema. Admins possess the capability to create new
movie entries.

– Cinemas & Rooms: The system manages cinema lists, allows for the creation
of rooms, and supports detailed seat configuration for specific rooms.

– Showtimes: Admins can create showtimes with strict unique constraints


to prevent scheduling overlaps within the same room.

• Booking & Seat Selection System:

45
System Design, Implementation and Testing Progress
Chapter 5. Implementation Progress

– Seat Interface: A visual seat map displays real-time status (AVAILABLE,


HELD, BOOKED) and visual indicators for seat types (VIP, Classic).

– Booking Logic:

∗ The system implements automatic seat holding (HELD status) during user
interaction.
∗ Race condition prevention is enforced via unique database constraints
to ensure no two users can book the same seat simultaneously.
∗ Dynamic total price calculation is performed based on selected seat types.
∗ Booking status is tracked through PENDING and CONFIRM states.

– Scheduled Tasks: An automatic cleanup task runs every 5 minutes to delete


bookings that have remained in the PENDING status for more than 15 minutes,
thereby releasing the seats.

• Payment Integration:

– Successful integration with the VNPAY payment gateway has been achieved.

– The workflow includes payment URL generation, callback handling, and a


verification process for payment approval.

• Dynamic Pricing System:

– The system calculates ticket prices flexibly based on Seat Type (VIP/Classic),
Day Type (Holiday/Weekend), and specific Cinema policies.

– Complex calculation logic is handled efficiently using Native SQL queries.

• Frontend User Interface:

– A responsive design has been finalized for key pages, including the Homepage
(Movie Listing), Movie Details, Seat Selection, Payment Confirmation, and
Login pages.

5.2 Planned & In-Progress Features


To complete the HDQ Cinema ecosystem, the following features are outlined in the
upcoming development roadmap:

• User Management: Profile management and personal Booking History.

46
System Design, Implementation and Testing Progress
Chapter 5. Implementation Progress

• Notifications: Integration of Email and SMS notifications for booking confirma-


tions.

• Advanced Administration: Admin Dashboard, Analytics, and Reporting tools.

• Engagement & Promotions: Movie rating and reviews, Loyalty programs, and
Promotional codes/discounts.

• Utilities: Advanced search and filtering capabilities.

47
Chapter 6

Testing Progress

6.1 Test Cases & Coverage Status

6.1.1 Backend Tests (Spring Boot)


Current Status:

• Minimal test coverage (estimated at ∼5%).

• The only existing test file is [Link], which


performs a basic context loading test.

Recommended Test Cases to Implement:

1. Unit Tests:

• BookingService:

– Verify createBooking() with valid requests.


– Verify createBooking() handles unavailable seats (Race Condition sim-
ulation).
– Validate error handling for invalid members or showtimes.
– Verify approvePayment() correctly transitions status to CONFIRM.
– Verify deleteExpiredBookings() successfully removes PENDING book-
ings.
– Validate dynamic price calculation logic.

• PaymentService:

– Verify createPayment() generates a valid VNPAY URL.


– Verify transactionResult() handles Success response (Code "00").

48
System Design, Implementation and Testing Progress Chapter 6. Testing Progress

– Verify transactionResult() handles Cancellation response (Code "24").


– Verify handling of failure responses.

• AuthenticationService:

– Validate authenticate() with valid vs. invalid credentials.


– Verify refreshToken() logic.
– Verify logout() successfully invalidates tokens.

• TicketPriceRepository:

– Test toPrice() query for VIP seats on weekends.


– Test toPrice() query for Classic seats on weekdays.
– Test holiday pricing logic.

• Repository Layer:

– Verify Unique Constraints on BookingDetail(seat_id, showtime_id)


and ShowTime(start_time, room_id).
– Verify Cascade Delete operations.

2. Integration Tests:

• Booking Flow: Create booking → Verify seats HELD → Approve payment


→ Verify seats BOOKED → Verify cleanup of expired bookings.

• Payment Flow: Create payment → Verify URL → Simulate Callback →


Verify Booking Approval.

• API Endpoints: Test POST /bookings, POST /bookings/{id} (Approve),


and Payment related endpoints.

6.1.2 Frontend Tests (ReactJS)


Current Status:

• Minimal test coverage (estimated at ∼5%).

• Only default React test exists in [Link] (Basic render test).

Recommended Test Cases to Implement:

• Component Tests: Verify rendering and state for SeatSelection, SeatMap (status
display), Ticket (price display), and MovieItem.

49
System Design, Implementation and Testing Progress Chapter 6. Testing Progress

• Integration Tests:

– Booking Flow: Select Seats → Create Booking → Payment Redirection.

– Login Flow: Credential Entry → Token Reception.

– Movie Browsing: Filter movies by status and search functionality.

• API Service Tests: Verify createBooking() and createPayment() calls and


error handling.

6.2 Testing Approach

6.2.1 Current Testing Strategy


• Backend: JUnit 5, Spring Boot Test. Coverage ∼5%.

• Frontend: React Testing Library, Jest. Coverage ∼5%.

6.2.2 Recommended Testing Strategy


• Backend:

– Unit Testing: Use JUnit 5 and Mockito to isolate business logic.

– Integration Testing: Use @SpringBootTest and Testcontainers for database


testing.

– Goals: Service (80%+), Repository (70%+), Controller (60%+).

• Frontend: Focus on Component Testing and Integration Testing for user flows
using mocked API responses.

6.2.3 Tools Used


• Backend: JUnit 5, Spring Boot Test. Planned: Mockito, Testcontainers, AssertJ.

• Frontend: React Testing Library, Jest.

50
System Design, Implementation and Testing Progress Chapter 6. Testing Progress

6.3 Issues Found & Current Resolution Status

6.3.1 Known Issues (Resolved)


1. Race Condition Prevention:

• Issue: Multiple users could book the same seat simultaneously.

• Solution: Implemented @UniqueConstraint on BookingDetail(seat_id, showtime_id).

• Status: RESOLVED

2. Expired Bookings Not Released:

• Issue: PENDING bookings were not cleaned up.

• Solution: Implemented @Scheduled task running every 5 minutes.

• Status: RESOLVED

3. Dynamic Pricing Complexity:

• Solution: Implemented native SQL query in TicketPriceRepository.

• Status: RESOLVED

4. Security Configuration (CSRF/CORS):

• Solution: Disabled CSRF for API and configured CORS filters.

• Status: RESOLVED

6.3.2 Potential Issues (To Be Tested)


• Concurrent Booking Attempts: Verify unique constraint under high load.

• Payment Timeout Handling: Verify behavior when payment exceeds 15 minutes.

• Database Transaction Isolation: Prevent dirty reads.

• JWT Token Expiration: Test refresh mechanism.

6.3.3 Testing Gaps


• No Load Testing (JMeter/Gatling required).

• No Security Testing (SQL Injection, XSS).

• No Performance Testing (Database query speed).

51
System Design, Implementation and Testing Progress Chapter 6. Testing Progress

6.4 Testing Roadmap


Phase 1 (Immediate): Write Unit Tests for core services (BookingService, PaymentService,
AuthenticationService) and Integration Tests for Booking Flow.

Phase 2 (Short-term): Write API/Repository/Frontend Component tests. Setup Ja-


CoCo coverage reporting.

Phase 3 (Medium-term): Implement E2E tests, Load testing, and Security testing.

52
Chapter 7

Conclusion

As of this reporting period, the HDQ Cinema - Online Movie Ticket Booking System
has successfully completed its core development phase, establishing a stable operational
platform built on a clear layered architecture of Spring Boot, ReactJS, and PostgreSQL.
The system now supports the complete end-user workflow, enabling seamless registration,
movie browsing, real-time seat selection, and secure payment processing via the VNPAY
gateway. Beyond standard functionality, the development team has effectively addressed
complex technical challenges, notably implementing specific database constraints to prevent
race conditions during concurrent bookings and deploying scheduled tasks to automatically
release expired seat holds, thereby ensuring data integrity and resource optimization.
Furthermore, the system demonstrates sophisticated business logic through its Dynamic
Pricing engine, which accurately handles complex price variations based on seat types,
weekends, and holidays. Security has also been prioritized with a robust JWT-based
authentication and authorization mechanism to protect user transactions. However, despite
these functional successes, the project currently faces a significant limitation regarding
quality assurance. The test coverage for both backend and frontend components remains
minimal at approximately 5
To address these gaps and finalize the ecosystem, the future development roadmap
is structured into three strategic phases. The immediate focus will be on consolidation,
prioritizing the implementation of unit and integration tests to achieve target coverage
rates of 80

References

53
Bibliography

[1] I. Sommerville, Software Engineering, 10th ed. Pearson Education Limited, 2016.

[2] R. S. Pressman and B. R. Maxim, Software Engineering: A Practitioner’s Approach,


9th ed. McGraw-Hill Education, 2020.

[3] IEEE Std 830-1998, IEEE Recommended Practice for Software Requirements Specifi-
cations, IEEE, 1998.

[4] ISO/IEC/IEEE 29148:2018, Systems and software engineering — Life cycle processes
— Requirements engineering, 2018.

[5] Creately, “UML Diagrams for Online Movie Ticket Booking


System,” Available: [Link]
online-movie-ticket-booking-system

[6] Visual Paradigm Online, “Use Case Diagram for Online Cinema Ticket Booking
System,” Available: [Link]

[7] GeeksforGeeks, “Software Requirements Specification (SRS) for Online Movie


Ticket Booking System,” 2023. Available: [Link]
software-requirements-specification-srs-for-online-movie-ticket-booking-system/

[8] TutorialsPoint, “Software Requirements Specification (SRS) – Example and


Template,” 2022. Available: [Link]
engineering/software_requirements.htm

[9] [Link], “ERD and Use Case Diagrams for Online Ticket Booking System,” 2023.
Available: [Link]

54

You might also like