You are on page 1of 26

RMIT University

ISYS2099 Database Applications

Assignment 2

DATABASE PROJECT

Student team: Team 1

Student name & ID: Nguyen Xuan Huy - s3877913

Nguyen Duc Dung - s3803749

Nguyen Thi Ha Thu - s3927104

Huynh Dac Tan Dat - s3777091

Lecturer: Tran Dang Tri

1
Table of Contents

1. Introduction.......................................................................................................................3

2. Database Design................................................................................................................3

a. Relational database....................................................................................................................3
i. Data analysis and ERD diagram.........................................................................................................3
ii. Data analysis and ERD diagram.........................................................................................................5

b. Explanation:...............................................................................................................................8

3. Performance Analysis:......................................................................................................9

a. Indexing: (only name and price)...............................................................................................9

b. Stored Procedures for Warehouse Selection Logic................................................................9

c. Transactions and Locking for Concurrent Access.................................................................9

4. Data Consistency:............................................................................................................10

5. Data Security....................................................................................................................19

b. User Accounts and Roles:........................................................................................................19


i. Usage:...................................................................................................................................................19
ii. Explanation:........................................................................................................................................19

c. Password Hashing Using bcrypt:...........................................................................................19


i. Usage:...................................................................................................................................................19
ii. Explanation:........................................................................................................................................19

d. Parameterized Queries to Prevent SQL Injection:...............................................................20


i. Usage:...................................................................................................................................................20

e. Check user input:.....................................................................................................................20


i. Usage:...................................................................................................................................................21
ii. Explanation:........................................................................................................................................21

6. Conclusion.......................................................................................................................24

2
1. Introduction

With the accessibility and adoption improvement of the global internet, online shopping has
become more popular and accessible worldwide (ref). Therefore, some e-commerce
platforms, for instance, Lazada, Shopee, and Tiki, have become indispensable and provide a
streamlined buying experience for customers and offer a variety of sales channels for
vendors. Besides providing a marketplace for sellers, some companies, like Tiki, also offer
drop shipping services, where vendors can store their products in Tiki’s warehouse to shorten
the delivery time and ensure user satisfaction with the urge to deeply understand the
Fulfillment By Tiki (FBT) model and for documentation purposes. This report examines the
architecture and mechanisms needed to support complex operations like user management,
order processing, product categorization, and customer reviews, offering insights into
creating a robust backend system for an online marketplace.

2. Database Design
a. Relational database

Efficiency in managing and storing structured data is essential for monitoring and decision-
making in the e-commerce industry (ref). In the Tiki project, the company provides an e-
commerce platform for end-users, which offers an FBT model to increase user satisfaction
and delivery utilities, which requires an efficient data management system for monitoring
processes and ensuring fulfillment. Therefore, adopting the relational database model can
connect each entity to manage data consistency and accuracy. For instance, some attributes
that can be mentioned, like products, orders, users, warehouses, and shipping, can be
compiled to manage complex 1:1 (one to one), 1:N (one to many), M:N (many to many),
which present real-world applications and enable complex querying and insight reporting.
This section will provide insight into each entity’s data structure and relationship when
applying a relational database model to the Tiki management system.

i. Data analysis and ERD diagram


The ERD diagram below illustrates the data structure of the Tiki simulation project, which
presents the relationship between each entity in the database system. In the database system,
some elements, including crucial store procedures, triggers, transactions, error handling, and
validation logic, are implemented to support the e-commerce management operations.

3
In the stored procedures, the “addProductToCart” and “PerformPayment” functions
summarize the business logic for modularity and reusability. The “addProductToCart”
handles adding the product to user’s cart. It validates the user authentication and product
existence, retrieves the user’s active cart, and issues new product quantity into the cart,
checking, inserting, and updating the cart item according to user input. This encapsulates the
logic in business for modifying cart contents. As for “PerformPayment”, this procedure
manages the payment process when the cart is checked out. It calculates the total bill,
validates the user has sufficient funds, changes the cart status to "success", deducts the
payment amount from the user's account, and updates the cart items' statement, centralizing
all the steps needed for updating data and payment procedure.

As for Triggers, this function enforces critical business rules and data consistency, like
preventing negative product stock and limiting warehouse capacity. Transactions utilize
rollback handlers to maintain ACID properties during multi-statement operations, preventing
partial updates.

Lastly, the Concurrency control is implemented by locking rows before updates to avoid race
conditions—input validation checks for valid user and product IDs to improve security.
Descriptive error messages are raised using SIGNAL for easier debugging. Location data is
normalized to track geography across users, carts, and orders. Enabling the FULLTEXT
index on product names improves search efficiency.

4
Table 1: Tiki’s stimulation ERD diagram

ii. Data analysis and ERD diagram


The table below illustrates the relationship between each table, including the constraints of
each relational schema:

5
Table name Description

admins
- Store information about administrators of the systems.

- Contain id (primary key), link and code defined as variable characters.

users
- Store user data for the platform.

- User information includes id (unique primary key), username, email, avatar (user
profile picture URL), location, amount (user balance or account balance), and
password.

- One user can have one to many user roles and one to many cart issues (each cart for
each payment).

carts
- Represent shopping carts for users.

- Fields include id (primary identifier), deliveryFrom, delivery, status (cart status,


possibly "on-going" for active carts), and userId (a reference to the user who owns the
cart).

- Cart is a dependency of users, and qualities tables.

- One cart can be one to many quality

categories
- Store information about product categories.

- Contains fields such as id (primary key), image (category image URL), name
(category name), slug (a URL-friendly version of the category name), code, link,
expectedSpace, and expectedQuality.

6
- A dependency table to the product.

warehouses
- Represent information about warehouses or storage locations.

- It includes fields like id (primary key), city, province, district, street, available
(available storage space), and totalArea.

- One warehouse can store many products.

products
- Stores product information.

- Fields include id (primary key), prName (product name), prId, space (product space
requirements), amount (quantity available), brand, prLink (product URL), image
(product image URL), cost, categoryId (a reference to the product category), and
warehouseId (a reference to the warehouse where the product is stored).

- Many products can be defined as one type in a category, one to many products can be
stored in one warehouse.

qualities
- This table represents product quality assessments or reviews.

- It contains fields such as id (primary key), productID, status (possibly review status),
product_option, product_image (image associated with the review), product_name
(product name), product_cost, quality (product quality rating), and cartId (a reference
to the shopping cart associated with the review).

roles
- Use to define user roles.

- It includes fields like id (primary) and name (role name).

7
- One role can be applied to one to many users.

user_role
- This table represents the relationship between users and their roles.

- It includes fields like createdAt and updatedAt (timestamps), roleId (a reference to the
role assigned to a user), and userId (a reference to the user).

Table 2: Database schema and relationship

b. Explanation:

The database design and structure have some competitive attributes that enhance the
efficiency of the Tiki e-commerce platform. Below is the explanation of its competitiveness:

Normalized Schema: The database follows a normalized schema, reducing data redundancy
and ensuring data integrity. For that reason, it provides efficient storage and minimizes the
chances of data inconsistencies.

Foreign Key Relationships: Using foreign keys and relationships between tables (e.g.,
between users, carts, products, and categories) enforces referential integrity, making it easier
to maintain data consistency and implement business rules.

Scalability: The database structure is designed to accommodate growth. Tables like


"warehouses," "products," and "categories" are appropriately structured to handle a large
number of records, making them suitable for scaling up the platform.

Data Integrity: Constraints and foreign keys are set up to maintain data integrity. For
instance, the "userId" foreign key in the "carts" table ensures that each cart is associated with
a valid user.

Flexibility: The schema allows for flexibility in managing product categories, warehouse
locations, and user roles. As the platform expands, new categories, warehouses, and roles can
be easily added.

8
Performance Optimization: Indexes are used on critical columns to improve query
performance, making data retrieval faster and more efficient.

Product Quality Reviews: The "qualities" table enables the recording of product quality
reviews associated with specific carts. This can help track and improve product quality in the
marketplace.

Location Handling: Including location fields in tables such as "users" and "warehouses"
provides the capability to manage shipping and delivery effectively, a critical aspect of an e-
commerce platform.

3. Performance Analysis:
a. Indexing: (only name and price)

Indexes have been implemented on frequently searched namely title and price in the products
table. This implementation can significantly speed up query performance by allowing the
database engine to locate the required rows, and payment procedure more efficienct.

9
b. Stored Procedures for Warehouse Selection Logic

Warehouse selection logic is encapsulated in stored procedures to standardize the process and
reduce the complexity of the application code. By offloading this business logic to the
database layer, developers also benefits from quicker data processing as the logic runs closer
to the data itself. Additionally, the stored procedure takes into account factors like warehouse
proximity, stock availability, and load to intelligently select the optimal warehouse for
fulfilling an order.

c. Transactions and Locking for Concurrent Access

Concurrent customer orders are managed through a transactional model to ensure data
consistency and isolation. When a customer places an order, a transaction is initiated that
locks the specific product rows involved, which prevents scenarios where two customers
might attempt to purchase more product units than are available in stock. Notably, locks are
released as soon as the transaction is committed or rolled back, thus minimizing the window
of lock contention and allowing for high concurrency. Row-level locking permits other
unrelated records to be accessed concurrently, thus improving system throughput.

4. Data Consistency:

The assumption testing process:

● Node data (clear data if needed).


● Register new one, Login as new user.
● Start Project as localhost:7000

Single Trigger control product update in quality:


In this case, the sql code to avoid quality returns a negative value (out of stock).

The trigger is designed to be active in scenarios where two users simultaneously attempt to
order a single product that is available in only one unit of stock. In such cases, the first user's
order will successfully proceed with the payment, while the second user's order will be
rejected due to the product being out of stock.

10
Testing scenario: out of stock product.

Using idk change value of product want to test:

Start order as user: dathuynhuser

11
Perform payment as user dathuynhuser(new user 1) as this time same step and perform
payment as user chomeoga(new user 2).

As user chomeoga:

As user dathuynhuser:

12
Database update:

● Double Trigger control mechanism facilitates the management of product storage and
retrieval in the warehouse:

13
In this scenario, the SQL code should be implemented to prevent insufficient space in the
warehouse and enable automatic updates of the available warehouse capacity.

The active state occurs when an administrator performs the insertion of a substantial quantity
of products or when a user initiates the process of ordering or deleting a product.

Testing scenario:
Adjust value in data.js
Assumption product space:

{
image:
"https://salt.tikicdn.com/ts/category/00/5d/97/384ca1a678c4ee93a0886a204f47645d.png",
name: "Thời trang nam",
slug: "thoi-trang-nam",
code: "915",
expectedSpace: (420.4 * 266.2 * 20.8) / 1000000000,
expectedQuality: 100,
link: "https://tiki.vn/thoi-trang-nam/c915"
},
{
image:
"https://salt.tikicdn.com/ts/category/13/64/43/226301adcc7660ffcf44a61bb6df99b7.png",
name: "Đồ Chơi - Mẹ & Bé",
slug: "do-choi-me-be",
code: "2549",
expectedSpace: (140.4 * 140.2 * 362.8) / 1000000000,
expectedQuality: 100,
link: "https://tiki.vn/do-choi-me-be/c2549"
},

Assumption regarding the input data:

14
The expectedSpace field will serve as the data repository for the packaging of products,
including the corresponding width, height, and length dimensions.

The expectedQuality will be quality as one product will be added in the warehouse.

Assumption regarding the input warehouse:

await WareHouse.bulkCreate([
{
city: 'Hồ Chí Minh',
district: 'Quận 7',
province: 'Nam Phong',
street: 'Nguyễn Thị Thập',
totalArea: 3000,
},
{
city: 'Đà nẵng',
district: 'Hải Châu',
province: 'Bình Hiên',
street: 'Hoàng diệu',
totalArea: 3000,
},

], { transaction });

There are 2 warehouse examples in which, one is from Ho Chi Minh and another is from Da
Nang:

The variable "totalArea" denotes the measurement of the space area in cubic metres ( m❑3).
It is recommended to initially test the space consistency by using an assumption value for the
area.

Assumption code active:

15
Function addCode with hash cookies from tiki to take real-time data.

● Identifier represent for code of category


● “1”, “2” will be the warehouse id 1 for warehouse in Ho chi Minh, and 2 in Da
Nang.
● 80 means adding a total of 80 products each product has 100 quality.

Start code with command line:

Note please check databases already have triggers if not: please run code.sql.

16
Node data will add product to warehouse and it will check to avoid database return negative
value:

Change database when perform payment:

17
Add 3 shirt with option value:

When Perform payment:

18
Change database availability when status changes to success:

Transactions to ensure consistent inventory when moving products between warehouses.

Data transaction:

Within the context of MySQL, a data transaction denotes a consecutive series of one or more
SQL statements that are performed as a unified and indivisible unit of work. The primary
objective of a transaction is to uphold the principles of data integrity and consistency by
enabling a cohesive set of interrelated database activities to either achieve success
collectively or encounter failure as a whole.
Transactions in MySQL adhere to the ACID (Atomicity, Consistency, Isolation, Durability)
criteria.
1. Atomicity refers to the property of treating a transaction as an indivisible and cohesive
item. All activities conducted by the system either result in successful execution and
subsequent application to the database, or they encounter failure, resulting in the database
remaining unaltered.
2. Consistency: Transactions guarantee the transfer of a database from one consistent state to
another. The system implements data integrity rules and limitations.Isolation refers to the
ability of several users to execute transactions concurrently, while ensuring that the changes
made by one transaction are kept separate from the changes made by others until the
transaction is fully completed. The implementation of this measure serves to mitigate any
interference and protect the integrity of data consistency. Durability refers to the
characteristic of a transaction where its modifications become permanent and persist even in
the event of system failures. The data is saved in a manner that guarantees durability.
In MySQL, transactions are commonly launched using the START TRANSACTION,
BEGIN, or BEGIN WORK statement, and they are terminated by either a COMMIT to
persist the modifications or a ROLLBACK to revert the modifications in the event of an error
or any other complication. The utilization of transactions is of utmost importance in

19
managing key data processes in order to uphold data integrity and consistency within a multi-
user database system.

5. Data Security
b. User Accounts and Roles:

i. Usage:
User accounts and roles are essential for controlling access to various system parts. They
ensure that users can only access the functionalities and data they are authorised to use.

ii. Explanation:
In your project, you have likely implemented user accounts with associated roles for
warehouse admins, sellers, and customers.

This segmentation is implemented for role-based access control (RBAC), ensuring that users
can perform actions based on their assigned roles. For example, admins may have full access
to all parts of the system, while customers may have limited entry.

c. Password Hashing Using bcrypt:

i. Usage:
Password hashing is crucial for protecting user passwords stored in the database. Hashing
ensures that passwords are not stored in plaintext, making it difficult for attackers to obtain
sensitive user information.

ii. Explanation:
By using bcrypt for password hashing, you have implemented a strong cryptographic hashing
algorithm that adds an additional layer of security.

20
Bcrypt is designed to be slow and computationally intensive, which makes it resistant to
brute-force and dictionary attacks. When users create or update their passwords, the system
hashes them before storing them in the database. During authentication, the system hashes the
provided password and compares it to the stored hash to verify the user's identity.

d. Parameterized Queries to Prevent SQL Injection:


i. Usage:
SQL injection is a common attack vector where malicious SQL queries are injected into user
inputs, potentially leading to unauthorized access or data manipulation. Parameterized queries
help prevent this type of attack.
e. Check user input:

Database Permissions Assigned to Roles:

21
i. Usage:
Database permissions control what actions and operations-specific roles can be performed
within the database. Assigning appropriate permissions helps limit the scope of actions that
each role can take.
ii. Explanation:
Roles, such as warehouse admins, sellers, and customers, likely have different levels of
access and permissions within the database. For instance, admins may have full CRUD
(Create, Read, Update, Delete) permissions on various tables, while customers may only have
read access to product information. This granular control over permissions ensures that users
can only interact with data and perform actions aligned with their roles and responsibilities.
JWT (JSON Web Tokens):

Using JSON Web Tokens (JWT) in session management is common in web applications
because it enhances security and efficiency. JWTs are digitally signed for data integrity and
authenticity, preventing tampering and unauthorized access. They are stateless, reducing
server overhead and making the system scalable. JWTs are compact and compatible with
Cross-Origin Resource Sharing (CORS). They include custom claims, control session
expiration, reduce database queries, and work well for mobile and single-page applications.
JWT-based authentication is decentralised, supports scalability, and is ideal for modern web
apps and APIs.

Step by step JWT implementation:

Authentication: When a user logs in, the server generates a JWT as a secure session token.

Token Generation: The server creates a JWT with user info and an expiration time.

Token Signing: The JWT is signed with a secret key for integrity.

Token Storage: The client stores the JWT securely in cookie

Authorization: For protected resources, the client sends the JWT in request headers.

22
Token Verification: The server verifies the token's signature, decodes it, and extracts user
info for authentication.

Test step login step:

Login or register new user:

For test purpose register new user will receive 99999999999 VND

Bad request check user input:

23
Cookies were added to the login process to verify the current user. The user's session
has ended in 24 hours.

Roles validation:

For user:

In back-end code router no need checking:

24
For check roles is admin or seller:

isAdmin validates that the current user is admin or seller to execute the same function as the
dependent role.

25
6. Conclusion

This project delivered a robust hybrid relational-NoSQL database optimized for an e-


commerce fulfillment workflow by methodically applying sound database architecture
principles including logical design focused on flexibility, integrity and normalization to
accurately model domain entities and processes; physical design using indexing, partitioning,
triggers and transactions to improve performance, consistency and reliability; and security
mechanisms like access control and input validation per best practices. The resulting
decentralized, scalable platform is capable of securely managing the structured and
unstructured data needs of a fulfillment-centric business model. Hands-on implementation
enhanced proficiency in requirements analysis, data modeling, query optimization, and
testing. Overall, the project demonstrated a comprehensive approach to engineering a tailored
database solution fitting the specialized needs of the domain.

26

You might also like